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/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/builder.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/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/exception/exception.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/mixin_super_invoked_names.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.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/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; /** * Instances of the class `ApiElementBuilder` traverse an AST structure and * build elements outside of function bodies and initializers. */ class ApiElementBuilder extends _BaseElementBuilder { /** * A table mapping field names to field elements for the fields defined in the current class, or * `null` if we are not in the scope of a class. */ Map<String, FieldElement> _fieldMap; /** * Whether the class being built has a constant constructor. */ bool _enclosingClassHasConstConstructor = false; /** * Initialize a newly created element builder to build the elements for a * compilation unit. The [initialHolder] is the element holder to which the * children of the visited compilation unit node will be added. */ ApiElementBuilder(ElementHolder initialHolder, CompilationUnitElementImpl compilationUnitElement) : super(initialHolder, compilationUnitElement); @override void visitAnnotation(Annotation node) { // Although it isn't valid to do so because closures are not constant // expressions, it's possible for one of the arguments to the constructor to // contain a closure. Wrapping the processing of the annotation this way // prevents these closures from being added to the list of functions in the // annotated declaration. ElementHolder holder = new ElementHolder(); ElementHolder previousHolder = _currentHolder; _currentHolder = holder; try { super.visitAnnotation(node); } finally { _currentHolder = previousHolder; } } @override void visitBlockFunctionBody(BlockFunctionBody node) {} @override void visitClassDeclaration(ClassDeclaration node) { _enclosingClassHasConstConstructor = false; for (var constructor in node.members) { if (constructor is ConstructorDeclaration && constructor.constKeyword != null) { _enclosingClassHasConstConstructor = true; break; } } ElementHolder holder = _buildClassMembers(node); SimpleIdentifier className = node.name; ClassElementImpl element = new ClassElementImpl.forNode(className); className.staticElement = element; element.isAbstract = node.isAbstract; _fillClassElement(node, element, holder); _currentHolder.addType(element); } @override void visitClassTypeAlias(ClassTypeAlias node) { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); SimpleIdentifier className = node.name; ClassElementImpl element = new ClassElementImpl.forNode(className); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); element.isAbstract = node.abstractKeyword != null; element.mixinApplication = true; element.typeParameters = holder.typeParameters; setElementDocumentationComment(element, node); _currentHolder.addType(element); className.staticElement = element; holder.validate(); } @override void visitCompilationUnit(CompilationUnit node) { if (_unitElement is ElementImpl) { _setCodeRange(_unitElement, node); } super.visitCompilationUnit(node); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); FunctionBody body = node.body; SimpleIdentifier constructorName = node.name; ConstructorElementImpl element = new ConstructorElementImpl.forNode(constructorName); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(element, node); if (node.externalKeyword != null) { element.external = true; } if (node.factoryKeyword != null) { element.factory = true; } element.encloseElements(holder.functions); element.encloseElements(holder.labels); element.encloseElements(holder.localVariables); element.parameters = holder.parameters; element.isConst = node.constKeyword != null; element.isCycleFree = element.isConst; if (body.isAsynchronous) { element.asynchronous = true; } if (body.isGenerator) { element.generator = true; } _currentHolder.addConstructor(element); (node as ConstructorDeclarationImpl).declaredElement = element; if (constructorName == null) { Identifier returnType = node.returnType; if (returnType != null) { element.nameOffset = returnType.offset; element.nameEnd = returnType.end; } } else { constructorName.staticElement = element; element.periodOffset = node.period.offset; element.nameEnd = constructorName.end; } holder.validate(); } @override void visitEnumDeclaration(EnumDeclaration node) { SimpleIdentifier enumName = node.name; EnumElementImpl enumElement = new EnumElementImpl.forNode(enumName); _setCodeRange(enumElement, node); enumElement.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(enumElement, node); InterfaceTypeImpl enumType = enumElement.thisType; // // Build the elements for the constants. These are minimal elements; the // rest of the constant elements (and elements for other fields) must be // built later after we can access the type provider. // List<FieldElement> fields = new List<FieldElement>(); NodeList<EnumConstantDeclaration> constants = node.constants; for (EnumConstantDeclaration constant in constants) { SimpleIdentifier constantName = constant.name; FieldElementImpl constantField = new ConstFieldElementImpl.forNode(constantName); constantField.isStatic = true; constantField.isConst = true; constantField.type = enumType; constantField.metadata = _createElementAnnotations(constant.metadata); setElementDocumentationComment(constantField, constant); fields.add(constantField); new PropertyAccessorElementImpl_ImplicitGetter(constantField); constantName.staticElement = constantField; } enumElement.fields = fields; enumElement.createToStringMethodElement(); _currentHolder.addEnum(enumElement); enumName.staticElement = enumElement; super.visitEnumDeclaration(node); } @override void visitExportDirective(ExportDirective node) { List<ElementAnnotation> annotations = _createElementAnnotations(node.metadata); _unitElement.setAnnotations(node.offset, annotations); super.visitExportDirective(node); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) {} @override void visitFunctionDeclaration(FunctionDeclaration node) { FunctionExpressionImpl expression = node.functionExpression; if (expression != null) { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); FunctionBody body = expression.body; Token property = node.propertyKeyword; if (property == null) { SimpleIdentifier functionName = node.name; FunctionElementImpl element = new FunctionElementImpl.forNode(functionName); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(element, node); if (node.externalKeyword != null || body is NativeFunctionBody) { element.external = true; } element.encloseElements(holder.functions); element.encloseElements(holder.labels); element.encloseElements(holder.localVariables); element.parameters = holder.parameters; element.typeParameters = holder.typeParameters; if (body.isAsynchronous) { element.asynchronous = true; } if (body.isGenerator) { element.generator = true; } if (node.returnType == null) { element.hasImplicitReturnType = true; } _currentHolder.addFunction(element); expression.declaredElement = element; functionName.staticElement = element; } else { SimpleIdentifier propertyNameNode = node.name; if (propertyNameNode == null) { // TODO(brianwilkerson) Report this internal error. return; } String propertyName = propertyNameNode.name; TopLevelVariableElementImpl variable = _currentHolder .getTopLevelVariable(propertyName) as TopLevelVariableElementImpl; if (variable == null) { variable = new TopLevelVariableElementImpl(node.name.name, -1); variable.isFinal = true; variable.isSynthetic = true; _currentHolder.addTopLevelVariable(variable); } if (node.isGetter) { PropertyAccessorElementImpl getter = new PropertyAccessorElementImpl.forNode(propertyNameNode); _setCodeRange(getter, node); getter.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(getter, node); if (node.externalKeyword != null || body is NativeFunctionBody) { getter.external = true; } getter.encloseElements(holder.functions); getter.encloseElements(holder.labels); getter.encloseElements(holder.localVariables); if (body.isAsynchronous) { getter.asynchronous = true; } if (body.isGenerator) { getter.generator = true; } getter.variable = variable; getter.getter = true; getter.isStatic = true; variable.getter = getter; if (node.returnType == null) { getter.hasImplicitReturnType = true; } _currentHolder.addAccessor(getter); expression.declaredElement = getter; propertyNameNode.staticElement = getter; } else { PropertyAccessorElementImpl setter = new PropertyAccessorElementImpl.forNode(propertyNameNode); _setCodeRange(setter, node); setter.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(setter, node); if (node.externalKeyword != null || body is NativeFunctionBody) { setter.external = true; } setter.encloseElements(holder.functions); setter.encloseElements(holder.labels); setter.encloseElements(holder.localVariables); setter.parameters = holder.parameters; if (body.isAsynchronous) { setter.asynchronous = true; } if (body.isGenerator) { setter.generator = true; } setter.variable = variable; setter.setter = true; setter.isStatic = true; if (node.returnType == null) { setter.hasImplicitReturnType = true; } variable.setter = setter; variable.isFinal = false; _currentHolder.addAccessor(setter); expression.declaredElement = setter; propertyNameNode.staticElement = setter; } } holder.validate(); } } @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is FunctionDeclaration) { // visitFunctionDeclaration has already created the element for the // declaration. We just need to visit children. super.visitFunctionExpression(node); return; } ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); FunctionBody body = node.body; FunctionElementImpl element = new FunctionElementImpl.forOffset(node.beginToken.offset); _setCodeRange(element, node); element.encloseElements(holder.functions); element.encloseElements(holder.labels); element.encloseElements(holder.localVariables); element.parameters = holder.parameters; element.typeParameters = holder.typeParameters; if (body.isAsynchronous) { element.asynchronous = true; } if (body.isGenerator) { element.generator = true; } element.type = new FunctionTypeImpl(element); element.hasImplicitReturnType = true; _currentHolder.addFunction(element); (node as FunctionExpressionImpl).declaredElement = element; holder.validate(); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); SimpleIdentifier aliasName = node.name; List<ParameterElement> parameters = holder.parameters; List<TypeParameterElement> typeParameters = holder.typeParameters; GenericTypeAliasElementImpl element = new GenericTypeAliasElementImpl.forNode(aliasName); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(element, node); element.function = new GenericFunctionTypeElementImpl.forOffset(-1) ..parameters = parameters; element.typeParameters = typeParameters; _createTypeParameterTypes(typeParameters); _currentHolder.addTypeAlias(element); aliasName.staticElement = element; holder.validate(); } @override void visitGenericTypeAlias(GenericTypeAlias node) { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); SimpleIdentifier aliasName = node.name; List<TypeParameterElement> typeParameters = holder.typeParameters; GenericTypeAliasElementImpl element = new GenericTypeAliasElementImpl.forNode(aliasName); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(element, node); element.typeParameters = typeParameters; _createTypeParameterTypes(typeParameters); element.function = node.functionType?.type?.element; _currentHolder.addTypeAlias(element); aliasName.staticElement = element; holder.validate(); } @override void visitImportDirective(ImportDirective node) { List<ElementAnnotation> annotations = _createElementAnnotations(node.metadata); _unitElement.setAnnotations(node.offset, annotations); super.visitImportDirective(node); } @override void visitLibraryDirective(LibraryDirective node) { List<ElementAnnotation> annotations = _createElementAnnotations(node.metadata); _unitElement.setAnnotations(node.offset, annotations); super.visitLibraryDirective(node); } @override void visitMethodDeclaration(MethodDeclaration node) { try { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); bool isStatic = node.isStatic; Token property = node.propertyKeyword; FunctionBody body = node.body; if (property == null) { SimpleIdentifier methodName = node.name; String nameOfMethod = methodName.name; if (nameOfMethod == TokenType.MINUS.lexeme && node.parameters.parameters.isEmpty) { nameOfMethod = "unary-"; } MethodElementImpl element = new MethodElementImpl(nameOfMethod, methodName.offset); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(element, node); element.isAbstract = node.isAbstract; if (node.externalKeyword != null || body is NativeFunctionBody) { element.external = true; } element.encloseElements(holder.functions); element.encloseElements(holder.labels); element.encloseElements(holder.localVariables); element.parameters = holder.parameters; element.isStatic = isStatic; element.typeParameters = holder.typeParameters; if (body.isAsynchronous) { element.asynchronous = true; } if (body.isGenerator) { element.generator = true; } if (node.returnType == null) { element.hasImplicitReturnType = true; } _currentHolder.addMethod(element); methodName.staticElement = element; } else { SimpleIdentifier propertyNameNode = node.name; String propertyName = propertyNameNode.name; FieldElementImpl field = _currentHolder.getField(propertyName, synthetic: true) as FieldElementImpl; if (field == null) { field = new FieldElementImpl(node.name.name, -1); field.isFinal = true; field.isStatic = isStatic; field.isSynthetic = true; _currentHolder.addField(field); } if (node.isGetter) { PropertyAccessorElementImpl getter = new PropertyAccessorElementImpl.forNode(propertyNameNode); _setCodeRange(getter, node); getter.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(getter, node); if (node.externalKeyword != null || body is NativeFunctionBody) { getter.external = true; } getter.encloseElements(holder.functions); getter.encloseElements(holder.labels); getter.encloseElements(holder.localVariables); if (body.isAsynchronous) { getter.asynchronous = true; } if (body.isGenerator) { getter.generator = true; } getter.variable = field; getter.isAbstract = node.isAbstract; getter.getter = true; getter.isStatic = isStatic; field.getter = getter; if (node.returnType == null) { getter.hasImplicitReturnType = true; } _currentHolder.addAccessor(getter); propertyNameNode.staticElement = getter; } else { PropertyAccessorElementImpl setter = new PropertyAccessorElementImpl.forNode(propertyNameNode); _setCodeRange(setter, node); setter.metadata = _createElementAnnotations(node.metadata); setElementDocumentationComment(setter, node); if (node.externalKeyword != null || body is NativeFunctionBody) { setter.external = true; } setter.encloseElements(holder.functions); setter.encloseElements(holder.labels); setter.encloseElements(holder.localVariables); setter.parameters = holder.parameters; if (body.isAsynchronous) { setter.asynchronous = true; } if (body.isGenerator) { setter.generator = true; } setter.variable = field; setter.isAbstract = node.isAbstract; setter.setter = true; setter.isStatic = isStatic; if (node.returnType == null) { setter.hasImplicitReturnType = true; } field.setter = setter; field.isFinal = false; _currentHolder.addAccessor(setter); propertyNameNode.staticElement = setter; } } holder.validate(); } catch (exception, stackTrace) { if (node.name.staticElement == null) { ClassDeclaration classNode = node.thisOrAncestorOfType<ClassDeclaration>(); StringBuffer buffer = new StringBuffer(); buffer.write("The element for the method "); buffer.write(node.name); buffer.write(" in "); buffer.write(classNode.name); buffer.write(" was not set while trying to build the element model."); AnalysisEngine.instance.logger.logError( buffer.toString(), new CaughtException(exception, stackTrace)); } else { String message = "Exception caught in ElementBuilder.visitMethodDeclaration()"; AnalysisEngine.instance.logger .logError(message, new CaughtException(exception, stackTrace)); } } finally { if (node.name.staticElement == null) { ClassDeclaration classNode = node.thisOrAncestorOfType<ClassDeclaration>(); StringBuffer buffer = new StringBuffer(); buffer.write("The element for the method "); buffer.write(node.name); buffer.write(" in "); buffer.write(classNode.name); buffer.write(" was not set while trying to resolve types."); AnalysisEngine.instance.logger.logError( buffer.toString(), new CaughtException( new AnalysisException(buffer.toString()), null)); } } } @override void visitMixinDeclaration(MixinDeclaration node) { ElementHolder holder = _buildClassMembers(node); SimpleIdentifier nameNode = node.name; MixinElementImpl element = new MixinElementImpl.forNode(nameNode); nameNode.staticElement = element; _fillClassElement(node, element, holder); _currentHolder.addMixin(element); } @override void visitPartDirective(PartDirective node) { List<ElementAnnotation> annotations = _createElementAnnotations(node.metadata); _unitElement.setAnnotations(node.offset, annotations); super.visitPartDirective(node); } @override void visitVariableDeclaration(VariableDeclaration node) { bool isConst = node.isConst; bool isFinal = node.isFinal; Expression initializerNode = node.initializer; bool hasInitializer = initializerNode != null; VariableDeclarationList varList = node.parent; FieldDeclaration fieldNode = varList.parent is FieldDeclaration ? varList.parent : null; VariableElementImpl element; if (fieldNode != null) { SimpleIdentifier fieldName = node.name; FieldElementImpl field; if ((isConst || isFinal && !fieldNode.isStatic && _enclosingClassHasConstConstructor) && hasInitializer) { field = new ConstFieldElementImpl.forNode(fieldName); } else { field = new FieldElementImpl.forNode(fieldName); } element = field; field.isCovariant = fieldNode.covariantKeyword != null; field.isStatic = fieldNode.isStatic; _setCodeRange(element, node); setElementDocumentationComment(element, fieldNode); field.hasImplicitType = varList.type == null; _currentHolder.addField(field); fieldName.staticElement = field; } else { SimpleIdentifier variableName = node.name; TopLevelVariableElementImpl variable; if (isConst && hasInitializer) { variable = new ConstTopLevelVariableElementImpl.forNode(variableName); } else { variable = new TopLevelVariableElementImpl.forNode(variableName); } element = variable; _setCodeRange(element, node); if (varList.parent is TopLevelVariableDeclaration) { setElementDocumentationComment(element, varList.parent); } variable.hasImplicitType = varList.type == null; _currentHolder.addTopLevelVariable(variable); variableName.staticElement = element; } element.isConst = isConst; element.isFinal = isFinal; if (element is PropertyInducingElementImpl) { PropertyAccessorElementImpl_ImplicitGetter getter = new PropertyAccessorElementImpl_ImplicitGetter(element); _currentHolder.addAccessor(getter); if (!isConst && !isFinal) { PropertyAccessorElementImpl_ImplicitSetter setter = new PropertyAccessorElementImpl_ImplicitSetter(element); if (fieldNode != null) { (setter.parameters[0] as ParameterElementImpl).isExplicitlyCovariant = fieldNode.covariantKeyword != null; } _currentHolder.addAccessor(setter); } } } @override void visitVariableDeclarationList(VariableDeclarationList node) { super.visitVariableDeclarationList(node); AstNode parent = node.parent; List<ElementAnnotation> elementAnnotations; if (parent is FieldDeclaration) { elementAnnotations = _createElementAnnotations(parent.metadata); } else if (parent is TopLevelVariableDeclaration) { elementAnnotations = _createElementAnnotations(parent.metadata); } else { // Local variable declaration elementAnnotations = _createElementAnnotations(node.metadata); } _setVariableDeclarationListAnnotations(node, elementAnnotations); _setVariableDeclarationListCodeRanges(node); } ElementHolder _buildClassMembers(AstNode classNode) { ElementHolder holder = new ElementHolder(); // // Process field declarations before constructors and methods so that field // formal parameters can be correctly resolved to their fields. // ElementHolder previousHolder = _currentHolder; _currentHolder = holder; try { List<ClassMember> nonFields = new List<ClassMember>(); classNode.visitChildren( new _ClassNotExecutableElementsBuilder(this, nonFields)); _buildFieldMap(holder.fieldsWithoutFlushing); int count = nonFields.length; for (int i = 0; i < count; i++) { nonFields[i].accept(this); } } finally { _currentHolder = previousHolder; _fieldMap = null; } return holder; } /** * Build the table mapping field names to field elements for the [fields] * defined in the current class. */ void _buildFieldMap(List<FieldElement> fields) { _fieldMap = new HashMap<String, FieldElement>(); int count = fields.length; for (int i = 0; i < count; i++) { FieldElement field = fields[i]; _fieldMap[field.name] ??= field; } } /** * Creates the [ConstructorElement]s array with the single default constructor element. * * @param interfaceType the interface type for which to create a default constructor * @return the [ConstructorElement]s array with the single default constructor element */ List<ConstructorElement> _createDefaultConstructors( ClassElementImpl definingClass) { ConstructorElementImpl constructor = new ConstructorElementImpl.forNode(null); constructor.isSynthetic = true; constructor.enclosingElement = definingClass; return <ConstructorElement>[constructor]; } /** * Create the types associated with the given type parameters, setting the type of each type * parameter, and return an array of types corresponding to the given parameters. * * @param typeParameters the type parameters for which types are to be created * @return an array of types corresponding to the given parameters */ List<DartType> _createTypeParameterTypes( List<TypeParameterElement> typeParameters) { int typeParameterCount = typeParameters.length; List<DartType> typeArguments = new List<DartType>(typeParameterCount); for (int i = 0; i < typeParameterCount; i++) { TypeParameterElementImpl typeParameter = typeParameters[i] as TypeParameterElementImpl; typeArguments[i] = TypeParameterTypeImpl(typeParameter); } return typeArguments; } void _fillClassElement( AnnotatedNode node, ClassElementImpl element, ElementHolder holder) { _setCodeRange(element, node); setElementDocumentationComment(element, node); element.metadata = _createElementAnnotations(node.metadata); element.accessors = holder.accessors; List<ConstructorElement> constructors = holder.constructors; if (constructors.isEmpty) { constructors = _createDefaultConstructors(element); } element.constructors = constructors; element.fields = holder.fields; element.methods = holder.methods; element.typeParameters = holder.typeParameters; holder.validate(); } @override void _setFieldParameterField( FormalParameter node, FieldFormalParameterElementImpl element) { if (node.parent?.parent is ConstructorDeclaration) { FieldElement field = _fieldMap == null ? null : _fieldMap[element.name]; if (field != null) { element.field = field; } } } } /** * A `CompilationUnitBuilder` builds an element model for a single compilation * unit. */ class CompilationUnitBuilder { /** * Build the compilation unit element for the given [source] based on the * compilation [unit] associated with the source. Throw an AnalysisException * if the element could not be built. [librarySource] is the source for the * containing library. */ CompilationUnitElementImpl buildCompilationUnit( Source source, CompilationUnit unit, Source librarySource) { return PerformanceStatistics.resolve.makeCurrentWhile(() { if (unit == null) { return null; } ElementHolder holder = new ElementHolder(); CompilationUnitElementImpl element = new CompilationUnitElementImpl(); ElementBuilder builder = new ElementBuilder(holder, element); unit.accept(builder); element.accessors = holder.accessors; element.enums = holder.enums; element.functions = holder.functions; element.source = source; element.librarySource = librarySource; element.mixins = holder.mixins; element.typeAliases = holder.typeAliases; element.types = holder.types; element.topLevelVariables = holder.topLevelVariables; unit.element = element; holder.validate(); return element; }); } } /** * Instances of the class `DirectiveElementBuilder` build elements for top * level library directives. */ class DirectiveElementBuilder extends SimpleAstVisitor<void> { /** * The analysis context within which directive elements are being built. */ final AnalysisContext context; /** * The library element for which directive elements are being built. */ final LibraryElementImpl libraryElement; /** * Map from sources referenced by this library to their modification times. */ final Map<Source, int> sourceModificationTimeMap; /** * Map from sources imported by this library to their corresponding library * elements. */ final Map<Source, LibraryElement> importLibraryMap; /** * Map from sources imported by this library to their corresponding source * kinds. */ final Map<Source, SourceKind> importSourceKindMap; /** * Map from sources exported by this library to their corresponding library * elements. */ final Map<Source, LibraryElement> exportLibraryMap; /** * Map from sources exported by this library to their corresponding source * kinds. */ final Map<Source, SourceKind> exportSourceKindMap; /** * The [ImportElement]s created so far. */ final List<ImportElement> imports = <ImportElement>[]; /** * The [ExportElement]s created so far. */ final List<ExportElement> exports = <ExportElement>[]; /** * The errors found while building directive elements. */ final List<AnalysisError> errors = <AnalysisError>[]; /** * Map from prefix names to their corresponding elements. */ final HashMap<String, PrefixElementImpl> nameToPrefixMap = new HashMap<String, PrefixElementImpl>(); /** * Indicates whether an explicit import of `dart:core` has been found. */ bool explicitlyImportsCore = false; DirectiveElementBuilder( this.context, this.libraryElement, this.sourceModificationTimeMap, this.importLibraryMap, this.importSourceKindMap, this.exportLibraryMap, this.exportSourceKindMap); @override void visitCompilationUnit(CompilationUnit node) { // // Resolve directives. // for (Directive directive in node.directives) { directive.accept(this); } // // Ensure "dart:core" import. // Source librarySource = libraryElement.source; Source coreLibrarySource = context.sourceFactory.forUri(DartSdk.DART_CORE); if (!explicitlyImportsCore && coreLibrarySource != librarySource) { ImportElementImpl importElement = new ImportElementImpl(-1); importElement.importedLibrary = importLibraryMap[coreLibrarySource]; importElement.isSynthetic = true; imports.add(importElement); } // // Populate the library element. // libraryElement.imports = imports; libraryElement.exports = exports; } @override void visitExportDirective(ExportDirective node) { // Remove previous element. (It will remain null if the target is missing.) node.element = null; Source exportedSource = node.selectedSource; int exportedTime = sourceModificationTimeMap[exportedSource] ?? -1; // The exported source will be null if the URI in the export // directive was invalid. LibraryElement exportedLibrary = exportLibraryMap[exportedSource]; ExportElementImpl exportElement = new ExportElementImpl(node.offset); exportElement.metadata = _getElementAnnotations(node.metadata); StringLiteral uriLiteral = node.uri; if (uriLiteral != null) { exportElement.uriOffset = uriLiteral.offset; exportElement.uriEnd = uriLiteral.end; } exportElement.uri = node.selectedUriContent; exportElement.combinators = _buildCombinators(node); exportElement.exportedLibrary = exportedLibrary; setElementDocumentationComment(exportElement, node); node.element = exportElement; exports.add(exportElement); if (exportedTime >= 0 && exportSourceKindMap[exportedSource] != SourceKind.LIBRARY) { int offset = node.offset; int length = node.length; if (uriLiteral != null) { offset = uriLiteral.offset; length = uriLiteral.length; } errors.add(new AnalysisError(libraryElement.source, offset, length, CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY, [uriLiteral.toSource()])); } } @override void visitImportDirective(ImportDirective node) { // Remove previous element. (It will remain null if the target is missing.) node.element = null; Source importedSource = node.selectedSource; int importedTime = sourceModificationTimeMap[importedSource] ?? -1; // The imported source will be null if the URI in the import // directive was invalid. LibraryElement importedLibrary = importLibraryMap[importedSource]; if (importedLibrary != null && importedLibrary.isDartCore) { explicitlyImportsCore = true; } ImportElementImpl importElement = new ImportElementImpl(node.offset); importElement.metadata = _getElementAnnotations(node.metadata); StringLiteral uriLiteral = node.uri; if (uriLiteral != null) { importElement.uriOffset = uriLiteral.offset; importElement.uriEnd = uriLiteral.end; } importElement.uri = node.selectedUriContent; importElement.deferred = node.deferredKeyword != null; importElement.combinators = _buildCombinators(node); importElement.importedLibrary = importedLibrary; setElementDocumentationComment(importElement, node); SimpleIdentifier prefixNode = node.prefix; if (prefixNode != null) { importElement.prefixOffset = prefixNode.offset; String prefixName = prefixNode.name; PrefixElementImpl prefix = nameToPrefixMap[prefixName]; if (prefix == null) { prefix = new PrefixElementImpl.forNode(prefixNode); nameToPrefixMap[prefixName] = prefix; } importElement.prefix = prefix; prefixNode.staticElement = prefix; } node.element = importElement; imports.add(importElement); if (importedTime >= 0 && importSourceKindMap[importedSource] != SourceKind.LIBRARY) { int offset = node.offset; int length = node.length; if (uriLiteral != null) { offset = uriLiteral.offset; length = uriLiteral.length; } errors.add(new AnalysisError(libraryElement.source, offset, length, CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY, [uriLiteral.toSource()])); } } @override void visitLibraryDirective(LibraryDirective node) { (node.element as LibraryElementImpl)?.metadata = _getElementAnnotations(node.metadata); } @override void visitPartDirective(PartDirective node) { (node.element as CompilationUnitElementImpl)?.metadata = _getElementAnnotations(node.metadata); } /** * Gather a list of the [ElementAnnotation]s referred to by the [Annotation]s * in [metadata]. */ List<ElementAnnotation> _getElementAnnotations( NodeList<Annotation> metadata) { if (metadata.isEmpty) { return const <ElementAnnotation>[]; } return metadata.map((Annotation a) => a.elementAnnotation).toList(); } /** * Build the element model representing the combinators declared by * the given [directive]. */ static List<NamespaceCombinator> _buildCombinators( NamespaceDirective directive) { _NamespaceCombinatorBuilder namespaceCombinatorBuilder = new _NamespaceCombinatorBuilder(); for (Combinator combinator in directive.combinators) { combinator.accept(namespaceCombinatorBuilder); } return namespaceCombinatorBuilder.combinators; } } /** * Instances of the class `ElementBuilder` traverse an AST structure and build the element * model representing the AST structure. */ class ElementBuilder extends ApiElementBuilder { /// List of names of methods, getters, setters, and operators that are /// super-invoked in the current mixin declaration. Set<String> _mixinSuperInvokedNames; /** * Initialize a newly created element builder to build the elements for a * compilation unit. The [initialHolder] is the element holder to which the * children of the visited compilation unit node will be added. */ ElementBuilder(ElementHolder initialHolder, CompilationUnitElement compilationUnitElement) : super(initialHolder, compilationUnitElement); @override void visitBlockFunctionBody(BlockFunctionBody node) { _buildLocal(node); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { super.visitDefaultFormalParameter(node); buildParameterInitializer( node.declaredElement as ParameterElementImpl, node.defaultValue); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { _buildLocal(node); } @override void visitMixinDeclaration(MixinDeclaration node) { _mixinSuperInvokedNames = new Set<String>(); try { super.visitMixinDeclaration(node); } finally { MixinElementImpl element = node.declaredElement; element.superInvokedNames = _mixinSuperInvokedNames.toList(); _mixinSuperInvokedNames = null; } } @override void visitVariableDeclaration(VariableDeclaration node) { super.visitVariableDeclaration(node); VariableElementImpl element = node.declaredElement as VariableElementImpl; buildVariableInitializer(element, node.initializer); } void _buildLocal(FunctionBody body) { body.accept(new LocalElementBuilder(_currentHolder, _unitElement)); // This is not efficient - we visit AST second time. if (_mixinSuperInvokedNames != null) { body.accept(new MixinSuperInvokedNamesCollector(_mixinSuperInvokedNames)); } } } /** * Traverse a [FunctionBody] and build elements for AST structures. */ class LocalElementBuilder extends _BaseElementBuilder { /** * Initialize a newly created element builder to build the elements for a * compilation unit. The [initialHolder] is the element holder to which the * children of the visited compilation unit node will be added. */ LocalElementBuilder(ElementHolder initialHolder, CompilationUnitElementImpl compilationUnitElement) : super(initialHolder, compilationUnitElement); /** * Initialize a newly created element builder as a first step to analyzing a * dangling dart expression. */ LocalElementBuilder.forDanglingExpression() : super(new ElementHolder(), null); /** * Builds the variable elements associated with [node] and stores them in * the element holder. */ void buildCatchVariableElements(CatchClause node) { SimpleIdentifier exceptionParameter = node.exceptionParameter; if (exceptionParameter != null) { // exception LocalVariableElementImpl exception = new LocalVariableElementImpl.forNode(exceptionParameter); if (node.exceptionType == null) { exception.hasImplicitType = true; } exception.setVisibleRange(node.offset, node.length); _currentHolder.addLocalVariable(exception); exceptionParameter.staticElement = exception; // stack trace SimpleIdentifier stackTraceParameter = node.stackTraceParameter; if (stackTraceParameter != null) { LocalVariableElementImpl stackTrace = new LocalVariableElementImpl.forNode(stackTraceParameter); _setCodeRange(stackTrace, stackTraceParameter); stackTrace.setVisibleRange(node.offset, node.length); _currentHolder.addLocalVariable(stackTrace); stackTraceParameter.staticElement = stackTrace; } } } /** * Builds the label elements associated with [labels] and stores them in the * element holder. */ void buildLabelElements( NodeList<Label> labels, bool onSwitchStatement, bool onSwitchMember) { for (Label label in labels) { SimpleIdentifier labelName = label.label; LabelElementImpl element = new LabelElementImpl.forNode( labelName, onSwitchStatement, onSwitchMember); labelName.staticElement = element; _currentHolder.addLabel(element); } } @override void visitCatchClause(CatchClause node) { buildCatchVariableElements(node); super.visitCatchClause(node); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { SimpleIdentifier variableName = node.identifier; LocalVariableElementImpl element = new LocalVariableElementImpl.forNode(variableName); _setCodeRange(element, node); element.metadata = _createElementAnnotations(node.metadata); var parent = node.parent; if (parent is ForEachPartsWithDeclaration) { var statement = parent.parent; element.setVisibleRange(statement.offset, statement.length); } element.isConst = node.isConst; element.isFinal = node.isFinal; if (node.type == null) { element.hasImplicitType = true; } else { // Note: this is a noop most of the time, however, not for // [GenericFunctionType] and perhaps others in the future. node.type.accept(this); } _currentHolder.addLocalVariable(element); variableName.staticElement = element; } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { super.visitDefaultFormalParameter(node); buildParameterInitializer( node.declaredElement as ParameterElementImpl, node.defaultValue); } @override void visitFunctionDeclaration(FunctionDeclaration node) { FunctionExpressionImpl expression = node.functionExpression; if (expression == null) { return; } ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); FunctionElementImpl element = new FunctionElementImpl.forNode(node.name); element.type = new FunctionTypeImpl(element); _setCodeRange(element, node); setElementDocumentationComment(element, node); element.metadata = _createElementAnnotations(node.metadata); FunctionBody body = expression.body; if (node.externalKeyword != null || body is NativeFunctionBody) { element.external = true; } element.encloseElements(holder.functions); element.encloseElements(holder.labels); element.encloseElements(holder.localVariables); element.parameters = holder.parameters; element.typeParameters = holder.typeParameters; if (body.isAsynchronous) { element.asynchronous = body.isAsynchronous; } if (body.isGenerator) { element.generator = true; } { Block enclosingBlock = node.thisOrAncestorOfType<Block>(); if (enclosingBlock != null) { element.setVisibleRange(enclosingBlock.offset, enclosingBlock.length); } } if (node.returnType == null) { element.hasImplicitReturnType = true; } _currentHolder.addFunction(element); expression.declaredElement = element; node.name.staticElement = element; holder.validate(); } @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is FunctionDeclaration) { // visitFunctionDeclaration has already created the element for the // declaration. We just need to visit children. super.visitFunctionExpression(node); return; } ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); FunctionElementImpl element = new FunctionElementImpl.forOffset(node.beginToken.offset); _setCodeRange(element, node); element.encloseElements(holder.functions); element.encloseElements(holder.labels); element.encloseElements(holder.localVariables); element.parameters = holder.parameters; element.typeParameters = holder.typeParameters; FunctionBody body = node.body; if (body.isAsynchronous) { element.asynchronous = true; } if (body.isGenerator) { element.generator = true; } Block enclosingBlock = node.thisOrAncestorOfType<Block>(); if (enclosingBlock != null) { element.setVisibleRange(enclosingBlock.offset, enclosingBlock.length); } element.type = new FunctionTypeImpl(element); element.hasImplicitReturnType = true; _currentHolder.addFunction(element); (node as FunctionExpressionImpl).declaredElement = element; holder.validate(); } @override void visitLabeledStatement(LabeledStatement node) { bool onSwitchStatement = node.statement is SwitchStatement; buildLabelElements(node.labels, onSwitchStatement, false); super.visitLabeledStatement(node); } @override void visitSwitchCase(SwitchCase node) { buildLabelElements(node.labels, false, true); super.visitSwitchCase(node); } @override void visitSwitchDefault(SwitchDefault node) { buildLabelElements(node.labels, false, true); super.visitSwitchDefault(node); } @override void visitVariableDeclaration(VariableDeclaration node) { bool isConst = node.isConst; bool isFinal = node.isFinal; Expression initializerNode = node.initializer; VariableDeclarationList varList = node.parent; SimpleIdentifier variableName = node.name; LocalVariableElementImpl element; if (isConst && initializerNode != null) { element = new ConstLocalVariableElementImpl.forNode(variableName); } else { element = new LocalVariableElementImpl.forNode(variableName); } _setCodeRange(element, node); _setVariableVisibleRange(element, node); element.hasImplicitType = varList.type == null; _currentHolder.addLocalVariable(element); variableName.staticElement = element; element.isConst = isConst; element.isFinal = isFinal; element.isLate = node.isLate; buildVariableInitializer(element, initializerNode); } @override void visitVariableDeclarationList(VariableDeclarationList node) { super.visitVariableDeclarationList(node); List<ElementAnnotation> elementAnnotations = _createElementAnnotations(node.metadata); _setVariableDeclarationListAnnotations(node, elementAnnotations); _setVariableDeclarationListCodeRanges(node); } void _setVariableVisibleRange( LocalVariableElementImpl element, VariableDeclaration node) { AstNode scopeNode; AstNode parent2 = node.parent.parent; if (parent2 is ForPartsWithDeclarations) { scopeNode = parent2.parent; } else { scopeNode = node.thisOrAncestorOfType<Block>(); } element.setVisibleRange(scopeNode.offset, scopeNode.length); } } /** * Base class for API and local element builders. */ abstract class _BaseElementBuilder extends RecursiveAstVisitor<void> { /** * The compilation unit element into which the elements being built will be * stored. */ final CompilationUnitElementImpl _unitElement; /** * The element holder associated with the element that is currently being built. */ ElementHolder _currentHolder; _BaseElementBuilder(this._currentHolder, this._unitElement); /** * If the [defaultValue] is not `null`, build the [FunctionElementImpl] * that corresponds it, and set it as the initializer for the [parameter]. */ void buildParameterInitializer( ParameterElementImpl parameter, Expression defaultValue) { if (defaultValue != null) { ElementHolder holder = new ElementHolder(); _visit(holder, defaultValue); FunctionElementImpl initializer = new FunctionElementImpl.forOffset(defaultValue.beginToken.offset); initializer.hasImplicitReturnType = true; initializer.encloseElements(holder.functions); initializer.encloseElements(holder.labels); initializer.encloseElements(holder.localVariables); initializer.parameters = holder.parameters; initializer.isSynthetic = true; initializer.type = new FunctionTypeImpl(initializer); parameter.initializer = initializer; parameter.defaultValueCode = defaultValue.toSource(); holder.validate(); } } /** * If the [initializer] is not `null`, build the [FunctionElementImpl] that * corresponds it, and set it as the initializer for the [variable]. */ void buildVariableInitializer( VariableElementImpl variable, Expression initializer) { if (initializer != null) { ElementHolder holder = new ElementHolder(); _visit(holder, initializer); FunctionElementImpl initializerElement = new FunctionElementImpl.forOffset(initializer.beginToken.offset); initializerElement.hasImplicitReturnType = true; initializerElement.encloseElements(holder.functions); initializerElement.encloseElements(holder.labels); initializerElement.encloseElements(holder.localVariables); initializerElement.isSynthetic = true; initializerElement.type = new FunctionTypeImpl(initializerElement); variable.initializer = initializerElement; holder.validate(); } } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { NormalFormalParameter normalParameter = node.parameter; SimpleIdentifier parameterName = normalParameter.identifier; ParameterElementImpl parameter; if (normalParameter is FieldFormalParameter) { DefaultFieldFormalParameterElementImpl fieldParameter = new DefaultFieldFormalParameterElementImpl.forNode(parameterName); _setFieldParameterField(node, fieldParameter); parameter = fieldParameter; } else { parameter = new DefaultParameterElementImpl.forNode(parameterName); } _setCodeRange(parameter, node); parameter.isConst = node.isConst; parameter.isExplicitlyCovariant = node.parameter.covariantKeyword != null; parameter.isFinal = node.isFinal; // ignore: deprecated_member_use_from_same_package parameter.parameterKind = node.kind; // visible range _setParameterVisibleRange(node, parameter); if (normalParameter is SimpleFormalParameter && normalParameter.type == null) { parameter.hasImplicitType = true; } _currentHolder.addParameter(parameter); if (normalParameter is SimpleFormalParameterImpl) { normalParameter.declaredElement = parameter; } parameterName?.staticElement = parameter; normalParameter.accept(this); } @override void visitFieldFormalParameter(FieldFormalParameter node) { if (node.parent is! DefaultFormalParameter) { SimpleIdentifier parameterName = node.identifier; FieldFormalParameterElementImpl parameter = new FieldFormalParameterElementImpl.forNode(parameterName); _setCodeRange(parameter, node); _setFieldParameterField(node, parameter); parameter.isConst = node.isConst; parameter.isExplicitlyCovariant = node.covariantKeyword != null; parameter.isFinal = node.isFinal; // ignore: deprecated_member_use_from_same_package parameter.parameterKind = node.kind; _currentHolder.addParameter(parameter); parameterName.staticElement = parameter; } // // The children of this parameter include any parameters defined on the type // of this parameter. // ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); ParameterElementImpl element = node.declaredElement; element.metadata = _createElementAnnotations(node.metadata); if (node.parameters != null) { _createGenericFunctionType(element, holder); } holder.validate(); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { if (node.parent is! DefaultFormalParameter) { SimpleIdentifier parameterName = node.identifier; ParameterElementImpl parameter = new ParameterElementImpl.forNode(parameterName); _setCodeRange(parameter, node); parameter.isConst = node.isConst; parameter.isExplicitlyCovariant = node.covariantKeyword != null; parameter.isFinal = node.isFinal; // ignore: deprecated_member_use_from_same_package parameter.parameterKind = node.kind; _setParameterVisibleRange(node, parameter); _currentHolder.addParameter(parameter); parameterName.staticElement = parameter; } // // The children of this parameter include any parameters defined on the type //of this parameter. // ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); ParameterElementImpl element = node.declaredElement; element.metadata = _createElementAnnotations(node.metadata); _createGenericFunctionType(element, holder); holder.validate(); } @override void visitGenericFunctionType(GenericFunctionType node) { ElementHolder holder = new ElementHolder(); _visitChildren(holder, node); GenericFunctionTypeElementImpl element = new GenericFunctionTypeElementImpl.forOffset(node.beginToken.offset); _setCodeRange(element, node); element.parameters = holder.parameters; element.typeParameters = holder.typeParameters; FunctionType type = new FunctionTypeImpl(element); element.type = type; (node as GenericFunctionTypeImpl).type = type; (node as GenericFunctionTypeImpl).declaredElement = element; holder.validate(); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { ParameterElementImpl parameter; if (node.parent is! DefaultFormalParameter) { SimpleIdentifier parameterName = node.identifier; parameter = new ParameterElementImpl.forNode(parameterName); _setCodeRange(parameter, node); parameter.isConst = node.isConst; parameter.isExplicitlyCovariant = node.covariantKeyword != null; parameter.isFinal = node.isFinal; // ignore: deprecated_member_use_from_same_package parameter.parameterKind = node.kind; _setParameterVisibleRange(node, parameter); if (node.type == null) { parameter.hasImplicitType = true; } _currentHolder.addParameter(parameter); (node as SimpleFormalParameterImpl).declaredElement = parameter; parameterName?.staticElement = parameter; } super.visitSimpleFormalParameter(node); parameter ??= node.declaredElement; parameter?.metadata = _createElementAnnotations(node.metadata); } @override void visitTypeParameter(TypeParameter node) { SimpleIdentifier parameterName = node.name; TypeParameterElementImpl typeParameter = new TypeParameterElementImpl.forNode(parameterName); _setCodeRange(typeParameter, node); typeParameter.metadata = _createElementAnnotations(node.metadata); _currentHolder.addTypeParameter(typeParameter); parameterName.staticElement = typeParameter; super.visitTypeParameter(node); } /** * For each [Annotation] found in [annotations], create a new * [ElementAnnotation] object and set the [Annotation] to point to it. */ List<ElementAnnotation> _createElementAnnotations( NodeList<Annotation> annotations) { if (annotations.isEmpty) { return const <ElementAnnotation>[]; } return annotations.map((Annotation a) { ElementAnnotationImpl elementAnnotation = new ElementAnnotationImpl(_unitElement); a.elementAnnotation = elementAnnotation; return elementAnnotation; }).toList(); } /** * If the [holder] has type parameters or formal parameters for the * given [parameter], wrap them into a new [GenericFunctionTypeElementImpl] * and set [FunctionTypeImpl] for the [parameter]. */ void _createGenericFunctionType( ParameterElementImpl parameter, ElementHolder holder) { var typeElement = new GenericFunctionTypeElementImpl.forOffset(-1); typeElement.enclosingElement = parameter; typeElement.typeParameters = holder.typeParameters; typeElement.parameters = holder.parameters; var type = new FunctionTypeImpl(typeElement); typeElement.type = type; parameter.type = type; } /** * Return the body of the function that contains the given [parameter], or * `null` if no function body could be found. */ FunctionBody _getFunctionBody(FormalParameter parameter) { AstNode parent = parameter?.parent?.parent; if (parent is ConstructorDeclaration) { return parent.body; } else if (parent is FunctionExpression) { return parent.body; } else if (parent is MethodDeclaration) { return parent.body; } return null; } void _setCodeRange(ElementImpl element, AstNode node) { element.setCodeRange(node.offset, node.length); } void _setFieldParameterField( FormalParameter node, FieldFormalParameterElementImpl element) {} /** * Sets the visible source range for formal parameter. */ void _setParameterVisibleRange( FormalParameter node, ParameterElementImpl element) { FunctionBody body = _getFunctionBody(node); if (body is BlockFunctionBody || body is ExpressionFunctionBody) { element.setVisibleRange(body.offset, body.length); } } void _setVariableDeclarationListAnnotations(VariableDeclarationList node, List<ElementAnnotation> elementAnnotations) { for (VariableDeclaration variableDeclaration in node.variables) { ElementImpl element = variableDeclaration.declaredElement as ElementImpl; element.metadata = elementAnnotations; } } void _setVariableDeclarationListCodeRanges(VariableDeclarationList node) { List<VariableDeclaration> variables = node.variables; for (var i = 0; i < variables.length; i++) { var variable = variables[i]; var offset = (i == 0 ? node.parent : variable).offset; var length = variable.end - offset; var element = variable.declaredElement as ElementImpl; element.setCodeRange(offset, length); } } /** * Make the given holder be the current holder while visiting the given node. * * @param holder the holder that will gather elements that are built while visiting the children * @param node the node to be visited */ void _visit(ElementHolder holder, AstNode node) { if (node != null) { ElementHolder previousHolder = _currentHolder; _currentHolder = holder; try { node.accept(this); } finally { _currentHolder = previousHolder; } } } /** * Make the given holder be the current holder while visiting the children of the given node. * * @param holder the holder that will gather elements that are built while visiting the children * @param node the node whose children are to be visited */ void _visitChildren(ElementHolder holder, AstNode node) { if (node != null) { ElementHolder previousHolder = _currentHolder; _currentHolder = holder; try { node.visitChildren(this); } finally { _currentHolder = previousHolder; } } } } /** * Builds elements for all node that are not constructors or methods. */ class _ClassNotExecutableElementsBuilder extends UnifyingAstVisitor<void> { final ApiElementBuilder builder; final List<ClassMember> nonFields; _ClassNotExecutableElementsBuilder(this.builder, this.nonFields); @override void visitConstructorDeclaration(ConstructorDeclaration node) { nonFields.add(node); } @override void visitMethodDeclaration(MethodDeclaration node) { nonFields.add(node); } @override void visitNode(AstNode node) => node.accept(builder); } /** * Instances of the class [_NamespaceCombinatorBuilder] can be used to visit * [Combinator] AST nodes and generate [NamespaceCombinator] elements. */ class _NamespaceCombinatorBuilder extends SimpleAstVisitor<void> { /** * Elements generated so far. */ final List<NamespaceCombinator> combinators = <NamespaceCombinator>[]; @override void visitHideCombinator(HideCombinator node) { HideElementCombinatorImpl hide = new HideElementCombinatorImpl(); hide.hiddenNames = _getIdentifiers(node.hiddenNames); combinators.add(hide); } @override void visitShowCombinator(ShowCombinator node) { ShowElementCombinatorImpl show = new ShowElementCombinatorImpl(); show.offset = node.offset; show.end = node.end; show.shownNames = _getIdentifiers(node.shownNames); combinators.add(show); } /** * Return the lexical identifiers associated with the given [identifiers]. */ static List<String> _getIdentifiers(NodeList<SimpleIdentifier> identifiers) { return identifiers.map((identifier) => identifier.name).toList(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/error/syntactic_errors.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. /** * The errors produced during syntactic analysis (scanning and parsing). */ import 'package:analyzer/error/error.dart'; export 'package:front_end/src/scanner/errors.dart' show ScannerErrorCode; part 'syntactic_errors.g.dart'; /** * The error codes used for errors detected by the parser. 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 ParserErrorCode extends ErrorCode { static const ParserErrorCode ABSTRACT_CLASS_MEMBER = _ABSTRACT_CLASS_MEMBER; static const ParserErrorCode ABSTRACT_ENUM = const ParserErrorCode( 'ABSTRACT_ENUM', "Enums can't be declared to be 'abstract'.", correction: "Try removing the keyword 'abstract'."); static const ParserErrorCode ABSTRACT_STATIC_METHOD = const ParserErrorCode( 'ABSTRACT_STATIC_METHOD', "Static methods can't be declared to be 'abstract'.", correction: "Try removing the keyword 'abstract'."); static const ParserErrorCode ABSTRACT_TOP_LEVEL_FUNCTION = const ParserErrorCode('ABSTRACT_TOP_LEVEL_FUNCTION', "Top-level functions can't be declared to be 'abstract'.", correction: "Try removing the keyword 'abstract'."); static const ParserErrorCode ABSTRACT_TOP_LEVEL_VARIABLE = const ParserErrorCode('ABSTRACT_TOP_LEVEL_VARIABLE', "Top-level variables can't be declared to be 'abstract'.", correction: "Try removing the keyword 'abstract'."); static const ParserErrorCode ABSTRACT_TYPEDEF = const ParserErrorCode( 'ABSTRACT_TYPEDEF', "Typedefs can't be declared to be 'abstract'.", correction: "Try removing the keyword 'abstract'."); static const ParserErrorCode ANNOTATION_WITH_TYPE_ARGUMENTS = _ANNOTATION_WITH_TYPE_ARGUMENTS; /** * 16.32 Identifier Reference: It is a compile-time error if any of the * identifiers async, await, or yield is used as an identifier in a function * body marked with either async, async*, or sync*. */ static const ParserErrorCode ASYNC_KEYWORD_USED_AS_IDENTIFIER = const ParserErrorCode( 'ASYNC_KEYWORD_USED_AS_IDENTIFIER', "The keywords 'await' and 'yield' can't be used as " "identifiers in an asynchronous or generator function."); static const ParserErrorCode BREAK_OUTSIDE_OF_LOOP = _BREAK_OUTSIDE_OF_LOOP; static const ParserErrorCode CATCH_SYNTAX = _CATCH_SYNTAX; static const ParserErrorCode CATCH_SYNTAX_EXTRA_PARAMETERS = _CATCH_SYNTAX_EXTRA_PARAMETERS; static const ParserErrorCode CLASS_IN_CLASS = _CLASS_IN_CLASS; static const ParserErrorCode COLON_IN_PLACE_OF_IN = _COLON_IN_PLACE_OF_IN; static const ParserErrorCode CONFLICTING_MODIFIERS = _CONFLICTING_MODIFIERS; // TODO(danrubel): Remove this unused error code static const ParserErrorCode CONST_AFTER_FACTORY = _MODIFIER_OUT_OF_ORDER; // TODO(danrubel): Remove this unused error code static const ParserErrorCode CONST_AND_COVARIANT = _CONFLICTING_MODIFIERS; static const ParserErrorCode CONST_AND_FINAL = _CONST_AND_FINAL; // TODO(danrubel): Remove this unused error code static const ParserErrorCode CONST_AND_VAR = _CONFLICTING_MODIFIERS; static const ParserErrorCode CONST_CLASS = _CONST_CLASS; static const ParserErrorCode CONST_CONSTRUCTOR_WITH_BODY = const ParserErrorCode('CONST_CONSTRUCTOR_WITH_BODY', "Const constructors can't have a body.", correction: "Try removing either the 'const' keyword or the body."); static const ParserErrorCode CONST_ENUM = const ParserErrorCode( 'CONST_ENUM', "Enums can't be declared to be 'const'.", correction: "Try removing the 'const' keyword."); static const ParserErrorCode CONST_FACTORY = _CONST_FACTORY; static const ParserErrorCode CONST_METHOD = _CONST_METHOD; static const ParserErrorCode CONST_TYPEDEF = const ParserErrorCode( 'CONST_TYPEDEF', "Type aliases can't be declared to be 'const'.", correction: "Try removing the 'const' keyword."); static const ParserErrorCode CONSTRUCTOR_WITH_RETURN_TYPE = _CONSTRUCTOR_WITH_RETURN_TYPE; static const ParserErrorCode CONTINUE_OUTSIDE_OF_LOOP = _CONTINUE_OUTSIDE_OF_LOOP; static const ParserErrorCode CONTINUE_WITHOUT_LABEL_IN_CASE = _CONTINUE_WITHOUT_LABEL_IN_CASE; // TODO(danrubel): Remove this unused error code static const ParserErrorCode COVARIANT_AFTER_FINAL = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode COVARIANT_AFTER_VAR = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode COVARIANT_AND_STATIC = _COVARIANT_AND_STATIC; static const ParserErrorCode COVARIANT_MEMBER = _COVARIANT_MEMBER; static const ParserErrorCode COVARIANT_TOP_LEVEL_DECLARATION = const ParserErrorCode('COVARIANT_TOP_LEVEL_DECLARATION', "Top-level declarations can't be declared to be covariant.", correction: "Try removing the keyword 'covariant'."); static const ParserErrorCode COVARIANT_CONSTRUCTOR = const ParserErrorCode( 'COVARIANT_CONSTRUCTOR', "A constructor can't be declared to be 'covariant'.", correction: "Try removing the keyword 'covariant'."); static const ParserErrorCode DEFERRED_AFTER_PREFIX = _DEFERRED_AFTER_PREFIX; static const ParserErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPE = const ParserErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPE', "Parameters in a function type cannot have default values", correction: "Try removing the default value."); static const ParserErrorCode DIRECTIVE_AFTER_DECLARATION = _DIRECTIVE_AFTER_DECLARATION; /** * Parameters: * 0: the label that was duplicated */ static const ParserErrorCode DUPLICATE_LABEL_IN_SWITCH_STATEMENT = _DUPLICATE_LABEL_IN_SWITCH_STATEMENT; static const ParserErrorCode DUPLICATE_DEFERRED = _DUPLICATE_DEFERRED; /** * Parameters: * 0: the modifier that was duplicated */ static const ParserErrorCode DUPLICATED_MODIFIER = _DUPLICATED_MODIFIER; static const ParserErrorCode DUPLICATE_PREFIX = _DUPLICATE_PREFIX; static const ParserErrorCode EMPTY_ENUM_BODY = const ParserErrorCode( 'EMPTY_ENUM_BODY', "An enum must declare at least one constant name.", correction: "Try declaring a constant."); static const ParserErrorCode ENUM_IN_CLASS = _ENUM_IN_CLASS; static const ParserErrorCode EQUALITY_CANNOT_BE_EQUALITY_OPERAND = _EQUALITY_CANNOT_BE_EQUALITY_OPERAND; static const ParserErrorCode EXPECTED_BODY = _EXPECTED_BODY; static const ParserErrorCode EXPECTED_CASE_OR_DEFAULT = const ParserErrorCode( 'EXPECTED_CASE_OR_DEFAULT', "Expected 'case' or 'default'.", correction: "Try placing this code inside a case clause."); static const ParserErrorCode EXPECTED_CLASS_MEMBER = const ParserErrorCode( 'EXPECTED_CLASS_MEMBER', "Expected a class member.", correction: "Try placing this code inside a class member."); static const ParserErrorCode EXPECTED_ELSE_OR_COMMA = _EXPECTED_ELSE_OR_COMMA; static const ParserErrorCode EXPECTED_EXECUTABLE = const ParserErrorCode( 'EXPECTED_EXECUTABLE', "Expected a method, getter, setter or operator declaration.", correction: "This appears to be incomplete code. Try removing it or completing it."); static const ParserErrorCode EXPECTED_LIST_OR_MAP_LITERAL = const ParserErrorCode( 'EXPECTED_LIST_OR_MAP_LITERAL', "Expected a list or map literal.", correction: "Try inserting a list or map literal, or remove the type arguments."); static const ParserErrorCode EXPECTED_STRING_LITERAL = const ParserErrorCode( 'EXPECTED_STRING_LITERAL', "Expected a string literal."); /** * Parameters: * 0: the token that was expected but not found */ static const ParserErrorCode EXPECTED_TOKEN = const ParserErrorCode('EXPECTED_TOKEN', "Expected to find '{0}'."); static const ParserErrorCode EXPECTED_INSTEAD = _EXPECTED_INSTEAD; static const ParserErrorCode EXPECTED_TYPE_NAME = const ParserErrorCode('EXPECTED_TYPE_NAME', "Expected a type name."); static const ParserErrorCode EXPERIMENT_NOT_ENABLED = _EXPERIMENT_NOT_ENABLED; static const ParserErrorCode EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE = _EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE; /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an abstract declaration is // declared in an extension. Extensions can declare only concrete members. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // int [!a!](); // } // ``` // // #### Common fixes // // Either provide an implementation for the member or remove it. static const ParserErrorCode EXTENSION_DECLARES_ABSTRACT_MEMBER = _EXTENSION_DECLARES_ABSTRACT_MEMBER; /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a constructor declaration is // found in an extension. It isn't valid to define a constructor because // extensions aren't classes, and it isn't possible to create an instance of // an extension. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // [!E!]() : super(); // } // ``` // // #### Common fixes // // Remove the constructor or replace it with a static method. static const ParserErrorCode EXTENSION_DECLARES_CONSTRUCTOR = _EXTENSION_DECLARES_CONSTRUCTOR; /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an instance field declaration is // found in an extension. It isn't valid to define an instance field because // extensions can only add behavior, not state. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // String [!s!]; // } // ``` // // #### Common fixes // // Remove the field, make it a static field, or convert it to be a getter, // setter, or method. static const ParserErrorCode EXTENSION_DECLARES_INSTANCE_FIELD = _EXTENSION_DECLARES_INSTANCE_FIELD; static const ParserErrorCode EXTERNAL_AFTER_CONST = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode EXTERNAL_AFTER_FACTORY = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode EXTERNAL_AFTER_STATIC = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode EXTERNAL_CLASS = _EXTERNAL_CLASS; static const ParserErrorCode EXTERNAL_CONSTRUCTOR_WITH_BODY = _EXTERNAL_CONSTRUCTOR_WITH_BODY; static const ParserErrorCode EXTERNAL_ENUM = _EXTERNAL_ENUM; static const ParserErrorCode EXTERNAL_FACTORY_REDIRECTION = _EXTERNAL_FACTORY_REDIRECTION; static const ParserErrorCode EXTERNAL_FACTORY_WITH_BODY = _EXTERNAL_FACTORY_WITH_BODY; static const ParserErrorCode EXTERNAL_FIELD = _EXTERNAL_FIELD; static const ParserErrorCode EXTERNAL_GETTER_WITH_BODY = const ParserErrorCode( 'EXTERNAL_GETTER_WITH_BODY', "External getters can't have a body.", correction: "Try removing the body of the getter, or " "removing the keyword 'external'."); static const ParserErrorCode EXTERNAL_METHOD_WITH_BODY = _EXTERNAL_METHOD_WITH_BODY; static const ParserErrorCode EXTERNAL_OPERATOR_WITH_BODY = const ParserErrorCode('EXTERNAL_OPERATOR_WITH_BODY', "External operators can't have a body.", correction: "Try removing the body of the operator, or " "removing the keyword 'external'."); static const ParserErrorCode EXTERNAL_SETTER_WITH_BODY = const ParserErrorCode( 'EXTERNAL_SETTER_WITH_BODY', "External setters can't have a body.", correction: "Try removing the body of the setter, or " "removing the keyword 'external'."); static const ParserErrorCode EXTERNAL_TYPEDEF = _EXTERNAL_TYPEDEF; static const ParserErrorCode EXTRANEOUS_MODIFIER = _EXTRANEOUS_MODIFIER; static const ParserErrorCode FACTORY_TOP_LEVEL_DECLARATION = _FACTORY_TOP_LEVEL_DECLARATION; static const ParserErrorCode FACTORY_WITH_INITIALIZERS = const ParserErrorCode( 'FACTORY_WITH_INITIALIZERS', "A 'factory' constructor can't have initializers.", correction: "Try removing the 'factory' keyword to make this a generative constructor, or " "removing the initializers."); static const ParserErrorCode FACTORY_WITHOUT_BODY = const ParserErrorCode( 'FACTORY_WITHOUT_BODY', "A non-redirecting 'factory' constructor must have a body.", correction: "Try adding a body to the constructor."); static const ParserErrorCode FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR = _FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR; static const ParserErrorCode FIELD_INITIALIZED_OUTSIDE_DECLARING_CLASS = _FIELD_INITIALIZED_OUTSIDE_DECLARING_CLASS; static const ParserErrorCode FINAL_AND_COVARIANT = _FINAL_AND_COVARIANT; static const ParserErrorCode FINAL_AND_VAR = _FINAL_AND_VAR; static const ParserErrorCode FINAL_CLASS = const ParserErrorCode( 'FINAL_CLASS', "Classes can't be declared to be 'final'.", correction: "Try removing the keyword 'final'."); static const ParserErrorCode FINAL_CONSTRUCTOR = const ParserErrorCode( 'FINAL_CONSTRUCTOR', "A constructor can't be declared to be 'final'.", correction: "Try removing the keyword 'final'."); static const ParserErrorCode FINAL_ENUM = const ParserErrorCode( 'FINAL_ENUM', "Enums can't be declared to be 'final'.", correction: "Try removing the keyword 'final'."); static const ParserErrorCode FINAL_METHOD = const ParserErrorCode( 'FINAL_METHOD', "Getters, setters and methods can't be declared to be 'final'.", correction: "Try removing the keyword 'final'."); static const ParserErrorCode FINAL_TYPEDEF = const ParserErrorCode( 'FINAL_TYPEDEF', "Typedefs can't be declared to be 'final'.", correction: "Try removing the keyword 'final'."); static const ParserErrorCode FUNCTION_TYPED_PARAMETER_VAR = const ParserErrorCode( 'FUNCTION_TYPED_PARAMETER_VAR', "Function-typed parameters can't specify 'const', 'final' or 'var' in place of a return type.", correction: "Try replacing the keyword with a return type."); static const ParserErrorCode GETTER_IN_FUNCTION = const ParserErrorCode( 'GETTER_IN_FUNCTION', "Getters can't be defined within methods or functions.", correction: "Try moving the getter outside the method or function, or " "converting the getter to a function."); static const ParserErrorCode GETTER_WITH_PARAMETERS = const ParserErrorCode( 'GETTER_WITH_PARAMETERS', "Getters must be declared without a parameter list.", correction: "Try removing the parameter list, or " "removing the keyword 'get' to define a method rather than a getter."); static const ParserErrorCode ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE = _ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE; static const ParserErrorCode IMPLEMENTS_BEFORE_EXTENDS = _IMPLEMENTS_BEFORE_EXTENDS; static const ParserErrorCode IMPLEMENTS_BEFORE_ON = _IMPLEMENTS_BEFORE_ON; static const ParserErrorCode IMPLEMENTS_BEFORE_WITH = _IMPLEMENTS_BEFORE_WITH; static const ParserErrorCode IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE = _IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE; static const ParserErrorCode INITIALIZED_VARIABLE_IN_FOR_EACH = _INITIALIZED_VARIABLE_IN_FOR_EACH; static const ParserErrorCode INVALID_AWAIT_IN_FOR = _INVALID_AWAIT_IN_FOR; /** * Parameters: * 0: the invalid escape sequence */ static const ParserErrorCode INVALID_CODE_POINT = const ParserErrorCode( 'INVALID_CODE_POINT', "The escape sequence '{0}' isn't a valid code point."); static const ParserErrorCode INVALID_COMMENT_REFERENCE = const ParserErrorCode( 'INVALID_COMMENT_REFERENCE', "Comment references should contain a possibly prefixed identifier and " "can start with 'new', but shouldn't contain anything else."); static const ParserErrorCode INVALID_CONSTRUCTOR_NAME = const ParserErrorCode( 'INVALID_CONSTRUCTOR_NAME', "The keyword '{0}' cannot be used to name a constructor.", correction: "Try giving the constructor a different name."); static const ParserErrorCode INVALID_GENERIC_FUNCTION_TYPE = const ParserErrorCode( 'INVALID_GENERIC_FUNCTION_TYPE', "Invalid generic function type.", correction: "Try using a generic function type (returnType 'Function(' parameters ')')."); static const ParserErrorCode INVALID_HEX_ESCAPE = _INVALID_HEX_ESCAPE; static const ParserErrorCode INVALID_INITIALIZER = _INVALID_INITIALIZER; static const ParserErrorCode INVALID_LITERAL_IN_CONFIGURATION = const ParserErrorCode('INVALID_LITERAL_IN_CONFIGURATION', "The literal in a configuration can't contain interpolation.", correction: "Try removing the interpolation expressions."); /** * Parameters: * 0: the operator that is invalid */ static const ParserErrorCode INVALID_OPERATOR = _INVALID_OPERATOR; /** * Parameters: * 0: the operator being applied to 'super' * * Only generated by the old parser. * Replaced by INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER. */ static const ParserErrorCode INVALID_OPERATOR_FOR_SUPER = const ParserErrorCode('INVALID_OPERATOR_FOR_SUPER', "The operator '{0}' can't be used with 'super'."); static const ParserErrorCode INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER = _INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER; static const ParserErrorCode INVALID_STAR_AFTER_ASYNC = const ParserErrorCode( 'INVALID_STAR_AFTER_ASYNC', "The modifier 'async*' isn't allowed for an expression function body.", correction: "Try converting the body to a block."); static const ParserErrorCode INVALID_SUPER_IN_INITIALIZER = _INVALID_SUPER_IN_INITIALIZER; static const ParserErrorCode INVALID_SYNC = const ParserErrorCode( 'INVALID_SYNC', "The modifier 'sync' isn't allowed for an expression function body.", correction: "Try converting the body to a block."); static const ParserErrorCode INVALID_THIS_IN_INITIALIZER = _INVALID_THIS_IN_INITIALIZER; static const ParserErrorCode INVALID_UNICODE_ESCAPE = _INVALID_UNICODE_ESCAPE; static const ParserErrorCode LIBRARY_DIRECTIVE_NOT_FIRST = _LIBRARY_DIRECTIVE_NOT_FIRST; static const ParserErrorCode LOCAL_FUNCTION_DECLARATION_MODIFIER = const ParserErrorCode('LOCAL_FUNCTION_DECLARATION_MODIFIER', "Local function declarations can't specify any modifiers.", correction: "Try removing the modifier."); static const ParserErrorCode MISSING_ASSIGNABLE_SELECTOR = _MISSING_ASSIGNABLE_SELECTOR; static const ParserErrorCode MISSING_ASSIGNMENT_IN_INITIALIZER = _MISSING_ASSIGNMENT_IN_INITIALIZER; static const ParserErrorCode MISSING_CATCH_OR_FINALLY = _MISSING_CATCH_OR_FINALLY; static const ParserErrorCode MISSING_CLASS_BODY = _EXPECTED_BODY; static const ParserErrorCode MISSING_CLOSING_PARENTHESIS = const ParserErrorCode( 'MISSING_CLOSING_PARENTHESIS', "The closing parenthesis is missing.", correction: "Try adding the closing parenthesis."); static const ParserErrorCode MISSING_CONST_FINAL_VAR_OR_TYPE = _MISSING_CONST_FINAL_VAR_OR_TYPE; static const ParserErrorCode MISSING_ENUM_BODY = const ParserErrorCode( 'MISSING_ENUM_BODY', "An enum definition must have a body with at least one constant name.", correction: "Try adding a body and defining at least one constant."); static const ParserErrorCode MISSING_EXPRESSION_IN_INITIALIZER = const ParserErrorCode('MISSING_EXPRESSION_IN_INITIALIZER', "Expected an expression after the assignment operator.", correction: "Try adding the value to be assigned, or " "remove the assignment operator."); static const ParserErrorCode MISSING_EXPRESSION_IN_THROW = _MISSING_EXPRESSION_IN_THROW; static const ParserErrorCode MISSING_FUNCTION_BODY = const ParserErrorCode( 'MISSING_FUNCTION_BODY', "A function body must be provided.", correction: "Try adding a function body."); static const ParserErrorCode MISSING_FUNCTION_KEYWORD = const ParserErrorCode( 'MISSING_FUNCTION_KEYWORD', "Function types must have the keyword 'Function' before the parameter list.", correction: "Try adding the keyword 'Function'."); static const ParserErrorCode MISSING_FUNCTION_PARAMETERS = const ParserErrorCode('MISSING_FUNCTION_PARAMETERS', "Functions must have an explicit list of parameters.", correction: "Try adding a parameter list."); static const ParserErrorCode MISSING_GET = const ParserErrorCode( 'MISSING_GET', "Getters must have the keyword 'get' before the getter name.", correction: "Try adding the keyword 'get'."); static const ParserErrorCode MISSING_IDENTIFIER = const ParserErrorCode('MISSING_IDENTIFIER', "Expected an identifier."); static const ParserErrorCode MISSING_INITIALIZER = _MISSING_INITIALIZER; static const ParserErrorCode MISSING_KEYWORD_OPERATOR = _MISSING_KEYWORD_OPERATOR; static const ParserErrorCode MISSING_METHOD_PARAMETERS = const ParserErrorCode('MISSING_METHOD_PARAMETERS', "Methods must have an explicit list of parameters.", correction: "Try adding a parameter list."); static const ParserErrorCode MISSING_NAME_FOR_NAMED_PARAMETER = const ParserErrorCode('MISSING_NAME_FOR_NAMED_PARAMETER', "Named parameters in a function type must have a name", correction: "Try providing a name for the parameter or removing the curly braces."); static const ParserErrorCode MISSING_NAME_IN_LIBRARY_DIRECTIVE = const ParserErrorCode('MISSING_NAME_IN_LIBRARY_DIRECTIVE', "Library directives must include a library name.", correction: "Try adding a library name after the keyword 'library', or " "remove the library directive if the library doesn't have any parts."); static const ParserErrorCode MISSING_NAME_IN_PART_OF_DIRECTIVE = const ParserErrorCode('MISSING_NAME_IN_PART_OF_DIRECTIVE', "Part-of directives must include a library name.", correction: "Try adding a library name after the 'of'."); static const ParserErrorCode MISSING_PREFIX_IN_DEFERRED_IMPORT = _MISSING_PREFIX_IN_DEFERRED_IMPORT; static const ParserErrorCode MISSING_STAR_AFTER_SYNC = const ParserErrorCode( 'MISSING_STAR_AFTER_SYNC', "The modifier 'sync' must be followed by a star ('*').", correction: "Try removing the modifier, or add a star."); static const ParserErrorCode MISSING_STATEMENT = _MISSING_STATEMENT; /** * Parameters: * 0: the terminator that is missing */ static const ParserErrorCode MISSING_TERMINATOR_FOR_PARAMETER_GROUP = const ParserErrorCode('MISSING_TERMINATOR_FOR_PARAMETER_GROUP', "There is no '{0}' to close the parameter group.", correction: "Try inserting a '{0}' at the end of the group."); static const ParserErrorCode MISSING_TYPEDEF_PARAMETERS = const ParserErrorCode('MISSING_TYPEDEF_PARAMETERS', "Typedefs must have an explicit list of parameters.", correction: "Try adding a parameter list."); static const ParserErrorCode MISSING_VARIABLE_IN_FOR_EACH = const ParserErrorCode( 'MISSING_VARIABLE_IN_FOR_EACH', "A loop variable must be declared in a for-each loop before the 'in', but none was found.", correction: "Try declaring a loop variable."); static const ParserErrorCode MIXED_PARAMETER_GROUPS = const ParserErrorCode( 'MIXED_PARAMETER_GROUPS', "Can't have both positional and named parameters in a single parameter list.", correction: "Try choosing a single style of optional parameters."); static const ParserErrorCode MIXIN_DECLARES_CONSTRUCTOR = _MIXIN_DECLARES_CONSTRUCTOR; static const ParserErrorCode MODIFIER_OUT_OF_ORDER = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode MULTIPLE_EXTENDS_CLAUSES = _MULTIPLE_EXTENDS_CLAUSES; static const ParserErrorCode MULTIPLE_IMPLEMENTS_CLAUSES = const ParserErrorCode( 'MULTIPLE_IMPLEMENTS_CLAUSES', "Each class or mixin definition can have at most one implements clause.", correction: "Try combining all of the implements clauses into a single clause."); static const ParserErrorCode MULTIPLE_LIBRARY_DIRECTIVES = _MULTIPLE_LIBRARY_DIRECTIVES; static const ParserErrorCode MULTIPLE_NAMED_PARAMETER_GROUPS = const ParserErrorCode('MULTIPLE_NAMED_PARAMETER_GROUPS', "Can't have multiple groups of named parameters in a single parameter list.", correction: "Try combining all of the groups into a single group."); static const ParserErrorCode MULTIPLE_ON_CLAUSES = _MULTIPLE_ON_CLAUSES; static const ParserErrorCode MULTIPLE_PART_OF_DIRECTIVES = _MULTIPLE_PART_OF_DIRECTIVES; static const ParserErrorCode MULTIPLE_POSITIONAL_PARAMETER_GROUPS = const ParserErrorCode('MULTIPLE_POSITIONAL_PARAMETER_GROUPS', "Can't have multiple groups of positional parameters in a single parameter list.", correction: "Try combining all of the groups into a single group."); /** * Parameters: * 0: the number of variables being declared */ static const ParserErrorCode MULTIPLE_VARIABLES_IN_FOR_EACH = const ParserErrorCode( 'MULTIPLE_VARIABLES_IN_FOR_EACH', "A single loop variable must be declared in a for-each loop before " "the 'in', but {0} were found.", correction: "Try moving all but one of the declarations inside the loop body."); static const ParserErrorCode MULTIPLE_VARIANCE_MODIFIERS = _MULTIPLE_VARIANCE_MODIFIERS; static const ParserErrorCode MULTIPLE_WITH_CLAUSES = _MULTIPLE_WITH_CLAUSES; static const ParserErrorCode NAMED_FUNCTION_EXPRESSION = const ParserErrorCode( 'NAMED_FUNCTION_EXPRESSION', "Function expressions can't be named.", correction: "Try removing the name, or " "moving the function expression to a function declaration statement."); static const ParserErrorCode NAMED_FUNCTION_TYPE = const ParserErrorCode( 'NAMED_FUNCTION_TYPE', "Function types can't be named.", correction: "Try replacing the name with the keyword 'Function'."); static const ParserErrorCode NAMED_PARAMETER_OUTSIDE_GROUP = const ParserErrorCode('NAMED_PARAMETER_OUTSIDE_GROUP', "Named parameters must be enclosed in curly braces ('{' and '}').", correction: "Try surrounding the named parameters in curly braces."); static const ParserErrorCode NATIVE_CLAUSE_IN_NON_SDK_CODE = const ParserErrorCode( 'NATIVE_CLAUSE_IN_NON_SDK_CODE', "Native clause can only be used in the SDK and code that is loaded " "through native extensions.", correction: "Try removing the native clause."); static const ParserErrorCode NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE = const ParserErrorCode( 'NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE', "Native functions can only be declared in the SDK and code that is " "loaded through native extensions.", correction: "Try removing the word 'native'."); static const ParserErrorCode NATIVE_CLAUSE_SHOULD_BE_ANNOTATION = _NATIVE_CLAUSE_SHOULD_BE_ANNOTATION; static const ParserErrorCode NON_CONSTRUCTOR_FACTORY = const ParserErrorCode( 'NON_CONSTRUCTOR_FACTORY', "Only a constructor can be declared to be a factory.", correction: "Try removing the keyword 'factory'."); static const ParserErrorCode NON_IDENTIFIER_LIBRARY_NAME = const ParserErrorCode('NON_IDENTIFIER_LIBRARY_NAME', "The name of a library must be an identifier.", correction: "Try using an identifier as the name of the library."); static const ParserErrorCode NON_PART_OF_DIRECTIVE_IN_PART = const ParserErrorCode('NON_PART_OF_DIRECTIVE_IN_PART', "The part-of directive must be the only directive in a part.", correction: "Try removing the other directives, or " "moving them to the library for which this is a part."); static const ParserErrorCode NON_STRING_LITERAL_AS_URI = const ParserErrorCode( 'NON_STRING_LITERAL_AS_URI', "The URI must be a string literal.", correction: "Try enclosing the URI in either single or double quotes."); /** * Parameters: * 0: the operator that the user is trying to define */ static const ParserErrorCode NON_USER_DEFINABLE_OPERATOR = const ParserErrorCode('NON_USER_DEFINABLE_OPERATOR', "The operator '{0}' isn't user definable."); static const ParserErrorCode NORMAL_BEFORE_OPTIONAL_PARAMETERS = const ParserErrorCode('NORMAL_BEFORE_OPTIONAL_PARAMETERS', "Normal parameters must occur before optional parameters.", correction: "Try moving all of the normal parameters before the optional parameters."); static const ErrorCode NULL_AWARE_CASCADE_OUT_OF_ORDER = _NULL_AWARE_CASCADE_OUT_OF_ORDER; static const ParserErrorCode POSITIONAL_AFTER_NAMED_ARGUMENT = const ParserErrorCode('POSITIONAL_AFTER_NAMED_ARGUMENT', "Positional arguments must occur before named arguments.", correction: "Try moving all of the positional arguments before the named arguments."); static const ParserErrorCode POSITIONAL_PARAMETER_OUTSIDE_GROUP = const ParserErrorCode('POSITIONAL_PARAMETER_OUTSIDE_GROUP', "Positional parameters must be enclosed in square brackets ('[' and ']').", correction: "Try surrounding the positional parameters in square brackets."); static const ParserErrorCode PREFIX_AFTER_COMBINATOR = _PREFIX_AFTER_COMBINATOR; static const ParserErrorCode REDIRECTING_CONSTRUCTOR_WITH_BODY = _REDIRECTING_CONSTRUCTOR_WITH_BODY; static const ParserErrorCode REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR = _REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR; static const ParserErrorCode SETTER_IN_FUNCTION = const ParserErrorCode( 'SETTER_IN_FUNCTION', "Setters can't be defined within methods or functions.", correction: "Try moving the setter outside the method or function."); static const ParserErrorCode STACK_OVERFLOW = _STACK_OVERFLOW; static const ParserErrorCode STATIC_AFTER_CONST = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode STATIC_AFTER_FINAL = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode STATIC_AFTER_VAR = _MODIFIER_OUT_OF_ORDER; static const ParserErrorCode STATIC_CONSTRUCTOR = _STATIC_CONSTRUCTOR; static const ParserErrorCode STATIC_GETTER_WITHOUT_BODY = const ParserErrorCode( 'STATIC_GETTER_WITHOUT_BODY', "A 'static' getter must have a body.", correction: "Try adding a body to the getter, or removing the keyword 'static'."); static const ParserErrorCode STATIC_OPERATOR = _STATIC_OPERATOR; static const ParserErrorCode STATIC_SETTER_WITHOUT_BODY = const ParserErrorCode( 'STATIC_SETTER_WITHOUT_BODY', "A 'static' setter must have a body.", correction: "Try adding a body to the setter, or removing the keyword 'static'."); static const ParserErrorCode STATIC_TOP_LEVEL_DECLARATION = const ParserErrorCode('STATIC_TOP_LEVEL_DECLARATION', "Top-level declarations can't be declared to be static.", correction: "Try removing the keyword 'static'."); static const ParserErrorCode SWITCH_HAS_CASE_AFTER_DEFAULT_CASE = _SWITCH_HAS_CASE_AFTER_DEFAULT_CASE; static const ParserErrorCode SWITCH_HAS_MULTIPLE_DEFAULT_CASES = _SWITCH_HAS_MULTIPLE_DEFAULT_CASES; static const ParserErrorCode TOP_LEVEL_OPERATOR = _TOP_LEVEL_OPERATOR; static const ParserErrorCode TYPE_ARGUMENTS_ON_TYPE_VARIABLE = _TYPE_ARGUMENTS_ON_TYPE_VARIABLE; static const ParserErrorCode TYPE_BEFORE_FACTORY = _TYPE_BEFORE_FACTORY; static const ParserErrorCode TYPEDEF_IN_CLASS = _TYPEDEF_IN_CLASS; /** * Parameters: * 0: the starting character that was missing */ static const ParserErrorCode UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP = const ParserErrorCode('UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP', "There is no '{0}' to open a parameter group.", correction: "Try inserting the '{0}' at the appropriate location."); /** * Parameters: * 0: the unexpected text that was found */ static const ParserErrorCode UNEXPECTED_TOKEN = const ParserErrorCode( 'UNEXPECTED_TOKEN', "Unexpected text '{0}'.", correction: "Try removing the text."); static const ParserErrorCode WITH_BEFORE_EXTENDS = _WITH_BEFORE_EXTENDS; static const ParserErrorCode WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER = const ParserErrorCode('WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER', "The default value of a positional parameter should be preceded by '='.", correction: "Try replacing the ':' with '='."); /** * Parameters: * 0: the terminator that was expected * 1: the terminator that was found */ static const ParserErrorCode WRONG_TERMINATOR_FOR_PARAMETER_GROUP = const ParserErrorCode('WRONG_TERMINATOR_FOR_PARAMETER_GROUP', "Expected '{0}' to close parameter group.", correction: "Try replacing '{0}' with '{1}'."); static const ParserErrorCode VAR_AND_TYPE = _VAR_AND_TYPE; static const ParserErrorCode VAR_AS_TYPE_NAME = _VAR_AS_TYPE_NAME; static const ParserErrorCode VAR_CLASS = const ParserErrorCode( 'VAR_CLASS', "Classes can't be declared to be 'var'.", correction: "Try removing the keyword 'var'."); static const ParserErrorCode VAR_ENUM = const ParserErrorCode( 'VAR_ENUM', "Enums can't be declared to be 'var'.", correction: "Try removing the keyword 'var'."); static const ParserErrorCode VAR_RETURN_TYPE = _VAR_RETURN_TYPE; static const ParserErrorCode VAR_TYPEDEF = const ParserErrorCode( 'VAR_TYPEDEF', "Typedefs can't be declared to be 'var'.", correction: "Try removing the keyword 'var', or " "replacing it with the name of the return type."); /** * 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 ParserErrorCode(String name, String message, {String correction, bool hasPublishedDocs}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs ?? false); @override ErrorSeverity get errorSeverity => ErrorSeverity.ERROR; @override ErrorType get type => ErrorType.SYNTACTIC_ERROR; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/error/todo_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 code indicating a marker in code for work that needs to be finished * or revisited. */ class TodoCode extends ErrorCode { /** * The single enum of TodoCode. */ static const TodoCode TODO = const TodoCode('TODO'); /** * This matches the two common Dart task styles * * * TODO: * * TODO(username): * * As well as * * TODO * * But not * * todo * * TODOS */ static RegExp TODO_REGEX = new RegExp("([\\s/\\*])((TODO[^\\w\\d][^\\r\\n]*)|(TODO:?\$))"); /** * Initialize a newly created error code to have the given [name]. */ const TodoCode(String name) : super.temporary(name, "{0}"); @override ErrorSeverity get errorSeverity => ErrorSeverity.INFO; @override ErrorType get type => ErrorType.TODO; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/error/hint_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/error/analyzer_error_code.dart'; /** * The hints and coding recommendations for best practices which are not * mentioned in the Dart Language Specification. */ class HintCode extends AnalyzerErrorCode { /** * When the target expression uses '?.' operator, it can be `null`, so all the * subsequent invocations should also use '?.' operator. */ static const HintCode CAN_BE_NULL_AFTER_NULL_AWARE = const HintCode( 'CAN_BE_NULL_AFTER_NULL_AWARE', "The target expression uses '?.', so its value can be null.", correction: "Replace the '.' with a '?.' in the invocation."); /** * Dead code is code that is never reached, this can happen for instance if a * statement follows a return statement. */ static const HintCode DEAD_CODE = const HintCode('DEAD_CODE', "Dead code.", correction: "Try removing the code, or " "fixing the code before it so that it can be reached."); /** * Dead code is code that is never reached. This case covers cases where the * user has catch clauses after `catch (e)` or `on Object catch (e)`. */ static const HintCode DEAD_CODE_CATCH_FOLLOWING_CATCH = const HintCode( 'DEAD_CODE_CATCH_FOLLOWING_CATCH', "Dead code: catch clauses after a 'catch (e)' or " "an 'on Object catch (e)' are never reached.", correction: "Try reordering the catch clauses so that they can be reached, or " "removing the unreachable catch clauses."); /** * Dead code is code that is never reached. This case covers cases where the * user has an on-catch clause such as `on A catch (e)`, where a supertype of * `A` was already caught. * * Parameters: * 0: name of the subtype * 1: name of the supertype */ static const HintCode DEAD_CODE_ON_CATCH_SUBTYPE = const HintCode( 'DEAD_CODE_ON_CATCH_SUBTYPE', "Dead code: this on-catch block will never be executed because '{0}' is " "a subtype of '{1}' and hence will have been caught above.", correction: "Try reordering the catch clauses so that this block can be reached, " "or removing the unreachable catch clause."); /** * Users should not create a class named `Function` anymore. */ static const HintCode DEPRECATED_FUNCTION_CLASS_DECLARATION = const HintCode( 'DEPRECATED_FUNCTION_CLASS_DECLARATION', "Declaring a class named 'Function' is deprecated.", correction: "Try renaming the class."); /** * `Function` should not be extended anymore. */ static const HintCode DEPRECATED_EXTENDS_FUNCTION = const HintCode( 'DEPRECATED_EXTENDS_FUNCTION', "Extending 'Function' is deprecated.", correction: "Try removing 'Function' from the 'extends' clause."); /** * Parameters: * 0: the name of the member */ // #### Description // // The analyzer produces this diagnostic when a deprecated library or class // member is used in a different package. // // #### Example // // If the method `m` in the class `C` is annotated with `@deprecated`, then // the following code produces this diagnostic: // // ```dart // void f(C c) { // c.[!m!](); // } // ``` // // #### Common fixes // // The documentation for declarations that are annotated with `@deprecated` // should indicate what code to use in place of the deprecated code. static const HintCode DEPRECATED_MEMBER_USE = const HintCode( 'DEPRECATED_MEMBER_USE', "'{0}' is deprecated and shouldn't be used.", correction: "Try replacing the use of the deprecated member with the " "replacement.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the member */ // #### Description // // The analyzer produces this diagnostic when a deprecated library member or // class member is used in the same package in which it's declared. // // #### Example // // The following code produces this diagnostic: // // ```dart // @deprecated // var x = 0; // var y = [!x!]; // ``` // // #### Common fixes // // The fix depends on what's been deprecated and what the replacement is. The // documentation for deprecated declarations should indicate what code to use // in place of the deprecated code. static const HintCode DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE = const HintCode('DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE', "'{0}' is deprecated and shouldn't be used.", correction: "Try replacing the use of the deprecated member with the " "replacement.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the member * 1: message details */ static const HintCode DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE_WITH_MESSAGE = const HintCodeWithUniqueName( 'DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE', 'HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE_WITH_MESSAGE', "'{0}' is deprecated and shouldn't be used. {1}.", correction: "Try replacing the use of the deprecated member with the " "replacement.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the member * 1: message details */ static const HintCode DEPRECATED_MEMBER_USE_WITH_MESSAGE = const HintCodeWithUniqueName( 'DEPRECATED_MEMBER_USE', 'HintCode.DEPRECATED_MEMBER_USE_WITH_MESSAGE', "'{0}' is deprecated and shouldn't be used. {1}.", correction: "Try replacing the use of the deprecated member with the " "replacement.", hasPublishedDocs: true); /** * `Function` should not be mixed in anymore. */ static const HintCode DEPRECATED_MIXIN_FUNCTION = const HintCode( 'DEPRECATED_MIXIN_FUNCTION', "Mixing in 'Function' is deprecated.", correction: "Try removing 'Function' from the 'with' clause."); /** * Hint to use the ~/ operator. */ static const HintCode DIVISION_OPTIMIZATION = const HintCode( 'DIVISION_OPTIMIZATION', "The operator x ~/ y is more efficient than (x / y).toInt().", correction: "Try re-writing the expression to use the '~/' operator."); /** * Duplicate imports. */ static const HintCode DUPLICATE_IMPORT = const HintCode( 'DUPLICATE_IMPORT', "Duplicate import.", correction: "Try removing all but one import of the library."); /** * Duplicate hidden names. */ static const HintCode DUPLICATE_HIDDEN_NAME = const HintCode('DUPLICATE_HIDDEN_NAME', "Duplicate hidden name.", correction: "Try removing the repeated name from the list of hidden " "members."); /** * Duplicate shown names. */ static const HintCode DUPLICATE_SHOWN_NAME = const HintCode('DUPLICATE_SHOWN_NAME', "Duplicate shown name.", correction: "Try removing the repeated name from the list of shown " "members."); /** * It is a bad practice for a source file in a package "lib" directory * hierarchy to traverse outside that directory hierarchy. For example, a * source file in the "lib" directory should not contain a directive such as * `import '../web/some.dart'` which references a file outside the lib * directory. */ static const HintCode FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE = const HintCode( 'FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE', "A file in the 'lib' directory shouldn't import a file outside the " "'lib' directory.", correction: "Try removing the import, or " "moving the imported file inside the 'lib' directory."); /** * It is a bad practice for a source file ouside a package "lib" directory * hierarchy to traverse into that directory hierarchy. For example, a source * file in the "web" directory should not contain a directive such as * `import '../lib/some.dart'` which references a file inside the lib * directory. */ static const HintCode FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE = const HintCode( 'FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE', "A file outside the 'lib' directory shouldn't reference a file " "inside the 'lib' directory using a relative path.", correction: "Try using a package: URI instead."); /** * Deferred libraries shouldn't define a top level function 'loadLibrary'. */ static const HintCode IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION = const HintCode( 'IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION', "The library '{0}' defines a top-level function named 'loadLibrary' " "which is hidden by deferring this library.", correction: "Try changing the import to not be deferred, or " "rename the function in the imported library."); /** * When "strict-inference" is enabled, collection literal types must be * inferred via the context type, or have type arguments. */ static const HintCode INFERENCE_FAILURE_ON_COLLECTION_LITERAL = HintCode( 'INFERENCE_FAILURE_ON_COLLECTION_LITERAL', "The type argument(s) of '{0}' can't be inferred.", correction: "Use explicit type argument(s) for '{0}'."); /** * When "strict-inference" is enabled, recursive local functions, top-level * functions, methods, and function-typed function parameters must all * specify a return type. See the strict-inference resource: * * https://github.com/dart-lang/language/blob/master/resources/type-system/strict-inference.md */ static const HintCode INFERENCE_FAILURE_ON_FUNCTION_RETURN_TYPE = HintCode( 'INFERENCE_FAILURE_ON_FUNCTION_RETURN_TYPE', "The return type of '{0}' cannot be inferred.", correction: "Declare the return type of '{0}'."); /** * When "strict-inference" is enabled, types in instance creation * (constructor calls) must be inferred via the context type, or have type * arguments. */ static const HintCode INFERENCE_FAILURE_ON_INSTANCE_CREATION = HintCode( 'INFERENCE_FAILURE_ON_INSTANCE_CREATION', "The type argument(s) of '{0}' can't be inferred.", correction: "Use explicit type argument(s) for '{0}'."); /** * When "strict-inference" in enabled, uninitialized variables must be * declared with a specific type. */ static const HintCode INFERENCE_FAILURE_ON_UNINITIALIZED_VARIABLE = const HintCode( 'INFERENCE_FAILURE_ON_UNINITIALIZED_VARIABLE', "The type of {0} can't be inferred without either a type or " "initializer.", correction: "Try specifying the type of the variable."); /** * When "strict-inference" in enabled, function parameters must be * declared with a specific type, or inherit a type. */ static const HintCode INFERENCE_FAILURE_ON_UNTYPED_PARAMETER = const HintCode( 'INFERENCE_FAILURE_ON_UNTYPED_PARAMETER', "The type of {0} can't be inferred; a type must be explicitly provided.", correction: "Try specifying the type of the parameter."); /** * This hint is generated anywhere a @factory annotation is associated with * anything other than a method. */ static const HintCode INVALID_FACTORY_ANNOTATION = const HintCode( 'INVALID_FACTORY_ANNOTATION', "Only methods can be annotated as factories."); /** * This hint is generated anywhere a @factory annotation is associated with * a method that does not declare a return type. */ static const HintCode INVALID_FACTORY_METHOD_DECL = const HintCode( 'INVALID_FACTORY_METHOD_DECL', "Factory method '{0}' must have a return type."); /** * This hint is generated anywhere a @factory annotation is associated with * a non-abstract method that can return anything other than a newly allocated * object. * * Parameters: * 0: the name of the method */ static const HintCode INVALID_FACTORY_METHOD_IMPL = const HintCode( 'INVALID_FACTORY_METHOD_IMPL', "Factory method '{0}' doesn't return a newly allocated object."); /** * This hint is generated anywhere an @immutable annotation is associated with * anything other than a class. */ static const HintCode INVALID_IMMUTABLE_ANNOTATION = const HintCode( 'INVALID_IMMUTABLE_ANNOTATION', "Only classes can be annotated as being immutable."); /** * No parameters. */ // #### Description // // The meaning of the `@literal` annotation is only defined when it's applied // to a const constructor. // // #### Example // // The following code produces this diagnostic: // // ```dart // import 'package:meta/meta.dart'; // // [!@literal!] // var x; // ``` // // #### Common fixes // // Remove the annotation: // // ```dart // var x; // ``` static const HintCode INVALID_LITERAL_ANNOTATION = const HintCode( 'INVALID_LITERAL_ANNOTATION', "Only const constructors can have the `@literal` annotation.", hasPublishedDocs: true); /** * This hint is generated anywhere where `@required` annotates a named * parameter with a default value. * * Parameters: * 0: the name of the member */ static const HintCode INVALID_REQUIRED_NAMED_PARAM = const HintCode( 'INVALID_REQUIRED_NAMED_PARAM', "The type parameter '{0}' is annotated with @required but only named " "parameters without a default value can be annotated with it.", correction: "Remove @required."); /** * This hint is generated anywhere where `@required` annotates an optional * positional parameter. * * Parameters: * 0: the name of the member */ static const HintCode INVALID_REQUIRED_OPTIONAL_POSITIONAL_PARAM = const HintCode( 'INVALID_REQUIRED_OPTIONAL_POSITIONAL_PARAM', "Incorrect use of the annotation @required on the optional " "positional parameter '{0}'. Optional positional parameters " "cannot be required.", correction: "Remove @required."); /** * This hint is generated anywhere where `@required` annotates a non named * parameter or a named parameter with default value. * * Parameters: * 0: the name of the member * * Deprecated: Use the more specific [INVALID_REQUIRED_NAMED_PARAM], * [INVALID_REQUIRED_OPTIONAL_POSITION_PARAM], and * [INVALID_REQUIRED_POSITION_PARAM] */ @deprecated static const HintCode INVALID_REQUIRED_PARAM = const HintCode( 'INVALID_REQUIRED_PARAM', "The type parameter '{0}' is annotated with @required but only named " "parameters without default value can be annotated with it.", correction: "Remove @required."); /** * This hint is generated anywhere where `@required` annotates a non optional * positional parameter. * * Parameters: * 0: the name of the member */ static const HintCode INVALID_REQUIRED_POSITIONAL_PARAM = const HintCode( 'INVALID_REQUIRED_POSITIONAL_PARAM', "Redundant use of the annotation @required on the required positional " "parameter '{0}'.", correction: "Remove @required."); /** * This hint is generated anywhere where `@sealed` annotates something other * than a class. * * Parameters: * 0: the name of the member */ static const HintCode INVALID_SEALED_ANNOTATION = const HintCode( 'INVALID_SEALED_ANNOTATION', "The member '{0}' is annotated with '@sealed' but only classes can be " "annotated with it.", correction: "Remove @sealed."); /** * This hint is generated anywhere where a member annotated with `@protected` * is used outside an instance member of a subclass. * * Parameters: * 0: the name of the member * 1: the name of the defining class */ static const HintCode INVALID_USE_OF_PROTECTED_MEMBER = const HintCode( 'INVALID_USE_OF_PROTECTED_MEMBER', "The member '{0}' can only be used within instance members of subclasses " "of '{1}'."); /// This hint is generated anywhere where a member annotated with /// `@visibleForTemplate` is used outside of a "template" Dart file. /// /// Parameters: /// 0: the name of the member /// 1: the name of the defining class static const HintCode INVALID_USE_OF_VISIBLE_FOR_TEMPLATE_MEMBER = const HintCode( 'INVALID_USE_OF_VISIBLE_FOR_TEMPLATE_MEMBER', "The member '{0}' can only be used within '{1}' or a template " "library."); /// This hint is generated anywhere where a member annotated with /// `@visibleForTesting` is used outside the defining library, or a test. /// /// Parameters: /// 0: the name of the member /// 1: the name of the defining class static const HintCode INVALID_USE_OF_VISIBLE_FOR_TESTING_MEMBER = const HintCode('INVALID_USE_OF_VISIBLE_FOR_TESTING_MEMBER', "The member '{0}' can only be used within '{1}' or a test."); /// This hint is generated anywhere where a private declaration is annotated /// with `@visibleForTemplate` or `@visibleForTesting`. /// /// Parameters: /// 0: the name of the member /// 1: the name of the annotation static const HintCode INVALID_VISIBILITY_ANNOTATION = const HintCode( 'INVALID_VISIBILITY_ANNOTATION', "The member '{0}' is annotated with '{1}', but this annotation is only " "meaningful on declarations of public members."); /** * Hint for the `x is double` type checks. */ static const HintCode IS_DOUBLE = const HintCode( 'IS_DOUBLE', "When compiled to JS, this test might return true when the left hand " "side is an int.", correction: "Try testing for 'num' instead."); /** * Hint for the `x is int` type checks. */ // TODO(brianwilkerson) This hint isn't being generated. Decide whether to // generate it or remove it. static const HintCode IS_INT = const HintCode( 'IS_INT', "When compiled to JS, this test might return true when the left hand " "side is a double.", correction: "Try testing for 'num' instead."); /** * Hint for the `x is! double` type checks. */ static const HintCode IS_NOT_DOUBLE = const HintCode( 'IS_NOT_DOUBLE', "When compiled to JS, this test might return false when the left hand " "side is an int.", correction: "Try testing for 'num' instead."); /** * Hint for the `x is! int` type checks. */ // TODO(brianwilkerson) This hint isn't being generated. Decide whether to // generate it or remove it. static const HintCode IS_NOT_INT = const HintCode( 'IS_NOT_INT', "When compiled to JS, this test might return false when the left hand " "side is a double.", correction: "Try testing for 'num' instead."); /** * Generate a hint for an element that is annotated with `@JS(...)` whose * library declaration is not similarly annotated. */ static const HintCode MISSING_JS_LIB_ANNOTATION = const HintCode( 'MISSING_JS_LIB_ANNOTATION', "The @JS() annotation can only be used if it is also declared on the " "library directive.", correction: "Try adding the annotation to the library directive."); /** * Generate a hint for a constructor, function or method invocation where a * required parameter is missing. * * Parameters: * 0: the name of the parameter */ static const HintCode MISSING_REQUIRED_PARAM = const HintCode( 'MISSING_REQUIRED_PARAM', "The parameter '{0}' is required."); /** * Generate a hint for a constructor, function or method invocation where a * required parameter is missing. * * Parameters: * 0: the name of the parameter * 1: message details */ static const HintCode MISSING_REQUIRED_PARAM_WITH_DETAILS = const HintCode( 'MISSING_REQUIRED_PARAM_WITH_DETAILS', "The parameter '{0}' is required. {1}."); /** * Parameters: * 0: the name of the declared return type */ // #### Description // // Any function or method that doesn't end with either an explicit return or a // throw implicitly returns `null`. This is rarely the desired behavior. The // analyzer produces this diagnostic when it finds an implicit return. // // #### Example // // The following code produces this diagnostic: // // ```dart // [!int!] f(int x) { // if (x < 0) { // return 0; // } // } // ``` // // #### Common fixes // // Add a return statement that makes the return value explicit, even if `null` // is the appropriate value. static const HintCode MISSING_RETURN = const HintCode( 'MISSING_RETURN', "This function has a return type of '{0}', but doesn't end with a " "return statement.", correction: "Try adding a return statement, " "or changing the return type to 'void'.", hasPublishedDocs: true); /** * This hint is generated anywhere where a `@sealed` class is used as a * a superclass constraint of a mixin. */ static const HintCode MIXIN_ON_SEALED_CLASS = const HintCode( 'MIXIN_ON_SEALED_CLASS', "The class '{0}' shouldn't be used as a mixin constraint because it is " "sealed, and any class mixing in this mixin has '{0}' as a " "superclass.", correction: "Try composing with this class, or refer to its documentation for " "more information."); /** * Generate a hint for classes that inherit from classes annotated with * `@immutable` but that are not immutable. */ static const HintCode MUST_BE_IMMUTABLE = const HintCode( 'MUST_BE_IMMUTABLE', "This class (or a class which this class inherits from) is marked as " "'@immutable', but one or more of its instance fields are not final: " "{0}"); /** * Generate a hint for methods that override methods annotated `@mustCallSuper` * that do not invoke the overridden super method. * * Parameters: * 0: the name of the class declaring the overridden method */ static const HintCode MUST_CALL_SUPER = const HintCode( 'MUST_CALL_SUPER', "This method overrides a method annotated as @mustCallSuper in '{0}', " "but doesn't invoke the overridden method."); /** * Generate a hint for non-const instance creation using a constructor * annotated with `@literal`. */ static const HintCode NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR = const HintCode( 'NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR', "This instance creation must be 'const', because the {0} constructor is " "marked as '@literal'.", correction: "Try adding a 'const' keyword."); /** * Generate a hint for non-const instance creation (with the `new` keyword) * using a constructor annotated with `@literal`. */ static const HintCode NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR_USING_NEW = const HintCode( 'NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR_USING_NEW', "This instance creation must be 'const', because the {0} constructor " "is marked as '@literal'.", correction: "Try replacing the 'new' keyword with 'const'."); /** * When the left operand of a binary expression uses '?.' operator, it can be * `null`. */ static const HintCode NULL_AWARE_BEFORE_OPERATOR = const HintCode( 'NULL_AWARE_BEFORE_OPERATOR', "The left operand uses '?.', so its value can be null."); /** * A condition in a control flow statement could evaluate to `null` because it * uses the null-aware '?.' operator. */ static const HintCode NULL_AWARE_IN_CONDITION = const HintCode( 'NULL_AWARE_IN_CONDITION', "The value of the '?.' operator can be 'null', which isn't appropriate " "in a condition.", correction: "Try replacing the '?.' with a '.', testing the left-hand side for " "null if necessary."); /** * A condition in operands of a logical operator could evaluate to `null` * because it uses the null-aware '?.' operator. */ static const HintCode NULL_AWARE_IN_LOGICAL_OPERATOR = const HintCode( 'NULL_AWARE_IN_LOGICAL_OPERATOR', "The value of the '?.' operator can be 'null', which isn't appropriate " "as an operand of a logical operator."); /** * Hint for classes that override equals, but not hashCode. * * Parameters: * 0: the name of the current class */ // TODO(brianwilkerson) Decide whether we want to implement this check // (possibly as a lint) or remove the hint code. static const HintCode OVERRIDE_EQUALS_BUT_NOT_HASH_CODE = const HintCode( 'OVERRIDE_EQUALS_BUT_NOT_HASH_CODE', "The class '{0}' overrides 'operator==', but not 'get hashCode'.", correction: "Try implementing 'hashCode'."); /** * A getter with the override annotation does not override an existing getter. */ static const HintCode OVERRIDE_ON_NON_OVERRIDING_GETTER = const HintCode( 'OVERRIDE_ON_NON_OVERRIDING_GETTER', "Getter doesn't override an inherited getter.", correction: "Try updating this class to match the superclass, or " "removing the override annotation."); /** * A field with the override annotation does not override a getter or setter. */ static const HintCode OVERRIDE_ON_NON_OVERRIDING_FIELD = const HintCode( 'OVERRIDE_ON_NON_OVERRIDING_FIELD', "Field doesn't override an inherited getter or setter.", correction: "Try updating this class to match the superclass, or " "removing the override annotation."); /** * A method with the override annotation does not override an existing method. */ static const HintCode OVERRIDE_ON_NON_OVERRIDING_METHOD = const HintCode( 'OVERRIDE_ON_NON_OVERRIDING_METHOD', "Method doesn't override an inherited method.", correction: "Try updating this class to match the superclass, or " "removing the override annotation."); /** * A setter with the override annotation does not override an existing setter. */ static const HintCode OVERRIDE_ON_NON_OVERRIDING_SETTER = const HintCode( 'OVERRIDE_ON_NON_OVERRIDING_SETTER', "Setter doesn't override an inherited setter.", correction: "Try updating this class to match the superclass, or " "removing the override annotation."); /** * It is a bad practice for a package import to reference anything outside the * given package, or more generally, it is bad practice for a package import * to contain a "..". For example, a source file should not contain a * directive such as `import 'package:foo/../some.dart'`. */ static const HintCode PACKAGE_IMPORT_CONTAINS_DOT_DOT = const HintCode( 'PACKAGE_IMPORT_CONTAINS_DOT_DOT', "A package import shouldn't contain '..'."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when either the class `Future` or // `Stream` is referenced in a library that doesn't import `dart:async` in // code that has an SDK constraint whose lower bound is less than 2.1.0. In // earlier versions, these classes weren't defined in `dart:core`, so the // import was necessary. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.1.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.0.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following produces this // diagnostic: // // ```dart // void f([!Future!] f) {} // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the classes to be referenced: // // ```yaml // environment: // sdk: '>=2.1.0 <2.4.0' // ``` // // If you need to support older versions of the SDK, then import the // `dart:async` library. // // ```dart // import 'dart:async'; // // void f(Future f) {} // ``` static const HintCode SDK_VERSION_ASYNC_EXPORTED_FROM_CORE = const HintCode( 'SDK_VERSION_ASYNC_EXPORTED_FROM_CORE', "The class '{0}' wasn't exported from 'dart:core' until version 2.1, " "but this code is required to be able to run on earlier versions.", correction: "Try either importing 'dart:async' or updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an as expression inside a // [constant context](#constant-context) is found in code that has an SDK // constraint whose lower bound is less than 2.3.2. Using an as expression in // a [constant context](#constant-context) wasn't supported in earlier // versions, so this code won't be able to run against earlier versions of the // SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.3.2: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.1.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following generates // this diagnostic: // // ```dart // const num n = 3; // const int i = [!n as int!]; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the expression to be used: // // ```yaml // environment: // sdk: '>=2.3.2 <2.4.0' // ``` // // If you need to support older versions of the SDK, then either rewrite the // code to not use an as expression, or change the code so that the as // expression is not in a [constant context](#constant-context).: // // ```dart // num x = 3; // int y = x as int; // ``` static const HintCode SDK_VERSION_AS_EXPRESSION_IN_CONST_CONTEXT = const HintCode( 'SDK_VERSION_AS_EXPRESSION_IN_CONST_CONTEXT', "The use of an as expression in a constant expression wasn't " "supported until version 2.3.2, but this code is required to be able " "to run on earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when any use of the `&`, `|` or `^` // operators on the class `bool` inside a // [constant context](#constant-context) is found in code that has an SDK // constraint whose lower bound is less than 2.3.2. Using these operators in a // [constant context](#constant-context) wasn't supported in earlier versions, // so this code won't be able to run against earlier versions of the SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.3.2: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.1.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following produces this // diagnostic: // // ```dart // const bool a = true; // const bool b = false; // const bool c = a [!&!] b; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the operators to be used: // // ```yaml // environment: // sdk: '>=2.3.2 <2.4.0' // ``` // // If you need to support older versions of the SDK, then either rewrite the // code to not use these operators, or change the code so that the expression // is not in a [constant context](#constant-context).: // // ```dart // const bool a = true; // const bool b = false; // bool c = a & b; // ``` static const HintCode SDK_VERSION_BOOL_OPERATOR_IN_CONST_CONTEXT = const HintCode( 'SDK_VERSION_BOOL_OPERATOR_IN_CONST_CONTEXT', "The use of the operator '{0}' for 'bool' operands in a constant context " "wasn't supported until version 2.3.2, but this code is required to " "be able to run on earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the operator `==` is used on a // non-primitive type inside a [constant context](#constant-context) is found // in code that has an SDK constraint whose lower bound is less than 2.3.2. // Using this operator in a [constant context](#constant-context) wasn't // supported in earlier versions, so this code won't be able to run against // earlier versions of the SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.3.2: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.1.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following produces this // diagnostic: // // ```dart // class C {} // const C a = null; // const C b = null; // const bool same = a [!==!] b; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the operator to be used: // // ```yaml // environment: // sdk: '>=2.3.2 <2.4.0' // ``` // // If you need to support older versions of the SDK, then either rewrite the // code to not use the `==` operator, or change the code so that the // expression is not in a [constant context](#constant-context).: // // ```dart // class C {} // const C a = null; // const C b = null; // bool same = a == b; // ``` static const HintCode SDK_VERSION_EQ_EQ_OPERATOR_IN_CONST_CONTEXT = const HintCode( 'SDK_VERSION_EQ_EQ_OPERATOR_IN_CONST_CONTEXT', "Using the operator '==' for non-primitive types wasn't supported " "until version 2.3.2, but this code is required to be able to " "run on earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an extension declaration or an // extension override is found in code that has an SDK constraint whose lower // bound is less than 2.6.0. Using extensions wasn't supported in earlier // versions, so this code won't be able to run against earlier versions of the // SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.6.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.4.0 <2.7.0' // ``` // // In the package that has that pubspec, code like the following generates // this diagnostic: // // ```dart // [!extension!] E on String { // void sayHello() { // print('Hello $this'); // } // } // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the syntax to be used: // // ```yaml // environment: // sdk: '>=2.6.0 <2.7.0' // ``` // // If you need to support older versions of the SDK, then rewrite the code to // not make use of extensions. The most common way to do this is to rewrite // the members of the extension as top-level functions (or methods) that take // the value that would have been bound to `this` as a parameter: // // ```dart // void sayHello(String s) { // print('Hello $s'); // } // ``` static const HintCode SDK_VERSION_EXTENSION_METHODS = const HintCode( 'SDK_VERSION_EXTENSION_METHODS', "Extension methods weren't supported until version 2.6.0, " "but this code is required to be able to run on earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ /* // #### Description // // The analyzer produces this diagnostic when the operator `>>>` is used in // code that has an SDK constraint whose lower bound is less than 2.X.0. This // operator wasn't supported in earlier versions, so this code won't be able // to run against earlier versions of the SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.X.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.0.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following produces this // diagnostic: // // ```dart // int x = 3 [!>>>!] 4; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the operator to be used: // // ```yaml // environment: // sdk: '>=2.3.2 <2.4.0' // ``` // // If you need to support older versions of the SDK, then rewrite the code to // not use the `>>>` operator: // // ```dart // int x = logicalShiftRight(3, 4); // // int logicalShiftRight(int leftOperand, int rightOperand) { // int divisor = 1 << rightOperand; // if (divisor == 0) { // return 0; // } // return leftOperand ~/ divisor; // } // ``` */ static const HintCode SDK_VERSION_GT_GT_GT_OPERATOR = const HintCode( 'SDK_VERSION_GT_GT_GT_OPERATOR', "The operator '>>>' wasn't supported until version 2.3.2, but this code " "is required to be able to run on earlier versions.", correction: "Try updating the SDK constraints."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an is expression inside a // [constant context](#constant-context) is found in code that has an SDK // constraint whose lower bound is less than 2.3.2. Using an is expression in // a [constant context](#constant-context) wasn't supported in earlier // versions, so this code won't be able to run against earlier versions of the // SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.3.2: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.1.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following generates // this diagnostic: // // ```dart // const x = 4; // const y = [!x is int!] ? 0 : 1; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the expression to be used: // // ```yaml // environment: // sdk: '>=2.3.2 <2.4.0' // ``` // // If you need to support older versions of the SDK, then either rewrite the // code to not use the is operator, or, if that's not possible, change the // code so that the is expression is not in a // [constant context](#constant-context).: // // ```dart // const x = 4; // var y = x is int ? 0 : 1; // ``` static const HintCode SDK_VERSION_IS_EXPRESSION_IN_CONST_CONTEXT = const HintCode( 'SDK_VERSION_IS_EXPRESSION_IN_CONST_CONTEXT', "The use of an is expression in a constant context wasn't supported " "until version 2.3.2, but this code is required to be able to run on " "earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a set literal is found in code // that has an SDK constraint whose lower bound is less than 2.2.0. Set // literals weren't supported in earlier versions, so this code won't be able // to run against earlier versions of the SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.2.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.1.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following produces this // diagnostic: // // ```dart // var s = [!<int>{}!]; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the syntax to be used: // // ```yaml // environment: // sdk: '>=2.2.0 <2.4.0' // ``` // // If you do need to support older versions of the SDK, then replace the set // literal with code that creates the set without the use of a literal: // // ```dart // var s = new Set<int>(); // ``` static const HintCode SDK_VERSION_SET_LITERAL = const HintCode( 'SDK_VERSION_SET_LITERAL', "Set literals weren't supported until version 2.2, but this code is " "required to be able to run on earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ /* // #### Description // // The analyzer produces this diagnostic when a reference to the class `Never` // is found in code that has an SDK constraint whose lower bound is less than // 2.X.0. This class wasn't defined in earlier versions, so this code won't be // able to run against earlier versions of the SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.X.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.5.0 <2.6.0' // ``` // // In the package that has that pubspec, code like the following produces this // diagnostic: // // ```dart // [!Never!] n; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the type to be used: // // ```yaml // environment: // sdk: '>=2.X.0 <2.7.0' // ``` // // If you need to support older versions of the SDK, then rewrite the code to // not reference this class: // // ```dart // dynamic x; // ``` */ static const HintCode SDK_VERSION_NEVER = const HintCode( // TODO(brianwilkerson) Replace the message with the following when we know // when this feature will ship: // The type 'Never' wasn't supported until version 2.X.0, but this code // is required to be able to run on earlier versions. 'SDK_VERSION_NEVER', "The type Never is not yet supported."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a for, if, or spread element is // found in code that has an SDK constraint whose lower bound is less than // 2.3.0. Using a for, if, or spread element wasn't supported in earlier // versions, so this code won't be able to run against earlier versions of the // SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.3.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.2.0 <2.4.0' // ``` // // In the package that has that pubspec, code like the following generates // this diagnostic: // // ```dart // var digits = [[!for (int i = 0; i < 10; i++) i!]]; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the syntax to be used: // // ```yaml // environment: // sdk: '>=2.3.0 <2.4.0' // ``` // // If you need to support older versions of the SDK, then rewrite the code to // not make use of those elements: // // ```dart // var digits = _initializeDigits(); // // List<int> _initializeDigits() { // var digits = <int>[]; // for (int i = 0; i < 10; i++) { // digits.add(i); // } // return digits; // } // ``` static const HintCode SDK_VERSION_UI_AS_CODE = const HintCode( 'SDK_VERSION_UI_AS_CODE', "The for, if, and spread elements weren't supported until version 2.2.2, " "but this code is required to be able to run on earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an if or spread element inside // a [constant context](#constant-context) is found in code that has an // SDK constraint whose lower bound is less than 2.5.0. Using an if or // spread element inside a [constant context](#constant-context) wasn't // supported in earlier versions, so this code won't be able to run against // earlier versions of the SDK. // // #### Example // // Here's an example of a pubspec that defines an SDK constraint with a lower // bound of less than 2.5.0: // // ```yaml // %uri="pubspec.yaml" // environment: // sdk: '>=2.4.0 <2.6.0' // ``` // // In the package that has that pubspec, code like the following generates // this diagnostic: // // ```dart // const a = [1, 2]; // const b = [[!...a!]]; // ``` // // #### Common fixes // // If you don't need to support older versions of the SDK, then you can // increase the SDK constraint to allow the syntax to be used: // // ```yaml // environment: // sdk: '>=2.5.0 <2.6.0' // ``` // // If you need to support older versions of the SDK, then rewrite the code to // not make use of those elements: // // ```dart // const a = [1, 2]; // const b = [1, 2]; // ``` // // If that's not possible, change the code so that the element is not in a // [constant context](#constant-context).: // // ```dart // const a = [1, 2]; // var b = [...a]; // ``` static const HintCode SDK_VERSION_UI_AS_CODE_IN_CONST_CONTEXT = const HintCode( 'SDK_VERSION_UI_AS_CODE_IN_CONST_CONTEXT', "The if and spread elements weren't supported in constant expressions " "until version 2.5.0, but this code is required to be able to run on " "earlier versions.", correction: "Try updating the SDK constraints.", hasPublishedDocs: true); /** * When "strict-raw-types" is enabled, raw types must be inferred via the * context type, or have type arguments. */ static const HintCode STRICT_RAW_TYPE = HintCode('STRICT_RAW_TYPE', "The generic type '{0}' should have explicit type arguments but doesn't.", correction: "Use explicit type arguments for '{0}'."); /** * This hint is generated anywhere where a `@sealed` class or mixin is used as * a super-type of a class. */ static const HintCode SUBTYPE_OF_SEALED_CLASS = const HintCode( 'SUBTYPE_OF_SEALED_CLASS', "The class '{0}' shouldn't be extended, mixed in, or implemented because " "it is sealed.", correction: "Try composing instead of inheriting, or refer to its documentation " "for more information."); /** * Type checks of the type `x is! Null` should be done with `x != null`. */ static const HintCode TYPE_CHECK_IS_NOT_NULL = const HintCode( 'TYPE_CHECK_IS_NOT_NULL', "Tests for non-null should be done with '!= null'.", correction: "Try replacing the 'is! Null' check with '!= null'."); /** * Type checks of the type `x is Null` should be done with `x == null`. */ static const HintCode TYPE_CHECK_IS_NULL = const HintCode( 'TYPE_CHECK_IS_NULL', "Tests for null should be done with '== null'.", correction: "Try replacing the 'is Null' check with '== null'."); /** * An undefined name hidden in an import or export directive. */ static const HintCode UNDEFINED_HIDDEN_NAME = const HintCode( 'UNDEFINED_HIDDEN_NAME', "The library '{0}' doesn't export a member with the hidden name '{1}'.", correction: "Try removing the name from the list of hidden members."); /** * An undefined name shown in an import or export directive. */ static const HintCode UNDEFINED_SHOWN_NAME = const HintCode( 'UNDEFINED_SHOWN_NAME', "The library '{0}' doesn't export a member with the shown name '{1}'.", correction: "Try removing the name from the list of shown members."); /** * Unnecessary cast. */ static const HintCode UNNECESSARY_CAST = const HintCode( 'UNNECESSARY_CAST', "Unnecessary cast.", correction: "Try removing the cast."); /** * Unnecessary `noSuchMethod` declaration. */ static const HintCode UNNECESSARY_NO_SUCH_METHOD = const HintCode( 'UNNECESSARY_NO_SUCH_METHOD', "Unnecessary 'noSuchMethod' declaration.", correction: "Try removing the declaration of 'noSuchMethod'."); /** * Unnecessary type checks, the result is always false. */ static const HintCode UNNECESSARY_TYPE_CHECK_FALSE = const HintCode( 'UNNECESSARY_TYPE_CHECK_FALSE', "Unnecessary type check, the result is always false.", correction: "Try correcting the type check, or removing the type check."); /** * Unnecessary type checks, the result is always true. */ static const HintCode UNNECESSARY_TYPE_CHECK_TRUE = const HintCode( 'UNNECESSARY_TYPE_CHECK_TRUE', "Unnecessary type check, the result is always true.", correction: "Try correcting the type check, or removing the type check."); /** * Unused catch exception variables. */ static const HintCode UNUSED_CATCH_CLAUSE = const HintCode( 'UNUSED_CATCH_CLAUSE', "The exception variable '{0}' isn't used, so the 'catch' clause can be " "removed.", // TODO(brianwilkerson) Split this error code so that we can differentiate // between removing the catch clause and replacing the catch clause with // an on clause. correction: "Try removing the catch clause."); /** * Unused catch stack trace variables. */ static const HintCode UNUSED_CATCH_STACK = const HintCode( 'UNUSED_CATCH_STACK', "The stack trace variable '{0}' isn't used and can be removed.", correction: "Try removing the stack trace variable, or using it."); /** * Parameters: * 0: the name that is declared but not referenced */ // #### Description // // The analyzer produces this diagnostic when a private class, enum, mixin, // typedef, top level variable, top level function, or method is declared but // never referenced. // // #### Example // // Assuming that no code in the library references `_C`, the following code // produces this diagnostic: // // ```dart // class [!_C!] {} // ``` // // #### Common fixes // // If the declaration isn't needed, then remove it. // // If the declaration was intended to be used, then add the missing code. static const HintCode UNUSED_ELEMENT = const HintCode( 'UNUSED_ELEMENT', "The declaration '{0}' isn't referenced.", correction: "Try removing the declaration of '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the unused field */ // #### Description // // The analyzer produces this diagnostic when a private field is declared but // never read, even if it's written in one or more places. // // #### Example // // The following code produces this diagnostic: // // ```dart // class Point { // int [!_x!]; // } // ``` // // #### Common fixes // // If the field isn't needed, then remove it. // // If the field was intended to be used, then add the missing code. static const HintCode UNUSED_FIELD = const HintCode( 'UNUSED_FIELD', "The value of the field '{0}' isn't used.", correction: "Try removing the field, or using it.", hasPublishedDocs: true); /** * Parameters: * 0: the content of the unused import's uri */ // #### Description // // The analyzer produces this diagnostic when an import isn't needed because // none of the names that are imported are referenced within the importing // library. // // #### Example // // The following code produces this diagnostic: // // ```dart // import [!'dart:async'!]; // // void main() {} // ``` // // #### Common fixes // // If the import isn't needed, then remove it. // // If some of the imported names are intended to be used, then add the missing // code. static const HintCode UNUSED_IMPORT = const HintCode( 'UNUSED_IMPORT', "Unused import: '{0}'.", correction: "Try removing the import directive.", hasPublishedDocs: true); /** * Unused labels are labels that are never referenced in either a 'break' or * 'continue' statement. */ static const HintCode UNUSED_LABEL = const HintCode('UNUSED_LABEL', "The label '{0}' isn't used.", correction: "Try removing the label, or " "using it in either a 'break' or 'continue' statement."); /** * Parameters: * 0: the name of the unused variable */ // #### Description // // The analyzer produces this diagnostic when a local variable is declared but // never read, even if it's written in one or more places. // // #### Example // // The following code produces this diagnostic: // // ```dart // void main() { // int [!count!] = 0; // } // ``` // // #### Common fixes // // If the variable isn't needed, then remove it. // // If the variable was intended to be used, then add the missing code. static const HintCode UNUSED_LOCAL_VARIABLE = const HintCode( 'UNUSED_LOCAL_VARIABLE', "The value of the local variable '{0}' isn't used.", correction: "Try removing the variable, or using it.", hasPublishedDocs: true); /** * Unused shown names are names shown on imports which are never used. */ static const HintCode UNUSED_SHOWN_NAME = const HintCode( 'UNUSED_SHOWN_NAME', "The name {0} is shown, but not used.", correction: "Try removing the name from the list of shown members."); /** * 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 HintCode(String name, String message, {String correction, bool hasPublishedDocs}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs); @override ErrorSeverity get errorSeverity => ErrorType.HINT.severity; @override ErrorType get type => ErrorType.HINT; } class HintCodeWithUniqueName extends HintCode { @override final String uniqueName; const HintCodeWithUniqueName(String name, this.uniqueName, String message, {String correction, bool hasPublishedDocs}) : super(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/error/syntactic_errors.g.dart
// // THIS FILE IS GENERATED. DO NOT EDIT. // // Instead modify 'pkg/front_end/messages.yaml' and run // 'dart pkg/analyzer/tool/messages/generate.dart' to update. part of 'syntactic_errors.dart'; final fastaAnalyzerErrorCodes = <ErrorCode>[ null, _EQUALITY_CANNOT_BE_EQUALITY_OPERAND, _CONTINUE_OUTSIDE_OF_LOOP, _EXTERNAL_CLASS, _STATIC_CONSTRUCTOR, _EXTERNAL_ENUM, _PREFIX_AFTER_COMBINATOR, _TYPEDEF_IN_CLASS, _EXPECTED_BODY, _INVALID_AWAIT_IN_FOR, _IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE, _WITH_BEFORE_EXTENDS, _VAR_RETURN_TYPE, _TYPE_ARGUMENTS_ON_TYPE_VARIABLE, _TOP_LEVEL_OPERATOR, _SWITCH_HAS_MULTIPLE_DEFAULT_CASES, _SWITCH_HAS_CASE_AFTER_DEFAULT_CASE, _STATIC_OPERATOR, _INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER, _STACK_OVERFLOW, _MISSING_CATCH_OR_FINALLY, _REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR, _REDIRECTING_CONSTRUCTOR_WITH_BODY, _NATIVE_CLAUSE_SHOULD_BE_ANNOTATION, _MULTIPLE_WITH_CLAUSES, _MULTIPLE_PART_OF_DIRECTIVES, _MULTIPLE_ON_CLAUSES, _MULTIPLE_LIBRARY_DIRECTIVES, _MULTIPLE_EXTENDS_CLAUSES, _MISSING_STATEMENT, _MISSING_PREFIX_IN_DEFERRED_IMPORT, _MISSING_KEYWORD_OPERATOR, _MISSING_EXPRESSION_IN_THROW, _MISSING_CONST_FINAL_VAR_OR_TYPE, _MISSING_ASSIGNMENT_IN_INITIALIZER, _MISSING_ASSIGNABLE_SELECTOR, _MISSING_INITIALIZER, _LIBRARY_DIRECTIVE_NOT_FIRST, _INVALID_UNICODE_ESCAPE, _INVALID_OPERATOR, _INVALID_HEX_ESCAPE, _EXPECTED_INSTEAD, _IMPLEMENTS_BEFORE_WITH, _IMPLEMENTS_BEFORE_ON, _IMPLEMENTS_BEFORE_EXTENDS, _ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE, _EXPECTED_ELSE_OR_COMMA, _INVALID_SUPER_IN_INITIALIZER, _EXPERIMENT_NOT_ENABLED, _EXTERNAL_METHOD_WITH_BODY, _EXTERNAL_FIELD, _ABSTRACT_CLASS_MEMBER, _BREAK_OUTSIDE_OF_LOOP, _CLASS_IN_CLASS, _COLON_IN_PLACE_OF_IN, _CONSTRUCTOR_WITH_RETURN_TYPE, _MODIFIER_OUT_OF_ORDER, _TYPE_BEFORE_FACTORY, _CONST_AND_FINAL, _CONFLICTING_MODIFIERS, _CONST_CLASS, _VAR_AS_TYPE_NAME, _CONST_FACTORY, _CONST_METHOD, _CONTINUE_WITHOUT_LABEL_IN_CASE, _INVALID_THIS_IN_INITIALIZER, _COVARIANT_AND_STATIC, _COVARIANT_MEMBER, _DEFERRED_AFTER_PREFIX, _DIRECTIVE_AFTER_DECLARATION, _DUPLICATED_MODIFIER, _DUPLICATE_DEFERRED, _DUPLICATE_LABEL_IN_SWITCH_STATEMENT, _DUPLICATE_PREFIX, _ENUM_IN_CLASS, _EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE, _EXTERNAL_TYPEDEF, _EXTRANEOUS_MODIFIER, _FACTORY_TOP_LEVEL_DECLARATION, _FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR, _FINAL_AND_COVARIANT, _FINAL_AND_VAR, _INITIALIZED_VARIABLE_IN_FOR_EACH, _CATCH_SYNTAX_EXTRA_PARAMETERS, _CATCH_SYNTAX, _EXTERNAL_FACTORY_REDIRECTION, _EXTERNAL_FACTORY_WITH_BODY, _EXTERNAL_CONSTRUCTOR_WITH_BODY, _FIELD_INITIALIZED_OUTSIDE_DECLARING_CLASS, _VAR_AND_TYPE, _INVALID_INITIALIZER, _ANNOTATION_WITH_TYPE_ARGUMENTS, _EXTENSION_DECLARES_CONSTRUCTOR, _EXTENSION_DECLARES_INSTANCE_FIELD, _EXTENSION_DECLARES_ABSTRACT_MEMBER, _MIXIN_DECLARES_CONSTRUCTOR, _NULL_AWARE_CASCADE_OUT_OF_ORDER, _MULTIPLE_VARIANCE_MODIFIERS, ]; const ParserErrorCode _ABSTRACT_CLASS_MEMBER = const ParserErrorCode( 'ABSTRACT_CLASS_MEMBER', r"Members of classes can't be declared to be 'abstract'.", correction: "Try removing the 'abstract' keyword. You can add the 'abstract' keyword before the class declaration."); const ParserErrorCode _ANNOTATION_WITH_TYPE_ARGUMENTS = const ParserErrorCode( 'ANNOTATION_WITH_TYPE_ARGUMENTS', r"An annotation (metadata) can't use type arguments."); const ParserErrorCode _BREAK_OUTSIDE_OF_LOOP = const ParserErrorCode( 'BREAK_OUTSIDE_OF_LOOP', r"A break statement can't be used outside of a loop or switch statement.", correction: "Try removing the break statement."); const ParserErrorCode _CATCH_SYNTAX = const ParserErrorCode('CATCH_SYNTAX', r"'catch' must be followed by '(identifier)' or '(identifier, identifier)'.", correction: "No types are needed, the first is given by 'on', the second is always 'StackTrace'."); const ParserErrorCode _CATCH_SYNTAX_EXTRA_PARAMETERS = const ParserErrorCode( 'CATCH_SYNTAX_EXTRA_PARAMETERS', r"'catch' must be followed by '(identifier)' or '(identifier, identifier)'.", correction: "No types are needed, the first is given by 'on', the second is always 'StackTrace'."); const ParserErrorCode _CLASS_IN_CLASS = const ParserErrorCode( 'CLASS_IN_CLASS', r"Classes can't be declared inside other classes.", correction: "Try moving the class to the top-level."); const ParserErrorCode _COLON_IN_PLACE_OF_IN = const ParserErrorCode( 'COLON_IN_PLACE_OF_IN', r"For-in loops use 'in' rather than a colon.", correction: "Try replacing the colon with the keyword 'in'."); const ParserErrorCode _CONFLICTING_MODIFIERS = const ParserErrorCode( 'CONFLICTING_MODIFIERS', r"Members can't be declared to be both '#string' and '#string2'.", correction: "Try removing one of the keywords."); const ParserErrorCode _CONSTRUCTOR_WITH_RETURN_TYPE = const ParserErrorCode( 'CONSTRUCTOR_WITH_RETURN_TYPE', r"Constructors can't have a return type.", correction: "Try removing the return type."); const ParserErrorCode _CONST_AND_FINAL = const ParserErrorCode( 'CONST_AND_FINAL', r"Members can't be declared to be both 'const' and 'final'.", correction: "Try removing either the 'const' or 'final' keyword."); const ParserErrorCode _CONST_CLASS = const ParserErrorCode( 'CONST_CLASS', r"Classes can't be declared to be 'const'.", correction: "Try removing the 'const' keyword. If you're trying to indicate that instances of the class can be constants, place the 'const' keyword on the class' constructor(s)."); const ParserErrorCode _CONST_FACTORY = const ParserErrorCode('CONST_FACTORY', r"Only redirecting factory constructors can be declared to be 'const'.", correction: "Try removing the 'const' keyword, or replacing the body with '=' followed by a valid target."); const ParserErrorCode _CONST_METHOD = const ParserErrorCode('CONST_METHOD', r"Getters, setters and methods can't be declared to be 'const'.", correction: "Try removing the 'const' keyword."); const ParserErrorCode _CONTINUE_OUTSIDE_OF_LOOP = const ParserErrorCode( 'CONTINUE_OUTSIDE_OF_LOOP', r"A continue statement can't be used outside of a loop or switch statement.", correction: "Try removing the continue statement."); const ParserErrorCode _CONTINUE_WITHOUT_LABEL_IN_CASE = const ParserErrorCode( 'CONTINUE_WITHOUT_LABEL_IN_CASE', r"A continue statement in a switch statement must have a label as a target.", correction: "Try adding a label associated with one of the case clauses to the continue statement."); const ParserErrorCode _COVARIANT_AND_STATIC = const ParserErrorCode( 'COVARIANT_AND_STATIC', r"Members can't be declared to be both 'covariant' and 'static'.", correction: "Try removing either the 'covariant' or 'static' keyword."); const ParserErrorCode _COVARIANT_MEMBER = const ParserErrorCode( 'COVARIANT_MEMBER', r"Getters, setters and methods can't be declared to be 'covariant'.", correction: "Try removing the 'covariant' keyword."); const ParserErrorCode _DEFERRED_AFTER_PREFIX = const ParserErrorCode( 'DEFERRED_AFTER_PREFIX', r"The deferred keyword should come immediately before the prefix ('as' clause).", correction: "Try moving the deferred keyword before the prefix."); const ParserErrorCode _DIRECTIVE_AFTER_DECLARATION = const ParserErrorCode( 'DIRECTIVE_AFTER_DECLARATION', r"Directives must appear before any declarations.", correction: "Try moving the directive before any declarations."); const ParserErrorCode _DUPLICATED_MODIFIER = const ParserErrorCode( 'DUPLICATED_MODIFIER', r"The modifier '#lexeme' was already specified.", correction: "Try removing all but one occurrence of the modifier."); const ParserErrorCode _DUPLICATE_DEFERRED = const ParserErrorCode( 'DUPLICATE_DEFERRED', r"An import directive can only have one 'deferred' keyword.", correction: "Try removing all but one 'deferred' keyword."); const ParserErrorCode _DUPLICATE_LABEL_IN_SWITCH_STATEMENT = const ParserErrorCode('DUPLICATE_LABEL_IN_SWITCH_STATEMENT', r"The label '#name' was already used in this switch statement.", correction: "Try choosing a different name for this label."); const ParserErrorCode _DUPLICATE_PREFIX = const ParserErrorCode( 'DUPLICATE_PREFIX', r"An import directive can only have one prefix ('as' clause).", correction: "Try removing all but one prefix."); const ParserErrorCode _ENUM_IN_CLASS = const ParserErrorCode( 'ENUM_IN_CLASS', r"Enums can't be declared inside classes.", correction: "Try moving the enum to the top-level."); const ParserErrorCode _EQUALITY_CANNOT_BE_EQUALITY_OPERAND = const ParserErrorCode( 'EQUALITY_CANNOT_BE_EQUALITY_OPERAND', r"A comparison expression can't be an operand of another comparison expression.", correction: "Try putting parentheses around one of the comparisons."); const ParserErrorCode _EXPECTED_BODY = const ParserErrorCode( 'EXPECTED_BODY', r"A #string must have a body, even if it is empty.", correction: "Try adding an empty body."); const ParserErrorCode _EXPECTED_ELSE_OR_COMMA = const ParserErrorCode( 'EXPECTED_ELSE_OR_COMMA', r"Expected 'else' or comma."); const ParserErrorCode _EXPECTED_INSTEAD = const ParserErrorCode( 'EXPECTED_INSTEAD', r"Expected '#string' instead of this."); const ParserErrorCode _EXPERIMENT_NOT_ENABLED = const ParserErrorCode( 'EXPERIMENT_NOT_ENABLED', r"This requires the '#string' experiment to be enabled.", correction: "Try enabling this experiment by adding it to the command line when compiling and running."); const ParserErrorCode _EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE = const ParserErrorCode('EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE', r"Export directives must precede part directives.", correction: "Try moving the export directives before the part directives."); const ParserErrorCode _EXTENSION_DECLARES_ABSTRACT_MEMBER = const ParserErrorCode('EXTENSION_DECLARES_ABSTRACT_MEMBER', r"Extensions can't declare abstract members.", correction: "Try providing an implementation for the member.", hasPublishedDocs: true); const ParserErrorCode _EXTENSION_DECLARES_CONSTRUCTOR = const ParserErrorCode( 'EXTENSION_DECLARES_CONSTRUCTOR', r"Extensions can't declare constructors.", correction: "Try removing the constructor declaration.", hasPublishedDocs: true); const ParserErrorCode _EXTENSION_DECLARES_INSTANCE_FIELD = const ParserErrorCode('EXTENSION_DECLARES_INSTANCE_FIELD', r"Extensions can't declare instance fields", correction: "Try removing the field declaration or making it a static field", hasPublishedDocs: true); const ParserErrorCode _EXTERNAL_CLASS = const ParserErrorCode( 'EXTERNAL_CLASS', r"Classes can't be declared to be 'external'.", correction: "Try removing the keyword 'external'."); const ParserErrorCode _EXTERNAL_CONSTRUCTOR_WITH_BODY = const ParserErrorCode( 'EXTERNAL_CONSTRUCTOR_WITH_BODY', r"External constructors can't have a body.", correction: "Try removing the body of the constructor, or removing the keyword 'external'."); const ParserErrorCode _EXTERNAL_ENUM = const ParserErrorCode( 'EXTERNAL_ENUM', r"Enums can't be declared to be 'external'.", correction: "Try removing the keyword 'external'."); const ParserErrorCode _EXTERNAL_FACTORY_REDIRECTION = const ParserErrorCode( 'EXTERNAL_FACTORY_REDIRECTION', r"A redirecting factory can't be external.", correction: "Try removing the 'external' modifier."); const ParserErrorCode _EXTERNAL_FACTORY_WITH_BODY = const ParserErrorCode( 'EXTERNAL_FACTORY_WITH_BODY', r"External factories can't have a body.", correction: "Try removing the body of the factory, or removing the keyword 'external'."); const ParserErrorCode _EXTERNAL_FIELD = const ParserErrorCode( 'EXTERNAL_FIELD', r"Fields can't be declared to be 'external'.", correction: "Try removing the keyword 'external', or replacing the field by an external getter and/or setter."); const ParserErrorCode _EXTERNAL_METHOD_WITH_BODY = const ParserErrorCode( 'EXTERNAL_METHOD_WITH_BODY', r"An external or native method can't have a body."); const ParserErrorCode _EXTERNAL_TYPEDEF = const ParserErrorCode( 'EXTERNAL_TYPEDEF', r"Typedefs can't be declared to be 'external'.", correction: "Try removing the keyword 'external'."); const ParserErrorCode _EXTRANEOUS_MODIFIER = const ParserErrorCode( 'EXTRANEOUS_MODIFIER', r"Can't have modifier '#lexeme' here.", correction: "Try removing '#lexeme'."); const ParserErrorCode _FACTORY_TOP_LEVEL_DECLARATION = const ParserErrorCode( 'FACTORY_TOP_LEVEL_DECLARATION', r"Top-level declarations can't be declared to be 'factory'.", correction: "Try removing the keyword 'factory'."); const ParserErrorCode _FIELD_INITIALIZED_OUTSIDE_DECLARING_CLASS = const ParserErrorCode('FIELD_INITIALIZED_OUTSIDE_DECLARING_CLASS', r"A field can only be initialized in its declaring class", correction: "Try passing a value into the superclass constructor, or moving the initialization into the constructor body."); const ParserErrorCode _FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR = const ParserErrorCode('FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR', r"Field formal parameters can only be used in a constructor.", correction: "Try removing 'this.'."); const ParserErrorCode _FINAL_AND_COVARIANT = const ParserErrorCode( 'FINAL_AND_COVARIANT', r"Members can't be declared to be both 'final' and 'covariant'.", correction: "Try removing either the 'final' or 'covariant' keyword."); const ParserErrorCode _FINAL_AND_VAR = const ParserErrorCode( 'FINAL_AND_VAR', r"Members can't be declared to be both 'final' and 'var'.", correction: "Try removing the keyword 'var'."); const ParserErrorCode _ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE = const ParserErrorCode('ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE', r"Illegal assignment to non-assignable expression."); const ParserErrorCode _IMPLEMENTS_BEFORE_EXTENDS = const ParserErrorCode( 'IMPLEMENTS_BEFORE_EXTENDS', r"The extends clause must be before the implements clause.", correction: "Try moving the extends clause before the implements clause."); const ParserErrorCode _IMPLEMENTS_BEFORE_ON = const ParserErrorCode( 'IMPLEMENTS_BEFORE_ON', r"The on clause must be before the implements clause.", correction: "Try moving the on clause before the implements clause."); const ParserErrorCode _IMPLEMENTS_BEFORE_WITH = const ParserErrorCode( 'IMPLEMENTS_BEFORE_WITH', r"The with clause must be before the implements clause.", correction: "Try moving the with clause before the implements clause."); const ParserErrorCode _IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE = const ParserErrorCode('IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE', r"Import directives must precede part directives.", correction: "Try moving the import directives before the part directives."); const ParserErrorCode _INITIALIZED_VARIABLE_IN_FOR_EACH = const ParserErrorCode( 'INITIALIZED_VARIABLE_IN_FOR_EACH', r"The loop variable in a for-each loop can't be initialized.", correction: "Try removing the initializer, or using a different kind of loop."); const ParserErrorCode _INVALID_AWAIT_IN_FOR = const ParserErrorCode( 'INVALID_AWAIT_IN_FOR', r"The keyword 'await' isn't allowed for a normal 'for' statement.", correction: "Try removing the keyword, or use a for-each statement."); const ParserErrorCode _INVALID_HEX_ESCAPE = const ParserErrorCode( 'INVALID_HEX_ESCAPE', r"An escape sequence starting with '\x' must be followed by 2 hexadecimal digits."); const ParserErrorCode _INVALID_INITIALIZER = const ParserErrorCode( 'INVALID_INITIALIZER', r"Not a valid initializer.", correction: "To initialize a field, use the syntax 'name = value'."); const ParserErrorCode _INVALID_OPERATOR = const ParserErrorCode( 'INVALID_OPERATOR', r"The string '#lexeme' isn't a user-definable operator."); const ParserErrorCode _INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER = const ParserErrorCode('INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER', r"The operator '?.' cannot be used with 'super' because 'super' cannot be null.", correction: "Try replacing '?.' with '.'"); const ParserErrorCode _INVALID_SUPER_IN_INITIALIZER = const ParserErrorCode( 'INVALID_SUPER_IN_INITIALIZER', r"Can only use 'super' in an initializer for calling the superclass constructor (e.g. 'super()' or 'super.namedConstructor()')"); const ParserErrorCode _INVALID_THIS_IN_INITIALIZER = const ParserErrorCode( 'INVALID_THIS_IN_INITIALIZER', r"Can only use 'this' in an initializer for field initialization (e.g. 'this.x = something') and constructor redirection (e.g. 'this()' or 'this.namedConstructor())"); const ParserErrorCode _INVALID_UNICODE_ESCAPE = const ParserErrorCode( 'INVALID_UNICODE_ESCAPE', r"An escape sequence starting with '\u' must be followed by 4 hexadecimal digits or from 1 to 6 digits between '{' and '}'."); const ParserErrorCode _LIBRARY_DIRECTIVE_NOT_FIRST = const ParserErrorCode( 'LIBRARY_DIRECTIVE_NOT_FIRST', r"The library directive must appear before all other directives.", correction: "Try moving the library directive before any other directives."); const ParserErrorCode _MISSING_ASSIGNABLE_SELECTOR = const ParserErrorCode( 'MISSING_ASSIGNABLE_SELECTOR', r"Missing selector such as '.identifier' or '[0]'.", correction: "Try adding a selector."); const ParserErrorCode _MISSING_ASSIGNMENT_IN_INITIALIZER = const ParserErrorCode('MISSING_ASSIGNMENT_IN_INITIALIZER', r"Expected an assignment after the field name.", correction: "To initialize a field, use the syntax 'name = value'."); const ParserErrorCode _MISSING_CATCH_OR_FINALLY = const ParserErrorCode( 'MISSING_CATCH_OR_FINALLY', r"A try block must be followed by an 'on', 'catch', or 'finally' clause.", correction: "Try adding either a catch or finally clause, or remove the try statement."); const ParserErrorCode _MISSING_CONST_FINAL_VAR_OR_TYPE = const ParserErrorCode( 'MISSING_CONST_FINAL_VAR_OR_TYPE', r"Variables must be declared using the keywords 'const', 'final', 'var' or a type name.", correction: "Try adding the name of the type of the variable or the keyword 'var'."); const ParserErrorCode _MISSING_EXPRESSION_IN_THROW = const ParserErrorCode( 'MISSING_EXPRESSION_IN_THROW', r"Missing expression after 'throw'.", correction: "Add an expression after 'throw' or use 'rethrow' to throw a caught exception"); const ParserErrorCode _MISSING_INITIALIZER = const ParserErrorCode('MISSING_INITIALIZER', r"Expected an initializer."); const ParserErrorCode _MISSING_KEYWORD_OPERATOR = const ParserErrorCode( 'MISSING_KEYWORD_OPERATOR', r"Operator declarations must be preceded by the keyword 'operator'.", correction: "Try adding the keyword 'operator'."); const ParserErrorCode _MISSING_PREFIX_IN_DEFERRED_IMPORT = const ParserErrorCode('MISSING_PREFIX_IN_DEFERRED_IMPORT', r"Deferred imports should have a prefix.", correction: "Try adding a prefix to the import by adding an 'as' clause."); const ParserErrorCode _MISSING_STATEMENT = const ParserErrorCode('MISSING_STATEMENT', r"Expected a statement."); const ParserErrorCode _MIXIN_DECLARES_CONSTRUCTOR = const ParserErrorCode( 'MIXIN_DECLARES_CONSTRUCTOR', r"Mixins can't declare constructors."); const ParserErrorCode _MODIFIER_OUT_OF_ORDER = const ParserErrorCode( 'MODIFIER_OUT_OF_ORDER', r"The modifier '#string' should be before the modifier '#string2'.", correction: "Try re-ordering the modifiers."); const ParserErrorCode _MULTIPLE_EXTENDS_CLAUSES = const ParserErrorCode( 'MULTIPLE_EXTENDS_CLAUSES', r"Each class definition can have at most one extends clause.", correction: "Try choosing one superclass and define your class to implement (or mix in) the others."); const ParserErrorCode _MULTIPLE_LIBRARY_DIRECTIVES = const ParserErrorCode( 'MULTIPLE_LIBRARY_DIRECTIVES', r"Only one library directive may be declared in a file.", correction: "Try removing all but one of the library directives."); const ParserErrorCode _MULTIPLE_ON_CLAUSES = const ParserErrorCode( 'MULTIPLE_ON_CLAUSES', r"Each mixin definition can have at most one on clause.", correction: "Try combining all of the on clauses into a single clause."); const ParserErrorCode _MULTIPLE_PART_OF_DIRECTIVES = const ParserErrorCode( 'MULTIPLE_PART_OF_DIRECTIVES', r"Only one part-of directive may be declared in a file.", correction: "Try removing all but one of the part-of directives."); const ParserErrorCode _MULTIPLE_VARIANCE_MODIFIERS = const ParserErrorCode( 'MULTIPLE_VARIANCE_MODIFIERS', r"Each type parameter can have at most one variance modifier.", correction: "Use at most one of the 'in', 'out', or 'inout' modifiers."); const ParserErrorCode _MULTIPLE_WITH_CLAUSES = const ParserErrorCode( 'MULTIPLE_WITH_CLAUSES', r"Each class definition can have at most one with clause.", correction: "Try combining all of the with clauses into a single clause."); const ParserErrorCode _NATIVE_CLAUSE_SHOULD_BE_ANNOTATION = const ParserErrorCode( 'NATIVE_CLAUSE_SHOULD_BE_ANNOTATION', r"Native clause in this form is deprecated.", correction: "Try removing this native clause and adding @native() or @native('native-name') before the declaration."); const ParserErrorCode _NULL_AWARE_CASCADE_OUT_OF_ORDER = const ParserErrorCode( 'NULL_AWARE_CASCADE_OUT_OF_ORDER', r"The '?..' cascade operator must be first in the cascade sequence.", correction: "Try moving the '?..' operator to be the first cascade operator in the sequence."); const ParserErrorCode _PREFIX_AFTER_COMBINATOR = const ParserErrorCode( 'PREFIX_AFTER_COMBINATOR', r"The prefix ('as' clause) should come before any show/hide combinators.", correction: "Try moving the prefix before the combinators."); const ParserErrorCode _REDIRECTING_CONSTRUCTOR_WITH_BODY = const ParserErrorCode( 'REDIRECTING_CONSTRUCTOR_WITH_BODY', r"Redirecting constructors can't have a body.", correction: "Try removing the body, or not making this a redirecting constructor."); const ParserErrorCode _REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR = const ParserErrorCode('REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR', r"Only factory constructor can specify '=' redirection.", correction: "Try making this a factory constructor, or remove the redirection."); const ParserErrorCode _STACK_OVERFLOW = const ParserErrorCode('STACK_OVERFLOW', r"The file has too many nested expressions or statements.", correction: "Try simplifying the code."); const ParserErrorCode _STATIC_CONSTRUCTOR = const ParserErrorCode( 'STATIC_CONSTRUCTOR', r"Constructors can't be static.", correction: "Try removing the keyword 'static'."); const ParserErrorCode _STATIC_OPERATOR = const ParserErrorCode( 'STATIC_OPERATOR', r"Operators can't be static.", correction: "Try removing the keyword 'static'."); const ParserErrorCode _SWITCH_HAS_CASE_AFTER_DEFAULT_CASE = const ParserErrorCode('SWITCH_HAS_CASE_AFTER_DEFAULT_CASE', r"The default case should be the last case in a switch statement.", correction: "Try moving the default case after the other case clauses."); const ParserErrorCode _SWITCH_HAS_MULTIPLE_DEFAULT_CASES = const ParserErrorCode('SWITCH_HAS_MULTIPLE_DEFAULT_CASES', r"The 'default' case can only be declared once.", correction: "Try removing all but one default case."); const ParserErrorCode _TOP_LEVEL_OPERATOR = const ParserErrorCode( 'TOP_LEVEL_OPERATOR', r"Operators must be declared within a class.", correction: "Try removing the operator, moving it to a class, or converting it to be a function."); const ParserErrorCode _TYPEDEF_IN_CLASS = const ParserErrorCode( 'TYPEDEF_IN_CLASS', r"Typedefs can't be declared inside classes.", correction: "Try moving the typedef to the top-level."); const ParserErrorCode _TYPE_ARGUMENTS_ON_TYPE_VARIABLE = const ParserErrorCode( 'TYPE_ARGUMENTS_ON_TYPE_VARIABLE', r"Can't use type arguments with type variable '#name'.", correction: "Try removing the type arguments."); const ParserErrorCode _TYPE_BEFORE_FACTORY = const ParserErrorCode( 'TYPE_BEFORE_FACTORY', r"Factory constructors cannot have a return type.", correction: "Try removing the type appearing before 'factory'."); const ParserErrorCode _VAR_AND_TYPE = const ParserErrorCode('VAR_AND_TYPE', r"Variables can't be declared using both 'var' and a type name.", correction: "Try removing 'var.'"); const ParserErrorCode _VAR_AS_TYPE_NAME = const ParserErrorCode( 'VAR_AS_TYPE_NAME', r"The keyword 'var' can't be used as a type name."); const ParserErrorCode _VAR_RETURN_TYPE = const ParserErrorCode( 'VAR_RETURN_TYPE', r"The return type can't be 'var'.", correction: "Try removing the keyword 'var', or replacing it with the name of the return type."); const ParserErrorCode _WITH_BEFORE_EXTENDS = const ParserErrorCode( 'WITH_BEFORE_EXTENDS', r"The extends clause must be before the with clause.", correction: "Try moving the extends clause before the with clause.");
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/error/lint_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'; /** * Defines style and best practice recommendations. * * Unlike [HintCode]s, which are akin to traditional static warnings from a * compiler, lint recommendations focus on matters of style and practices that * might aggregated to define a project's style guide. */ class LintCode extends ErrorCode { const LintCode(String name, String message, {String correction}) : super.temporary(name, message, correction: correction); @override ErrorSeverity get errorSeverity => ErrorSeverity.INFO; @override ErrorType get type => ErrorType.LINT; /** * Overridden so that [LintCode] and its subclasses share the same uniqueName * pattern (we know how to identify a lint even if we don't know the specific * subclass the lint's code is defined in. */ String get uniqueName => "LintCode.$name"; @override String get url => 'https://dart-lang.github.io/linter/lints/${name.toLowerCase()}.html'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/scanner/scanner.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/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/error/syntactic_errors.dart'; import 'package:analyzer/src/dart/scanner/reader.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:front_end/src/fasta/scanner.dart' as fasta; import 'package:front_end/src/scanner/errors.dart' show translateErrorToken; import 'package:front_end/src/scanner/token.dart' show Token, TokenType; import 'package:pub_semver/pub_semver.dart'; export 'package:analyzer/src/dart/error/syntactic_errors.dart'; /** * The class `Scanner` implements a scanner for Dart code. * * The lexical structure of Dart is ambiguous without knowledge of the context * in which a token is being scanned. For example, without context we cannot * determine whether source of the form "<<" should be scanned as a single * left-shift operator or as two left angle brackets. This scanner does not have * any context, so it always resolves such conflicts by scanning the longest * possible token. */ class Scanner { final Source source; /** * The text to be scanned. */ final String _contents; /** * The offset of the first character from the reader. */ final int _readerOffset; /** * The error listener that will be informed of any errors that are found * during the scan. */ final AnalysisErrorListener _errorListener; /** * The flag specifying whether documentation comments should be parsed. */ bool _preserveComments = true; final List<int> lineStarts = <int>[]; Token firstToken; /** * A flag indicating whether the scanner should recognize the `>>>` operator * and the `>>>=` operator. * * Use [configureFeatures] rather than this field. */ bool enableGtGtGt = false; /** * A flag indicating whether the scanner should recognize the `late` and * `required` keywords. * * Use [configureFeatures] rather than this field. */ bool enableNonNullable = false; FeatureSet _featureSet; /** * Initialize a newly created scanner to scan characters from the given * [source]. The given character [reader] will be used to read the characters * in the source. The given [_errorListener] will be informed of any errors * that are found. */ factory Scanner(Source source, CharacterReader reader, AnalysisErrorListener errorListener) => new Scanner.fasta(source, errorListener, contents: reader.getContents(), offset: reader.offset); factory Scanner.fasta(Source source, AnalysisErrorListener errorListener, {String contents, int offset: -1}) { return new Scanner._( source, contents ?? source.contents.data, offset, errorListener); } Scanner._( this.source, this._contents, this._readerOffset, this._errorListener) { lineStarts.add(0); } /** * The features associated with this scanner. * * If a language version comment (e.g. '// @dart = 2.3') is detected * when calling [tokenize] and this field is non-null, then this field * will be updated to contain a downgraded feature set based upon the * language version specified. * * Use [configureFeatures] to set the features. */ FeatureSet get featureSet => _featureSet; set preserveComments(bool preserveComments) { this._preserveComments = preserveComments; } /// Configures the scanner appropriately for the given [featureSet]. /// /// TODO(paulberry): stop exposing `enableGtGtGt` and `enableNonNullable` so /// that callers are forced to use this API. Note that this would be a /// breaking change. void configureFeatures(FeatureSet featureSet) { this._featureSet = featureSet; enableGtGtGt = featureSet.isEnabled(Feature.triple_shift); enableNonNullable = featureSet.isEnabled(Feature.non_nullable); } void reportError( ScannerErrorCode errorCode, int offset, List<Object> arguments) { _errorListener .onError(new AnalysisError(source, offset, 1, errorCode, arguments)); } void setSourceStart(int line, int column) { int offset = _readerOffset; if (line < 1 || column < 1 || offset < 0 || (line + column - 2) >= offset) { return; } lineStarts.removeAt(0); for (int i = 2; i < line; i++) { lineStarts.add(1); } lineStarts.add(offset - column + 1); } /// The fasta parser handles error tokens produced by the scanner /// but the old parser used by angular does not /// and expects that scanner errors to be reported by this method. /// Set [reportScannerErrors] `true` when using the old parser. Token tokenize({bool reportScannerErrors = true}) { fasta.ScannerResult result = fasta.scanString(_contents, configuration: _featureSet != null ? buildConfig(_featureSet) : fasta.ScannerConfiguration( enableTripleShift: enableGtGtGt, enableNonNullable: enableNonNullable), includeComments: _preserveComments, languageVersionChanged: _languageVersionChanged); // fasta pretends there is an additional line at EOF result.lineStarts.removeLast(); // for compatibility, there is already a first entry in lineStarts result.lineStarts.removeAt(0); lineStarts.addAll(result.lineStarts); fasta.Token token = result.tokens; // The fasta parser handles error tokens produced by the scanner // but the old parser used by angular does not // and expects that scanner errors to be reported here if (reportScannerErrors) { // The default recovery strategy used by scanString // places all error tokens at the head of the stream. while (token.type == TokenType.BAD_INPUT) { translateErrorToken(token, reportError); token = token.next; } } firstToken = token; // Update all token offsets based upon the reader's starting offset if (_readerOffset != -1) { final int delta = _readerOffset + 1; do { token.offset += delta; token = token.next; } while (!token.isEof); } return firstToken; } void _languageVersionChanged( fasta.Scanner scanner, fasta.LanguageVersionToken languageVersion) { if (_featureSet != null) { _featureSet = _featureSet.restrictToVersion( Version(languageVersion.major, languageVersion.minor, 0)); scanner.configuration = buildConfig(_featureSet); } } /// Return a ScannerConfiguration based upon the specified feature set. static fasta.ScannerConfiguration buildConfig(FeatureSet featureSet) => featureSet == null ? fasta.ScannerConfiguration() : fasta.ScannerConfiguration( enableExtensionMethods: featureSet.isEnabled(Feature.extension_methods), enableTripleShift: featureSet.isEnabled(Feature.triple_shift), enableNonNullable: featureSet.isEnabled(Feature.non_nullable)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/scanner/reader.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:front_end/src/scanner/reader.dart'; export 'package:front_end/src/scanner/reader.dart' show CharacterReader, CharSequenceReader, SubSequenceReader; /** * A [CharacterReader] that reads a range of characters from another character * reader. */ class CharacterRangeReader extends CharacterReader { /** * The reader from which the characters are actually being read. */ final CharacterReader baseReader; /** * The first character to be read. */ final int startIndex; /** * The last character to be read. */ final int endIndex; /** * Initialize a newly created reader to read the characters from the given * [baseReader] between the [startIndex] inclusive to [endIndex] exclusive. */ CharacterRangeReader(this.baseReader, this.startIndex, this.endIndex) { baseReader.offset = startIndex - 1; } @override int get offset => baseReader.offset; @override void set offset(int offset) { baseReader.offset = offset; } @override int advance() { if (baseReader.offset + 1 >= endIndex) { return -1; } return baseReader.advance(); } @override String getContents() => baseReader.getContents().substring(startIndex, endIndex); @override String getString(int start, int endDelta) => baseReader.getString(start, endDelta); @override int peek() { if (baseReader.offset + 1 >= endIndex) { return -1; } return baseReader.peek(); } }
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/plugin/resolver_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 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/generated/source.dart'; /** * A function that will return a [UriResolver] that can be used to resolve a * specific kind of URI within the analysis context rooted at the given * [folder]. */ typedef UriResolver ResolverProvider(Folder folder);
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/plugin/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. /// Support for client code that wants to consume options contributed to the /// analysis options file. import 'package:analyzer/error/listener.dart'; import 'package:yaml/yaml.dart'; /// Validates options as defined in an analysis options file. /// /// The options file format is intentionally very open-ended, giving clients /// utmost flexibility in defining their own options. The only hard and fast /// expectation is that options files will contain a mapping from Strings /// (identifying 'scopes') to associated options. For example, the given /// content /// /// linter: /// rules: /// camel_case_types: true /// compiler: /// resolver: /// useMultiPackage: true /// packagePaths: /// - /foo/bar/pkg /// - /bar/baz/pkg /// /// defines two scopes, `linter` and `compiler`. Parsing would result in a /// map, mapping the `linter` and `compiler` scope identifiers to their /// respective parsed option node contents. Extracting values is a simple /// matter of inspecting the parsed nodes. For example, testing whether the /// compiler's resolver is set to use the `useMultiPackage` option might look /// something like this (eliding error-checking): /// /// bool useMultiPackage = /// options['compiler']['resolver']['useMultiPackage']; /// /// Clients may implement this class when implementing plugins. /// abstract class OptionsValidator { /// Validate [options], reporting any errors to the given [reporter]. void validate(ErrorReporter reporter, YamlMap options); }
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/summary/idl.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. /// This file is an "idl" style description of the summary format. It /// contains abstract classes which declare the interface for reading data from /// summaries. It is parsed and transformed into code that implements the /// summary format. /// /// The code generation process introduces the following semantics: /// - Getters of type List never return null, and have a default value of the /// empty list. /// - Getters of type int return unsigned 32-bit integers, never null, and have /// a default value of zero. /// - Getters of type String never return null, and have a default value of ''. /// - Getters of type bool never return null, and have a default value of false. /// - Getters of type double never return null, and have a default value of /// `0.0`. /// - Getters whose type is an enum never return null, and have a default value /// of the first value declared in the enum. /// /// Terminology used in this document: /// - "Unlinked" refers to information that can be determined from reading a /// single .dart file in isolation. /// - "Prelinked" refers to information that can be determined from the defining /// compilation unit of a library, plus direct imports, plus the transitive /// closure of exports reachable from those libraries, plus all part files /// constituting those libraries. /// - "Linked" refers to all other information; in theory, this information may /// depend on all files in the transitive import/export closure. However, in /// practice we expect that the number of additional dependencies will usually /// be small, since the additional dependencies only need to be consulted for /// type propagation, type inference, and constant evaluation, which typically /// have short dependency chains. /// /// Since we expect "linked" and "prelinked" dependencies to be similar, we only /// rarely distinguish between them; most information is that is not "unlinked" /// is typically considered "linked" for simplicity. /// /// Except as otherwise noted, synthetic elements are not stored in the summary; /// they are re-synthesized at the time the summary is read. import 'package:analyzer/dart/element/element.dart'; import 'base.dart' as base; import 'base.dart' show Id, TopLevel, Variant, VariantId; import 'format.dart' as generated; /// Annotation describing information which is not part of Dart semantics; in /// other words, if this information (or any information it refers to) changes, /// static analysis and runtime behavior of the library are unaffected. /// /// Information that has purely local effect (in other words, it does not affect /// the API of the code being analyzed) is also marked as `informative`. const informative = null; /// Information about the context of an exception in analysis driver. @TopLevel('ADEC') abstract class AnalysisDriverExceptionContext extends base.SummaryClass { factory AnalysisDriverExceptionContext.fromBuffer(List<int> buffer) => generated.readAnalysisDriverExceptionContext(buffer); /// The exception string. @Id(1) String get exception; /// The state of files when the exception happened. @Id(3) List<AnalysisDriverExceptionFile> get files; /// The path of the file being analyzed when the exception happened. @Id(0) String get path; /// The exception stack trace string. @Id(2) String get stackTrace; } /// Information about a single file in [AnalysisDriverExceptionContext]. abstract class AnalysisDriverExceptionFile extends base.SummaryClass { /// The content of the file. @Id(1) String get content; /// The path of the file. @Id(0) String get path; } /// Information about a resolved unit. @TopLevel('ADRU') abstract class AnalysisDriverResolvedUnit extends base.SummaryClass { factory AnalysisDriverResolvedUnit.fromBuffer(List<int> buffer) => generated.readAnalysisDriverResolvedUnit(buffer); /// The full list of analysis errors, both syntactic and semantic. @Id(0) List<AnalysisDriverUnitError> get errors; /// The index of the unit. @Id(1) AnalysisDriverUnitIndex get index; } /// Information about a subtype of one or more classes. abstract class AnalysisDriverSubtype extends base.SummaryClass { /// The names of defined instance members. /// They are indexes into [AnalysisDriverUnitError.strings] list. /// The list is sorted in ascending order. @Id(1) List<int> get members; /// The name of the class. /// It is an index into [AnalysisDriverUnitError.strings] list. @Id(0) int get name; } /// Information about an error in a resolved unit. abstract class AnalysisDriverUnitError extends base.SummaryClass { /// The context messages associated with the error. @Id(5) List<DiagnosticMessage> get contextMessages; /// The optional correction hint for the error. @Id(4) String get correction; /// The length of the error in the file. @Id(1) int get length; /// The message of the error. @Id(3) String get message; /// The offset from the beginning of the file. @Id(0) int get offset; /// The unique name of the error code. @Id(2) String get uniqueName; } /// Information about a resolved unit. @TopLevel('ADUI') abstract class AnalysisDriverUnitIndex extends base.SummaryClass { factory AnalysisDriverUnitIndex.fromBuffer(List<int> buffer) => generated.readAnalysisDriverUnitIndex(buffer); /// Each item of this list corresponds to a unique referenced element. It is /// the kind of the synthetic element. @Id(4) List<IndexSyntheticElementKind> get elementKinds; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the class member element name, or `null` if the element /// is a top-level element. The list is sorted in ascending order, so that /// the client can quickly check whether an element is referenced in this /// index. @Id(7) List<int> get elementNameClassMemberIds; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the named parameter name, or `null` if the element is /// not a named parameter. The list is sorted in ascending order, so that the /// client can quickly check whether an element is referenced in this index. @Id(8) List<int> get elementNameParameterIds; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the top-level element name, or `null` if the element is /// the unit. The list is sorted in ascending order, so that the client can /// quickly check whether an element is referenced in this index. @Id(6) List<int> get elementNameUnitMemberIds; /// Each item of this list corresponds to a unique referenced element. It is /// the index into [unitLibraryUris] and [unitUnitUris] for the library /// specific unit where the element is declared. @Id(5) List<int> get elementUnits; /// Identifier of the null string in [strings]. @Id(1) int get nullStringId; /// List of unique element strings used in this index. The list is sorted in /// ascending order, so that the client can quickly check the presence of a /// string in this index. @Id(0) List<String> get strings; /// The list of classes declared in the unit. @Id(19) List<AnalysisDriverSubtype> get subtypes; /// The identifiers of supertypes of elements at corresponding indexes /// in [subtypes]. They are indexes into [strings] list. The list is sorted /// in ascending order. There might be more than one element with the same /// value if there is more than one subtype of this supertype. @Id(18) List<int> get supertypes; /// Each item of this list corresponds to the library URI of a unique library /// specific unit referenced in the index. It is an index into [strings] /// list. @Id(2) List<int> get unitLibraryUris; /// Each item of this list corresponds to the unit URI of a unique library /// specific unit referenced in the index. It is an index into [strings] /// list. @Id(3) List<int> get unitUnitUris; /// Each item of this list is the `true` if the corresponding element usage /// is qualified with some prefix. @Id(13) List<bool> get usedElementIsQualifiedFlags; /// Each item of this list is the kind of the element usage. @Id(10) List<IndexRelationKind> get usedElementKinds; /// Each item of this list is the length of the element usage. @Id(12) List<int> get usedElementLengths; /// Each item of this list is the offset of the element usage relative to the /// beginning of the file. @Id(11) List<int> get usedElementOffsets; /// Each item of this list is the index into [elementUnits], /// [elementNameUnitMemberIds], [elementNameClassMemberIds] and /// [elementNameParameterIds]. The list is sorted in ascending order, so /// that the client can quickly find element references in this index. @Id(9) List<int> get usedElements; /// Each item of this list is the `true` if the corresponding name usage /// is qualified with some prefix. @Id(17) List<bool> get usedNameIsQualifiedFlags; /// Each item of this list is the kind of the name usage. @Id(15) List<IndexRelationKind> get usedNameKinds; /// Each item of this list is the offset of the name usage relative to the /// beginning of the file. @Id(16) List<int> get usedNameOffsets; /// Each item of this list is the index into [strings] for a used name. The /// list is sorted in ascending order, so that the client can quickly find /// whether a name is used in this index. @Id(14) List<int> get usedNames; } /// Information about an unlinked unit. @TopLevel('ADUU') abstract class AnalysisDriverUnlinkedUnit extends base.SummaryClass { factory AnalysisDriverUnlinkedUnit.fromBuffer(List<int> buffer) => generated.readAnalysisDriverUnlinkedUnit(buffer); /// List of class member names defined by the unit. @Id(3) List<String> get definedClassMemberNames; /// List of top-level names defined by the unit. @Id(2) List<String> get definedTopLevelNames; /// List of external names referenced by the unit. @Id(0) List<String> get referencedNames; /// List of names which are used in `extends`, `with` or `implements` clauses /// in the file. Import prefixes and type arguments are not included. @Id(4) List<String> get subtypedNames; /// Unlinked information for the unit. @Id(1) UnlinkedUnit get unit; /// Unlinked information for the unit. @Id(5) UnlinkedUnit2 get unit2; } /// Information about a single declaration. abstract class AvailableDeclaration extends base.SummaryClass { @Id(0) List<AvailableDeclaration> get children; @Id(1) int get codeLength; @Id(2) int get codeOffset; @Id(3) String get defaultArgumentListString; @Id(4) List<int> get defaultArgumentListTextRanges; @Id(5) String get docComplete; @Id(6) String get docSummary; @Id(7) int get fieldMask; @Id(8) bool get isAbstract; @Id(9) bool get isConst; @Id(10) bool get isDeprecated; @Id(11) bool get isFinal; /// The kind of the declaration. @Id(12) AvailableDeclarationKind get kind; @Id(13) int get locationOffset; @Id(14) int get locationStartColumn; @Id(15) int get locationStartLine; /// The first part of the declaration name, usually the only one, for example /// the name of a class like `MyClass`, or a function like `myFunction`. @Id(16) String get name; @Id(17) List<String> get parameterNames; @Id(18) String get parameters; @Id(19) List<String> get parameterTypes; /// The partial list of relevance tags. Not every declaration has one (for /// example, function do not currently), and not every declaration has to /// store one (for classes it can be computed when we know the library that /// includes this file). @Id(20) List<String> get relevanceTags; @Id(21) int get requiredParameterCount; @Id(22) String get returnType; @Id(23) String get typeParameters; } /// Enum of declaration kinds in available files. enum AvailableDeclarationKind { CLASS, CLASS_TYPE_ALIAS, CONSTRUCTOR, ENUM, ENUM_CONSTANT, EXTENSION, FIELD, FUNCTION, FUNCTION_TYPE_ALIAS, GETTER, METHOD, MIXIN, SETTER, VARIABLE } /// Information about an available, even if not yet imported file. @TopLevel('UICF') abstract class AvailableFile extends base.SummaryClass { factory AvailableFile.fromBuffer(List<int> buffer) => generated.readAvailableFile(buffer); /// Declarations of the file. @Id(0) List<AvailableDeclaration> get declarations; /// The Dartdoc directives in the file. @Id(1) DirectiveInfo get directiveInfo; /// Exports directives of the file. @Id(2) List<AvailableFileExport> get exports; /// Is `true` if this file is a library. @Id(3) bool get isLibrary; /// Is `true` if this file is a library, and it is deprecated. @Id(4) bool get isLibraryDeprecated; /// Offsets of the first character of each line in the source code. @informative @Id(5) List<int> get lineStarts; /// URIs of `part` directives. @Id(6) List<String> get parts; } /// Information about an export directive. abstract class AvailableFileExport extends base.SummaryClass { /// Combinators contained in this export directive. @Id(1) List<AvailableFileExportCombinator> get combinators; /// URI of the exported library. @Id(0) String get uri; } /// Information about a `show` or `hide` combinator in an export directive. abstract class AvailableFileExportCombinator extends base.SummaryClass { /// List of names which are hidden. Empty if this is a `show` combinator. @Id(1) List<String> get hides; /// List of names which are shown. Empty if this is a `hide` combinator. @Id(0) List<String> get shows; } /// Information about an element code range. abstract class CodeRange extends base.SummaryClass { /// Length of the element code. @Id(1) int get length; /// Offset of the element code relative to the beginning of the file. @Id(0) int get offset; } abstract class DiagnosticMessage extends base.SummaryClass { /// The absolute and normalized path of the file associated with this message. @Id(0) String get filePath; /// The length of the source range associated with this message. @Id(1) int get length; /// The text of the message. @Id(2) String get message; /// The zero-based offset from the start of the file to the beginning of the /// source range associated with this message. @Id(3) int get offset; } /// Information about the Dartdoc directives in an [AvailableFile]. abstract class DirectiveInfo extends base.SummaryClass { /// The names of the defined templates. @Id(0) List<String> get templateNames; /// The values of the defined templates. @Id(1) List<String> get templateValues; } /// Summary information about a reference to an entity such as a type, top level /// executable, or executable within a class. abstract class EntityRef extends base.SummaryClass { /// The kind of entity being represented. @Id(8) EntityRefKind get entityKind; /// Notice: This will be deprecated. However, its not deprecated yet, as we're /// keeping it for backwards compatibilty, and marking it deprecated makes it /// unreadable. /// /// TODO(mfairhurst) mark this deprecated, and remove its logic. /// /// If this is a reference to a function type implicitly defined by a /// function-typed parameter, a list of zero-based indices indicating the path /// from the entity referred to by [reference] to the appropriate type /// parameter. Otherwise the empty list. /// /// If there are N indices in this list, then the entity being referred to is /// the function type implicitly defined by a function-typed parameter of a /// function-typed parameter, to N levels of nesting. The first index in the /// list refers to the outermost level of nesting; for example if [reference] /// refers to the entity defined by: /// /// void f(x, void g(y, z, int h(String w))) { ... } /// /// Then to refer to the function type implicitly defined by parameter `h` /// (which is parameter 2 of parameter 1 of `f`), then /// [implicitFunctionTypeIndices] should be [1, 2]. /// /// Note that if the entity being referred to is a generic method inside a /// generic class, then the type arguments in [typeArguments] are applied /// first to the class and then to the method. @Id(4) List<int> get implicitFunctionTypeIndices; /// If the reference represents a type, the nullability of the type. @Id(10) EntityRefNullabilitySuffix get nullabilitySuffix; /// If this is a reference to a type parameter, one-based index into the list /// of [UnlinkedTypeParam]s currently in effect. Indexing is done using De /// Bruijn index conventions; that is, innermost parameters come first, and /// if a class or method has multiple parameters, they are indexed from right /// to left. So for instance, if the enclosing declaration is /// /// class C<T,U> { /// m<V,W> { /// ... /// } /// } /// /// Then [paramReference] values of 1, 2, 3, and 4 represent W, V, U, and T, /// respectively. /// /// If the type being referred to is not a type parameter, [paramReference] is /// zero. @Id(3) int get paramReference; /// Index into [UnlinkedUnit.references] for the entity being referred to, or /// zero if this is a reference to a type parameter. @Id(0) int get reference; /// If this [EntityRef] appears in a syntactic context where its type /// arguments might need to be inferred by a method other than /// instantiate-to-bounds, and [typeArguments] is empty, a slot id (which is /// unique within the compilation unit). If an entry appears in /// [LinkedUnit.types] whose [slot] matches this value, that entry will /// contain the complete inferred type. /// /// This is called `refinedSlot` to clarify that if it points to an inferred /// type, it points to a type that is a "refinement" of this one (one in which /// some type arguments have been inferred). @Id(9) int get refinedSlot; /// If this [EntityRef] is contained within [LinkedUnit.types], slot id (which /// is unique within the compilation unit) identifying the target of type /// propagation or type inference with which this [EntityRef] is associated. /// /// Otherwise zero. @Id(2) int get slot; /// If this [EntityRef] is a reference to a function type whose /// [FunctionElement] is not in any library (e.g. a function type that was /// synthesized by a LUB computation), the function parameters. Otherwise /// empty. @Id(6) List<UnlinkedParam> get syntheticParams; /// If this [EntityRef] is a reference to a function type whose /// [FunctionElement] is not in any library (e.g. a function type that was /// synthesized by a LUB computation), the return type of the function. /// Otherwise `null`. @Id(5) EntityRef get syntheticReturnType; /// If this is an instantiation of a generic type or generic executable, the /// type arguments used to instantiate it (if any). @Id(1) List<EntityRef> get typeArguments; /// If this is a function type, the type parameters defined for the function /// type (if any). @Id(7) List<UnlinkedTypeParam> get typeParameters; } /// Enum used to indicate the kind of an entity reference. enum EntityRefKind { /// The entity represents a named type. named, /// The entity represents a generic function type. genericFunctionType, /// The entity represents a function type that was synthesized by a LUB /// computation. syntheticFunction } /// Enum representing nullability suffixes in summaries. /// /// This enum is similar to [NullabilitySuffix], but the order is different so /// that [EntityRefNullabilitySuffix.starOrIrrelevant] can be the default. enum EntityRefNullabilitySuffix { /// An indication that the canonical representation of the type under /// consideration ends with `*`. Types having this nullability suffix are /// called "legacy types"; it has not yet been determined whether they should /// be unioned with the Null type. /// /// Also used in circumstances where no nullability suffix information is /// needed. starOrIrrelevant, /// An indication that the canonical representation of the type under /// consideration ends with `?`. Types having this nullability suffix should /// be interpreted as being unioned with the Null type. question, /// An indication that the canonical representation of the type under /// consideration does not end with either `?` or `*`. none, } /// Enum used to indicate the kind of a name in index. enum IndexNameKind { /// A top-level element. topLevel, /// A class member. classMember } /// Enum used to indicate the kind of an index relation. enum IndexRelationKind { /// Left: class. /// Is ancestor of (is extended or implemented, directly or indirectly). /// Right: other class declaration. IS_ANCESTOR_OF, /// Left: class. /// Is extended by. /// Right: other class declaration. IS_EXTENDED_BY, /// Left: class. /// Is implemented by. /// Right: other class declaration. IS_IMPLEMENTED_BY, /// Left: class. /// Is mixed into. /// Right: other class declaration. IS_MIXED_IN_BY, /// Left: method, property accessor, function, variable. /// Is invoked at. /// Right: location. IS_INVOKED_BY, /// Left: any element. /// Is referenced (and not invoked, read/written) at. /// Right: location. IS_REFERENCED_BY, /// Left: unresolved member name. /// Is read at. /// Right: location. IS_READ_BY, /// Left: unresolved member name. /// Is both read and written at. /// Right: location. IS_READ_WRITTEN_BY, /// Left: unresolved member name. /// Is written at. /// Right: location. IS_WRITTEN_BY } /// When we need to reference a synthetic element in [PackageIndex] we use a /// value of this enum to specify which kind of the synthetic element we /// actually reference. enum IndexSyntheticElementKind { /// Not a synthetic element. notSynthetic, /// The unnamed synthetic constructor a class element. constructor, /// The synthetic field element. field, /// The synthetic getter of a property introducing element. getter, /// The synthetic setter of a property introducing element. setter, /// The synthetic top-level variable element. topLevelVariable, /// The synthetic `loadLibrary` element. loadLibrary, /// The synthetic `index` getter of an enum. enumIndex, /// The synthetic `values` getter of an enum. enumValues, /// The synthetic `toString` method of an enum. enumToString, /// The containing unit itself. unit } /// Information about a dependency that exists between one library and another /// due to an "import" declaration. abstract class LinkedDependency extends base.SummaryClass { /// Absolute URI for the compilation units listed in the library's `part` /// declarations, empty string for invalid URI. @Id(1) List<String> get parts; /// The absolute URI of the dependent library, e.g. `package:foo/bar.dart`. @Id(0) String get uri; } /// Information about a single name in the export namespace of the library that /// is not in the public namespace. abstract class LinkedExportName extends base.SummaryClass { /// Index into [LinkedLibrary.dependencies] for the library in which the /// entity is defined. @Id(0) int get dependency; /// The kind of the entity being referred to. @Id(3) ReferenceKind get kind; /// Name of the exported entity. For an exported setter, this name includes /// the trailing '='. @Id(1) String get name; /// Integer index indicating which unit in the exported library contains the /// definition of the entity. As with indices into [LinkedLibrary.units], /// zero represents the defining compilation unit, and nonzero values /// represent parts in the order of the corresponding `part` declarations. @Id(2) int get unit; } /// Linked summary of a library. @TopLevel('LLib') abstract class LinkedLibrary extends base.SummaryClass { factory LinkedLibrary.fromBuffer(List<int> buffer) => generated.readLinkedLibrary(buffer); /// The libraries that this library depends on (either via an explicit import /// statement or via the implicit dependencies on `dart:core` and /// `dart:async`). The first element of this array is a pseudo-dependency /// representing the library itself (it is also used for `dynamic` and /// `void`). This is followed by elements representing "prelinked" /// dependencies (direct imports and the transitive closure of exports). /// After the prelinked dependencies are elements representing "linked" /// dependencies. /// /// A library is only included as a "linked" dependency if it is a true /// dependency (e.g. a propagated or inferred type or constant value /// implicitly refers to an element declared in the library) or /// anti-dependency (e.g. the result of type propagation or type inference /// depends on the lack of a certain declaration in the library). @Id(0) List<LinkedDependency> get dependencies; /// For each export in [UnlinkedUnit.exports], an index into [dependencies] /// of the library being exported. @Id(6) List<int> get exportDependencies; /// Information about entities in the export namespace of the library that are /// not in the public namespace of the library (that is, entities that are /// brought into the namespace via `export` directives). /// /// Sorted by name. @Id(4) List<LinkedExportName> get exportNames; /// Indicates whether this library was summarized in "fallback mode". If /// true, all other fields in the data structure have their default values. @deprecated @Id(5) bool get fallbackMode; /// For each import in [UnlinkedUnit.imports], an index into [dependencies] /// of the library being imported. @Id(1) List<int> get importDependencies; /// The number of elements in [dependencies] which are not "linked" /// dependencies (that is, the number of libraries in the direct imports plus /// the transitive closure of exports, plus the library itself). @Id(2) int get numPrelinkedDependencies; /// The linked summary of all the compilation units constituting the /// library. The summary of the defining compilation unit is listed first, /// followed by the summary of each part, in the order of the `part` /// declarations in the defining compilation unit. @Id(3) List<LinkedUnit> get units; } /// Information about a linked AST node. @Variant('kind') abstract class LinkedNode extends base.SummaryClass { /// The explicit or inferred return type of a function typed node. @VariantId(24, variantList: [ LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionExpression, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericFunctionType, LinkedNodeKind.methodDeclaration, ]) LinkedNodeType get actualReturnType; /// The explicit or inferred type of a variable. @VariantId(24, variantList: [ LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.variableDeclaration, ]) LinkedNodeType get actualType; @VariantId(2, variant: LinkedNodeKind.adjacentStrings) List<LinkedNode> get adjacentStrings_strings; @VariantId(4, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.constructorDeclaration, LinkedNodeKind.declaredIdentifier, LinkedNodeKind.enumDeclaration, LinkedNodeKind.enumConstantDeclaration, LinkedNodeKind.exportDirective, LinkedNodeKind.extensionDeclaration, LinkedNodeKind.fieldDeclaration, LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.importDirective, LinkedNodeKind.libraryDirective, LinkedNodeKind.methodDeclaration, LinkedNodeKind.mixinDeclaration, LinkedNodeKind.partDirective, LinkedNodeKind.partOfDirective, LinkedNodeKind.topLevelVariableDeclaration, LinkedNodeKind.typeParameter, LinkedNodeKind.variableDeclaration, LinkedNodeKind.variableDeclarationList, ]) List<LinkedNode> get annotatedNode_metadata; @VariantId(6, variant: LinkedNodeKind.annotation) LinkedNode get annotation_arguments; @VariantId(7, variant: LinkedNodeKind.annotation) LinkedNode get annotation_constructorName; @VariantId(17, variant: LinkedNodeKind.annotation) int get annotation_element; @VariantId(8, variant: LinkedNodeKind.annotation) LinkedNode get annotation_name; @VariantId(38, variant: LinkedNodeKind.annotation) LinkedNodeTypeSubstitution get annotation_substitution; @VariantId(2, variant: LinkedNodeKind.argumentList) List<LinkedNode> get argumentList_arguments; @VariantId(6, variant: LinkedNodeKind.asExpression) LinkedNode get asExpression_expression; @VariantId(7, variant: LinkedNodeKind.asExpression) LinkedNode get asExpression_type; @VariantId(6, variant: LinkedNodeKind.assertInitializer) LinkedNode get assertInitializer_condition; @VariantId(7, variant: LinkedNodeKind.assertInitializer) LinkedNode get assertInitializer_message; @VariantId(6, variant: LinkedNodeKind.assertStatement) LinkedNode get assertStatement_condition; @VariantId(7, variant: LinkedNodeKind.assertStatement) LinkedNode get assertStatement_message; @VariantId(15, variant: LinkedNodeKind.assignmentExpression) int get assignmentExpression_element; @VariantId(6, variant: LinkedNodeKind.assignmentExpression) LinkedNode get assignmentExpression_leftHandSide; @VariantId(28, variant: LinkedNodeKind.assignmentExpression) UnlinkedTokenType get assignmentExpression_operator; @VariantId(7, variant: LinkedNodeKind.assignmentExpression) LinkedNode get assignmentExpression_rightHandSide; @VariantId(38, variant: LinkedNodeKind.assignmentExpression) LinkedNodeTypeSubstitution get assignmentExpression_substitution; @VariantId(6, variant: LinkedNodeKind.awaitExpression) LinkedNode get awaitExpression_expression; @VariantId(15, variant: LinkedNodeKind.binaryExpression) int get binaryExpression_element; @VariantId(24, variant: LinkedNodeKind.binaryExpression) LinkedNodeType get binaryExpression_invokeType; @VariantId(6, variant: LinkedNodeKind.binaryExpression) LinkedNode get binaryExpression_leftOperand; @VariantId(28, variant: LinkedNodeKind.binaryExpression) UnlinkedTokenType get binaryExpression_operator; @VariantId(7, variant: LinkedNodeKind.binaryExpression) LinkedNode get binaryExpression_rightOperand; @VariantId(38, variant: LinkedNodeKind.binaryExpression) LinkedNodeTypeSubstitution get binaryExpression_substitution; @VariantId(2, variant: LinkedNodeKind.block) List<LinkedNode> get block_statements; @VariantId(6, variant: LinkedNodeKind.blockFunctionBody) LinkedNode get blockFunctionBody_block; @VariantId(27, variant: LinkedNodeKind.booleanLiteral) bool get booleanLiteral_value; @VariantId(6, variant: LinkedNodeKind.breakStatement) LinkedNode get breakStatement_label; @VariantId(2, variant: LinkedNodeKind.cascadeExpression) List<LinkedNode> get cascadeExpression_sections; @VariantId(6, variant: LinkedNodeKind.cascadeExpression) LinkedNode get cascadeExpression_target; @VariantId(6, variant: LinkedNodeKind.catchClause) LinkedNode get catchClause_body; @VariantId(7, variant: LinkedNodeKind.catchClause) LinkedNode get catchClause_exceptionParameter; @VariantId(8, variant: LinkedNodeKind.catchClause) LinkedNode get catchClause_exceptionType; @VariantId(9, variant: LinkedNodeKind.catchClause) LinkedNode get catchClause_stackTraceParameter; @VariantId(6, variant: LinkedNodeKind.classDeclaration) LinkedNode get classDeclaration_extendsClause; @VariantId(27, variant: LinkedNodeKind.classDeclaration) bool get classDeclaration_isDartObject; @VariantId(8, variant: LinkedNodeKind.classDeclaration) LinkedNode get classDeclaration_nativeClause; @VariantId(7, variant: LinkedNodeKind.classDeclaration) LinkedNode get classDeclaration_withClause; @VariantId(12, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.mixinDeclaration, ]) LinkedNode get classOrMixinDeclaration_implementsClause; @VariantId(5, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.mixinDeclaration, ]) List<LinkedNode> get classOrMixinDeclaration_members; @VariantId(13, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.mixinDeclaration, ]) LinkedNode get classOrMixinDeclaration_typeParameters; @VariantId(9, variant: LinkedNodeKind.classTypeAlias) LinkedNode get classTypeAlias_implementsClause; @VariantId(7, variant: LinkedNodeKind.classTypeAlias) LinkedNode get classTypeAlias_superclass; @VariantId(6, variant: LinkedNodeKind.classTypeAlias) LinkedNode get classTypeAlias_typeParameters; @VariantId(8, variant: LinkedNodeKind.classTypeAlias) LinkedNode get classTypeAlias_withClause; @VariantId(2, variant: LinkedNodeKind.comment) List<LinkedNode> get comment_references; @VariantId(33, variant: LinkedNodeKind.comment) List<String> get comment_tokens; @VariantId(29, variant: LinkedNodeKind.comment) LinkedNodeCommentType get comment_type; @VariantId(6, variant: LinkedNodeKind.commentReference) LinkedNode get commentReference_identifier; @VariantId(2, variant: LinkedNodeKind.compilationUnit) List<LinkedNode> get compilationUnit_declarations; @VariantId(3, variant: LinkedNodeKind.compilationUnit) List<LinkedNode> get compilationUnit_directives; @VariantId(6, variant: LinkedNodeKind.compilationUnit) LinkedNode get compilationUnit_scriptTag; @VariantId(6, variant: LinkedNodeKind.conditionalExpression) LinkedNode get conditionalExpression_condition; @VariantId(7, variant: LinkedNodeKind.conditionalExpression) LinkedNode get conditionalExpression_elseExpression; @VariantId(8, variant: LinkedNodeKind.conditionalExpression) LinkedNode get conditionalExpression_thenExpression; @VariantId(6, variant: LinkedNodeKind.configuration) LinkedNode get configuration_name; @VariantId(8, variant: LinkedNodeKind.configuration) LinkedNode get configuration_uri; @VariantId(7, variant: LinkedNodeKind.configuration) LinkedNode get configuration_value; @VariantId(6, variant: LinkedNodeKind.constructorDeclaration) LinkedNode get constructorDeclaration_body; @VariantId(2, variant: LinkedNodeKind.constructorDeclaration) List<LinkedNode> get constructorDeclaration_initializers; @VariantId(8, variant: LinkedNodeKind.constructorDeclaration) LinkedNode get constructorDeclaration_parameters; @VariantId(9, variant: LinkedNodeKind.constructorDeclaration) LinkedNode get constructorDeclaration_redirectedConstructor; @VariantId(10, variant: LinkedNodeKind.constructorDeclaration) LinkedNode get constructorDeclaration_returnType; @VariantId(6, variant: LinkedNodeKind.constructorFieldInitializer) LinkedNode get constructorFieldInitializer_expression; @VariantId(7, variant: LinkedNodeKind.constructorFieldInitializer) LinkedNode get constructorFieldInitializer_fieldName; @VariantId(15, variant: LinkedNodeKind.constructorName) int get constructorName_element; @VariantId(6, variant: LinkedNodeKind.constructorName) LinkedNode get constructorName_name; @VariantId(38, variant: LinkedNodeKind.constructorName) LinkedNodeTypeSubstitution get constructorName_substitution; @VariantId(7, variant: LinkedNodeKind.constructorName) LinkedNode get constructorName_type; @VariantId(6, variant: LinkedNodeKind.continueStatement) LinkedNode get continueStatement_label; @VariantId(6, variant: LinkedNodeKind.declaredIdentifier) LinkedNode get declaredIdentifier_identifier; @VariantId(7, variant: LinkedNodeKind.declaredIdentifier) LinkedNode get declaredIdentifier_type; @VariantId(6, variant: LinkedNodeKind.defaultFormalParameter) LinkedNode get defaultFormalParameter_defaultValue; @VariantId(26, variant: LinkedNodeKind.defaultFormalParameter) LinkedNodeFormalParameterKind get defaultFormalParameter_kind; @VariantId(7, variant: LinkedNodeKind.defaultFormalParameter) LinkedNode get defaultFormalParameter_parameter; @VariantId(6, variant: LinkedNodeKind.doStatement) LinkedNode get doStatement_body; @VariantId(7, variant: LinkedNodeKind.doStatement) LinkedNode get doStatement_condition; @VariantId(2, variant: LinkedNodeKind.dottedName) List<LinkedNode> get dottedName_components; @VariantId(21, variant: LinkedNodeKind.doubleLiteral) double get doubleLiteral_value; @VariantId(15, variant: LinkedNodeKind.emptyFunctionBody) int get emptyFunctionBody_fake; @VariantId(15, variant: LinkedNodeKind.emptyStatement) int get emptyStatement_fake; @VariantId(2, variant: LinkedNodeKind.enumDeclaration) List<LinkedNode> get enumDeclaration_constants; @VariantId(25, variantList: [ LinkedNodeKind.assignmentExpression, LinkedNodeKind.asExpression, LinkedNodeKind.awaitExpression, LinkedNodeKind.binaryExpression, LinkedNodeKind.cascadeExpression, LinkedNodeKind.conditionalExpression, LinkedNodeKind.functionExpressionInvocation, LinkedNodeKind.indexExpression, LinkedNodeKind.instanceCreationExpression, LinkedNodeKind.integerLiteral, LinkedNodeKind.listLiteral, LinkedNodeKind.methodInvocation, LinkedNodeKind.nullLiteral, LinkedNodeKind.parenthesizedExpression, LinkedNodeKind.prefixExpression, LinkedNodeKind.prefixedIdentifier, LinkedNodeKind.propertyAccess, LinkedNodeKind.postfixExpression, LinkedNodeKind.rethrowExpression, LinkedNodeKind.setOrMapLiteral, LinkedNodeKind.simpleIdentifier, LinkedNodeKind.superExpression, LinkedNodeKind.symbolLiteral, LinkedNodeKind.thisExpression, LinkedNodeKind.throwExpression, ]) LinkedNodeType get expression_type; @VariantId(6, variant: LinkedNodeKind.expressionFunctionBody) LinkedNode get expressionFunctionBody_expression; @VariantId(6, variant: LinkedNodeKind.expressionStatement) LinkedNode get expressionStatement_expression; @VariantId(6, variant: LinkedNodeKind.extendsClause) LinkedNode get extendsClause_superclass; @VariantId(7, variant: LinkedNodeKind.extensionDeclaration) LinkedNode get extensionDeclaration_extendedType; @VariantId(5, variant: LinkedNodeKind.extensionDeclaration) List<LinkedNode> get extensionDeclaration_members; @VariantId(20, variant: LinkedNodeKind.extensionDeclaration) String get extensionDeclaration_refName; @VariantId(6, variant: LinkedNodeKind.extensionDeclaration) LinkedNode get extensionDeclaration_typeParameters; @VariantId(2, variant: LinkedNodeKind.extensionOverride) List<LinkedNode> get extensionOverride_arguments; @VariantId(24, variant: LinkedNodeKind.extensionOverride) LinkedNodeType get extensionOverride_extendedType; @VariantId(7, variant: LinkedNodeKind.extensionOverride) LinkedNode get extensionOverride_extensionName; @VariantId(8, variant: LinkedNodeKind.extensionOverride) LinkedNode get extensionOverride_typeArguments; @VariantId(39, variant: LinkedNodeKind.extensionOverride) List<LinkedNodeType> get extensionOverride_typeArgumentTypes; @VariantId(6, variant: LinkedNodeKind.fieldDeclaration) LinkedNode get fieldDeclaration_fields; @VariantId(8, variant: LinkedNodeKind.fieldFormalParameter) LinkedNode get fieldFormalParameter_formalParameters; @VariantId(6, variant: LinkedNodeKind.fieldFormalParameter) LinkedNode get fieldFormalParameter_type; @VariantId(7, variant: LinkedNodeKind.fieldFormalParameter) LinkedNode get fieldFormalParameter_typeParameters; @Id(18) int get flags; @VariantId(6, variantList: [ LinkedNodeKind.forEachPartsWithDeclaration, LinkedNodeKind.forEachPartsWithIdentifier, ]) LinkedNode get forEachParts_iterable; @VariantId(7, variant: LinkedNodeKind.forEachPartsWithDeclaration) LinkedNode get forEachPartsWithDeclaration_loopVariable; @VariantId(7, variant: LinkedNodeKind.forEachPartsWithIdentifier) LinkedNode get forEachPartsWithIdentifier_identifier; @VariantId(7, variant: LinkedNodeKind.forElement) LinkedNode get forElement_body; @VariantId(2, variant: LinkedNodeKind.formalParameterList) List<LinkedNode> get formalParameterList_parameters; @VariantId(6, variantList: [ LinkedNodeKind.forElement, LinkedNodeKind.forStatement, ]) LinkedNode get forMixin_forLoopParts; @VariantId(6, variantList: [ LinkedNodeKind.forPartsWithDeclarations, LinkedNodeKind.forPartsWithExpression, ]) LinkedNode get forParts_condition; @VariantId(5, variantList: [ LinkedNodeKind.forPartsWithDeclarations, LinkedNodeKind.forPartsWithExpression, ]) List<LinkedNode> get forParts_updaters; @VariantId(7, variant: LinkedNodeKind.forPartsWithDeclarations) LinkedNode get forPartsWithDeclarations_variables; @VariantId(7, variant: LinkedNodeKind.forPartsWithExpression) LinkedNode get forPartsWithExpression_initialization; @VariantId(7, variant: LinkedNodeKind.forStatement) LinkedNode get forStatement_body; @VariantId(6, variant: LinkedNodeKind.functionDeclaration) LinkedNode get functionDeclaration_functionExpression; @VariantId(7, variant: LinkedNodeKind.functionDeclaration) LinkedNode get functionDeclaration_returnType; @VariantId(6, variant: LinkedNodeKind.functionDeclarationStatement) LinkedNode get functionDeclarationStatement_functionDeclaration; @VariantId(6, variant: LinkedNodeKind.functionExpression) LinkedNode get functionExpression_body; @VariantId(7, variant: LinkedNodeKind.functionExpression) LinkedNode get functionExpression_formalParameters; @VariantId(8, variant: LinkedNodeKind.functionExpression) LinkedNode get functionExpression_typeParameters; @VariantId(6, variant: LinkedNodeKind.functionExpressionInvocation) LinkedNode get functionExpressionInvocation_function; @VariantId(6, variant: LinkedNodeKind.functionTypeAlias) LinkedNode get functionTypeAlias_formalParameters; @VariantId(7, variant: LinkedNodeKind.functionTypeAlias) LinkedNode get functionTypeAlias_returnType; @VariantId(8, variant: LinkedNodeKind.functionTypeAlias) LinkedNode get functionTypeAlias_typeParameters; @VariantId(6, variant: LinkedNodeKind.functionTypedFormalParameter) LinkedNode get functionTypedFormalParameter_formalParameters; @VariantId(7, variant: LinkedNodeKind.functionTypedFormalParameter) LinkedNode get functionTypedFormalParameter_returnType; @VariantId(8, variant: LinkedNodeKind.functionTypedFormalParameter) LinkedNode get functionTypedFormalParameter_typeParameters; @VariantId(8, variant: LinkedNodeKind.genericFunctionType) LinkedNode get genericFunctionType_formalParameters; @VariantId(17, variant: LinkedNodeKind.genericFunctionType) int get genericFunctionType_id; @VariantId(7, variant: LinkedNodeKind.genericFunctionType) LinkedNode get genericFunctionType_returnType; @VariantId(25, variant: LinkedNodeKind.genericFunctionType) LinkedNodeType get genericFunctionType_type; @VariantId(6, variant: LinkedNodeKind.genericFunctionType) LinkedNode get genericFunctionType_typeParameters; @VariantId(7, variant: LinkedNodeKind.genericTypeAlias) LinkedNode get genericTypeAlias_functionType; @VariantId(6, variant: LinkedNodeKind.genericTypeAlias) LinkedNode get genericTypeAlias_typeParameters; @VariantId(9, variant: LinkedNodeKind.ifElement) LinkedNode get ifElement_elseElement; @VariantId(8, variant: LinkedNodeKind.ifElement) LinkedNode get ifElement_thenElement; @VariantId(6, variantList: [ LinkedNodeKind.ifElement, LinkedNodeKind.ifStatement, ]) LinkedNode get ifMixin_condition; @VariantId(7, variant: LinkedNodeKind.ifStatement) LinkedNode get ifStatement_elseStatement; @VariantId(8, variant: LinkedNodeKind.ifStatement) LinkedNode get ifStatement_thenStatement; @VariantId(2, variant: LinkedNodeKind.implementsClause) List<LinkedNode> get implementsClause_interfaces; @VariantId(1, variant: LinkedNodeKind.importDirective) String get importDirective_prefix; @VariantId(15, variant: LinkedNodeKind.indexExpression) int get indexExpression_element; @VariantId(6, variant: LinkedNodeKind.indexExpression) LinkedNode get indexExpression_index; @VariantId(38, variant: LinkedNodeKind.indexExpression) LinkedNodeTypeSubstitution get indexExpression_substitution; @VariantId(7, variant: LinkedNodeKind.indexExpression) LinkedNode get indexExpression_target; @VariantId(36, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.compilationUnit, LinkedNodeKind.compilationUnit, LinkedNodeKind.constructorDeclaration, LinkedNodeKind.defaultFormalParameter, LinkedNodeKind.enumConstantDeclaration, LinkedNodeKind.enumDeclaration, LinkedNodeKind.exportDirective, LinkedNodeKind.extensionDeclaration, LinkedNodeKind.fieldDeclaration, LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.hideCombinator, LinkedNodeKind.importDirective, LinkedNodeKind.libraryDirective, LinkedNodeKind.methodDeclaration, LinkedNodeKind.mixinDeclaration, LinkedNodeKind.partDirective, LinkedNodeKind.partOfDirective, LinkedNodeKind.showCombinator, LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.topLevelVariableDeclaration, LinkedNodeKind.typeParameter, LinkedNodeKind.variableDeclaration, LinkedNodeKind.variableDeclarationList, ]) @informative int get informativeId; @VariantId(27, variantList: [ LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.variableDeclaration, ]) bool get inheritsCovariant; @VariantId(2, variant: LinkedNodeKind.instanceCreationExpression) List<LinkedNode> get instanceCreationExpression_arguments; @VariantId(7, variant: LinkedNodeKind.instanceCreationExpression) LinkedNode get instanceCreationExpression_constructorName; @VariantId(8, variant: LinkedNodeKind.instanceCreationExpression) LinkedNode get instanceCreationExpression_typeArguments; @VariantId(16, variant: LinkedNodeKind.integerLiteral) int get integerLiteral_value; @VariantId(6, variant: LinkedNodeKind.interpolationExpression) LinkedNode get interpolationExpression_expression; @VariantId(30, variant: LinkedNodeKind.interpolationString) String get interpolationString_value; @VariantId(14, variantList: [ LinkedNodeKind.functionExpressionInvocation, LinkedNodeKind.methodInvocation, ]) LinkedNode get invocationExpression_arguments; @VariantId(24, variantList: [ LinkedNodeKind.functionExpressionInvocation, LinkedNodeKind.methodInvocation, ]) LinkedNodeType get invocationExpression_invokeType; @VariantId(12, variantList: [ LinkedNodeKind.functionExpressionInvocation, LinkedNodeKind.methodInvocation, ]) LinkedNode get invocationExpression_typeArguments; @VariantId(6, variant: LinkedNodeKind.isExpression) LinkedNode get isExpression_expression; @VariantId(7, variant: LinkedNodeKind.isExpression) LinkedNode get isExpression_type; @Id(0) LinkedNodeKind get kind; @VariantId(6, variant: LinkedNodeKind.label) LinkedNode get label_label; @VariantId(2, variant: LinkedNodeKind.labeledStatement) List<LinkedNode> get labeledStatement_labels; @VariantId(6, variant: LinkedNodeKind.labeledStatement) LinkedNode get labeledStatement_statement; @VariantId(6, variant: LinkedNodeKind.libraryDirective) LinkedNode get libraryDirective_name; @VariantId(2, variant: LinkedNodeKind.libraryIdentifier) List<LinkedNode> get libraryIdentifier_components; @VariantId(3, variant: LinkedNodeKind.listLiteral) List<LinkedNode> get listLiteral_elements; @VariantId(6, variant: LinkedNodeKind.mapLiteralEntry) LinkedNode get mapLiteralEntry_key; @VariantId(7, variant: LinkedNodeKind.mapLiteralEntry) LinkedNode get mapLiteralEntry_value; @VariantId(6, variant: LinkedNodeKind.methodDeclaration) LinkedNode get methodDeclaration_body; @VariantId(7, variant: LinkedNodeKind.methodDeclaration) LinkedNode get methodDeclaration_formalParameters; @VariantId(8, variant: LinkedNodeKind.methodDeclaration) LinkedNode get methodDeclaration_returnType; @VariantId(9, variant: LinkedNodeKind.methodDeclaration) LinkedNode get methodDeclaration_typeParameters; @VariantId(6, variant: LinkedNodeKind.methodInvocation) LinkedNode get methodInvocation_methodName; @VariantId(7, variant: LinkedNodeKind.methodInvocation) LinkedNode get methodInvocation_target; @VariantId(6, variant: LinkedNodeKind.mixinDeclaration) LinkedNode get mixinDeclaration_onClause; @VariantId(34, variant: LinkedNodeKind.mixinDeclaration) List<String> get mixinDeclaration_superInvokedNames; @Id(37) String get name; @VariantId(6, variant: LinkedNodeKind.namedExpression) LinkedNode get namedExpression_expression; @VariantId(7, variant: LinkedNodeKind.namedExpression) LinkedNode get namedExpression_name; @VariantId(34, variantList: [ LinkedNodeKind.hideCombinator, LinkedNodeKind.showCombinator, LinkedNodeKind.symbolLiteral, ]) List<String> get names; @VariantId(2, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, ]) List<LinkedNode> get namespaceDirective_combinators; @VariantId(3, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, ]) List<LinkedNode> get namespaceDirective_configurations; @VariantId(20, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, ]) String get namespaceDirective_selectedUri; @VariantId(6, variant: LinkedNodeKind.nativeClause) LinkedNode get nativeClause_name; @VariantId(6, variant: LinkedNodeKind.nativeFunctionBody) LinkedNode get nativeFunctionBody_stringLiteral; @VariantId(4, variantList: [ LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.simpleFormalParameter, ]) List<LinkedNode> get normalFormalParameter_metadata; @VariantId(15, variant: LinkedNodeKind.nullLiteral) int get nullLiteral_fake; @VariantId(2, variant: LinkedNodeKind.onClause) List<LinkedNode> get onClause_superclassConstraints; @VariantId(6, variant: LinkedNodeKind.parenthesizedExpression) LinkedNode get parenthesizedExpression_expression; @VariantId(6, variant: LinkedNodeKind.partOfDirective) LinkedNode get partOfDirective_libraryName; @VariantId(7, variant: LinkedNodeKind.partOfDirective) LinkedNode get partOfDirective_uri; @VariantId(15, variant: LinkedNodeKind.postfixExpression) int get postfixExpression_element; @VariantId(6, variant: LinkedNodeKind.postfixExpression) LinkedNode get postfixExpression_operand; @VariantId(28, variant: LinkedNodeKind.postfixExpression) UnlinkedTokenType get postfixExpression_operator; @VariantId(38, variant: LinkedNodeKind.postfixExpression) LinkedNodeTypeSubstitution get postfixExpression_substitution; @VariantId(6, variant: LinkedNodeKind.prefixedIdentifier) LinkedNode get prefixedIdentifier_identifier; @VariantId(7, variant: LinkedNodeKind.prefixedIdentifier) LinkedNode get prefixedIdentifier_prefix; @VariantId(15, variant: LinkedNodeKind.prefixExpression) int get prefixExpression_element; @VariantId(6, variant: LinkedNodeKind.prefixExpression) LinkedNode get prefixExpression_operand; @VariantId(28, variant: LinkedNodeKind.prefixExpression) UnlinkedTokenType get prefixExpression_operator; @VariantId(38, variant: LinkedNodeKind.prefixExpression) LinkedNodeTypeSubstitution get prefixExpression_substitution; @VariantId(28, variant: LinkedNodeKind.propertyAccess) UnlinkedTokenType get propertyAccess_operator; @VariantId(6, variant: LinkedNodeKind.propertyAccess) LinkedNode get propertyAccess_propertyName; @VariantId(7, variant: LinkedNodeKind.propertyAccess) LinkedNode get propertyAccess_target; @VariantId(6, variant: LinkedNodeKind.redirectingConstructorInvocation) LinkedNode get redirectingConstructorInvocation_arguments; @VariantId(7, variant: LinkedNodeKind.redirectingConstructorInvocation) LinkedNode get redirectingConstructorInvocation_constructorName; @VariantId(15, variant: LinkedNodeKind.redirectingConstructorInvocation) int get redirectingConstructorInvocation_element; @VariantId(38, variant: LinkedNodeKind.redirectingConstructorInvocation) LinkedNodeTypeSubstitution get redirectingConstructorInvocation_substitution; @VariantId(6, variant: LinkedNodeKind.returnStatement) LinkedNode get returnStatement_expression; @VariantId(3, variant: LinkedNodeKind.setOrMapLiteral) List<LinkedNode> get setOrMapLiteral_elements; @VariantId(6, variant: LinkedNodeKind.simpleFormalParameter) LinkedNode get simpleFormalParameter_type; @VariantId(15, variant: LinkedNodeKind.simpleIdentifier) int get simpleIdentifier_element; @VariantId(38, variant: LinkedNodeKind.simpleIdentifier) LinkedNodeTypeSubstitution get simpleIdentifier_substitution; @VariantId(20, variant: LinkedNodeKind.simpleStringLiteral) String get simpleStringLiteral_value; @VariantId(31, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.mixinDeclaration, ]) bool get simplyBoundable_isSimplyBounded; @VariantId(6, variant: LinkedNodeKind.spreadElement) LinkedNode get spreadElement_expression; @VariantId(35, variant: LinkedNodeKind.spreadElement) UnlinkedTokenType get spreadElement_spreadOperator; @VariantId(2, variant: LinkedNodeKind.stringInterpolation) List<LinkedNode> get stringInterpolation_elements; @VariantId(6, variant: LinkedNodeKind.superConstructorInvocation) LinkedNode get superConstructorInvocation_arguments; @VariantId(7, variant: LinkedNodeKind.superConstructorInvocation) LinkedNode get superConstructorInvocation_constructorName; @VariantId(15, variant: LinkedNodeKind.superConstructorInvocation) int get superConstructorInvocation_element; @VariantId(38, variant: LinkedNodeKind.superConstructorInvocation) LinkedNodeTypeSubstitution get superConstructorInvocation_substitution; @VariantId(6, variant: LinkedNodeKind.switchCase) LinkedNode get switchCase_expression; @VariantId(3, variantList: [ LinkedNodeKind.switchCase, LinkedNodeKind.switchDefault, ]) List<LinkedNode> get switchMember_labels; @VariantId(4, variantList: [ LinkedNodeKind.switchCase, LinkedNodeKind.switchDefault, ]) List<LinkedNode> get switchMember_statements; @VariantId(7, variant: LinkedNodeKind.switchStatement) LinkedNode get switchStatement_expression; @VariantId(2, variant: LinkedNodeKind.switchStatement) List<LinkedNode> get switchStatement_members; @VariantId(6, variant: LinkedNodeKind.throwExpression) LinkedNode get throwExpression_expression; @VariantId(32, variantList: [ LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.variableDeclaration, ]) TopLevelInferenceError get topLevelTypeInferenceError; @VariantId(6, variant: LinkedNodeKind.topLevelVariableDeclaration) LinkedNode get topLevelVariableDeclaration_variableList; @VariantId(6, variant: LinkedNodeKind.tryStatement) LinkedNode get tryStatement_body; @VariantId(2, variant: LinkedNodeKind.tryStatement) List<LinkedNode> get tryStatement_catchClauses; @VariantId(7, variant: LinkedNodeKind.tryStatement) LinkedNode get tryStatement_finallyBlock; @VariantId(27, variantList: [ LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericTypeAlias, ]) bool get typeAlias_hasSelfReference; @VariantId(2, variant: LinkedNodeKind.typeArgumentList) List<LinkedNode> get typeArgumentList_arguments; @VariantId(2, variantList: [ LinkedNodeKind.listLiteral, LinkedNodeKind.setOrMapLiteral, ]) List<LinkedNode> get typedLiteral_typeArguments; @VariantId(6, variant: LinkedNodeKind.typeName) LinkedNode get typeName_name; @VariantId(23, variant: LinkedNodeKind.typeName) LinkedNodeType get typeName_type; @VariantId(2, variant: LinkedNodeKind.typeName) List<LinkedNode> get typeName_typeArguments; @VariantId(6, variant: LinkedNodeKind.typeParameter) LinkedNode get typeParameter_bound; @VariantId(23, variant: LinkedNodeKind.typeParameter) LinkedNodeType get typeParameter_defaultType; @VariantId(2, variant: LinkedNodeKind.typeParameterList) List<LinkedNode> get typeParameterList_typeParameters; @VariantId(11, variantList: [ LinkedNodeKind.classDeclaration, ]) LinkedNode get unused11; @VariantId(14, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, LinkedNodeKind.partDirective, ]) LinkedNode get uriBasedDirective_uri; @VariantId(22, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, LinkedNodeKind.partDirective, ]) String get uriBasedDirective_uriContent; @VariantId(19, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, LinkedNodeKind.partDirective, ]) int get uriBasedDirective_uriElement; @VariantId(6, variant: LinkedNodeKind.variableDeclaration) LinkedNode get variableDeclaration_initializer; @VariantId(6, variant: LinkedNodeKind.variableDeclarationList) LinkedNode get variableDeclarationList_type; @VariantId(2, variant: LinkedNodeKind.variableDeclarationList) List<LinkedNode> get variableDeclarationList_variables; @VariantId(6, variant: LinkedNodeKind.variableDeclarationStatement) LinkedNode get variableDeclarationStatement_variables; @VariantId(6, variant: LinkedNodeKind.whileStatement) LinkedNode get whileStatement_body; @VariantId(7, variant: LinkedNodeKind.whileStatement) LinkedNode get whileStatement_condition; @VariantId(2, variant: LinkedNodeKind.withClause) List<LinkedNode> get withClause_mixinTypes; @VariantId(6, variant: LinkedNodeKind.yieldStatement) LinkedNode get yieldStatement_expression; } /// Information about a group of libraries linked together, for example because /// they form a single cycle, or because they represent a single build artifact. @TopLevel('LNBn') abstract class LinkedNodeBundle extends base.SummaryClass { factory LinkedNodeBundle.fromBuffer(List<int> buffer) => generated.readLinkedNodeBundle(buffer); @Id(1) List<LinkedNodeLibrary> get libraries; /// The shared list of references used in the [libraries]. @Id(0) LinkedNodeReferences get references; } /// Types of comments. enum LinkedNodeCommentType { block, documentation, endOfLine } /// Kinds of formal parameters. enum LinkedNodeFormalParameterKind { requiredPositional, optionalPositional, optionalNamed, requiredNamed } /// Kinds of [LinkedNode]. enum LinkedNodeKind { adjacentStrings, annotation, argumentList, asExpression, assertInitializer, assertStatement, assignmentExpression, awaitExpression, binaryExpression, block, blockFunctionBody, booleanLiteral, breakStatement, cascadeExpression, catchClause, classDeclaration, classTypeAlias, comment, commentReference, compilationUnit, conditionalExpression, configuration, constructorDeclaration, constructorFieldInitializer, constructorName, continueStatement, declaredIdentifier, defaultFormalParameter, doubleLiteral, doStatement, dottedName, emptyFunctionBody, emptyStatement, enumConstantDeclaration, enumDeclaration, exportDirective, expressionFunctionBody, expressionStatement, extendsClause, extensionDeclaration, fieldDeclaration, fieldFormalParameter, formalParameterList, forEachPartsWithDeclaration, forEachPartsWithIdentifier, forElement, forPartsWithDeclarations, forPartsWithExpression, forStatement, functionDeclaration, functionDeclarationStatement, functionExpression, functionExpressionInvocation, functionTypeAlias, functionTypedFormalParameter, genericFunctionType, genericTypeAlias, hideCombinator, ifElement, ifStatement, implementsClause, importDirective, instanceCreationExpression, indexExpression, integerLiteral, interpolationExpression, interpolationString, isExpression, label, labeledStatement, libraryDirective, libraryIdentifier, listLiteral, mapLiteralEntry, methodDeclaration, methodInvocation, mixinDeclaration, namedExpression, nativeClause, nativeFunctionBody, nullLiteral, onClause, parenthesizedExpression, partDirective, partOfDirective, postfixExpression, prefixExpression, prefixedIdentifier, propertyAccess, redirectingConstructorInvocation, rethrowExpression, returnStatement, setOrMapLiteral, showCombinator, simpleFormalParameter, simpleIdentifier, simpleStringLiteral, spreadElement, stringInterpolation, superConstructorInvocation, superExpression, switchCase, switchDefault, switchStatement, symbolLiteral, thisExpression, throwExpression, topLevelVariableDeclaration, tryStatement, typeArgumentList, typeName, typeParameter, typeParameterList, variableDeclaration, variableDeclarationList, variableDeclarationStatement, whileStatement, withClause, yieldStatement, extensionOverride, } /// Information about a single library in a [LinkedNodeBundle]. abstract class LinkedNodeLibrary extends base.SummaryClass { @Id(2) List<int> get exports; @Id(3) String get name; @Id(5) int get nameLength; @Id(4) int get nameOffset; @Id(1) List<LinkedNodeUnit> get units; @Id(0) String get uriStr; } /// Flattened tree of declarations referenced from [LinkedNode]s. abstract class LinkedNodeReferences extends base.SummaryClass { @Id(1) List<String> get name; @Id(0) List<int> get parent; } /// Information about a Dart type. abstract class LinkedNodeType extends base.SummaryClass { @Id(0) List<LinkedNodeTypeFormalParameter> get functionFormalParameters; @Id(1) LinkedNodeType get functionReturnType; /// The typedef this function type is created for. @Id(9) int get functionTypedef; @Id(10) List<LinkedNodeType> get functionTypedefTypeArguments; @Id(2) List<LinkedNodeTypeTypeParameter> get functionTypeParameters; /// Reference to a [LinkedNodeReferences]. @Id(3) int get interfaceClass; @Id(4) List<LinkedNodeType> get interfaceTypeArguments; @Id(5) LinkedNodeTypeKind get kind; @Id(8) EntityRefNullabilitySuffix get nullabilitySuffix; @Id(6) int get typeParameterElement; @Id(7) int get typeParameterId; } /// Information about a formal parameter in a function type. abstract class LinkedNodeTypeFormalParameter extends base.SummaryClass { @Id(0) LinkedNodeFormalParameterKind get kind; @Id(1) String get name; @Id(2) LinkedNodeType get type; } /// Kinds of [LinkedNodeType]s. enum LinkedNodeTypeKind { bottom, dynamic_, function, interface, typeParameter, void_ } /// Information about a type substitution. abstract class LinkedNodeTypeSubstitution extends base.SummaryClass { @Id(1) List<LinkedNodeType> get typeArguments; @Id(0) List<int> get typeParameters; } /// Information about a type parameter in a function type. abstract class LinkedNodeTypeTypeParameter extends base.SummaryClass { @Id(1) LinkedNodeType get bound; @Id(0) String get name; } /// Information about a single library in a [LinkedNodeLibrary]. abstract class LinkedNodeUnit extends base.SummaryClass { @Id(4) bool get isNNBD; @Id(3) bool get isSynthetic; @Id(2) LinkedNode get node; /// If the unit is a part, the URI specified in the `part` directive. /// Otherwise empty. @Id(5) String get partUriStr; @Id(1) UnlinkedTokens get tokens; /// The absolute URI. @Id(0) String get uriStr; } /// Information about the resolution of an [UnlinkedReference]. abstract class LinkedReference extends base.SummaryClass { /// If this [LinkedReference] doesn't have an associated [UnlinkedReference], /// and the entity being referred to is contained within another entity, index /// of the containing entity. This behaves similarly to /// [UnlinkedReference.prefixReference], however it is only used for class /// members, not for prefixed imports. /// /// Containing references must always point backward; that is, for all i, if /// LinkedUnit.references[i].containingReference != 0, then /// LinkedUnit.references[i].containingReference < i. @Id(5) int get containingReference; /// Index into [LinkedLibrary.dependencies] indicating which imported library /// declares the entity being referred to. /// /// Zero if this entity is contained within another entity (e.g. a class /// member), or if [kind] is [ReferenceKind.prefix]. @Id(1) int get dependency; /// The kind of the entity being referred to. For the pseudo-types `dynamic` /// and `void`, the kind is [ReferenceKind.classOrEnum]. @Id(2) ReferenceKind get kind; /// If [kind] is [ReferenceKind.function] (that is, the entity being referred /// to is a local function), the index of the function within /// [UnlinkedExecutable.localFunctions]. Otherwise zero. @deprecated @Id(6) int get localIndex; /// If this [LinkedReference] doesn't have an associated [UnlinkedReference], /// name of the entity being referred to. For the pseudo-type `dynamic`, the /// string is "dynamic". For the pseudo-type `void`, the string is "void". @Id(3) String get name; /// If the entity being referred to is generic, the number of type parameters /// it declares (does not include type parameters of enclosing entities). /// Otherwise zero. @Id(4) int get numTypeParameters; /// Integer index indicating which unit in the imported library contains the /// definition of the entity. As with indices into [LinkedLibrary.units], /// zero represents the defining compilation unit, and nonzero values /// represent parts in the order of the corresponding `part` declarations. /// /// Zero if this entity is contained within another entity (e.g. a class /// member). @Id(0) int get unit; } /// Linked summary of a compilation unit. abstract class LinkedUnit extends base.SummaryClass { /// List of slot ids (referring to [UnlinkedExecutable.constCycleSlot]) /// corresponding to const constructors that are part of cycles. @Id(2) List<int> get constCycles; /// List of slot ids (referring to [UnlinkedClass.notSimplyBoundedSlot] or /// [UnlinkedTypedef.notSimplyBoundedSlot]) corresponding to classes and /// typedefs that are not simply bounded. @Id(5) List<int> get notSimplyBounded; /// List of slot ids (referring to [UnlinkedParam.inheritsCovariantSlot] or /// [UnlinkedVariable.inheritsCovariantSlot]) corresponding to parameters /// that inherit `@covariant` behavior from a base class. @Id(3) List<int> get parametersInheritingCovariant; /// Information about the resolution of references within the compilation /// unit. Each element of [UnlinkedUnit.references] has a corresponding /// element in this list (at the same index). If this list has additional /// elements beyond the number of elements in [UnlinkedUnit.references], those /// additional elements are references that are only referred to implicitly /// (e.g. elements involved in inferred or propagated types). @Id(0) List<LinkedReference> get references; /// The list of type inference errors. @Id(4) List<TopLevelInferenceError> get topLevelInferenceErrors; /// List associating slot ids found inside the unlinked summary for the /// compilation unit with propagated and inferred types. @Id(1) List<EntityRef> get types; } /// Summary information about a package. @TopLevel('PBdl') abstract class PackageBundle extends base.SummaryClass { factory PackageBundle.fromBuffer(List<int> buffer) => generated.readPackageBundle(buffer); /// MD5 hash of the non-informative fields of the [PackageBundle] (not /// including this one). This can be used to identify when the API of a /// package may have changed. @Id(7) @deprecated String get apiSignature; /// The version 2 of the summary. @Id(9) LinkedNodeBundle get bundle2; /// Information about the packages this package depends on, if known. @Id(8) @informative @deprecated List<PackageDependencyInfo> get dependencies; /// Linked libraries. @Id(0) List<LinkedLibrary> get linkedLibraries; /// The list of URIs of items in [linkedLibraries], e.g. `dart:core` or /// `package:foo/bar.dart`. @Id(1) List<String> get linkedLibraryUris; /// Major version of the summary format. See /// [PackageBundleAssembler.currentMajorVersion]. @Id(5) int get majorVersion; /// Minor version of the summary format. See /// [PackageBundleAssembler.currentMinorVersion]. @Id(6) int get minorVersion; /// List of MD5 hashes of the files listed in [unlinkedUnitUris]. Each hash /// is encoded as a hexadecimal string using lower case letters. @Id(4) @deprecated @informative List<String> get unlinkedUnitHashes; /// Unlinked information for the compilation units constituting the package. @Id(2) List<UnlinkedUnit> get unlinkedUnits; /// The list of URIs of items in [unlinkedUnits], e.g. `dart:core/bool.dart`. @Id(3) List<String> get unlinkedUnitUris; } /// Information about a single dependency of a summary package. @deprecated abstract class PackageDependencyInfo extends base.SummaryClass { /// API signature of this dependency. @Id(0) String get apiSignature; /// If this dependency summarizes any files whose URI takes the form /// "package:<package_name>/...", a list of all such package names, sorted /// lexicographically. Otherwise empty. @Id(2) List<String> get includedPackageNames; /// Indicates whether this dependency summarizes any files whose URI takes the /// form "dart:...". @Id(4) bool get includesDartUris; /// Indicates whether this dependency summarizes any files whose URI takes the /// form "file:...". @Id(3) bool get includesFileUris; /// Relative path to the summary file for this dependency. This is intended /// as a hint to help the analysis server locate summaries of dependencies. /// We don't specify precisely what this path is relative to, but we expect /// it to be relative to a directory the analysis server can find (e.g. for /// projects built using Bazel, it would be relative to the "bazel-bin" /// directory). /// /// Absent if the path is not known. @Id(1) String get summaryPath; } /// Index information about a package. @TopLevel('Indx') abstract class PackageIndex extends base.SummaryClass { factory PackageIndex.fromBuffer(List<int> buffer) => generated.readPackageIndex(buffer); /// Each item of this list corresponds to a unique referenced element. It is /// the kind of the synthetic element. @Id(5) List<IndexSyntheticElementKind> get elementKinds; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the class member element name, or `null` if the element /// is a top-level element. The list is sorted in ascending order, so that /// the client can quickly check whether an element is referenced in this /// [PackageIndex]. @Id(7) List<int> get elementNameClassMemberIds; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the named parameter name, or `null` if the element is /// not a named parameter. The list is sorted in ascending order, so that the /// client can quickly check whether an element is referenced in this /// [PackageIndex]. @Id(8) List<int> get elementNameParameterIds; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the top-level element name, or `null` if the element is /// the unit. The list is sorted in ascending order, so that the client can /// quickly check whether an element is referenced in this [PackageIndex]. @Id(1) List<int> get elementNameUnitMemberIds; /// Each item of this list corresponds to a unique referenced element. It is /// the index into [unitLibraryUris] and [unitUnitUris] for the library /// specific unit where the element is declared. @Id(0) List<int> get elementUnits; /// List of unique element strings used in this [PackageIndex]. The list is /// sorted in ascending order, so that the client can quickly check the /// presence of a string in this [PackageIndex]. @Id(6) List<String> get strings; /// Each item of this list corresponds to the library URI of a unique library /// specific unit referenced in the [PackageIndex]. It is an index into /// [strings] list. @Id(2) List<int> get unitLibraryUris; /// List of indexes of each unit in this [PackageIndex]. @Id(4) List<UnitIndex> get units; /// Each item of this list corresponds to the unit URI of a unique library /// specific unit referenced in the [PackageIndex]. It is an index into /// [strings] list. @Id(3) List<int> get unitUnitUris; } /// Enum used to indicate the kind of entity referred to by a /// [LinkedReference]. enum ReferenceKind { /// The entity is a class or enum. classOrEnum, /// The entity is a constructor. constructor, /// The entity is a getter or setter inside a class. Note: this is used in /// the case where a constant refers to a static const declared inside a /// class. propertyAccessor, /// The entity is a method. method, /// The entity is a typedef. typedef, /// The entity is a local function. function, /// The entity is a local variable. variable, /// The entity is a top level function. topLevelFunction, /// The entity is a top level getter or setter. topLevelPropertyAccessor, /// The entity is a prefix. prefix, /// The entity being referred to does not exist. unresolved, /// The entity is a typedef expressed using generic function type syntax. genericFunctionTypedef } /// Summary information about a top-level type inference error. abstract class TopLevelInferenceError extends base.SummaryClass { /// The [kind] specific arguments. @Id(2) List<String> get arguments; /// The kind of the error. @Id(1) TopLevelInferenceErrorKind get kind; /// The slot id (which is unique within the compilation unit) identifying the /// target of type inference with which this [TopLevelInferenceError] is /// associated. @Id(0) int get slot; } /// Enum used to indicate the kind of the error during top-level inference. enum TopLevelInferenceErrorKind { assignment, instanceGetter, dependencyCycle, overrideConflictFieldType, overrideConflictReturnType, overrideConflictParameterType } /// Enum used to indicate the style of a typedef. enum TypedefStyle { /// A typedef that defines a non-generic function type. The syntax is /// ``` /// 'typedef' returnType? identifier typeParameters? formalParameterList ';' /// ``` /// The typedef can have type parameters associated with it, but the function /// type that results from applying type arguments does not. functionType, /// A typedef expressed using generic function type syntax. The syntax is /// ``` /// typeAlias ::= /// 'typedef' identifier typeParameters? '=' genericFunctionType ';' /// genericFunctionType ::= /// returnType? 'Function' typeParameters? parameterTypeList /// ``` /// Both the typedef itself and the function type that results from applying /// type arguments can have type parameters. genericFunctionType } /// Index information about a unit in a [PackageIndex]. abstract class UnitIndex extends base.SummaryClass { /// Each item of this list is the kind of an element defined in this unit. @Id(6) List<IndexNameKind> get definedNameKinds; /// Each item of this list is the name offset of an element defined in this /// unit relative to the beginning of the file. @Id(7) List<int> get definedNameOffsets; /// Each item of this list corresponds to an element defined in this unit. It /// is an index into [PackageIndex.strings] list. The list is sorted in /// ascending order, so that the client can quickly find name definitions in /// this [UnitIndex]. @Id(5) List<int> get definedNames; /// Index into [PackageIndex.unitLibraryUris] and [PackageIndex.unitUnitUris] /// for the library specific unit that corresponds to this [UnitIndex]. @Id(0) int get unit; /// Each item of this list is the `true` if the corresponding element usage /// is qualified with some prefix. @Id(11) List<bool> get usedElementIsQualifiedFlags; /// Each item of this list is the kind of the element usage. @Id(4) List<IndexRelationKind> get usedElementKinds; /// Each item of this list is the length of the element usage. @Id(1) List<int> get usedElementLengths; /// Each item of this list is the offset of the element usage relative to the /// beginning of the file. @Id(2) List<int> get usedElementOffsets; /// Each item of this list is the index into [PackageIndex.elementUnits] and /// [PackageIndex.elementOffsets]. The list is sorted in ascending order, so /// that the client can quickly find element references in this [UnitIndex]. @Id(3) List<int> get usedElements; /// Each item of this list is the `true` if the corresponding name usage /// is qualified with some prefix. @Id(12) List<bool> get usedNameIsQualifiedFlags; /// Each item of this list is the kind of the name usage. @Id(10) List<IndexRelationKind> get usedNameKinds; /// Each item of this list is the offset of the name usage relative to the /// beginning of the file. @Id(9) List<int> get usedNameOffsets; /// Each item of this list is the index into [PackageIndex.strings] for a /// used name. The list is sorted in ascending order, so that the client can /// quickly find name uses in this [UnitIndex]. @Id(8) List<int> get usedNames; } /// Unlinked summary information about a class declaration. abstract class UnlinkedClass extends base.SummaryClass { /// Annotations for this class. @Id(5) List<UnlinkedExpr> get annotations; /// Code range of the class. @informative @Id(13) CodeRange get codeRange; /// Documentation comment for the class, or `null` if there is no /// documentation comment. @informative @Id(6) UnlinkedDocumentationComment get documentationComment; /// Executable objects (methods, getters, and setters) contained in the class. @Id(2) List<UnlinkedExecutable> get executables; /// Field declarations contained in the class. @Id(4) List<UnlinkedVariable> get fields; /// Indicates whether this class is the core "Object" class (and hence has no /// supertype) @Id(12) bool get hasNoSupertype; /// Interfaces appearing in an `implements` clause, if any. @Id(7) List<EntityRef> get interfaces; /// Indicates whether the class is declared with the `abstract` keyword. @Id(8) bool get isAbstract; /// Indicates whether the class is declared using mixin application syntax. @Id(11) bool get isMixinApplication; /// Mixins appearing in a `with` clause, if any. @Id(10) List<EntityRef> get mixins; /// Name of the class. @Id(0) String get name; /// Offset of the class name relative to the beginning of the file. @informative @Id(1) int get nameOffset; /// If the class might not be simply bounded, a nonzero slot id which is unique /// within this compilation unit. If this id is found in /// [LinkedUnit.notSimplyBounded], then at least one of this class's type /// parameters is not simply bounded, hence this class can't be used as a raw /// type when specifying the bound of a type parameter. /// /// Otherwise, zero. @Id(16) int get notSimplyBoundedSlot; /// Superclass constraints for this mixin declaration. The list will be empty /// if this class is not a mixin declaration, or if the declaration does not /// have an `on` clause (in which case the type `Object` is implied). @Id(14) List<EntityRef> get superclassConstraints; /// Names of methods, getters, setters, and operators that this mixin /// declaration super-invokes. For setters this includes the trailing "=". /// The list will be empty if this class is not a mixin declaration. @Id(15) List<String> get superInvokedNames; /// Supertype of the class, or `null` if either (a) the class doesn't /// explicitly declare a supertype (and hence has supertype `Object`), or (b) /// the class *is* `Object` (and hence has no supertype). @Id(3) EntityRef get supertype; /// Type parameters of the class, if any. @Id(9) List<UnlinkedTypeParam> get typeParameters; } /// Unlinked summary information about a `show` or `hide` combinator in an /// import or export declaration. abstract class UnlinkedCombinator extends base.SummaryClass { /// If this is a `show` combinator, offset of the end of the list of shown /// names. Otherwise zero. @informative @Id(3) int get end; /// List of names which are hidden. Empty if this is a `show` combinator. @Id(1) List<String> get hides; /// If this is a `show` combinator, offset of the `show` keyword. Otherwise /// zero. @informative @Id(2) int get offset; /// List of names which are shown. Empty if this is a `hide` combinator. @Id(0) List<String> get shows; } /// Unlinked summary information about a single import or export configuration. abstract class UnlinkedConfiguration extends base.SummaryClass { /// The name of the declared variable whose value is being used in the /// condition. @Id(0) String get name; /// The URI of the implementation library to be used if the condition is true. @Id(2) String get uri; /// The value to which the value of the declared variable will be compared, /// or `true` if the condition does not include an equality test. @Id(1) String get value; } /// Unlinked summary information about a constructor initializer. abstract class UnlinkedConstructorInitializer extends base.SummaryClass { /// If there are `m` [arguments] and `n` [argumentNames], then each argument /// from [arguments] with index `i` such that `n + i - m >= 0`, should be used /// with the name at `n + i - m`. @Id(4) List<String> get argumentNames; /// If [kind] is `thisInvocation` or `superInvocation`, the arguments of the /// invocation. Otherwise empty. @Id(3) List<UnlinkedExpr> get arguments; /// If [kind] is `field`, the expression of the field initializer. /// Otherwise `null`. @Id(1) UnlinkedExpr get expression; /// The kind of the constructor initializer (field, redirect, super). @Id(2) UnlinkedConstructorInitializerKind get kind; /// If [kind] is `field`, the name of the field declared in the class. If /// [kind] is `thisInvocation`, the name of the constructor, declared in this /// class, to redirect to. If [kind] is `superInvocation`, the name of the /// constructor, declared in the superclass, to invoke. @Id(0) String get name; } /// Enum used to indicate the kind of an constructor initializer. enum UnlinkedConstructorInitializerKind { /// Initialization of a field. field, /// Invocation of a constructor in the same class. thisInvocation, /// Invocation of a superclass' constructor. superInvocation, /// Invocation of `assert`. assertInvocation } /// Unlinked summary information about a documentation comment. abstract class UnlinkedDocumentationComment extends base.SummaryClass { /// Length of the documentation comment (prior to replacing '\r\n' with '\n'). @Id(0) @deprecated int get length; /// Offset of the beginning of the documentation comment relative to the /// beginning of the file. @Id(2) @deprecated int get offset; /// Text of the documentation comment, with '\r\n' replaced by '\n'. /// /// References appearing within the doc comment in square brackets are not /// specially encoded. @Id(1) String get text; } /// Unlinked summary information about an enum declaration. abstract class UnlinkedEnum extends base.SummaryClass { /// Annotations for this enum. @Id(4) List<UnlinkedExpr> get annotations; /// Code range of the enum. @informative @Id(5) CodeRange get codeRange; /// Documentation comment for the enum, or `null` if there is no documentation /// comment. @informative @Id(3) UnlinkedDocumentationComment get documentationComment; /// Name of the enum type. @Id(0) String get name; /// Offset of the enum name relative to the beginning of the file. @informative @Id(1) int get nameOffset; /// Values listed in the enum declaration, in declaration order. @Id(2) List<UnlinkedEnumValue> get values; } /// Unlinked summary information about a single enumerated value in an enum /// declaration. abstract class UnlinkedEnumValue extends base.SummaryClass { /// Annotations for this value. @Id(3) List<UnlinkedExpr> get annotations; /// Documentation comment for the enum value, or `null` if there is no /// documentation comment. @informative @Id(2) UnlinkedDocumentationComment get documentationComment; /// Name of the enumerated value. @Id(0) String get name; /// Offset of the enum value name relative to the beginning of the file. @informative @Id(1) int get nameOffset; } /// Unlinked summary information about a function, method, getter, or setter /// declaration. abstract class UnlinkedExecutable extends base.SummaryClass { /// Annotations for this executable. @Id(6) List<UnlinkedExpr> get annotations; /// If this executable's function body is declared using `=>`, the expression /// to the right of the `=>`. May be omitted if neither type inference nor /// constant evaluation depends on the function body. @Id(29) UnlinkedExpr get bodyExpr; /// Code range of the executable. @informative @Id(26) CodeRange get codeRange; /// If a constant [UnlinkedExecutableKind.constructor], the constructor /// initializers. Otherwise empty. @Id(14) List<UnlinkedConstructorInitializer> get constantInitializers; /// If [kind] is [UnlinkedExecutableKind.constructor] and [isConst] is `true`, /// a nonzero slot id which is unique within this compilation unit. If this /// id is found in [LinkedUnit.constCycles], then this constructor is part of /// a cycle. /// /// Otherwise, zero. @Id(25) int get constCycleSlot; /// Documentation comment for the executable, or `null` if there is no /// documentation comment. @informative @Id(7) UnlinkedDocumentationComment get documentationComment; /// If this executable's return type is inferable, nonzero slot id /// identifying which entry in [LinkedUnit.types] contains the inferred /// return type. If there is no matching entry in [LinkedUnit.types], then /// no return type was inferred for this variable, so its static type is /// `dynamic`. @Id(5) int get inferredReturnTypeSlot; /// Indicates whether the executable is declared using the `abstract` keyword. @Id(10) bool get isAbstract; /// Indicates whether the executable has body marked as being asynchronous. @informative @Id(27) bool get isAsynchronous; /// Indicates whether the executable is declared using the `const` keyword. @Id(12) bool get isConst; /// Indicates whether the executable is declared using the `external` keyword. @Id(11) bool get isExternal; /// Indicates whether the executable is declared using the `factory` keyword. @Id(8) bool get isFactory; /// Indicates whether the executable has body marked as being a generator. @informative @Id(28) bool get isGenerator; /// Indicates whether the executable is a redirected constructor. @Id(13) bool get isRedirectedConstructor; /// Indicates whether the executable is declared using the `static` keyword. /// /// Note that for top level executables, this flag is false, since they are /// not declared using the `static` keyword (even though they are considered /// static for semantic purposes). @Id(9) bool get isStatic; /// The kind of the executable (function/method, getter, setter, or /// constructor). @Id(4) UnlinkedExecutableKind get kind; /// The list of local functions. @Id(18) List<UnlinkedExecutable> get localFunctions; /// The list of local labels. @informative @deprecated @Id(22) List<String> get localLabels; /// The list of local variables. @informative @deprecated @Id(19) List<UnlinkedVariable> get localVariables; /// Name of the executable. For setters, this includes the trailing "=". For /// named constructors, this excludes the class name and excludes the ".". /// For unnamed constructors, this is the empty string. @Id(1) String get name; /// If [kind] is [UnlinkedExecutableKind.constructor] and [name] is not empty, /// the offset of the end of the constructor name. Otherwise zero. @informative @Id(23) int get nameEnd; /// Offset of the executable name relative to the beginning of the file. For /// named constructors, this excludes the class name and excludes the ".". /// For unnamed constructors, this is the offset of the class name (i.e. the /// offset of the second "C" in "class C { C(); }"). @informative @Id(0) int get nameOffset; /// Parameters of the executable, if any. Note that getters have no /// parameters (hence this will be the empty list), and setters have a single /// parameter. @Id(2) List<UnlinkedParam> get parameters; /// If [kind] is [UnlinkedExecutableKind.constructor] and [name] is not empty, /// the offset of the period before the constructor name. Otherwise zero. @informative @Id(24) int get periodOffset; /// If [isRedirectedConstructor] and [isFactory] are both `true`, the /// constructor to which this constructor redirects; otherwise empty. @Id(15) EntityRef get redirectedConstructor; /// If [isRedirectedConstructor] is `true` and [isFactory] is `false`, the /// name of the constructor that this constructor redirects to; otherwise /// empty. @Id(17) String get redirectedConstructorName; /// Declared return type of the executable. Absent if the executable is a /// constructor or the return type is implicit. Absent for executables /// associated with variable initializers and closures, since these /// executables may have return types that are not accessible via direct /// imports. @Id(3) EntityRef get returnType; /// Type parameters of the executable, if any. Empty if support for generic /// method syntax is disabled. @Id(16) List<UnlinkedTypeParam> get typeParameters; /// If a local function, the length of the visible range; zero otherwise. @informative @Id(20) int get visibleLength; /// If a local function, the beginning of the visible range; zero otherwise. @informative @Id(21) int get visibleOffset; } /// Enum used to indicate the kind of an executable. enum UnlinkedExecutableKind { /// Executable is a function or method. functionOrMethod, /// Executable is a getter. getter, /// Executable is a setter. setter, /// Executable is a constructor. constructor } /// Unlinked summary information about an export declaration (stored outside /// [UnlinkedPublicNamespace]). abstract class UnlinkedExportNonPublic extends base.SummaryClass { /// Annotations for this export directive. @Id(3) List<UnlinkedExpr> get annotations; /// Offset of the "export" keyword. @informative @Id(0) int get offset; /// End of the URI string (including quotes) relative to the beginning of the /// file. @informative @Id(1) int get uriEnd; /// Offset of the URI string (including quotes) relative to the beginning of /// the file. @informative @Id(2) int get uriOffset; } /// Unlinked summary information about an export declaration (stored inside /// [UnlinkedPublicNamespace]). abstract class UnlinkedExportPublic extends base.SummaryClass { /// Combinators contained in this export declaration. @Id(1) List<UnlinkedCombinator> get combinators; /// Configurations used to control which library will actually be loaded at /// run-time. @Id(2) List<UnlinkedConfiguration> get configurations; /// URI used in the source code to reference the exported library. @Id(0) String get uri; } /// Unlinked summary information about an expression. /// /// Expressions are represented using a simple stack-based language /// where [operations] is a sequence of operations to execute starting with an /// empty stack. Once all operations have been executed, the stack should /// contain a single value which is the value of the constant. Note that some /// operations consume additional data from the other fields of this class. abstract class UnlinkedExpr extends base.SummaryClass { /// Sequence of operators used by assignment operations. @Id(6) List<UnlinkedExprAssignOperator> get assignmentOperators; /// Sequence of 64-bit doubles consumed by the operation `pushDouble`. @Id(4) List<double> get doubles; /// Sequence of unsigned 32-bit integers consumed by the operations /// `pushArgument`, `pushInt`, `shiftOr`, `concatenate`, `invokeConstructor`, /// `makeList`, and `makeMap`. @Id(1) List<int> get ints; /// Indicates whether the expression is a valid potentially constant /// expression. @Id(5) bool get isValidConst; /// Sequence of operations to execute (starting with an empty stack) to form /// the constant value. @Id(0) List<UnlinkedExprOperation> get operations; /// Sequence of language constructs consumed by the operations /// `pushReference`, `invokeConstructor`, `makeList`, and `makeMap`. Note /// that in the case of `pushReference` (and sometimes `invokeConstructor` the /// actual entity being referred to may be something other than a type. @Id(2) List<EntityRef> get references; /// String representation of the expression in a form suitable to be tokenized /// and parsed. @Id(7) String get sourceRepresentation; /// Sequence of strings consumed by the operations `pushString` and /// `invokeConstructor`. @Id(3) List<String> get strings; } /// Enum representing the various kinds of assignment operations combined /// with: /// [UnlinkedExprOperation.assignToRef], /// [UnlinkedExprOperation.assignToProperty], /// [UnlinkedExprOperation.assignToIndex]. enum UnlinkedExprAssignOperator { /// Perform simple assignment `target = operand`. assign, /// Perform `target ??= operand`. ifNull, /// Perform `target *= operand`. multiply, /// Perform `target /= operand`. divide, /// Perform `target ~/= operand`. floorDivide, /// Perform `target %= operand`. modulo, /// Perform `target += operand`. plus, /// Perform `target -= operand`. minus, /// Perform `target <<= operand`. shiftLeft, /// Perform `target >>= operand`. shiftRight, /// Perform `target &= operand`. bitAnd, /// Perform `target ^= operand`. bitXor, /// Perform `target |= operand`. bitOr, /// Perform `++target`. prefixIncrement, /// Perform `--target`. prefixDecrement, /// Perform `target++`. postfixIncrement, /// Perform `target++`. postfixDecrement, } /// Enum representing the various kinds of operations which may be performed to /// in an expression. These options are assumed to execute in the /// context of a stack which is initially empty. enum UnlinkedExprOperation { /// Push the next value from [UnlinkedExpr.ints] (a 32-bit unsigned integer) /// onto the stack. /// /// Note that Dart supports integers larger than 32 bits; these are /// represented by composing 32-bit values using the [pushLongInt] operation. pushInt, /// Get the number of components from [UnlinkedExpr.ints], then do this number /// of times the following operations: multiple the current value by 2^32, /// "or" it with the next value in [UnlinkedExpr.ints]. The initial value is /// zero. Push the result into the stack. pushLongInt, /// Push the next value from [UnlinkedExpr.doubles] (a double precision /// floating point value) onto the stack. pushDouble, /// Push the constant `true` onto the stack. pushTrue, /// Push the constant `false` onto the stack. pushFalse, /// Push the next value from [UnlinkedExpr.strings] onto the stack. pushString, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), convert them to strings (if they aren't already), /// concatenate them into a single string, and push it back onto the stack. /// /// This operation is used to represent constants whose value is a literal /// string containing string interpolations. concatenate, /// Get the next value from [UnlinkedExpr.strings], convert it to a symbol, /// and push it onto the stack. makeSymbol, /// Push the constant `null` onto the stack. pushNull, /// Push the value of the function parameter with the name obtained from /// [UnlinkedExpr.strings]. pushParameter, /// Evaluate a (potentially qualified) identifier expression and push the /// resulting value onto the stack. The identifier to be evaluated is /// obtained from [UnlinkedExpr.references]. /// /// This operation is used to represent the following kinds of constants /// (which are indistinguishable from an unresolved AST alone): /// /// - A qualified reference to a static constant variable (e.g. `C.v`, where /// C is a class and `v` is a constant static variable in `C`). /// - An identifier expression referring to a constant variable. /// - A simple or qualified identifier denoting a class or type alias. /// - A simple or qualified identifier denoting a top-level function or a /// static method. pushReference, /// Pop the top value from the stack, extract the value of the property with /// the name obtained from [UnlinkedExpr.strings], and push the result back /// onto the stack. extractProperty, /// Pop the top `n` values from the stack (where `n` is obtained from /// [UnlinkedExpr.ints]) into a list (filled from the end) and take the next /// `n` values from [UnlinkedExpr.strings] and use the lists of names and /// values to create named arguments. Then pop the top `m` values from the /// stack (where `m` is obtained from [UnlinkedExpr.ints]) into a list (filled /// from the end) and use them as positional arguments. Use the lists of /// positional and names arguments to invoke a constant constructor obtained /// from [UnlinkedExpr.references], and push the resulting value back onto the /// stack. /// /// Arguments are skipped, and `0` are specified as the numbers of arguments /// on the stack, if the expression is not a constant. We store expression of /// variable initializers to perform top-level inference, and arguments are /// never used to infer types. /// /// Note that for an invocation of the form `const a.b(...)` (where no type /// arguments are specified), it is impossible to tell from the unresolved AST /// alone whether `a` is a class name and `b` is a constructor name, or `a` is /// a prefix name and `b` is a class name. For consistency between AST based /// and elements based summaries, references to default constructors are /// always recorded as references to corresponding classes. invokeConstructor, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), place them in a [List], and push the result back /// onto the stack. The type parameter for the [List] is implicitly /// `dynamic`. makeUntypedList, /// Pop the top 2*n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), interpret them as key/value pairs, place them in a /// [Map], and push the result back onto the stack. The two type parameters /// for the [Map] are implicitly `dynamic`. /// /// To be replaced with [makeUntypedSetOrMap] for unified collections. makeUntypedMap, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), place them in a [List], and push the result back /// onto the stack. The type parameter for the [List] is obtained from /// [UnlinkedExpr.references]. makeTypedList, /// Pop the top 2*n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), interpret them as key/value pairs, place them in a /// [Map], and push the result back onto the stack. The two type parameters /// for the [Map] are obtained from [UnlinkedExpr.references]. /// /// To be replaced with [makeTypedMap2] for unified collections. This is not /// forwards compatible with [makeTypedMap2] because it expects /// [CollectionElement]s instead of pairs of [Expression]s. makeTypedMap, /// Pop the top 2 values from the stack, evaluate `v1 == v2`, and push the /// result back onto the stack. equal, /// Pop the top 2 values from the stack, evaluate `v1 != v2`, and push the /// result back onto the stack. notEqual, /// Pop the top value from the stack, compute its boolean negation, and push /// the result back onto the stack. not, /// Pop the top 2 values from the stack, compute `v1 && v2`, and push the /// result back onto the stack. and, /// Pop the top 2 values from the stack, compute `v1 || v2`, and push the /// result back onto the stack. or, /// Pop the top value from the stack, compute its integer complement, and push /// the result back onto the stack. complement, /// Pop the top 2 values from the stack, compute `v1 ^ v2`, and push the /// result back onto the stack. bitXor, /// Pop the top 2 values from the stack, compute `v1 & v2`, and push the /// result back onto the stack. bitAnd, /// Pop the top 2 values from the stack, compute `v1 | v2`, and push the /// result back onto the stack. bitOr, /// Pop the top 2 values from the stack, compute `v1 >> v2`, and push the /// result back onto the stack. bitShiftRight, /// Pop the top 2 values from the stack, compute `v1 << v2`, and push the /// result back onto the stack. bitShiftLeft, /// Pop the top 2 values from the stack, compute `v1 + v2`, and push the /// result back onto the stack. add, /// Pop the top value from the stack, compute its integer negation, and push /// the result back onto the stack. negate, /// Pop the top 2 values from the stack, compute `v1 - v2`, and push the /// result back onto the stack. subtract, /// Pop the top 2 values from the stack, compute `v1 * v2`, and push the /// result back onto the stack. multiply, /// Pop the top 2 values from the stack, compute `v1 / v2`, and push the /// result back onto the stack. divide, /// Pop the top 2 values from the stack, compute `v1 ~/ v2`, and push the /// result back onto the stack. floorDivide, /// Pop the top 2 values from the stack, compute `v1 > v2`, and push the /// result back onto the stack. greater, /// Pop the top 2 values from the stack, compute `v1 < v2`, and push the /// result back onto the stack. less, /// Pop the top 2 values from the stack, compute `v1 >= v2`, and push the /// result back onto the stack. greaterEqual, /// Pop the top 2 values from the stack, compute `v1 <= v2`, and push the /// result back onto the stack. lessEqual, /// Pop the top 2 values from the stack, compute `v1 % v2`, and push the /// result back onto the stack. modulo, /// Pop the top 3 values from the stack, compute `v1 ? v2 : v3`, and push the /// result back onto the stack. conditional, /// Pop from the stack `value` and get the next `target` reference from /// [UnlinkedExpr.references] - a top-level variable (prefixed or not), an /// assignable field of a class (prefixed or not), or a sequence of getters /// ending with an assignable property `a.b.b.c.d.e`. In general `a.b` cannot /// not be distinguished between: `a` is a prefix and `b` is a top-level /// variable; or `a` is an object and `b` is the name of a property. Perform /// `reference op= value` where `op` is the next assignment operator from /// [UnlinkedExpr.assignmentOperators]. Push `value` back into the stack. /// /// If the assignment operator is a prefix/postfix increment/decrement, then /// `value` is not present in the stack, so it should not be popped and the /// corresponding value of the `target` after/before update is pushed into the /// stack instead. assignToRef, /// Pop from the stack `target` and `value`. Get the name of the property /// from `UnlinkedConst.strings` and assign the `value` to the named property /// of the `target`. This operation is used when we know that the `target` /// is an object reference expression, e.g. `new Foo().a.b.c` or `a.b[0].c.d`. /// Perform `target.property op= value` where `op` is the next assignment /// operator from [UnlinkedExpr.assignmentOperators]. Push `value` back into /// the stack. /// /// If the assignment operator is a prefix/postfix increment/decrement, then /// `value` is not present in the stack, so it should not be popped and the /// corresponding value of the `target` after/before update is pushed into the /// stack instead. assignToProperty, /// Pop from the stack `index`, `target` and `value`. Perform /// `target[index] op= value` where `op` is the next assignment operator from /// [UnlinkedExpr.assignmentOperators]. Push `value` back into the stack. /// /// If the assignment operator is a prefix/postfix increment/decrement, then /// `value` is not present in the stack, so it should not be popped and the /// corresponding value of the `target` after/before update is pushed into the /// stack instead. assignToIndex, /// Pop from the stack `index` and `target`. Push into the stack the result /// of evaluation of `target[index]`. extractIndex, /// Pop the top `n` values from the stack (where `n` is obtained from /// [UnlinkedExpr.ints]) into a list (filled from the end) and take the next /// `n` values from [UnlinkedExpr.strings] and use the lists of names and /// values to create named arguments. Then pop the top `m` values from the /// stack (where `m` is obtained from [UnlinkedExpr.ints]) into a list (filled /// from the end) and use them as positional arguments. Use the lists of /// positional and names arguments to invoke a method (or a function) with /// the reference from [UnlinkedExpr.references]. If `k` is nonzero (where /// `k` is obtained from [UnlinkedExpr.ints]), obtain `k` type arguments from /// [UnlinkedExpr.references] and use them as generic type arguments for the /// aforementioned method or function. Push the result of the invocation onto /// the stack. /// /// Arguments are skipped, and `0` are specified as the numbers of arguments /// on the stack, if the expression is not a constant. We store expression of /// variable initializers to perform top-level inference, and arguments are /// never used to infer types. /// /// In general `a.b` cannot not be distinguished between: `a` is a prefix and /// `b` is a top-level function; or `a` is an object and `b` is the name of a /// method. This operation should be used for a sequence of identifiers /// `a.b.b.c.d.e` ending with an invokable result. invokeMethodRef, /// Pop the top `n` values from the stack (where `n` is obtained from /// [UnlinkedExpr.ints]) into a list (filled from the end) and take the next /// `n` values from [UnlinkedExpr.strings] and use the lists of names and /// values to create named arguments. Then pop the top `m` values from the /// stack (where `m` is obtained from [UnlinkedExpr.ints]) into a list (filled /// from the end) and use them as positional arguments. Use the lists of /// positional and names arguments to invoke the method with the name from /// [UnlinkedExpr.strings] of the target popped from the stack. If `k` is /// nonzero (where `k` is obtained from [UnlinkedExpr.ints]), obtain `k` type /// arguments from [UnlinkedExpr.references] and use them as generic type /// arguments for the aforementioned method. Push the result of the /// invocation onto the stack. /// /// Arguments are skipped, and `0` are specified as the numbers of arguments /// on the stack, if the expression is not a constant. We store expression of /// variable initializers to perform top-level inference, and arguments are /// never used to infer types. /// /// This operation should be used for invocation of a method invocation /// where `target` is known to be an object instance. invokeMethod, /// Begin a new cascade section. Duplicate the top value of the stack. cascadeSectionBegin, /// End a new cascade section. Pop the top value from the stack and throw it /// away. cascadeSectionEnd, /// Pop the top value from the stack and cast it to the type with reference /// from [UnlinkedExpr.references], push the result into the stack. typeCast, /// Pop the top value from the stack and check whether it is a subclass of the /// type with reference from [UnlinkedExpr.references], push the result into /// the stack. typeCheck, /// Pop the top value from the stack and raise an exception with this value. throwException, /// Obtain two values `n` and `m` from [UnlinkedExpr.ints]. Then, starting at /// the executable element for the expression being evaluated, if n > 0, pop /// to the nth enclosing function element. Then, push the mth local function /// of that element onto the stack. pushLocalFunctionReference, /// Pop the top two values from the stack. If the first value is non-null, /// keep it and discard the second. Otherwise, keep the second and discard /// the first. ifNull, /// Pop the top value from the stack. Treat it as a Future and await its /// completion. Then push the awaited value onto the stack. await, /// Push an abstract value onto the stack. Abstract values mark the presence /// of a value, but whose details are not included. /// /// This is not used by the summary generators today, but it will be used to /// experiment with prunning the initializer expression tree, so only /// information that is necessary gets included in the output summary file. pushUntypedAbstract, /// Get the next type reference from [UnlinkedExpr.references] and push an /// abstract value onto the stack that has that type. /// /// Like [pushUntypedAbstract], this is also not used by the summary /// generators today. The plan is to experiment with prunning the initializer /// expression tree, and include just enough type information to perform /// strong-mode type inference, but not all the details of how this type was /// obtained. pushTypedAbstract, /// Push an error onto the stack. /// /// Like [pushUntypedAbstract], this is not used by summary generators today. /// This will be used to experiment with prunning the const expression tree. /// If a constant has an error, we can omit the subexpression containing the /// error and only include a marker that an error was detected. pushError, /// Push `this` expression onto the stack. pushThis, /// Push `super` expression onto the stack. pushSuper, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), place them in a [Set], and push the result back /// onto the stack. The type parameter for the [Set] is implicitly /// `dynamic`. makeUntypedSet, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), place them in a [Set], and push the result back /// onto the stack. The type parameter for the [Set] is obtained from /// [UnlinkedExpr.references]. makeTypedSet, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), which should be [CollectionElement]s, place them in /// a [SetOrMap], and push the result back onto the stack. makeUntypedSetOrMap, /// Pop the top n values from the stack (where n is obtained from /// [UnlinkedExpr.ints]), which should be [CollectionElement]s, place them in /// a [Map], and push the result back onto the stack. The two type parameters /// for the [Map] are obtained from [UnlinkedExpr.references]. /// /// To replace [makeTypedMap] for unified collections. This is not backwards /// compatible with [makeTypedMap] because it expects [CollectionElement]s /// instead of pairs of [Expression]s. makeTypedMap2, /// Pop the top 2 values from the stack, place them in a [MapLiteralEntry], /// and push the result back onto the stack. makeMapLiteralEntry, /// Pop the top value from the stack, convert it to a spread element of type /// `...`, and push the result back onto the stack. spreadElement, /// Pop the top value from the stack, convert it to a spread element of type /// `...?`, and push the result back onto the stack. nullAwareSpreadElement, /// Pop the top two values from the stack. The first is a condition /// and the second is a collection element. Push an "if" element having the /// given condition, with the collection element as its "then" clause. ifElement, /// Pop the top three values from the stack. The first is a condition and the /// other two are collection elements. Push an "if" element having the given /// condition, with the two collection elements as its "then" and "else" /// clauses, respectively. ifElseElement, /// Pop the top n+2 values from the stack, where n is obtained from /// [UnlinkedExpr.ints]. The first two are the initialization and condition /// of the for-loop; the remainder are the updaters. forParts, /// Pop the top 2 values from the stack. The first is the for loop parts. /// The second is the body. forElement, /// Push the empty expression (used for missing initializers and conditions in /// `for` loops) pushEmptyExpression, /// Add a variable to the current scope whose name is obtained from /// [UnlinkedExpr.strings]. This is separate from [variableDeclaration] /// because the scope of the variable includes its own initializer. variableDeclarationStart, /// Pop the top value from the stack, and use it as the initializer for a /// variable declaration; the variable being declared is obtained by looking /// at the nth variable most recently added to the scope (where n counts from /// zero and is obtained from [UnlinkedExpr.ints]). variableDeclaration, /// Pop the top n values from the stack, which should all be variable /// declarations, and use them to create an untyped for-initializer /// declaration. The value of n is obtained from [UnlinkedExpr.ints]. forInitializerDeclarationsUntyped, /// Pop the top n values from the stack, which should all be variable /// declarations, and use them to create a typed for-initializer /// declaration. The value of n is obtained from [UnlinkedExpr.ints]. The /// type is obtained from [UnlinkedExpr.references]. forInitializerDeclarationsTyped, /// Pop from the stack `value` and get a string from [UnlinkedExpr.strings]. /// Use this string to look up a parameter. Perform `parameter op= value`, /// where `op` is the next assignment operator from /// [UnlinkedExpr.assignmentOperators]. Push `value` back onto the stack. /// /// If the assignment operator is a prefix/postfix increment/decrement, then /// `value` is not present in the stack, so it should not be popped and the /// corresponding value of the parameter after/before update is pushed onto /// the stack instead. assignToParameter, /// Pop from the stack an identifier and an expression, and create for-each /// parts of the form `identifier in expression`. forEachPartsWithIdentifier, /// Pop the top 2 values from the stack. The first is the for loop parts. /// The second is the body. forElementWithAwait, /// Pop an expression from the stack, and create for-each parts of the form /// `var name in expression`, where `name` is obtained from /// [UnlinkedExpr.strings]. forEachPartsWithUntypedDeclaration, /// Pop an expression from the stack, and create for-each parts of the form /// `Type name in expression`, where `name` is obtained from /// [UnlinkedExpr.strings], and `Type` is obtained from /// [UnlinkedExpr.references]. forEachPartsWithTypedDeclaration, /// Pop the top 2 values from the stack, compute `v1 >>> v2`, and push the /// result back onto the stack. bitShiftRightLogical, } /// Unlinked summary information about an extension declaration. abstract class UnlinkedExtension extends base.SummaryClass { /// Annotations for this extension. @Id(4) List<UnlinkedExpr> get annotations; /// Code range of the extension. @informative @Id(7) CodeRange get codeRange; /// Documentation comment for the extension, or `null` if there is no /// documentation comment. @informative @Id(5) UnlinkedDocumentationComment get documentationComment; /// Executable objects (methods, getters, and setters) contained in the /// extension. @Id(2) List<UnlinkedExecutable> get executables; /// The type being extended. @Id(3) EntityRef get extendedType; /// Field declarations contained in the extension. @Id(8) List<UnlinkedVariable> get fields; /// Name of the extension, or an empty string if there is no name. @Id(0) String get name; /// Offset of the extension name relative to the beginning of the file, or /// zero if there is no name. @informative @Id(1) int get nameOffset; /// Type parameters of the extension, if any. @Id(6) List<UnlinkedTypeParam> get typeParameters; } /// Unlinked summary information about an import declaration. abstract class UnlinkedImport extends base.SummaryClass { /// Annotations for this import declaration. @Id(8) List<UnlinkedExpr> get annotations; /// Combinators contained in this import declaration. @Id(4) List<UnlinkedCombinator> get combinators; /// Configurations used to control which library will actually be loaded at /// run-time. @Id(10) List<UnlinkedConfiguration> get configurations; /// Indicates whether the import declaration uses the `deferred` keyword. @Id(9) bool get isDeferred; /// Indicates whether the import declaration is implicit. @Id(5) bool get isImplicit; /// If [isImplicit] is false, offset of the "import" keyword. If [isImplicit] /// is true, zero. @informative @Id(0) int get offset; /// Offset of the prefix name relative to the beginning of the file, or zero /// if there is no prefix. @informative @Id(6) int get prefixOffset; /// Index into [UnlinkedUnit.references] of the prefix declared by this /// import declaration, or zero if this import declaration declares no prefix. /// /// Note that multiple imports can declare the same prefix. @Id(7) int get prefixReference; /// URI used in the source code to reference the imported library. @Id(1) String get uri; /// End of the URI string (including quotes) relative to the beginning of the /// file. If [isImplicit] is true, zero. @informative @Id(2) int get uriEnd; /// Offset of the URI string (including quotes) relative to the beginning of /// the file. If [isImplicit] is true, zero. @informative @Id(3) int get uriOffset; } @Variant('kind') abstract class UnlinkedInformativeData extends base.SummaryClass { @VariantId(2, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.compilationUnit, LinkedNodeKind.constructorDeclaration, LinkedNodeKind.defaultFormalParameter, LinkedNodeKind.enumConstantDeclaration, LinkedNodeKind.enumDeclaration, LinkedNodeKind.extensionDeclaration, LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.methodDeclaration, LinkedNodeKind.mixinDeclaration, LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.typeParameter, LinkedNodeKind.variableDeclaration, ]) int get codeLength; @VariantId(3, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.compilationUnit, LinkedNodeKind.constructorDeclaration, LinkedNodeKind.defaultFormalParameter, LinkedNodeKind.enumConstantDeclaration, LinkedNodeKind.enumDeclaration, LinkedNodeKind.extensionDeclaration, LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.methodDeclaration, LinkedNodeKind.mixinDeclaration, LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.typeParameter, LinkedNodeKind.variableDeclaration, ]) int get codeOffset; @VariantId(9, variantList: [ LinkedNodeKind.hideCombinator, LinkedNodeKind.showCombinator, ]) int get combinatorEnd; @VariantId(8, variantList: [ LinkedNodeKind.hideCombinator, LinkedNodeKind.showCombinator, ]) int get combinatorKeywordOffset; /// Offsets of the first character of each line in the source code. @VariantId(7, variant: LinkedNodeKind.compilationUnit) List<int> get compilationUnit_lineStarts; @VariantId(6, variant: LinkedNodeKind.constructorDeclaration) int get constructorDeclaration_periodOffset; @VariantId(5, variant: LinkedNodeKind.constructorDeclaration) int get constructorDeclaration_returnTypeOffset; /// If the parameter has a default value, the source text of the constant /// expression in the default value. Otherwise the empty string. @VariantId(10, variant: LinkedNodeKind.defaultFormalParameter) String get defaultFormalParameter_defaultValueCode; @VariantId(1, variantList: [ LinkedNodeKind.exportDirective, LinkedNodeKind.importDirective, LinkedNodeKind.libraryDirective, LinkedNodeKind.partDirective, LinkedNodeKind.partOfDirective, ]) int get directiveKeywordOffset; @VariantId(4, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.constructorDeclaration, LinkedNodeKind.enumDeclaration, LinkedNodeKind.enumConstantDeclaration, LinkedNodeKind.extensionDeclaration, LinkedNodeKind.fieldDeclaration, LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.libraryDirective, LinkedNodeKind.methodDeclaration, LinkedNodeKind.mixinDeclaration, LinkedNodeKind.topLevelVariableDeclaration, ]) List<String> get documentationComment_tokens; @VariantId(8, variant: LinkedNodeKind.importDirective) int get importDirective_prefixOffset; /// The kind of the node. @Id(0) LinkedNodeKind get kind; @VariantId(1, variantList: [ LinkedNodeKind.classDeclaration, LinkedNodeKind.classTypeAlias, LinkedNodeKind.constructorDeclaration, LinkedNodeKind.enumConstantDeclaration, LinkedNodeKind.enumDeclaration, LinkedNodeKind.extensionDeclaration, LinkedNodeKind.fieldFormalParameter, LinkedNodeKind.functionDeclaration, LinkedNodeKind.functionTypedFormalParameter, LinkedNodeKind.functionTypeAlias, LinkedNodeKind.genericTypeAlias, LinkedNodeKind.methodDeclaration, LinkedNodeKind.mixinDeclaration, LinkedNodeKind.simpleFormalParameter, LinkedNodeKind.typeParameter, LinkedNodeKind.variableDeclaration, ]) int get nameOffset; } /// Unlinked summary information about a function parameter. abstract class UnlinkedParam extends base.SummaryClass { /// Annotations for this parameter. @Id(9) List<UnlinkedExpr> get annotations; /// Code range of the parameter. @informative @Id(7) CodeRange get codeRange; /// If the parameter has a default value, the source text of the constant /// expression in the default value. Otherwise the empty string. @informative @Id(13) String get defaultValueCode; /// If this parameter's type is inferable, nonzero slot id identifying which /// entry in [LinkedLibrary.types] contains the inferred type. If there is no /// matching entry in [LinkedLibrary.types], then no type was inferred for /// this variable, so its static type is `dynamic`. /// /// Note that although strong mode considers initializing formals to be /// inferable, they are not marked as such in the summary; if their type is /// not specified, they always inherit the static type of the corresponding /// field. @Id(2) int get inferredTypeSlot; /// If this is a parameter of an instance method, a nonzero slot id which is /// unique within this compilation unit. If this id is found in /// [LinkedUnit.parametersInheritingCovariant], then this parameter inherits /// `@covariant` behavior from a base class. /// /// Otherwise, zero. @Id(14) int get inheritsCovariantSlot; /// The synthetic initializer function of the parameter. Absent if the /// variable does not have an initializer. @Id(12) UnlinkedExecutable get initializer; /// Indicates whether this parameter is explicitly marked as being covariant. @Id(15) bool get isExplicitlyCovariant; /// Indicates whether the parameter is declared using the `final` keyword. @Id(16) bool get isFinal; /// Indicates whether this is a function-typed parameter. A parameter is /// function-typed if the declaration of the parameter has explicit formal /// parameters /// ``` /// int functionTyped(int p) /// ``` /// but is not function-typed if it does not, even if the type of the /// parameter is a function type. @Id(5) bool get isFunctionTyped; /// Indicates whether this is an initializing formal parameter (i.e. it is /// declared using `this.` syntax). @Id(6) bool get isInitializingFormal; /// Kind of the parameter. @Id(4) UnlinkedParamKind get kind; /// Name of the parameter. @Id(0) String get name; /// Offset of the parameter name relative to the beginning of the file. @informative @Id(1) int get nameOffset; /// If [isFunctionTyped] is `true`, the parameters of the function type. @Id(8) List<UnlinkedParam> get parameters; /// If [isFunctionTyped] is `true`, the declared return type. If /// [isFunctionTyped] is `false`, the declared type. Absent if the type is /// implicit. @Id(3) EntityRef get type; /// The length of the visible range. @informative @Id(10) int get visibleLength; /// The beginning of the visible range. @informative @Id(11) int get visibleOffset; } /// Enum used to indicate the kind of a parameter. enum UnlinkedParamKind { /// Parameter is required and positional. requiredPositional, /// Parameter is optional and positional (enclosed in `[]`) optionalPositional, /// Parameter is optional and named (enclosed in `{}`) optionalNamed, /// Parameter is required and named (enclosed in `{}`). requiredNamed } /// Unlinked summary information about a part declaration. abstract class UnlinkedPart extends base.SummaryClass { /// Annotations for this part declaration. @Id(2) List<UnlinkedExpr> get annotations; /// End of the URI string (including quotes) relative to the beginning of the /// file. @informative @Id(0) int get uriEnd; /// Offset of the URI string (including quotes) relative to the beginning of /// the file. @informative @Id(1) int get uriOffset; } /// Unlinked summary information about a specific name contributed by a /// compilation unit to a library's public namespace. /// /// TODO(paulberry): some of this information is redundant with information /// elsewhere in the summary. Consider reducing the redundancy to reduce /// summary size. abstract class UnlinkedPublicName extends base.SummaryClass { /// The kind of object referred to by the name. @Id(1) ReferenceKind get kind; /// If this [UnlinkedPublicName] is a class, the list of members which can be /// referenced statically - static fields, static methods, and constructors. /// Otherwise empty. /// /// Unnamed constructors are not included since they do not constitute a /// separate name added to any namespace. @Id(2) List<UnlinkedPublicName> get members; /// The name itself. @Id(0) String get name; /// If the entity being referred to is generic, the number of type parameters /// it accepts. Otherwise zero. @Id(3) int get numTypeParameters; } /// Unlinked summary information about what a compilation unit contributes to a /// library's public namespace. This is the subset of [UnlinkedUnit] that is /// required from dependent libraries in order to perform prelinking. @TopLevel('UPNS') abstract class UnlinkedPublicNamespace extends base.SummaryClass { factory UnlinkedPublicNamespace.fromBuffer(List<int> buffer) => generated.readUnlinkedPublicNamespace(buffer); /// Export declarations in the compilation unit. @Id(2) List<UnlinkedExportPublic> get exports; /// Public names defined in the compilation unit. /// /// TODO(paulberry): consider sorting these names to reduce unnecessary /// relinking. @Id(0) List<UnlinkedPublicName> get names; /// URIs referenced by part declarations in the compilation unit. @Id(1) List<String> get parts; } /// Unlinked summary information about a name referred to in one library that /// might be defined in another. abstract class UnlinkedReference extends base.SummaryClass { /// Name of the entity being referred to. For the pseudo-type `dynamic`, the /// string is "dynamic". For the pseudo-type `void`, the string is "void". /// For the pseudo-type `bottom`, the string is "*bottom*". @Id(0) String get name; /// Prefix used to refer to the entity, or zero if no prefix is used. This is /// an index into [UnlinkedUnit.references]. /// /// Prefix references must always point backward; that is, for all i, if /// UnlinkedUnit.references[i].prefixReference != 0, then /// UnlinkedUnit.references[i].prefixReference < i. @Id(1) int get prefixReference; } /// TODO(scheglov) document enum UnlinkedTokenKind { nothing, comment, keyword, simple, string } /// TODO(scheglov) document abstract class UnlinkedTokens extends base.SummaryClass { /// The token that corresponds to this token, or `0` if this token is not /// the first of a pair of matching tokens (such as parentheses). @Id(0) List<int> get endGroup; /// Return `true` if this token is a synthetic token. A synthetic token is a /// token that was introduced by the parser in order to recover from an error /// in the code. @Id(1) List<bool> get isSynthetic; @Id(2) List<UnlinkedTokenKind> get kind; @Id(3) List<int> get length; @Id(4) List<String> get lexeme; /// The next token in the token stream, `0` for [UnlinkedTokenType.EOF] or /// the last comment token. @Id(5) List<int> get next; @Id(6) List<int> get offset; /// The first comment token in the list of comments that precede this token, /// or `0` if there are no comments preceding this token. Additional comments /// can be reached by following the token stream using [next] until `0` is /// reached. @Id(7) List<int> get precedingComment; @Id(8) List<UnlinkedTokenType> get type; } /// TODO(scheglov) document enum UnlinkedTokenType { NOTHING, ABSTRACT, AMPERSAND, AMPERSAND_AMPERSAND, AMPERSAND_EQ, AS, ASSERT, ASYNC, AT, AWAIT, BACKPING, BACKSLASH, BANG, BANG_EQ, BANG_EQ_EQ, BAR, BAR_BAR, BAR_EQ, BREAK, CARET, CARET_EQ, CASE, CATCH, CLASS, CLOSE_CURLY_BRACKET, CLOSE_PAREN, CLOSE_SQUARE_BRACKET, COLON, COMMA, CONST, CONTINUE, COVARIANT, DEFAULT, DEFERRED, DO, DOUBLE, DYNAMIC, ELSE, ENUM, EOF, EQ, EQ_EQ, EQ_EQ_EQ, EXPORT, EXTENDS, EXTERNAL, FACTORY, FALSE, FINAL, FINALLY, FOR, FUNCTION, FUNCTION_KEYWORD, GET, GT, GT_EQ, GT_GT, GT_GT_EQ, GT_GT_GT, GT_GT_GT_EQ, HASH, HEXADECIMAL, HIDE, IDENTIFIER, IF, IMPLEMENTS, IMPORT, IN, INDEX, INDEX_EQ, INT, INTERFACE, IS, LATE, LIBRARY, LT, LT_EQ, LT_LT, LT_LT_EQ, MINUS, MINUS_EQ, MINUS_MINUS, MIXIN, MULTI_LINE_COMMENT, NATIVE, NEW, NULL, OF, ON, OPEN_CURLY_BRACKET, OPEN_PAREN, OPEN_SQUARE_BRACKET, OPERATOR, PART, PATCH, PERCENT, PERCENT_EQ, PERIOD, PERIOD_PERIOD, PERIOD_PERIOD_PERIOD, PERIOD_PERIOD_PERIOD_QUESTION, PLUS, PLUS_EQ, PLUS_PLUS, QUESTION, QUESTION_PERIOD, QUESTION_QUESTION, QUESTION_QUESTION_EQ, REQUIRED, RETHROW, RETURN, SCRIPT_TAG, SEMICOLON, SET, SHOW, SINGLE_LINE_COMMENT, SLASH, SLASH_EQ, SOURCE, STAR, STAR_EQ, STATIC, STRING, STRING_INTERPOLATION_EXPRESSION, STRING_INTERPOLATION_IDENTIFIER, SUPER, SWITCH, SYNC, THIS, THROW, TILDE, TILDE_SLASH, TILDE_SLASH_EQ, TRUE, TRY, TYPEDEF, VAR, VOID, WHILE, WITH, YIELD, } /// Unlinked summary information about a typedef declaration. abstract class UnlinkedTypedef extends base.SummaryClass { /// Annotations for this typedef. @Id(4) List<UnlinkedExpr> get annotations; /// Code range of the typedef. @informative @Id(7) CodeRange get codeRange; /// Documentation comment for the typedef, or `null` if there is no /// documentation comment. @informative @Id(6) UnlinkedDocumentationComment get documentationComment; /// Name of the typedef. @Id(0) String get name; /// Offset of the typedef name relative to the beginning of the file. @informative @Id(1) int get nameOffset; /// If the typedef might not be simply bounded, a nonzero slot id which is /// unique within this compilation unit. If this id is found in /// [LinkedUnit.notSimplyBounded], then at least one of this typedef's type /// parameters is not simply bounded, hence this typedef can't be used as a /// raw type when specifying the bound of a type parameter. /// /// Otherwise, zero. @Id(9) int get notSimplyBoundedSlot; /// Parameters of the executable, if any. @Id(3) List<UnlinkedParam> get parameters; /// If [style] is [TypedefStyle.functionType], the return type of the typedef. /// If [style] is [TypedefStyle.genericFunctionType], the function type being /// defined. @Id(2) EntityRef get returnType; /// The style of the typedef. @Id(8) TypedefStyle get style; /// Type parameters of the typedef, if any. @Id(5) List<UnlinkedTypeParam> get typeParameters; } /// Unlinked summary information about a type parameter declaration. abstract class UnlinkedTypeParam extends base.SummaryClass { /// Annotations for this type parameter. @Id(3) List<UnlinkedExpr> get annotations; /// Bound of the type parameter, if a bound is explicitly declared. Otherwise /// null. @Id(2) EntityRef get bound; /// Code range of the type parameter. @informative @Id(4) CodeRange get codeRange; /// Name of the type parameter. @Id(0) String get name; /// Offset of the type parameter name relative to the beginning of the file. @informative @Id(1) int get nameOffset; } /// Unlinked summary information about a compilation unit ("part file"). @TopLevel('UUnt') abstract class UnlinkedUnit extends base.SummaryClass { factory UnlinkedUnit.fromBuffer(List<int> buffer) => generated.readUnlinkedUnit(buffer); /// MD5 hash of the non-informative fields of the [UnlinkedUnit] (not /// including this one) as 16 unsigned 8-bit integer values. This can be used /// to identify when the API of a unit may have changed. @Id(19) List<int> get apiSignature; /// Classes declared in the compilation unit. @Id(2) List<UnlinkedClass> get classes; /// Code range of the unit. @informative @Id(15) CodeRange get codeRange; /// Enums declared in the compilation unit. @Id(12) List<UnlinkedEnum> get enums; /// Top level executable objects (functions, getters, and setters) declared in /// the compilation unit. @Id(4) List<UnlinkedExecutable> get executables; /// Export declarations in the compilation unit. @Id(13) List<UnlinkedExportNonPublic> get exports; /// Extensions declared in the compilation unit. @Id(22) List<UnlinkedExtension> get extensions; /// If this compilation unit was summarized in fallback mode, the path where /// the compilation unit may be found on disk. Otherwise empty. /// /// When this field is non-empty, all other fields in the data structure have /// their default values. @deprecated @Id(16) String get fallbackModePath; /// Import declarations in the compilation unit. @Id(5) List<UnlinkedImport> get imports; /// Indicates whether this compilation unit is opted into NNBD. @Id(21) bool get isNNBD; /// Indicates whether the unit contains a "part of" declaration. @Id(18) bool get isPartOf; /// Annotations for the library declaration, or the empty list if there is no /// library declaration. @Id(14) List<UnlinkedExpr> get libraryAnnotations; /// Documentation comment for the library, or `null` if there is no /// documentation comment. @informative @Id(9) UnlinkedDocumentationComment get libraryDocumentationComment; /// Name of the library (from a "library" declaration, if present). @Id(6) String get libraryName; /// Length of the library name as it appears in the source code (or 0 if the /// library has no name). @informative @Id(7) int get libraryNameLength; /// Offset of the library name relative to the beginning of the file (or 0 if /// the library has no name). @informative @Id(8) int get libraryNameOffset; /// Offsets of the first character of each line in the source code. @informative @Id(17) List<int> get lineStarts; /// Mixins declared in the compilation unit. @Id(20) List<UnlinkedClass> get mixins; /// Part declarations in the compilation unit. @Id(11) List<UnlinkedPart> get parts; /// Unlinked public namespace of this compilation unit. @Id(0) UnlinkedPublicNamespace get publicNamespace; /// Top level and prefixed names referred to by this compilation unit. The /// zeroth element of this array is always populated and is used to represent /// the absence of a reference in places where a reference is optional (for /// example [UnlinkedReference.prefixReference or /// UnlinkedImport.prefixReference]). @Id(1) List<UnlinkedReference> get references; /// Typedefs declared in the compilation unit. @Id(10) List<UnlinkedTypedef> get typedefs; /// Top level variables declared in the compilation unit. @Id(3) List<UnlinkedVariable> get variables; } /// Unlinked summary information about a compilation unit. @TopLevel('UUN2') abstract class UnlinkedUnit2 extends base.SummaryClass { factory UnlinkedUnit2.fromBuffer(List<int> buffer) => generated.readUnlinkedUnit2(buffer); /// The MD5 hash signature of the API portion of this unit. It depends on all /// tokens that might affect APIs of declarations in the unit. @Id(0) List<int> get apiSignature; /// URIs of `export` directives. @Id(1) List<String> get exports; /// Is `true` if the unit contains a `library` directive. @Id(6) bool get hasLibraryDirective; /// Is `true` if the unit contains a `part of` directive. @Id(3) bool get hasPartOfDirective; /// URIs of `import` directives. @Id(2) List<String> get imports; @Id(7) List<UnlinkedInformativeData> get informativeData; /// Offsets of the first character of each line in the source code. @informative @Id(5) List<int> get lineStarts; /// URIs of `part` directives. @Id(4) List<String> get parts; } /// Unlinked summary information about a top level variable, local variable, or /// a field. abstract class UnlinkedVariable extends base.SummaryClass { /// Annotations for this variable. @Id(8) List<UnlinkedExpr> get annotations; /// Code range of the variable. @informative @Id(5) CodeRange get codeRange; /// Documentation comment for the variable, or `null` if there is no /// documentation comment. @informative @Id(10) UnlinkedDocumentationComment get documentationComment; /// If this variable is inferable, nonzero slot id identifying which entry in /// [LinkedLibrary.types] contains the inferred type for this variable. If /// there is no matching entry in [LinkedLibrary.types], then no type was /// inferred for this variable, so its static type is `dynamic`. @Id(9) int get inferredTypeSlot; /// If this is an instance non-final field, a nonzero slot id which is unique /// within this compilation unit. If this id is found in /// [LinkedUnit.parametersInheritingCovariant], then the parameter of the /// synthetic setter inherits `@covariant` behavior from a base class. /// /// Otherwise, zero. @Id(15) int get inheritsCovariantSlot; /// The synthetic initializer function of the variable. Absent if the /// variable does not have an initializer. @Id(13) UnlinkedExecutable get initializer; /// Indicates whether the variable is declared using the `const` keyword. @Id(6) bool get isConst; /// Indicates whether this variable is declared using the `covariant` keyword. /// This should be false for everything except instance fields. @Id(14) bool get isCovariant; /// Indicates whether the variable is declared using the `final` keyword. @Id(7) bool get isFinal; /// Indicates whether the variable is declared using the `late` keyword. @Id(16) bool get isLate; /// Indicates whether the variable is declared using the `static` keyword. /// /// Note that for top level variables, this flag is false, since they are not /// declared using the `static` keyword (even though they are considered /// static for semantic purposes). @Id(4) bool get isStatic; /// Name of the variable. @Id(0) String get name; /// Offset of the variable name relative to the beginning of the file. @informative @Id(1) int get nameOffset; /// If this variable is propagable, nonzero slot id identifying which entry in /// [LinkedLibrary.types] contains the propagated type for this variable. If /// there is no matching entry in [LinkedLibrary.types], then this variable's /// propagated type is the same as its declared type. /// /// Non-propagable variables have a [propagatedTypeSlot] of zero. @Id(2) int get propagatedTypeSlot; /// Declared type of the variable. Absent if the type is implicit. @Id(3) EntityRef get type; /// If a local variable, the length of the visible range; zero otherwise. @deprecated @informative @Id(11) int get visibleLength; /// If a local variable, the beginning of the visible range; zero otherwise. @deprecated @informative @Id(12) int get visibleOffset; }
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/summary/flat_buffers.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 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; /** * Reader of lists of boolean values. * * The returned unmodifiable lists lazily read values on access. */ class BoolListReader extends Reader<List<bool>> { const BoolListReader(); @override int get size => 4; @override List<bool> read(BufferContext bc, int offset) => new _FbBoolList(bc, bc.derefObject(offset)); } /** * The reader of booleans. */ class BoolReader extends Reader<bool> { const BoolReader() : super(); @override int get size => 1; @override bool read(BufferContext bc, int offset) => bc._getInt8(offset) != 0; } /** * Buffer with data and some context about it. */ class BufferContext { final ByteData _buffer; factory BufferContext.fromBytes(List<int> byteList) { Uint8List uint8List = _asUint8List(byteList); ByteData buf = new ByteData.view(uint8List.buffer, uint8List.offsetInBytes); return new BufferContext._(buf); } BufferContext._(this._buffer); int derefObject(int offset) { return offset + _getUint32(offset); } Uint8List _asUint8LIst(int offset, int length) => _buffer.buffer.asUint8List(_buffer.offsetInBytes + offset, length); double _getFloat64(int offset) => _buffer.getFloat64(offset, Endian.little); int _getInt32(int offset) => _buffer.getInt32(offset, Endian.little); int _getInt8(int offset) => _buffer.getInt8(offset); int _getUint16(int offset) => _buffer.getUint16(offset, Endian.little); int _getUint32(int offset) => _buffer.getUint32(offset, Endian.little); int _getUint8(int offset) => _buffer.getUint8(offset); /** * If the [byteList] is already a [Uint8List] return it. * Otherwise return a [Uint8List] copy of the [byteList]. */ static Uint8List _asUint8List(List<int> byteList) { if (byteList is Uint8List) { return byteList; } else { return new Uint8List.fromList(byteList); } } } /** * Class that helps building flat buffers. */ class Builder { final int initialSize; /** * The list of field tails, reused by [_VTable] instances. */ final Int32List _reusedFieldTails = Int32List(1024); /** * The list of field offsets, reused by [_VTable] instances. */ final Int32List _reusedFieldOffsets = Int32List(1024); /** * The list of existing VTable(s). */ final List<_VTable> _vTables = <_VTable>[]; ByteData _buf; /** * The maximum alignment that has been seen so far. If [_buf] has to be * reallocated in the future (to insert room at its start for more bytes) the * reallocation will need to be a multiple of this many bytes. */ int _maxAlign; /** * The number of bytes that have been written to the buffer so far. The * most recently written byte is this many bytes from the end of [_buf]. */ int _tail; /** * The location of the end of the current table, measured in bytes from the * end of [_buf], or `null` if a table is not currently being built. */ int _currentTableEndTail; _VTable _currentVTable; /** * Map containing all strings that have been written so far. This allows us * to avoid duplicating strings. */ Map<String, Offset<String>> _strings = <String, Offset<String>>{}; Builder({this.initialSize: 1024}) { reset(); } /** * Add the [field] with the given boolean [value]. The field is not added if * the [value] is equal to [def]. Booleans are stored as 8-bit fields with * `0` for `false` and `1` for `true`. */ void addBool(int field, bool value, [bool def]) { _ensureCurrentVTable(); if (value != null && value != def) { int size = 1; _prepare(size, 1); _trackField(field); _buf.setInt8(_buf.lengthInBytes - _tail, value ? 1 : 0); } } /** * Add the [field] with the given 64-bit float [value]. */ void addFloat64(int field, double value, [double def]) { _ensureCurrentVTable(); if (value != null && value != def) { int size = 8; _prepare(size, 1); _trackField(field); _setFloat64AtTail(_buf, _tail, value); } } /** * Add the [field] with the given 32-bit signed integer [value]. The field is * not added if the [value] is equal to [def]. */ void addInt32(int field, int value, [int def]) { _ensureCurrentVTable(); if (value != null && value != def) { int size = 4; _prepare(size, 1); _trackField(field); _setInt32AtTail(_buf, _tail, value); } } /** * Add the [field] with the given 8-bit signed integer [value]. The field is * not added if the [value] is equal to [def]. */ void addInt8(int field, int value, [int def]) { _ensureCurrentVTable(); if (value != null && value != def) { int size = 1; _prepare(size, 1); _trackField(field); _buf.setInt8(_buf.lengthInBytes - _tail, value); } } /** * Add the [field] referencing an object with the given [offset]. */ void addOffset(int field, Offset offset) { _ensureCurrentVTable(); if (offset != null) { _prepare(4, 1); _trackField(field); _setUint32AtTail(_buf, _tail, _tail - offset._tail); } } /** * Add the [field] with the given 32-bit unsigned integer [value]. The field * is not added if the [value] is equal to [def]. */ void addUint32(int field, int value, [int def]) { _ensureCurrentVTable(); if (value != null && value != def) { int size = 4; _prepare(size, 1); _trackField(field); _setUint32AtTail(_buf, _tail, value); } } /** * Add the [field] with the given 8-bit unsigned integer [value]. The field * is not added if the [value] is equal to [def]. */ void addUint8(int field, int value, [int def]) { _ensureCurrentVTable(); if (value != null && value != def) { int size = 1; _prepare(size, 1); _trackField(field); _setUint8AtTail(_buf, _tail, value); } } /** * End the current table and return its offset. */ Offset endTable() { if (_currentVTable == null) { throw new StateError('Start a table before ending it.'); } // Prepare for writing the VTable. _prepare(4, 1); int tableTail = _tail; // Prepare the size of the current table. _currentVTable.tableSize = tableTail - _currentTableEndTail; // Prepare the VTable to use for the current table. int vTableTail; { _currentVTable.computeFieldOffsets(tableTail); // Try to find an existing compatible VTable. for (int i = 0; i < _vTables.length; i++) { _VTable vTable = _vTables[i]; if (_currentVTable.canUseExistingVTable(vTable)) { vTableTail = vTable.tail; break; } } // Write a new VTable. if (vTableTail == null) { _currentVTable.takeFieldOffsets(); _prepare(2, _currentVTable.numOfUint16); vTableTail = _tail; _currentVTable.tail = vTableTail; _currentVTable.output(_buf, _buf.lengthInBytes - _tail); _vTables.add(_currentVTable); } } // Set the VTable offset. _setInt32AtTail(_buf, tableTail, vTableTail - tableTail); // Done with this table. _currentVTable = null; return new Offset(tableTail); } /** * Finish off the creation of the buffer. The given [offset] is used as the * root object offset, and usually references directly or indirectly every * written object. If [fileIdentifier] is specified (and not `null`), it is * interpreted as a 4-byte Latin-1 encoded string that should be placed at * bytes 4-7 of the file. */ Uint8List finish(Offset offset, [String fileIdentifier]) { _prepare(max(4, _maxAlign), fileIdentifier == null ? 1 : 2); int alignedTail = _tail + ((-_tail) % _maxAlign); _setUint32AtTail(_buf, alignedTail, alignedTail - offset._tail); if (fileIdentifier != null) { for (int i = 0; i < 4; i++) { _setUint8AtTail( _buf, alignedTail - 4 - i, fileIdentifier.codeUnitAt(i)); } } return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail); } /** * This is a low-level method, it should not be invoked by clients. */ Uint8List lowFinish() { int alignedTail = _tail + ((-_tail) % _maxAlign); return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail); } /** * This is a low-level method, it should not be invoked by clients. */ void lowReset() { _buf = new ByteData(initialSize); _maxAlign = 1; _tail = 0; } /** * This is a low-level method, it should not be invoked by clients. */ void lowWriteUint32(int value) { _prepare(4, 1); _setUint32AtTail(_buf, _tail, value); } /** * This is a low-level method, it should not be invoked by clients. */ void lowWriteUint8(int value) { _prepare(1, 1); _buf.setUint8(_buf.lengthInBytes - _tail, value); } /** * Reset the builder and make it ready for filling a new buffer. */ void reset() { _buf = new ByteData(initialSize); _maxAlign = 1; _tail = 0; _currentVTable = null; } /** * Start a new table. Must be finished with [endTable] invocation. */ void startTable() { if (_currentVTable != null) { throw new StateError('Inline tables are not supported.'); } _currentVTable = new _VTable(_reusedFieldTails, _reusedFieldOffsets); _currentTableEndTail = _tail; } /** * Write the given list of [values]. */ Offset writeList(List<Offset> values) { _ensureNoVTable(); _prepare(4, 1 + values.length); Offset result = new Offset(_tail); int tail = _tail; _setUint32AtTail(_buf, tail, values.length); tail -= 4; for (Offset value in values) { _setUint32AtTail(_buf, tail, tail - value._tail); tail -= 4; } return result; } /** * Write the given list of boolean [values]. */ Offset writeListBool(List<bool> values) { int bitLength = values.length; int padding = (-bitLength) % 8; int byteLength = (bitLength + padding) ~/ 8; // Prepare the backing Uint8List. Uint8List bytes = new Uint8List(byteLength + 1); // Record every bit. int byteIndex = 0; int byte = 0; int mask = 1; for (int bitIndex = 0; bitIndex < bitLength; bitIndex++) { if (bitIndex != 0 && (bitIndex % 8 == 0)) { bytes[byteIndex++] = byte; byte = 0; mask = 1; } if (values[bitIndex]) { byte |= mask; } mask <<= 1; } // Write the last byte, even if it may be on the padding. bytes[byteIndex] = byte; // Write the padding length. bytes[byteLength] = padding; // Write as a Uint8 list. return writeListUint8(bytes); } /** * Write the given list of 64-bit float [values]. */ Offset writeListFloat64(List<double> values) { _ensureNoVTable(); _prepare(8, 1 + values.length); Offset result = new Offset(_tail); int tail = _tail; _setUint32AtTail(_buf, tail, values.length); tail -= 8; for (double value in values) { _setFloat64AtTail(_buf, tail, value); tail -= 8; } return result; } /** * Write the given list of signed 32-bit integer [values]. */ Offset writeListInt32(List<int> values) { _ensureNoVTable(); _prepare(4, 1 + values.length); Offset result = new Offset(_tail); int tail = _tail; _setUint32AtTail(_buf, tail, values.length); tail -= 4; for (int value in values) { _setInt32AtTail(_buf, tail, value); tail -= 4; } return result; } /** * Write the given list of unsigned 32-bit integer [values]. */ Offset writeListUint32(List<int> values) { _ensureNoVTable(); _prepare(4, 1 + values.length); Offset result = new Offset(_tail); int tail = _tail; _setUint32AtTail(_buf, tail, values.length); tail -= 4; for (int value in values) { _setUint32AtTail(_buf, tail, value); tail -= 4; } return result; } /** * Write the given list of unsigned 8-bit integer [values]. */ Offset writeListUint8(List<int> values) { _ensureNoVTable(); _prepare(4, 1, additionalBytes: values.length); Offset result = new Offset(_tail); int tail = _tail; _setUint32AtTail(_buf, tail, values.length); tail -= 4; for (int value in values) { _setUint8AtTail(_buf, tail, value); tail -= 1; } return result; } /** * Write the given string [value] and return its [Offset], or `null` if * the [value] is equal to [def]. */ Offset<String> writeString(String value, [String def]) { _ensureNoVTable(); if (value != def) { return _strings.putIfAbsent(value, () { // TODO(scheglov) optimize for ASCII strings List<int> bytes = utf8.encode(value); int length = bytes.length; _prepare(4, 1, additionalBytes: length); Offset<String> result = new Offset(_tail); _setUint32AtTail(_buf, _tail, length); int offset = _buf.lengthInBytes - _tail + 4; for (int i = 0; i < length; i++) { _buf.setUint8(offset++, bytes[i]); } return result; }); } return null; } /** * Throw an exception if there is not currently a vtable. */ void _ensureCurrentVTable() { if (_currentVTable == null) { throw new StateError('Start a table before adding values.'); } } /** * Throw an exception if there is currently a vtable. */ void _ensureNoVTable() { if (_currentVTable != null) { throw new StateError( 'Cannot write a non-scalar value while writing a table.'); } } /** * Prepare for writing the given [count] of scalars of the given [size]. * Additionally allocate the specified [additionalBytes]. Update the current * tail pointer to point at the allocated space. */ void _prepare(int size, int count, {int additionalBytes: 0}) { // Update the alignment. if (_maxAlign < size) { _maxAlign = size; } // Prepare amount of required space. int dataSize = size * count + additionalBytes; int alignDelta = (-(_tail + dataSize)) % size; int bufSize = alignDelta + dataSize; // Ensure that we have the required amount of space. { int oldCapacity = _buf.lengthInBytes; if (_tail + bufSize > oldCapacity) { int desiredNewCapacity = (oldCapacity + bufSize) * 2; int deltaCapacity = desiredNewCapacity - oldCapacity; deltaCapacity += (-deltaCapacity) % _maxAlign; int newCapacity = oldCapacity + deltaCapacity; ByteData newBuf = new ByteData(newCapacity); newBuf.buffer .asUint8List() .setAll(deltaCapacity, _buf.buffer.asUint8List()); _buf = newBuf; } } // Update the tail pointer. _tail += bufSize; } /** * Record the offset of the given [field]. */ void _trackField(int field) { _currentVTable.addField(field, _tail); } static void _setFloat64AtTail(ByteData _buf, int tail, double x) { _buf.setFloat64(_buf.lengthInBytes - tail, x, Endian.little); } static void _setInt32AtTail(ByteData _buf, int tail, int x) { _buf.setInt32(_buf.lengthInBytes - tail, x, Endian.little); } static void _setUint32AtTail(ByteData _buf, int tail, int x) { _buf.setUint32(_buf.lengthInBytes - tail, x, Endian.little); } static void _setUint8AtTail(ByteData _buf, int tail, int x) { _buf.setUint8(_buf.lengthInBytes - tail, x); } } /** * The reader of lists of 64-bit float values. * * The returned unmodifiable lists lazily read values on access. */ class Float64ListReader extends Reader<List<double>> { const Float64ListReader(); @override int get size => 4; @override List<double> read(BufferContext bc, int offset) => new _FbFloat64List(bc, bc.derefObject(offset)); } /** * The reader of 64-bit floats. */ class Float64Reader extends Reader<double> { const Float64Reader() : super(); @override int get size => 8; @override double read(BufferContext bc, int offset) => bc._getFloat64(offset); } /** * The reader of signed 32-bit integers. */ class Int32Reader extends Reader<int> { const Int32Reader() : super(); @override int get size => 4; @override int read(BufferContext bc, int offset) => bc._getInt32(offset); } /** * The reader of 8-bit signed integers. */ class Int8Reader extends Reader<int> { const Int8Reader() : super(); @override int get size => 1; @override int read(BufferContext bc, int offset) => bc._getInt8(offset); } /** * The reader of lists of objects. * * The returned unmodifiable lists lazily read objects on access. */ class ListReader<E> extends Reader<List<E>> { final Reader<E> _elementReader; const ListReader(this._elementReader); @override int get size => 4; @override List<E> read(BufferContext bc, int offset) => new _FbGenericList<E>(_elementReader, bc, bc.derefObject(offset)); } /** * The offset from the end of the buffer to a serialized object of the type [T]. */ class Offset<T> { final int _tail; Offset(this._tail); } /** * Object that can read a value at a [BufferContext]. */ abstract class Reader<T> { const Reader(); /** * The size of the value in bytes. */ int get size; /** * Read the value at the given [offset] in [bc]. */ T read(BufferContext bc, int offset); /** * Read the value of the given [field] in the given [object]. */ T vTableGet(BufferContext object, int offset, int field, [T defaultValue]) { int vTableSOffset = object._getInt32(offset); int vTableOffset = offset - vTableSOffset; int vTableSize = object._getUint16(vTableOffset); int vTableFieldOffset = (1 + 1 + field) * 2; if (vTableFieldOffset < vTableSize) { int fieldOffsetInObject = object._getUint16(vTableOffset + vTableFieldOffset); if (fieldOffsetInObject != 0) { return read(object, offset + fieldOffsetInObject); } } return defaultValue; } } /** * The reader of string values. */ class StringReader extends Reader<String> { const StringReader() : super(); @override int get size => 4; @override String read(BufferContext bc, int offset) { int strOffset = bc.derefObject(offset); int length = bc._getUint32(strOffset); Uint8List bytes = bc._asUint8LIst(strOffset + 4, length); if (_isLatin(bytes)) { return new String.fromCharCodes(bytes); } return utf8.decode(bytes); } static bool _isLatin(Uint8List bytes) { int length = bytes.length; for (int i = 0; i < length; i++) { if (bytes[i] > 127) { return false; } } return true; } } /** * An abstract reader for tables. */ abstract class TableReader<T> extends Reader<T> { const TableReader(); @override int get size => 4; /** * Return the object at [offset]. */ T createObject(BufferContext bc, int offset); @override T read(BufferContext bp, int offset) { int objectOffset = bp.derefObject(offset); return createObject(bp, objectOffset); } } /** * Reader of lists of unsigned 32-bit integer values. * * The returned unmodifiable lists lazily read values on access. */ class Uint32ListReader extends Reader<List<int>> { const Uint32ListReader(); @override int get size => 4; @override List<int> read(BufferContext bc, int offset) => new _FbUint32List(bc, bc.derefObject(offset)); } /** * The reader of unsigned 32-bit integers. */ class Uint32Reader extends Reader<int> { const Uint32Reader() : super(); @override int get size => 4; @override int read(BufferContext bc, int offset) => bc._getUint32(offset); } /** * Reader of lists of unsigned 8-bit integer values. * * The returned unmodifiable lists lazily read values on access. */ class Uint8ListReader extends Reader<List<int>> { const Uint8ListReader(); @override int get size => 4; @override List<int> read(BufferContext bc, int offset) => new _FbUint8List(bc, bc.derefObject(offset)); } /** * The reader of unsigned 8-bit integers. */ class Uint8Reader extends Reader<int> { const Uint8Reader() : super(); @override int get size => 1; @override int read(BufferContext bc, int offset) => bc._getUint8(offset); } /** * List of booleans backed by 8-bit unsigned integers. */ class _FbBoolList with ListMixin<bool> implements List<bool> { final BufferContext bc; final int offset; int _length; _FbBoolList(this.bc, this.offset); @override int get length { if (_length == null) { int byteLength = bc._getUint32(offset); _length = (byteLength - 1) * 8 - _getByte(byteLength - 1); } return _length; } @override void set length(int i) => throw new StateError('Attempt to modify immutable list'); @override bool operator [](int i) { int index = i ~/ 8; int mask = 1 << i % 8; return _getByte(index) & mask != 0; } @override void operator []=(int i, bool e) => throw new StateError('Attempt to modify immutable list'); int _getByte(int index) => bc._getUint8(offset + 4 + index); } /** * The list backed by 64-bit values - Uint64 length and Float64. */ class _FbFloat64List extends _FbList<double> { _FbFloat64List(BufferContext bc, int offset) : super(bc, offset); @override double operator [](int i) { return bc._getFloat64(offset + 8 + 8 * i); } } /** * List backed by a generic object which may have any size. */ class _FbGenericList<E> extends _FbList<E> { final Reader<E> elementReader; List<E> _items; _FbGenericList(this.elementReader, BufferContext bp, int offset) : super(bp, offset); @override E operator [](int i) { _items ??= new List<E>(length); E item = _items[i]; if (item == null) { item = elementReader.read(bc, offset + 4 + elementReader.size * i); _items[i] = item; } return item; } } /** * The base class for immutable lists read from flat buffers. */ abstract class _FbList<E> with ListMixin<E> implements List<E> { final BufferContext bc; final int offset; int _length; _FbList(this.bc, this.offset); @override int get length { _length ??= bc._getUint32(offset); return _length; } @override void set length(int i) => throw new StateError('Attempt to modify immutable list'); @override void operator []=(int i, E e) => throw new StateError('Attempt to modify immutable list'); } /** * List backed by 32-bit unsigned integers. */ class _FbUint32List extends _FbList<int> { _FbUint32List(BufferContext bc, int offset) : super(bc, offset); @override int operator [](int i) { return bc._getUint32(offset + 4 + 4 * i); } } /** * List backed by 8-bit unsigned integers. */ class _FbUint8List extends _FbList<int> { _FbUint8List(BufferContext bc, int offset) : super(bc, offset); @override int operator [](int i) { return bc._getUint8(offset + 4 + i); } } /** * Class that describes the structure of a table. */ class _VTable { final Int32List _reusedFieldTails; final Int32List _reusedFieldOffsets; /** * The number of fields in [_reusedFieldTails]. */ int _fieldCount = 0; /** * The private copy of [_reusedFieldOffsets], which is made only when we * find that this table is unique. */ Int32List _fieldOffsets; /** * The size of the table that uses this VTable. */ int tableSize; /** * The tail of this VTable. It is used to share the same VTable between * multiple tables of identical structure. */ int tail; _VTable(this._reusedFieldTails, this._reusedFieldOffsets); int get numOfUint16 => 1 + 1 + _fieldCount; void addField(int field, int offset) { while (_fieldCount <= field) { _reusedFieldTails[_fieldCount++] = -1; } _reusedFieldTails[field] = offset; } /** * Return `true` if the [existing] VTable can be used instead of this. */ bool canUseExistingVTable(_VTable existing) { assert(tail == null); assert(existing.tail != null); if (tableSize == existing.tableSize && _fieldCount == existing._fieldCount) { for (int i = 0; i < _fieldCount; i++) { if (_reusedFieldOffsets[i] != existing._fieldOffsets[i]) { return false; } } return true; } return false; } /** * Fill the [_reusedFieldOffsets] field. */ void computeFieldOffsets(int tableTail) { for (int i = 0; i < _fieldCount; ++i) { int fieldTail = _reusedFieldTails[i]; _reusedFieldOffsets[i] = fieldTail == -1 ? 0 : tableTail - fieldTail; } } /** * Outputs this VTable to [buf], which is is expected to be aligned to 16-bit * and have at least [numOfUint16] 16-bit words available. */ void output(ByteData buf, int bufOffset) { // VTable size. buf.setUint16(bufOffset, numOfUint16 * 2, Endian.little); bufOffset += 2; // Table size. buf.setUint16(bufOffset, tableSize, Endian.little); bufOffset += 2; // Field offsets. for (int fieldOffset in _fieldOffsets) { buf.setUint16(bufOffset, fieldOffset, Endian.little); bufOffset += 2; } } /** * Fill the [_fieldOffsets] field. */ void takeFieldOffsets() { assert(_fieldOffsets == null); _fieldOffsets = Int32List(_fieldCount); for (int i = 0; i < _fieldCount; ++i) { _fieldOffsets[i] = _reusedFieldOffsets[i]; } } }
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/summary/summary_sdk.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/file_system/file_system.dart' show ResourceProvider; import 'package:analyzer/src/context/context.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart' show DartUriResolver, Source, SourceFactory; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary/package_bundle_reader.dart'; /** * An implementation of [DartSdk] which provides analysis results for `dart:` * libraries from the given summary file. This implementation is limited and * suitable only for command-line tools, but not for IDEs - it does not * implement [sdkLibraries], [sdkVersion], [uris] and [fromFileUri]. */ class SummaryBasedDartSdk implements DartSdk { SummaryDataStore _dataStore; InSummaryUriResolver _uriResolver; PackageBundle _bundle; ResourceProvider resourceProvider; /** * The [AnalysisContext] which is used for all of the sources in this sdk. */ InternalAnalysisContext _analysisContext; SummaryBasedDartSdk(String summaryPath, bool _, {this.resourceProvider}) { _dataStore = new SummaryDataStore(<String>[summaryPath], resourceProvider: resourceProvider); _uriResolver = new InSummaryUriResolver(resourceProvider, _dataStore); _bundle = _dataStore.bundles.single; } SummaryBasedDartSdk.fromBundle(bool _, PackageBundle bundle, {this.resourceProvider}) { _dataStore = new SummaryDataStore([], resourceProvider: resourceProvider); _dataStore.addBundle('dart_sdk.sum', bundle); _uriResolver = new InSummaryUriResolver(resourceProvider, _dataStore); _bundle = bundle; } /** * Return the [PackageBundle] for this SDK, not `null`. */ PackageBundle get bundle => _bundle; @override AnalysisContext get context { if (_analysisContext == null) { AnalysisOptionsImpl analysisOptions = new AnalysisOptionsImpl(); _analysisContext = new SdkAnalysisContext(analysisOptions); SourceFactory factory = new SourceFactory( [new DartUriResolver(this)], null, resourceProvider); _analysisContext.sourceFactory = factory; } return _analysisContext; } @override List<SdkLibrary> get sdkLibraries { throw new UnimplementedError(); } @override String get sdkVersion { throw new UnimplementedError(); } bool get strongMode => true; @override List<String> get uris { throw new UnimplementedError(); } @override Source fromFileUri(Uri uri) { return null; } @override PackageBundle getLinkedBundle() => _bundle; @override SdkLibrary getSdkLibrary(String uri) { // This is not quite correct, but currently it's used only in // to report errors on importing or exporting of internal libraries. return null; } @override Source mapDartUri(String uriStr) { Uri uri = Uri.parse(uriStr); return _uriResolver.resolveAbsolute(uri); } }
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/summary/api_signature.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:convert'; import 'dart:typed_data'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart'; /** * An instance of [ApiSignature] collects data in the form of primitive types * (strings, ints, bools, etc.) from a summary "builder" object, and uses them * to generate an MD5 signature of a the non-informative parts of the summary * (i.e. those parts representing the API of the code being summarized). * * Note that the data passed to the MD5 signature algorithm is untyped. So, for * instance, an API signature built from a sequence of `false` booleans is * likely to match an API signature built from a sequence of zeros. The caller * should take this into account; e.g. if a data structure may be represented * either by a boolean or an int, the caller should encode a tag distinguishing * the two representations before encoding the data. */ class ApiSignature { /** * Version number of the code in this class. Any time this class is changed * in a way that affects the data collected in [_data], this version number * should be incremented, so that a summary signed by a newer version of the * signature algorithm won't accidentally have the same signature as a summary * signed by an older version. */ static const int _VERSION = 0; /** * Data accumulated so far. */ ByteData _data = new ByteData(4096); /** * Offset into [_data] where the next byte should be written. */ int _offset = 0; /** * Create an [ApiSignature] which is ready to accept data. */ ApiSignature() { addInt(_VERSION); } /** * For testing only: create an [ApiSignature] which doesn't include any * version information. This makes it easier to unit tests, since the data * is stable even if [_VERSION] is changed. */ ApiSignature.unversioned(); /** * Collect a boolean value. */ void addBool(bool b) { _makeRoom(1); _data.setUint8(_offset, b ? 1 : 0); _offset++; } /** * Collect a sequence of arbitrary bytes. Note that the length is not * collected, so for example `addBytes([1, 2]);` will have the same effect as * `addBytes([1]); addBytes([2]);`. */ void addBytes(List<int> bytes) { int length = bytes.length; _makeRoom(length); for (int i = 0; i < length; i++) { _data.setUint8(_offset + i, bytes[i]); } _offset += length; } /** * Collect a double-precision floating point value. */ void addDouble(double d) { _makeRoom(8); _data.setFloat64(_offset, d, Endian.little); _offset += 8; } /** * Collect a 32-bit unsigned integer value. */ void addInt(int i) { _makeRoom(4); _data.setUint32(_offset, i, Endian.little); _offset += 4; } /** * Collect a string. */ void addString(String s) { List<int> bytes = utf8.encode(s); addInt(bytes.length); addBytes(bytes); } /** * Collect the given [Uint32List]. */ void addUint32List(Uint32List data) { addBytes(data.buffer.asUint8List()); } /** * For testing only: retrieve the internal representation of the data that * has been collected. */ List<int> getBytes_forDebug() { return new Uint8List.view(_data.buffer, 0, _offset).toList(); } /** * Return the bytes of the MD5 hash of the data collected so far. */ List<int> toByteList() { return md5.convert(new Uint8List.view(_data.buffer, 0, _offset)).bytes; } /** * Return a hex-encoded MD5 signature of the data collected so far. */ String toHex() { return hex.encode(toByteList()); } /** * Ensure that [spaceNeeded] bytes can be added to [_data] at [_offset] * (copying it to a larger object if necessary). */ void _makeRoom(int spaceNeeded) { int oldLength = _data.lengthInBytes; if (_offset + spaceNeeded > oldLength) { int newLength = 2 * (_offset + spaceNeeded); ByteData newData = new ByteData(newLength); new Uint8List.view(newData.buffer) .setRange(0, oldLength, new Uint8List.view(_data.buffer)); _data = newData; } } }
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/summary/link.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. /** * An instance of [DependencyWalker] contains the core algorithms for * walking a dependency graph and evaluating nodes in a safe order. */ abstract class DependencyWalker<NodeType extends Node<NodeType>> { /** * Called by [walk] to evaluate a single non-cyclical node, after * all that node's dependencies have been evaluated. */ void evaluate(NodeType v); /** * Called by [walk] to evaluate a strongly connected component * containing one or more nodes. All dependencies of the strongly * connected component have been evaluated. */ void evaluateScc(List<NodeType> scc); /** * Walk the dependency graph starting at [startingPoint], finding * strongly connected components and evaluating them in a safe order * by calling [evaluate] and [evaluateScc]. * * This is an implementation of Tarjan's strongly connected * components algorithm * (https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm). */ void walk(NodeType startingPoint) { // TODO(paulberry): consider rewriting in a non-recursive way so // that long dependency chains don't cause stack overflow. // TODO(paulberry): in the event that an exception occurs during // the walk, restore the state of the [Node] data structures so // that further evaluation will be safe. // The index which will be assigned to the next node that is // freshly visited. int index = 1; // Stack of nodes which have been seen so far and whose strongly // connected component is still being determined. Nodes are only // popped off the stack when they are evaluated, so sometimes the // stack contains nodes that were visited after the current node. List<NodeType> stack = <NodeType>[]; void strongConnect(NodeType node) { bool hasTrivialCycle = false; // Assign the current node an index and add it to the stack. We // haven't seen any of its dependencies yet, so set its lowLink // to its index, indicating that so far it is the only node in // its strongly connected component. node._index = node._lowLink = index++; stack.add(node); // Consider the node's dependencies one at a time. for (NodeType dependency in Node.getDependencies(node)) { // If the dependency has already been evaluated, it can't be // part of this node's strongly connected component, so we can // skip it. if (dependency.isEvaluated) { continue; } if (identical(node, dependency)) { // If a node includes itself as a dependency, there is no need to // explore the dependency further. hasTrivialCycle = true; } else if (dependency._index == 0) { // The dependency hasn't been seen yet, so recurse on it. strongConnect(dependency); // If the dependency's lowLink refers to a node that was // visited before the current node, that means that the // current node, the dependency, and the node referred to by // the dependency's lowLink are all part of the same // strongly connected component, so we need to update the // current node's lowLink accordingly. if (dependency._lowLink < node._lowLink) { node._lowLink = dependency._lowLink; } } else { // The dependency has already been seen, so it is part of // the current node's strongly connected component. If it // was visited earlier than the current node's lowLink, then // it is a new addition to the current node's strongly // connected component, so we need to update the current // node's lowLink accordingly. if (dependency._index < node._lowLink) { node._lowLink = dependency._index; } } } // If the current node's lowLink is the same as its index, then // we have finished visiting a strongly connected component, so // pop the stack and evaluate it before moving on. if (node._lowLink == node._index) { // The strongly connected component has only one node. If there is a // cycle, it's a trivial one. if (identical(stack.last, node)) { stack.removeLast(); if (hasTrivialCycle) { evaluateScc(<NodeType>[node]); } else { evaluate(node); } } else { // There are multiple nodes in the strongly connected // component. List<NodeType> scc = <NodeType>[]; while (true) { NodeType otherNode = stack.removeLast(); scc.add(otherNode); if (identical(otherNode, node)) { break; } } evaluateScc(scc); } } } // Kick off the algorithm starting with the starting point. strongConnect(startingPoint); } } /** * Instances of [Node] represent nodes in a dependency graph. The * type parameter, [NodeType], is the derived type (this affords some * extra type safety by making it difficult to accidentally construct * bridges between unrelated dependency graphs). */ abstract class Node<NodeType> { /** * Index used by Tarjan's strongly connected components algorithm. * Zero means the node has not been visited yet; a nonzero value * counts the order in which the node was visited. */ int _index = 0; /** * Low link used by Tarjan's strongly connected components * algorithm. This represents the smallest [_index] of all the nodes * in the strongly connected component to which this node belongs. */ int _lowLink = 0; List<NodeType> _dependencies; /** * Indicates whether this node has been evaluated yet. */ bool get isEvaluated; /** * Compute the dependencies of this node. */ List<NodeType> computeDependencies(); /** * Gets the dependencies of the given node, computing them if necessary. */ static List<NodeType> getDependencies<NodeType>(Node<NodeType> node) { return node._dependencies ??= node.computeDependencies(); } }
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/summary/package_bundle_reader.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:io' as io; import 'dart:math' show min; 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/generated/source_io.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:analyzer/src/summary/idl.dart'; /** * A [ConflictingSummaryException] indicates that two different summaries * provided to a [SummaryDataStore] conflict. */ class ConflictingSummaryException implements Exception { final String duplicatedUri; final String summary1Uri; final String summary2Uri; String _message; ConflictingSummaryException(Iterable<String> summaryPaths, this.duplicatedUri, this.summary1Uri, this.summary2Uri) { // Paths are often quite long. Find and extract out a common prefix to // build a more readable error message. var prefix = _commonPrefix(summaryPaths.toList()); _message = ''' These summaries conflict because they overlap: - ${summary1Uri.substring(prefix)} - ${summary2Uri.substring(prefix)} Both contain the file: $duplicatedUri. This typically indicates an invalid build rule where two or more targets include the same source. '''; } String toString() => _message; /// Given a set of file paths, find a common prefix. int _commonPrefix(List<String> strings) { if (strings.isEmpty) return 0; var first = strings.first; int common = first.length; for (int i = 1; i < strings.length; ++i) { var current = strings[i]; common = min(common, current.length); for (int j = 0; j < common; ++j) { if (first[j] != current[j]) { common = j; if (common == 0) return 0; break; } } } // The prefix should end with a file separator. var last = first.substring(0, common).lastIndexOf(io.Platform.pathSeparator); return last < 0 ? 0 : last + 1; } } /** * The [UriResolver] that knows about sources that are served from their * summaries. */ @deprecated class InSummaryPackageUriResolver extends UriResolver { final SummaryDataStore _dataStore; InSummaryPackageUriResolver(this._dataStore); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { actualUri ??= uri; String uriString = uri.toString(); UnlinkedUnit unit = _dataStore.unlinkedMap[uriString]; if (unit != null) { String summaryPath = _dataStore.uriToSummaryPath[uriString]; return new InSummarySource(actualUri, summaryPath); } return null; } } /** * A placeholder of a source that is part of a package whose analysis results * are served from its summary. This source uses its URI as [fullName] and has * empty contents. */ class InSummarySource extends BasicSource { /** * The summary file where this source was defined. */ final String summaryPath; InSummarySource(Uri uri, this.summaryPath) : super(uri); @override TimestampedData<String> get contents => new TimestampedData<String>(0, ''); @override int get modificationStamp => 0; @override UriKind get uriKind => UriKind.PACKAGE_URI; @override bool exists() => true; @override String toString() => uri.toString(); } /** * The [UriResolver] that knows about sources that are served from their * summaries. */ class InSummaryUriResolver extends UriResolver { ResourceProvider resourceProvider; final SummaryDataStore _dataStore; InSummaryUriResolver(this.resourceProvider, this._dataStore); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { actualUri ??= uri; String uriString = uri.toString(); String summaryPath = _dataStore.uriToSummaryPath[uriString]; if (summaryPath != null) { return new InSummarySource(actualUri, summaryPath); } return null; } } /** * A [SummaryDataStore] is a container for the data extracted from a set of * summary package bundles. It contains maps which can be used to find linked * and unlinked summaries by URI. */ class SummaryDataStore { /** * List of all [PackageBundle]s. */ final List<PackageBundle> bundles = <PackageBundle>[]; /** * Map from the URI of a compilation unit to the unlinked summary of that * compilation unit. */ final Map<String, UnlinkedUnit> unlinkedMap = <String, UnlinkedUnit>{}; /** * Map from the URI of a library to the linked summary of that library. */ final Map<String, LinkedLibrary> linkedMap = <String, LinkedLibrary>{}; /** * Map from the URI of a unit to the summary path that contained it. */ final Map<String, String> uriToSummaryPath = <String, String>{}; final Set<String> _libraryUris = Set<String>(); final Set<String> _partUris = Set<String>(); /** * List of summary paths. */ final Iterable<String> _summaryPaths; /** * If true, do not accept multiple summaries that contain the same Dart uri. */ bool _disallowOverlappingSummaries; /** * Create a [SummaryDataStore] and populate it with the summaries in * [summaryPaths]. */ SummaryDataStore(Iterable<String> summaryPaths, {bool disallowOverlappingSummaries: false, ResourceProvider resourceProvider}) : _summaryPaths = summaryPaths, _disallowOverlappingSummaries = disallowOverlappingSummaries { summaryPaths.forEach((String path) => _fillMaps(path, resourceProvider)); } /** * Add the given [bundle] loaded from the file with the given [path]. */ void addBundle(String path, PackageBundle bundle) { bundles.add(bundle); for (int i = 0; i < bundle.unlinkedUnitUris.length; i++) { String uri = bundle.unlinkedUnitUris[i]; if (_disallowOverlappingSummaries && uriToSummaryPath.containsKey(uri) && (uriToSummaryPath[uri] != path)) { throw new ConflictingSummaryException( _summaryPaths, uri, uriToSummaryPath[uri], path); } uriToSummaryPath[uri] = path; addUnlinkedUnit(uri, bundle.unlinkedUnits[i]); } for (int i = 0; i < bundle.linkedLibraryUris.length; i++) { String uri = bundle.linkedLibraryUris[i]; addLinkedLibrary(uri, bundle.linkedLibraries[i]); } if (bundle.bundle2 != null) { for (var library in bundle.bundle2.libraries) { var libraryUri = library.uriStr; _libraryUris.add(libraryUri); for (var unit in library.units) { var unitUri = unit.uriStr; uriToSummaryPath[unitUri] = path; if (unitUri != libraryUri) { _partUris.add(unitUri); } } } } } /** * Add the given [linkedLibrary] with the given [uri]. */ void addLinkedLibrary(String uri, LinkedLibrary linkedLibrary) { linkedMap[uri] = linkedLibrary; } /** * Add into this store the unlinked units and linked libraries of [other]. */ void addStore(SummaryDataStore other) { unlinkedMap.addAll(other.unlinkedMap); linkedMap.addAll(other.linkedMap); } /** * Add the given [unlinkedUnit] with the given [uri]. */ void addUnlinkedUnit(String uri, UnlinkedUnit unlinkedUnit) { unlinkedMap[uri] = unlinkedUnit; } /** * Return a list of absolute URIs of the libraries that contain the unit with * the given [unitUriString], or `null` if no such library is in the store. */ List<String> getContainingLibraryUris(String unitUriString) { // The unit is the defining unit of a library. if (linkedMap.containsKey(unitUriString)) { return <String>[unitUriString]; } // Check every unlinked unit whether it uses [unitUri] as a part. List<String> libraryUriStrings = <String>[]; unlinkedMap.forEach((unlinkedUnitUriString, unlinkedUnit) { Uri libraryUri = Uri.parse(unlinkedUnitUriString); for (String partUriString in unlinkedUnit.publicNamespace.parts) { Uri partUri = Uri.parse(partUriString); String partAbsoluteUriString = resolveRelativeUri(libraryUri, partUri).toString(); if (partAbsoluteUriString == unitUriString) { libraryUriStrings.add(unlinkedUnitUriString); } } }); return libraryUriStrings.isNotEmpty ? libraryUriStrings : null; } /** * Return `true` if the store contains the linked summary for the library * with the given absolute [uri]. */ bool hasLinkedLibrary(String uri) { return _libraryUris.contains(uri); } /** * Return `true` if the store contains the unlinked summary for the unit * with the given absolute [uri]. */ bool hasUnlinkedUnit(String uri) { return uriToSummaryPath.containsKey(uri); } /** * Return `true` if the unit with the [uri] is a part unit in the store. */ bool isPartUnit(String uri) { return _partUris.contains(uri); } void _fillMaps(String path, ResourceProvider resourceProvider) { List<int> buffer; if (resourceProvider != null) { var file = resourceProvider.getFile(path); buffer = file.readAsBytesSync(); } else { io.File file = new io.File(path); buffer = file.readAsBytesSync(); } PackageBundle bundle = new PackageBundle.fromBuffer(buffer); addBundle(path, bundle); } }
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/summary/base.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. /** * Base functionality which code generated summary classes are built upon. */ library analyzer.src.summary.base; /** * Annotation used in the summary IDL to indicate the id of a field. The set * of ids used by a class must cover the contiguous range from 0 to N-1, where * N is the number of fields. * * In order to preserve forwards and backwards compatibility, id numbers must * be stable between releases. So when new fields are added they should take * the next available id without renumbering other fields. */ class Id { final int value; const Id(this.value); } /** * Instances of this class represent data that has been read from a summary. */ abstract class SummaryClass { /** * Translate the data in this class into a JSON map, whose keys are the names * of fields and whose values are the data stored in those fields, * recursively converted into JSON. * * Fields containing their default value are elided. * * Intended for testing and debugging only. */ Map<String, Object> toJson(); /** * Translate the data in this class into a map whose keys are the names of * fields and whose values are the data stored in those fields. * * Intended for testing and debugging only. */ Map<String, Object> toMap(); } /** * Annotation used in the summary IDL to indicate that a summary class can be * the top level object in an encoded summary. */ class TopLevel { /** * If non-null, identifier that will be stored in bytes 4-7 of the file, * prior all other file data. Must be exactly 4 Latin1 characters. */ final String fileIdentifier; const TopLevel([this.fileIdentifier]); } /** * Annotation used in the summary IDL to indicate the field name that is used * to distinguish variants, or logical views on the same physical layout of * fields. */ class Variant { final String fieldName; const Variant(this.fieldName); } /** * Annotation used in the summary IDL to indicate the id of a field that * represents a logical field. The set of ids used by a class must cover the * contiguous range from 0 to N-1, where N is the number of fields. All logical * fields must have the same type, which will become the type of the actual * field. * * In order to preserve forwards and backwards compatibility, id numbers must * be stable between releases. So when new fields are added they should take * the next available id without renumbering other fields. */ class VariantId { /// The ID of the actual field. final int value; /// The value of the variant field in [Variant]. final Object variant; /// The list of variant values for which this field exists. final List<Object> variantList; const VariantId(this.value, {this.variant, this.variantList}); }
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/summary/format.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. // // This file has been automatically generated. Please do not edit it manually. // To regenerate the file, use the SDK script // "pkg/analyzer/tool/summary/generate.dart $IDL_FILE_PATH", // or "pkg/analyzer/tool/generate_files" for the analyzer package IDL/sources. library analyzer.src.summary.format; import 'dart:convert' as convert; import 'package:analyzer/src/summary/api_signature.dart' as api_sig; import 'package:analyzer/src/summary/flat_buffers.dart' as fb; import 'idl.dart' as idl; class _AvailableDeclarationKindReader extends fb.Reader<idl.AvailableDeclarationKind> { const _AvailableDeclarationKindReader() : super(); @override int get size => 1; @override idl.AvailableDeclarationKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.AvailableDeclarationKind.values.length ? idl.AvailableDeclarationKind.values[index] : idl.AvailableDeclarationKind.CLASS; } } class _EntityRefKindReader extends fb.Reader<idl.EntityRefKind> { const _EntityRefKindReader() : super(); @override int get size => 1; @override idl.EntityRefKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.EntityRefKind.values.length ? idl.EntityRefKind.values[index] : idl.EntityRefKind.named; } } class _EntityRefNullabilitySuffixReader extends fb.Reader<idl.EntityRefNullabilitySuffix> { const _EntityRefNullabilitySuffixReader() : super(); @override int get size => 1; @override idl.EntityRefNullabilitySuffix read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.EntityRefNullabilitySuffix.values.length ? idl.EntityRefNullabilitySuffix.values[index] : idl.EntityRefNullabilitySuffix.starOrIrrelevant; } } class _IndexNameKindReader extends fb.Reader<idl.IndexNameKind> { const _IndexNameKindReader() : super(); @override int get size => 1; @override idl.IndexNameKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.IndexNameKind.values.length ? idl.IndexNameKind.values[index] : idl.IndexNameKind.topLevel; } } class _IndexRelationKindReader extends fb.Reader<idl.IndexRelationKind> { const _IndexRelationKindReader() : super(); @override int get size => 1; @override idl.IndexRelationKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.IndexRelationKind.values.length ? idl.IndexRelationKind.values[index] : idl.IndexRelationKind.IS_ANCESTOR_OF; } } class _IndexSyntheticElementKindReader extends fb.Reader<idl.IndexSyntheticElementKind> { const _IndexSyntheticElementKindReader() : super(); @override int get size => 1; @override idl.IndexSyntheticElementKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.IndexSyntheticElementKind.values.length ? idl.IndexSyntheticElementKind.values[index] : idl.IndexSyntheticElementKind.notSynthetic; } } class _LinkedNodeCommentTypeReader extends fb.Reader<idl.LinkedNodeCommentType> { const _LinkedNodeCommentTypeReader() : super(); @override int get size => 1; @override idl.LinkedNodeCommentType read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.LinkedNodeCommentType.values.length ? idl.LinkedNodeCommentType.values[index] : idl.LinkedNodeCommentType.block; } } class _LinkedNodeFormalParameterKindReader extends fb.Reader<idl.LinkedNodeFormalParameterKind> { const _LinkedNodeFormalParameterKindReader() : super(); @override int get size => 1; @override idl.LinkedNodeFormalParameterKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.LinkedNodeFormalParameterKind.values.length ? idl.LinkedNodeFormalParameterKind.values[index] : idl.LinkedNodeFormalParameterKind.requiredPositional; } } class _LinkedNodeKindReader extends fb.Reader<idl.LinkedNodeKind> { const _LinkedNodeKindReader() : super(); @override int get size => 1; @override idl.LinkedNodeKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.LinkedNodeKind.values.length ? idl.LinkedNodeKind.values[index] : idl.LinkedNodeKind.adjacentStrings; } } class _LinkedNodeTypeKindReader extends fb.Reader<idl.LinkedNodeTypeKind> { const _LinkedNodeTypeKindReader() : super(); @override int get size => 1; @override idl.LinkedNodeTypeKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.LinkedNodeTypeKind.values.length ? idl.LinkedNodeTypeKind.values[index] : idl.LinkedNodeTypeKind.bottom; } } class _ReferenceKindReader extends fb.Reader<idl.ReferenceKind> { const _ReferenceKindReader() : super(); @override int get size => 1; @override idl.ReferenceKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.ReferenceKind.values.length ? idl.ReferenceKind.values[index] : idl.ReferenceKind.classOrEnum; } } class _TopLevelInferenceErrorKindReader extends fb.Reader<idl.TopLevelInferenceErrorKind> { const _TopLevelInferenceErrorKindReader() : super(); @override int get size => 1; @override idl.TopLevelInferenceErrorKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.TopLevelInferenceErrorKind.values.length ? idl.TopLevelInferenceErrorKind.values[index] : idl.TopLevelInferenceErrorKind.assignment; } } class _TypedefStyleReader extends fb.Reader<idl.TypedefStyle> { const _TypedefStyleReader() : super(); @override int get size => 1; @override idl.TypedefStyle read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.TypedefStyle.values.length ? idl.TypedefStyle.values[index] : idl.TypedefStyle.functionType; } } class _UnlinkedConstructorInitializerKindReader extends fb.Reader<idl.UnlinkedConstructorInitializerKind> { const _UnlinkedConstructorInitializerKindReader() : super(); @override int get size => 1; @override idl.UnlinkedConstructorInitializerKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedConstructorInitializerKind.values.length ? idl.UnlinkedConstructorInitializerKind.values[index] : idl.UnlinkedConstructorInitializerKind.field; } } class _UnlinkedExecutableKindReader extends fb.Reader<idl.UnlinkedExecutableKind> { const _UnlinkedExecutableKindReader() : super(); @override int get size => 1; @override idl.UnlinkedExecutableKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedExecutableKind.values.length ? idl.UnlinkedExecutableKind.values[index] : idl.UnlinkedExecutableKind.functionOrMethod; } } class _UnlinkedExprAssignOperatorReader extends fb.Reader<idl.UnlinkedExprAssignOperator> { const _UnlinkedExprAssignOperatorReader() : super(); @override int get size => 1; @override idl.UnlinkedExprAssignOperator read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedExprAssignOperator.values.length ? idl.UnlinkedExprAssignOperator.values[index] : idl.UnlinkedExprAssignOperator.assign; } } class _UnlinkedExprOperationReader extends fb.Reader<idl.UnlinkedExprOperation> { const _UnlinkedExprOperationReader() : super(); @override int get size => 1; @override idl.UnlinkedExprOperation read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedExprOperation.values.length ? idl.UnlinkedExprOperation.values[index] : idl.UnlinkedExprOperation.pushInt; } } class _UnlinkedParamKindReader extends fb.Reader<idl.UnlinkedParamKind> { const _UnlinkedParamKindReader() : super(); @override int get size => 1; @override idl.UnlinkedParamKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedParamKind.values.length ? idl.UnlinkedParamKind.values[index] : idl.UnlinkedParamKind.requiredPositional; } } class _UnlinkedTokenKindReader extends fb.Reader<idl.UnlinkedTokenKind> { const _UnlinkedTokenKindReader() : super(); @override int get size => 1; @override idl.UnlinkedTokenKind read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedTokenKind.values.length ? idl.UnlinkedTokenKind.values[index] : idl.UnlinkedTokenKind.nothing; } } class _UnlinkedTokenTypeReader extends fb.Reader<idl.UnlinkedTokenType> { const _UnlinkedTokenTypeReader() : super(); @override int get size => 1; @override idl.UnlinkedTokenType read(fb.BufferContext bc, int offset) { int index = const fb.Uint8Reader().read(bc, offset); return index < idl.UnlinkedTokenType.values.length ? idl.UnlinkedTokenType.values[index] : idl.UnlinkedTokenType.NOTHING; } } class AnalysisDriverExceptionContextBuilder extends Object with _AnalysisDriverExceptionContextMixin implements idl.AnalysisDriverExceptionContext { String _exception; List<AnalysisDriverExceptionFileBuilder> _files; String _path; String _stackTrace; @override String get exception => _exception ??= ''; /// The exception string. set exception(String value) { this._exception = value; } @override List<AnalysisDriverExceptionFileBuilder> get files => _files ??= <AnalysisDriverExceptionFileBuilder>[]; /// The state of files when the exception happened. set files(List<AnalysisDriverExceptionFileBuilder> value) { this._files = value; } @override String get path => _path ??= ''; /// The path of the file being analyzed when the exception happened. set path(String value) { this._path = value; } @override String get stackTrace => _stackTrace ??= ''; /// The exception stack trace string. set stackTrace(String value) { this._stackTrace = value; } AnalysisDriverExceptionContextBuilder( {String exception, List<AnalysisDriverExceptionFileBuilder> files, String path, String stackTrace}) : _exception = exception, _files = files, _path = path, _stackTrace = stackTrace; /// Flush [informative] data recursively. void flushInformative() { _files?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._path ?? ''); signature.addString(this._exception ?? ''); signature.addString(this._stackTrace ?? ''); if (this._files == null) { signature.addInt(0); } else { signature.addInt(this._files.length); for (var x in this._files) { x?.collectApiSignature(signature); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "ADEC"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_exception; fb.Offset offset_files; fb.Offset offset_path; fb.Offset offset_stackTrace; if (_exception != null) { offset_exception = fbBuilder.writeString(_exception); } if (!(_files == null || _files.isEmpty)) { offset_files = fbBuilder.writeList(_files.map((b) => b.finish(fbBuilder)).toList()); } if (_path != null) { offset_path = fbBuilder.writeString(_path); } if (_stackTrace != null) { offset_stackTrace = fbBuilder.writeString(_stackTrace); } fbBuilder.startTable(); if (offset_exception != null) { fbBuilder.addOffset(1, offset_exception); } if (offset_files != null) { fbBuilder.addOffset(3, offset_files); } if (offset_path != null) { fbBuilder.addOffset(0, offset_path); } if (offset_stackTrace != null) { fbBuilder.addOffset(2, offset_stackTrace); } return fbBuilder.endTable(); } } idl.AnalysisDriverExceptionContext readAnalysisDriverExceptionContext( List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _AnalysisDriverExceptionContextReader().read(rootRef, 0); } class _AnalysisDriverExceptionContextReader extends fb.TableReader<_AnalysisDriverExceptionContextImpl> { const _AnalysisDriverExceptionContextReader(); @override _AnalysisDriverExceptionContextImpl createObject( fb.BufferContext bc, int offset) => new _AnalysisDriverExceptionContextImpl(bc, offset); } class _AnalysisDriverExceptionContextImpl extends Object with _AnalysisDriverExceptionContextMixin implements idl.AnalysisDriverExceptionContext { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverExceptionContextImpl(this._bc, this._bcOffset); String _exception; List<idl.AnalysisDriverExceptionFile> _files; String _path; String _stackTrace; @override String get exception { _exception ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _exception; } @override List<idl.AnalysisDriverExceptionFile> get files { _files ??= const fb.ListReader<idl.AnalysisDriverExceptionFile>( const _AnalysisDriverExceptionFileReader()) .vTableGet( _bc, _bcOffset, 3, const <idl.AnalysisDriverExceptionFile>[]); return _files; } @override String get path { _path ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _path; } @override String get stackTrace { _stackTrace ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 2, ''); return _stackTrace; } } abstract class _AnalysisDriverExceptionContextMixin implements idl.AnalysisDriverExceptionContext { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (exception != '') _result["exception"] = exception; if (files.isNotEmpty) _result["files"] = files.map((_value) => _value.toJson()).toList(); if (path != '') _result["path"] = path; if (stackTrace != '') _result["stackTrace"] = stackTrace; return _result; } @override Map<String, Object> toMap() => { "exception": exception, "files": files, "path": path, "stackTrace": stackTrace, }; @override String toString() => convert.json.encode(toJson()); } class AnalysisDriverExceptionFileBuilder extends Object with _AnalysisDriverExceptionFileMixin implements idl.AnalysisDriverExceptionFile { String _content; String _path; @override String get content => _content ??= ''; /// The content of the file. set content(String value) { this._content = value; } @override String get path => _path ??= ''; /// The path of the file. set path(String value) { this._path = value; } AnalysisDriverExceptionFileBuilder({String content, String path}) : _content = content, _path = path; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._path ?? ''); signature.addString(this._content ?? ''); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_content; fb.Offset offset_path; if (_content != null) { offset_content = fbBuilder.writeString(_content); } if (_path != null) { offset_path = fbBuilder.writeString(_path); } fbBuilder.startTable(); if (offset_content != null) { fbBuilder.addOffset(1, offset_content); } if (offset_path != null) { fbBuilder.addOffset(0, offset_path); } return fbBuilder.endTable(); } } class _AnalysisDriverExceptionFileReader extends fb.TableReader<_AnalysisDriverExceptionFileImpl> { const _AnalysisDriverExceptionFileReader(); @override _AnalysisDriverExceptionFileImpl createObject( fb.BufferContext bc, int offset) => new _AnalysisDriverExceptionFileImpl(bc, offset); } class _AnalysisDriverExceptionFileImpl extends Object with _AnalysisDriverExceptionFileMixin implements idl.AnalysisDriverExceptionFile { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverExceptionFileImpl(this._bc, this._bcOffset); String _content; String _path; @override String get content { _content ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _content; } @override String get path { _path ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _path; } } abstract class _AnalysisDriverExceptionFileMixin implements idl.AnalysisDriverExceptionFile { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (content != '') _result["content"] = content; if (path != '') _result["path"] = path; return _result; } @override Map<String, Object> toMap() => { "content": content, "path": path, }; @override String toString() => convert.json.encode(toJson()); } class AnalysisDriverResolvedUnitBuilder extends Object with _AnalysisDriverResolvedUnitMixin implements idl.AnalysisDriverResolvedUnit { List<AnalysisDriverUnitErrorBuilder> _errors; AnalysisDriverUnitIndexBuilder _index; @override List<AnalysisDriverUnitErrorBuilder> get errors => _errors ??= <AnalysisDriverUnitErrorBuilder>[]; /// The full list of analysis errors, both syntactic and semantic. set errors(List<AnalysisDriverUnitErrorBuilder> value) { this._errors = value; } @override AnalysisDriverUnitIndexBuilder get index => _index; /// The index of the unit. set index(AnalysisDriverUnitIndexBuilder value) { this._index = value; } AnalysisDriverResolvedUnitBuilder( {List<AnalysisDriverUnitErrorBuilder> errors, AnalysisDriverUnitIndexBuilder index}) : _errors = errors, _index = index; /// Flush [informative] data recursively. void flushInformative() { _errors?.forEach((b) => b.flushInformative()); _index?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._errors == null) { signature.addInt(0); } else { signature.addInt(this._errors.length); for (var x in this._errors) { x?.collectApiSignature(signature); } } signature.addBool(this._index != null); this._index?.collectApiSignature(signature); } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "ADRU"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_errors; fb.Offset offset_index; if (!(_errors == null || _errors.isEmpty)) { offset_errors = fbBuilder.writeList(_errors.map((b) => b.finish(fbBuilder)).toList()); } if (_index != null) { offset_index = _index.finish(fbBuilder); } fbBuilder.startTable(); if (offset_errors != null) { fbBuilder.addOffset(0, offset_errors); } if (offset_index != null) { fbBuilder.addOffset(1, offset_index); } return fbBuilder.endTable(); } } idl.AnalysisDriverResolvedUnit readAnalysisDriverResolvedUnit( List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _AnalysisDriverResolvedUnitReader().read(rootRef, 0); } class _AnalysisDriverResolvedUnitReader extends fb.TableReader<_AnalysisDriverResolvedUnitImpl> { const _AnalysisDriverResolvedUnitReader(); @override _AnalysisDriverResolvedUnitImpl createObject( fb.BufferContext bc, int offset) => new _AnalysisDriverResolvedUnitImpl(bc, offset); } class _AnalysisDriverResolvedUnitImpl extends Object with _AnalysisDriverResolvedUnitMixin implements idl.AnalysisDriverResolvedUnit { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverResolvedUnitImpl(this._bc, this._bcOffset); List<idl.AnalysisDriverUnitError> _errors; idl.AnalysisDriverUnitIndex _index; @override List<idl.AnalysisDriverUnitError> get errors { _errors ??= const fb.ListReader<idl.AnalysisDriverUnitError>( const _AnalysisDriverUnitErrorReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.AnalysisDriverUnitError>[]); return _errors; } @override idl.AnalysisDriverUnitIndex get index { _index ??= const _AnalysisDriverUnitIndexReader() .vTableGet(_bc, _bcOffset, 1, null); return _index; } } abstract class _AnalysisDriverResolvedUnitMixin implements idl.AnalysisDriverResolvedUnit { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (errors.isNotEmpty) _result["errors"] = errors.map((_value) => _value.toJson()).toList(); if (index != null) _result["index"] = index.toJson(); return _result; } @override Map<String, Object> toMap() => { "errors": errors, "index": index, }; @override String toString() => convert.json.encode(toJson()); } class AnalysisDriverSubtypeBuilder extends Object with _AnalysisDriverSubtypeMixin implements idl.AnalysisDriverSubtype { List<int> _members; int _name; @override List<int> get members => _members ??= <int>[]; /// The names of defined instance members. /// They are indexes into [AnalysisDriverUnitError.strings] list. /// The list is sorted in ascending order. set members(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._members = value; } @override int get name => _name ??= 0; /// The name of the class. /// It is an index into [AnalysisDriverUnitError.strings] list. set name(int value) { assert(value == null || value >= 0); this._name = value; } AnalysisDriverSubtypeBuilder({List<int> members, int name}) : _members = members, _name = name; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._name ?? 0); if (this._members == null) { signature.addInt(0); } else { signature.addInt(this._members.length); for (var x in this._members) { signature.addInt(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_members; if (!(_members == null || _members.isEmpty)) { offset_members = fbBuilder.writeListUint32(_members); } fbBuilder.startTable(); if (offset_members != null) { fbBuilder.addOffset(1, offset_members); } if (_name != null && _name != 0) { fbBuilder.addUint32(0, _name); } return fbBuilder.endTable(); } } class _AnalysisDriverSubtypeReader extends fb.TableReader<_AnalysisDriverSubtypeImpl> { const _AnalysisDriverSubtypeReader(); @override _AnalysisDriverSubtypeImpl createObject(fb.BufferContext bc, int offset) => new _AnalysisDriverSubtypeImpl(bc, offset); } class _AnalysisDriverSubtypeImpl extends Object with _AnalysisDriverSubtypeMixin implements idl.AnalysisDriverSubtype { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverSubtypeImpl(this._bc, this._bcOffset); List<int> _members; int _name; @override List<int> get members { _members ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 1, const <int>[]); return _members; } @override int get name { _name ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _name; } } abstract class _AnalysisDriverSubtypeMixin implements idl.AnalysisDriverSubtype { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (members.isNotEmpty) _result["members"] = members; if (name != 0) _result["name"] = name; return _result; } @override Map<String, Object> toMap() => { "members": members, "name": name, }; @override String toString() => convert.json.encode(toJson()); } class AnalysisDriverUnitErrorBuilder extends Object with _AnalysisDriverUnitErrorMixin implements idl.AnalysisDriverUnitError { List<DiagnosticMessageBuilder> _contextMessages; String _correction; int _length; String _message; int _offset; String _uniqueName; @override List<DiagnosticMessageBuilder> get contextMessages => _contextMessages ??= <DiagnosticMessageBuilder>[]; /// The context messages associated with the error. set contextMessages(List<DiagnosticMessageBuilder> value) { this._contextMessages = value; } @override String get correction => _correction ??= ''; /// The optional correction hint for the error. set correction(String value) { this._correction = value; } @override int get length => _length ??= 0; /// The length of the error in the file. set length(int value) { assert(value == null || value >= 0); this._length = value; } @override String get message => _message ??= ''; /// The message of the error. set message(String value) { this._message = value; } @override int get offset => _offset ??= 0; /// The offset from the beginning of the file. set offset(int value) { assert(value == null || value >= 0); this._offset = value; } @override String get uniqueName => _uniqueName ??= ''; /// The unique name of the error code. set uniqueName(String value) { this._uniqueName = value; } AnalysisDriverUnitErrorBuilder( {List<DiagnosticMessageBuilder> contextMessages, String correction, int length, String message, int offset, String uniqueName}) : _contextMessages = contextMessages, _correction = correction, _length = length, _message = message, _offset = offset, _uniqueName = uniqueName; /// Flush [informative] data recursively. void flushInformative() { _contextMessages?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._offset ?? 0); signature.addInt(this._length ?? 0); signature.addString(this._uniqueName ?? ''); signature.addString(this._message ?? ''); signature.addString(this._correction ?? ''); if (this._contextMessages == null) { signature.addInt(0); } else { signature.addInt(this._contextMessages.length); for (var x in this._contextMessages) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_contextMessages; fb.Offset offset_correction; fb.Offset offset_message; fb.Offset offset_uniqueName; if (!(_contextMessages == null || _contextMessages.isEmpty)) { offset_contextMessages = fbBuilder .writeList(_contextMessages.map((b) => b.finish(fbBuilder)).toList()); } if (_correction != null) { offset_correction = fbBuilder.writeString(_correction); } if (_message != null) { offset_message = fbBuilder.writeString(_message); } if (_uniqueName != null) { offset_uniqueName = fbBuilder.writeString(_uniqueName); } fbBuilder.startTable(); if (offset_contextMessages != null) { fbBuilder.addOffset(5, offset_contextMessages); } if (offset_correction != null) { fbBuilder.addOffset(4, offset_correction); } if (_length != null && _length != 0) { fbBuilder.addUint32(1, _length); } if (offset_message != null) { fbBuilder.addOffset(3, offset_message); } if (_offset != null && _offset != 0) { fbBuilder.addUint32(0, _offset); } if (offset_uniqueName != null) { fbBuilder.addOffset(2, offset_uniqueName); } return fbBuilder.endTable(); } } class _AnalysisDriverUnitErrorReader extends fb.TableReader<_AnalysisDriverUnitErrorImpl> { const _AnalysisDriverUnitErrorReader(); @override _AnalysisDriverUnitErrorImpl createObject(fb.BufferContext bc, int offset) => new _AnalysisDriverUnitErrorImpl(bc, offset); } class _AnalysisDriverUnitErrorImpl extends Object with _AnalysisDriverUnitErrorMixin implements idl.AnalysisDriverUnitError { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverUnitErrorImpl(this._bc, this._bcOffset); List<idl.DiagnosticMessage> _contextMessages; String _correction; int _length; String _message; int _offset; String _uniqueName; @override List<idl.DiagnosticMessage> get contextMessages { _contextMessages ??= const fb.ListReader<idl.DiagnosticMessage>( const _DiagnosticMessageReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.DiagnosticMessage>[]); return _contextMessages; } @override String get correction { _correction ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 4, ''); return _correction; } @override int get length { _length ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _length; } @override String get message { _message ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 3, ''); return _message; } @override int get offset { _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _offset; } @override String get uniqueName { _uniqueName ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 2, ''); return _uniqueName; } } abstract class _AnalysisDriverUnitErrorMixin implements idl.AnalysisDriverUnitError { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (contextMessages.isNotEmpty) _result["contextMessages"] = contextMessages.map((_value) => _value.toJson()).toList(); if (correction != '') _result["correction"] = correction; if (length != 0) _result["length"] = length; if (message != '') _result["message"] = message; if (offset != 0) _result["offset"] = offset; if (uniqueName != '') _result["uniqueName"] = uniqueName; return _result; } @override Map<String, Object> toMap() => { "contextMessages": contextMessages, "correction": correction, "length": length, "message": message, "offset": offset, "uniqueName": uniqueName, }; @override String toString() => convert.json.encode(toJson()); } class AnalysisDriverUnitIndexBuilder extends Object with _AnalysisDriverUnitIndexMixin implements idl.AnalysisDriverUnitIndex { List<idl.IndexSyntheticElementKind> _elementKinds; List<int> _elementNameClassMemberIds; List<int> _elementNameParameterIds; List<int> _elementNameUnitMemberIds; List<int> _elementUnits; int _nullStringId; List<String> _strings; List<AnalysisDriverSubtypeBuilder> _subtypes; List<int> _supertypes; List<int> _unitLibraryUris; List<int> _unitUnitUris; List<bool> _usedElementIsQualifiedFlags; List<idl.IndexRelationKind> _usedElementKinds; List<int> _usedElementLengths; List<int> _usedElementOffsets; List<int> _usedElements; List<bool> _usedNameIsQualifiedFlags; List<idl.IndexRelationKind> _usedNameKinds; List<int> _usedNameOffsets; List<int> _usedNames; @override List<idl.IndexSyntheticElementKind> get elementKinds => _elementKinds ??= <idl.IndexSyntheticElementKind>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the kind of the synthetic element. set elementKinds(List<idl.IndexSyntheticElementKind> value) { this._elementKinds = value; } @override List<int> get elementNameClassMemberIds => _elementNameClassMemberIds ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the class member element name, or `null` if the element /// is a top-level element. The list is sorted in ascending order, so that /// the client can quickly check whether an element is referenced in this /// index. set elementNameClassMemberIds(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementNameClassMemberIds = value; } @override List<int> get elementNameParameterIds => _elementNameParameterIds ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the named parameter name, or `null` if the element is /// not a named parameter. The list is sorted in ascending order, so that the /// client can quickly check whether an element is referenced in this index. set elementNameParameterIds(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementNameParameterIds = value; } @override List<int> get elementNameUnitMemberIds => _elementNameUnitMemberIds ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the top-level element name, or `null` if the element is /// the unit. The list is sorted in ascending order, so that the client can /// quickly check whether an element is referenced in this index. set elementNameUnitMemberIds(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementNameUnitMemberIds = value; } @override List<int> get elementUnits => _elementUnits ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the index into [unitLibraryUris] and [unitUnitUris] for the library /// specific unit where the element is declared. set elementUnits(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementUnits = value; } @override int get nullStringId => _nullStringId ??= 0; /// Identifier of the null string in [strings]. set nullStringId(int value) { assert(value == null || value >= 0); this._nullStringId = value; } @override List<String> get strings => _strings ??= <String>[]; /// List of unique element strings used in this index. The list is sorted in /// ascending order, so that the client can quickly check the presence of a /// string in this index. set strings(List<String> value) { this._strings = value; } @override List<AnalysisDriverSubtypeBuilder> get subtypes => _subtypes ??= <AnalysisDriverSubtypeBuilder>[]; /// The list of classes declared in the unit. set subtypes(List<AnalysisDriverSubtypeBuilder> value) { this._subtypes = value; } @override List<int> get supertypes => _supertypes ??= <int>[]; /// The identifiers of supertypes of elements at corresponding indexes /// in [subtypes]. They are indexes into [strings] list. The list is sorted /// in ascending order. There might be more than one element with the same /// value if there is more than one subtype of this supertype. set supertypes(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._supertypes = value; } @override List<int> get unitLibraryUris => _unitLibraryUris ??= <int>[]; /// Each item of this list corresponds to the library URI of a unique library /// specific unit referenced in the index. It is an index into [strings] /// list. set unitLibraryUris(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._unitLibraryUris = value; } @override List<int> get unitUnitUris => _unitUnitUris ??= <int>[]; /// Each item of this list corresponds to the unit URI of a unique library /// specific unit referenced in the index. It is an index into [strings] /// list. set unitUnitUris(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._unitUnitUris = value; } @override List<bool> get usedElementIsQualifiedFlags => _usedElementIsQualifiedFlags ??= <bool>[]; /// Each item of this list is the `true` if the corresponding element usage /// is qualified with some prefix. set usedElementIsQualifiedFlags(List<bool> value) { this._usedElementIsQualifiedFlags = value; } @override List<idl.IndexRelationKind> get usedElementKinds => _usedElementKinds ??= <idl.IndexRelationKind>[]; /// Each item of this list is the kind of the element usage. set usedElementKinds(List<idl.IndexRelationKind> value) { this._usedElementKinds = value; } @override List<int> get usedElementLengths => _usedElementLengths ??= <int>[]; /// Each item of this list is the length of the element usage. set usedElementLengths(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedElementLengths = value; } @override List<int> get usedElementOffsets => _usedElementOffsets ??= <int>[]; /// Each item of this list is the offset of the element usage relative to the /// beginning of the file. set usedElementOffsets(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedElementOffsets = value; } @override List<int> get usedElements => _usedElements ??= <int>[]; /// Each item of this list is the index into [elementUnits], /// [elementNameUnitMemberIds], [elementNameClassMemberIds] and /// [elementNameParameterIds]. The list is sorted in ascending order, so /// that the client can quickly find element references in this index. set usedElements(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedElements = value; } @override List<bool> get usedNameIsQualifiedFlags => _usedNameIsQualifiedFlags ??= <bool>[]; /// Each item of this list is the `true` if the corresponding name usage /// is qualified with some prefix. set usedNameIsQualifiedFlags(List<bool> value) { this._usedNameIsQualifiedFlags = value; } @override List<idl.IndexRelationKind> get usedNameKinds => _usedNameKinds ??= <idl.IndexRelationKind>[]; /// Each item of this list is the kind of the name usage. set usedNameKinds(List<idl.IndexRelationKind> value) { this._usedNameKinds = value; } @override List<int> get usedNameOffsets => _usedNameOffsets ??= <int>[]; /// Each item of this list is the offset of the name usage relative to the /// beginning of the file. set usedNameOffsets(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedNameOffsets = value; } @override List<int> get usedNames => _usedNames ??= <int>[]; /// Each item of this list is the index into [strings] for a used name. The /// list is sorted in ascending order, so that the client can quickly find /// whether a name is used in this index. set usedNames(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedNames = value; } AnalysisDriverUnitIndexBuilder( {List<idl.IndexSyntheticElementKind> elementKinds, List<int> elementNameClassMemberIds, List<int> elementNameParameterIds, List<int> elementNameUnitMemberIds, List<int> elementUnits, int nullStringId, List<String> strings, List<AnalysisDriverSubtypeBuilder> subtypes, List<int> supertypes, List<int> unitLibraryUris, List<int> unitUnitUris, List<bool> usedElementIsQualifiedFlags, List<idl.IndexRelationKind> usedElementKinds, List<int> usedElementLengths, List<int> usedElementOffsets, List<int> usedElements, List<bool> usedNameIsQualifiedFlags, List<idl.IndexRelationKind> usedNameKinds, List<int> usedNameOffsets, List<int> usedNames}) : _elementKinds = elementKinds, _elementNameClassMemberIds = elementNameClassMemberIds, _elementNameParameterIds = elementNameParameterIds, _elementNameUnitMemberIds = elementNameUnitMemberIds, _elementUnits = elementUnits, _nullStringId = nullStringId, _strings = strings, _subtypes = subtypes, _supertypes = supertypes, _unitLibraryUris = unitLibraryUris, _unitUnitUris = unitUnitUris, _usedElementIsQualifiedFlags = usedElementIsQualifiedFlags, _usedElementKinds = usedElementKinds, _usedElementLengths = usedElementLengths, _usedElementOffsets = usedElementOffsets, _usedElements = usedElements, _usedNameIsQualifiedFlags = usedNameIsQualifiedFlags, _usedNameKinds = usedNameKinds, _usedNameOffsets = usedNameOffsets, _usedNames = usedNames; /// Flush [informative] data recursively. void flushInformative() { _subtypes?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._strings == null) { signature.addInt(0); } else { signature.addInt(this._strings.length); for (var x in this._strings) { signature.addString(x); } } signature.addInt(this._nullStringId ?? 0); if (this._unitLibraryUris == null) { signature.addInt(0); } else { signature.addInt(this._unitLibraryUris.length); for (var x in this._unitLibraryUris) { signature.addInt(x); } } if (this._unitUnitUris == null) { signature.addInt(0); } else { signature.addInt(this._unitUnitUris.length); for (var x in this._unitUnitUris) { signature.addInt(x); } } if (this._elementKinds == null) { signature.addInt(0); } else { signature.addInt(this._elementKinds.length); for (var x in this._elementKinds) { signature.addInt(x.index); } } if (this._elementUnits == null) { signature.addInt(0); } else { signature.addInt(this._elementUnits.length); for (var x in this._elementUnits) { signature.addInt(x); } } if (this._elementNameUnitMemberIds == null) { signature.addInt(0); } else { signature.addInt(this._elementNameUnitMemberIds.length); for (var x in this._elementNameUnitMemberIds) { signature.addInt(x); } } if (this._elementNameClassMemberIds == null) { signature.addInt(0); } else { signature.addInt(this._elementNameClassMemberIds.length); for (var x in this._elementNameClassMemberIds) { signature.addInt(x); } } if (this._elementNameParameterIds == null) { signature.addInt(0); } else { signature.addInt(this._elementNameParameterIds.length); for (var x in this._elementNameParameterIds) { signature.addInt(x); } } if (this._usedElements == null) { signature.addInt(0); } else { signature.addInt(this._usedElements.length); for (var x in this._usedElements) { signature.addInt(x); } } if (this._usedElementKinds == null) { signature.addInt(0); } else { signature.addInt(this._usedElementKinds.length); for (var x in this._usedElementKinds) { signature.addInt(x.index); } } if (this._usedElementOffsets == null) { signature.addInt(0); } else { signature.addInt(this._usedElementOffsets.length); for (var x in this._usedElementOffsets) { signature.addInt(x); } } if (this._usedElementLengths == null) { signature.addInt(0); } else { signature.addInt(this._usedElementLengths.length); for (var x in this._usedElementLengths) { signature.addInt(x); } } if (this._usedElementIsQualifiedFlags == null) { signature.addInt(0); } else { signature.addInt(this._usedElementIsQualifiedFlags.length); for (var x in this._usedElementIsQualifiedFlags) { signature.addBool(x); } } if (this._usedNames == null) { signature.addInt(0); } else { signature.addInt(this._usedNames.length); for (var x in this._usedNames) { signature.addInt(x); } } if (this._usedNameKinds == null) { signature.addInt(0); } else { signature.addInt(this._usedNameKinds.length); for (var x in this._usedNameKinds) { signature.addInt(x.index); } } if (this._usedNameOffsets == null) { signature.addInt(0); } else { signature.addInt(this._usedNameOffsets.length); for (var x in this._usedNameOffsets) { signature.addInt(x); } } if (this._usedNameIsQualifiedFlags == null) { signature.addInt(0); } else { signature.addInt(this._usedNameIsQualifiedFlags.length); for (var x in this._usedNameIsQualifiedFlags) { signature.addBool(x); } } if (this._supertypes == null) { signature.addInt(0); } else { signature.addInt(this._supertypes.length); for (var x in this._supertypes) { signature.addInt(x); } } if (this._subtypes == null) { signature.addInt(0); } else { signature.addInt(this._subtypes.length); for (var x in this._subtypes) { x?.collectApiSignature(signature); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "ADUI"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_elementKinds; fb.Offset offset_elementNameClassMemberIds; fb.Offset offset_elementNameParameterIds; fb.Offset offset_elementNameUnitMemberIds; fb.Offset offset_elementUnits; fb.Offset offset_strings; fb.Offset offset_subtypes; fb.Offset offset_supertypes; fb.Offset offset_unitLibraryUris; fb.Offset offset_unitUnitUris; fb.Offset offset_usedElementIsQualifiedFlags; fb.Offset offset_usedElementKinds; fb.Offset offset_usedElementLengths; fb.Offset offset_usedElementOffsets; fb.Offset offset_usedElements; fb.Offset offset_usedNameIsQualifiedFlags; fb.Offset offset_usedNameKinds; fb.Offset offset_usedNameOffsets; fb.Offset offset_usedNames; if (!(_elementKinds == null || _elementKinds.isEmpty)) { offset_elementKinds = fbBuilder.writeListUint8(_elementKinds.map((b) => b.index).toList()); } if (!(_elementNameClassMemberIds == null || _elementNameClassMemberIds.isEmpty)) { offset_elementNameClassMemberIds = fbBuilder.writeListUint32(_elementNameClassMemberIds); } if (!(_elementNameParameterIds == null || _elementNameParameterIds.isEmpty)) { offset_elementNameParameterIds = fbBuilder.writeListUint32(_elementNameParameterIds); } if (!(_elementNameUnitMemberIds == null || _elementNameUnitMemberIds.isEmpty)) { offset_elementNameUnitMemberIds = fbBuilder.writeListUint32(_elementNameUnitMemberIds); } if (!(_elementUnits == null || _elementUnits.isEmpty)) { offset_elementUnits = fbBuilder.writeListUint32(_elementUnits); } if (!(_strings == null || _strings.isEmpty)) { offset_strings = fbBuilder .writeList(_strings.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_subtypes == null || _subtypes.isEmpty)) { offset_subtypes = fbBuilder .writeList(_subtypes.map((b) => b.finish(fbBuilder)).toList()); } if (!(_supertypes == null || _supertypes.isEmpty)) { offset_supertypes = fbBuilder.writeListUint32(_supertypes); } if (!(_unitLibraryUris == null || _unitLibraryUris.isEmpty)) { offset_unitLibraryUris = fbBuilder.writeListUint32(_unitLibraryUris); } if (!(_unitUnitUris == null || _unitUnitUris.isEmpty)) { offset_unitUnitUris = fbBuilder.writeListUint32(_unitUnitUris); } if (!(_usedElementIsQualifiedFlags == null || _usedElementIsQualifiedFlags.isEmpty)) { offset_usedElementIsQualifiedFlags = fbBuilder.writeListBool(_usedElementIsQualifiedFlags); } if (!(_usedElementKinds == null || _usedElementKinds.isEmpty)) { offset_usedElementKinds = fbBuilder .writeListUint8(_usedElementKinds.map((b) => b.index).toList()); } if (!(_usedElementLengths == null || _usedElementLengths.isEmpty)) { offset_usedElementLengths = fbBuilder.writeListUint32(_usedElementLengths); } if (!(_usedElementOffsets == null || _usedElementOffsets.isEmpty)) { offset_usedElementOffsets = fbBuilder.writeListUint32(_usedElementOffsets); } if (!(_usedElements == null || _usedElements.isEmpty)) { offset_usedElements = fbBuilder.writeListUint32(_usedElements); } if (!(_usedNameIsQualifiedFlags == null || _usedNameIsQualifiedFlags.isEmpty)) { offset_usedNameIsQualifiedFlags = fbBuilder.writeListBool(_usedNameIsQualifiedFlags); } if (!(_usedNameKinds == null || _usedNameKinds.isEmpty)) { offset_usedNameKinds = fbBuilder.writeListUint8(_usedNameKinds.map((b) => b.index).toList()); } if (!(_usedNameOffsets == null || _usedNameOffsets.isEmpty)) { offset_usedNameOffsets = fbBuilder.writeListUint32(_usedNameOffsets); } if (!(_usedNames == null || _usedNames.isEmpty)) { offset_usedNames = fbBuilder.writeListUint32(_usedNames); } fbBuilder.startTable(); if (offset_elementKinds != null) { fbBuilder.addOffset(4, offset_elementKinds); } if (offset_elementNameClassMemberIds != null) { fbBuilder.addOffset(7, offset_elementNameClassMemberIds); } if (offset_elementNameParameterIds != null) { fbBuilder.addOffset(8, offset_elementNameParameterIds); } if (offset_elementNameUnitMemberIds != null) { fbBuilder.addOffset(6, offset_elementNameUnitMemberIds); } if (offset_elementUnits != null) { fbBuilder.addOffset(5, offset_elementUnits); } if (_nullStringId != null && _nullStringId != 0) { fbBuilder.addUint32(1, _nullStringId); } if (offset_strings != null) { fbBuilder.addOffset(0, offset_strings); } if (offset_subtypes != null) { fbBuilder.addOffset(19, offset_subtypes); } if (offset_supertypes != null) { fbBuilder.addOffset(18, offset_supertypes); } if (offset_unitLibraryUris != null) { fbBuilder.addOffset(2, offset_unitLibraryUris); } if (offset_unitUnitUris != null) { fbBuilder.addOffset(3, offset_unitUnitUris); } if (offset_usedElementIsQualifiedFlags != null) { fbBuilder.addOffset(13, offset_usedElementIsQualifiedFlags); } if (offset_usedElementKinds != null) { fbBuilder.addOffset(10, offset_usedElementKinds); } if (offset_usedElementLengths != null) { fbBuilder.addOffset(12, offset_usedElementLengths); } if (offset_usedElementOffsets != null) { fbBuilder.addOffset(11, offset_usedElementOffsets); } if (offset_usedElements != null) { fbBuilder.addOffset(9, offset_usedElements); } if (offset_usedNameIsQualifiedFlags != null) { fbBuilder.addOffset(17, offset_usedNameIsQualifiedFlags); } if (offset_usedNameKinds != null) { fbBuilder.addOffset(15, offset_usedNameKinds); } if (offset_usedNameOffsets != null) { fbBuilder.addOffset(16, offset_usedNameOffsets); } if (offset_usedNames != null) { fbBuilder.addOffset(14, offset_usedNames); } return fbBuilder.endTable(); } } idl.AnalysisDriverUnitIndex readAnalysisDriverUnitIndex(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _AnalysisDriverUnitIndexReader().read(rootRef, 0); } class _AnalysisDriverUnitIndexReader extends fb.TableReader<_AnalysisDriverUnitIndexImpl> { const _AnalysisDriverUnitIndexReader(); @override _AnalysisDriverUnitIndexImpl createObject(fb.BufferContext bc, int offset) => new _AnalysisDriverUnitIndexImpl(bc, offset); } class _AnalysisDriverUnitIndexImpl extends Object with _AnalysisDriverUnitIndexMixin implements idl.AnalysisDriverUnitIndex { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverUnitIndexImpl(this._bc, this._bcOffset); List<idl.IndexSyntheticElementKind> _elementKinds; List<int> _elementNameClassMemberIds; List<int> _elementNameParameterIds; List<int> _elementNameUnitMemberIds; List<int> _elementUnits; int _nullStringId; List<String> _strings; List<idl.AnalysisDriverSubtype> _subtypes; List<int> _supertypes; List<int> _unitLibraryUris; List<int> _unitUnitUris; List<bool> _usedElementIsQualifiedFlags; List<idl.IndexRelationKind> _usedElementKinds; List<int> _usedElementLengths; List<int> _usedElementOffsets; List<int> _usedElements; List<bool> _usedNameIsQualifiedFlags; List<idl.IndexRelationKind> _usedNameKinds; List<int> _usedNameOffsets; List<int> _usedNames; @override List<idl.IndexSyntheticElementKind> get elementKinds { _elementKinds ??= const fb.ListReader<idl.IndexSyntheticElementKind>( const _IndexSyntheticElementKindReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.IndexSyntheticElementKind>[]); return _elementKinds; } @override List<int> get elementNameClassMemberIds { _elementNameClassMemberIds ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 7, const <int>[]); return _elementNameClassMemberIds; } @override List<int> get elementNameParameterIds { _elementNameParameterIds ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 8, const <int>[]); return _elementNameParameterIds; } @override List<int> get elementNameUnitMemberIds { _elementNameUnitMemberIds ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 6, const <int>[]); return _elementNameUnitMemberIds; } @override List<int> get elementUnits { _elementUnits ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 5, const <int>[]); return _elementUnits; } @override int get nullStringId { _nullStringId ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nullStringId; } @override List<String> get strings { _strings ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 0, const <String>[]); return _strings; } @override List<idl.AnalysisDriverSubtype> get subtypes { _subtypes ??= const fb.ListReader<idl.AnalysisDriverSubtype>( const _AnalysisDriverSubtypeReader()) .vTableGet(_bc, _bcOffset, 19, const <idl.AnalysisDriverSubtype>[]); return _subtypes; } @override List<int> get supertypes { _supertypes ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 18, const <int>[]); return _supertypes; } @override List<int> get unitLibraryUris { _unitLibraryUris ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 2, const <int>[]); return _unitLibraryUris; } @override List<int> get unitUnitUris { _unitUnitUris ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 3, const <int>[]); return _unitUnitUris; } @override List<bool> get usedElementIsQualifiedFlags { _usedElementIsQualifiedFlags ??= const fb.BoolListReader().vTableGet(_bc, _bcOffset, 13, const <bool>[]); return _usedElementIsQualifiedFlags; } @override List<idl.IndexRelationKind> get usedElementKinds { _usedElementKinds ??= const fb.ListReader<idl.IndexRelationKind>( const _IndexRelationKindReader()) .vTableGet(_bc, _bcOffset, 10, const <idl.IndexRelationKind>[]); return _usedElementKinds; } @override List<int> get usedElementLengths { _usedElementLengths ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 12, const <int>[]); return _usedElementLengths; } @override List<int> get usedElementOffsets { _usedElementOffsets ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 11, const <int>[]); return _usedElementOffsets; } @override List<int> get usedElements { _usedElements ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 9, const <int>[]); return _usedElements; } @override List<bool> get usedNameIsQualifiedFlags { _usedNameIsQualifiedFlags ??= const fb.BoolListReader().vTableGet(_bc, _bcOffset, 17, const <bool>[]); return _usedNameIsQualifiedFlags; } @override List<idl.IndexRelationKind> get usedNameKinds { _usedNameKinds ??= const fb.ListReader<idl.IndexRelationKind>( const _IndexRelationKindReader()) .vTableGet(_bc, _bcOffset, 15, const <idl.IndexRelationKind>[]); return _usedNameKinds; } @override List<int> get usedNameOffsets { _usedNameOffsets ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 16, const <int>[]); return _usedNameOffsets; } @override List<int> get usedNames { _usedNames ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 14, const <int>[]); return _usedNames; } } abstract class _AnalysisDriverUnitIndexMixin implements idl.AnalysisDriverUnitIndex { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (elementKinds.isNotEmpty) _result["elementKinds"] = elementKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (elementNameClassMemberIds.isNotEmpty) _result["elementNameClassMemberIds"] = elementNameClassMemberIds; if (elementNameParameterIds.isNotEmpty) _result["elementNameParameterIds"] = elementNameParameterIds; if (elementNameUnitMemberIds.isNotEmpty) _result["elementNameUnitMemberIds"] = elementNameUnitMemberIds; if (elementUnits.isNotEmpty) _result["elementUnits"] = elementUnits; if (nullStringId != 0) _result["nullStringId"] = nullStringId; if (strings.isNotEmpty) _result["strings"] = strings; if (subtypes.isNotEmpty) _result["subtypes"] = subtypes.map((_value) => _value.toJson()).toList(); if (supertypes.isNotEmpty) _result["supertypes"] = supertypes; if (unitLibraryUris.isNotEmpty) _result["unitLibraryUris"] = unitLibraryUris; if (unitUnitUris.isNotEmpty) _result["unitUnitUris"] = unitUnitUris; if (usedElementIsQualifiedFlags.isNotEmpty) _result["usedElementIsQualifiedFlags"] = usedElementIsQualifiedFlags; if (usedElementKinds.isNotEmpty) _result["usedElementKinds"] = usedElementKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (usedElementLengths.isNotEmpty) _result["usedElementLengths"] = usedElementLengths; if (usedElementOffsets.isNotEmpty) _result["usedElementOffsets"] = usedElementOffsets; if (usedElements.isNotEmpty) _result["usedElements"] = usedElements; if (usedNameIsQualifiedFlags.isNotEmpty) _result["usedNameIsQualifiedFlags"] = usedNameIsQualifiedFlags; if (usedNameKinds.isNotEmpty) _result["usedNameKinds"] = usedNameKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (usedNameOffsets.isNotEmpty) _result["usedNameOffsets"] = usedNameOffsets; if (usedNames.isNotEmpty) _result["usedNames"] = usedNames; return _result; } @override Map<String, Object> toMap() => { "elementKinds": elementKinds, "elementNameClassMemberIds": elementNameClassMemberIds, "elementNameParameterIds": elementNameParameterIds, "elementNameUnitMemberIds": elementNameUnitMemberIds, "elementUnits": elementUnits, "nullStringId": nullStringId, "strings": strings, "subtypes": subtypes, "supertypes": supertypes, "unitLibraryUris": unitLibraryUris, "unitUnitUris": unitUnitUris, "usedElementIsQualifiedFlags": usedElementIsQualifiedFlags, "usedElementKinds": usedElementKinds, "usedElementLengths": usedElementLengths, "usedElementOffsets": usedElementOffsets, "usedElements": usedElements, "usedNameIsQualifiedFlags": usedNameIsQualifiedFlags, "usedNameKinds": usedNameKinds, "usedNameOffsets": usedNameOffsets, "usedNames": usedNames, }; @override String toString() => convert.json.encode(toJson()); } class AnalysisDriverUnlinkedUnitBuilder extends Object with _AnalysisDriverUnlinkedUnitMixin implements idl.AnalysisDriverUnlinkedUnit { List<String> _definedClassMemberNames; List<String> _definedTopLevelNames; List<String> _referencedNames; List<String> _subtypedNames; UnlinkedUnitBuilder _unit; UnlinkedUnit2Builder _unit2; @override List<String> get definedClassMemberNames => _definedClassMemberNames ??= <String>[]; /// List of class member names defined by the unit. set definedClassMemberNames(List<String> value) { this._definedClassMemberNames = value; } @override List<String> get definedTopLevelNames => _definedTopLevelNames ??= <String>[]; /// List of top-level names defined by the unit. set definedTopLevelNames(List<String> value) { this._definedTopLevelNames = value; } @override List<String> get referencedNames => _referencedNames ??= <String>[]; /// List of external names referenced by the unit. set referencedNames(List<String> value) { this._referencedNames = value; } @override List<String> get subtypedNames => _subtypedNames ??= <String>[]; /// List of names which are used in `extends`, `with` or `implements` clauses /// in the file. Import prefixes and type arguments are not included. set subtypedNames(List<String> value) { this._subtypedNames = value; } @override UnlinkedUnitBuilder get unit => _unit; /// Unlinked information for the unit. set unit(UnlinkedUnitBuilder value) { this._unit = value; } @override UnlinkedUnit2Builder get unit2 => _unit2; /// Unlinked information for the unit. set unit2(UnlinkedUnit2Builder value) { this._unit2 = value; } AnalysisDriverUnlinkedUnitBuilder( {List<String> definedClassMemberNames, List<String> definedTopLevelNames, List<String> referencedNames, List<String> subtypedNames, UnlinkedUnitBuilder unit, UnlinkedUnit2Builder unit2}) : _definedClassMemberNames = definedClassMemberNames, _definedTopLevelNames = definedTopLevelNames, _referencedNames = referencedNames, _subtypedNames = subtypedNames, _unit = unit, _unit2 = unit2; /// Flush [informative] data recursively. void flushInformative() { _unit?.flushInformative(); _unit2?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._referencedNames == null) { signature.addInt(0); } else { signature.addInt(this._referencedNames.length); for (var x in this._referencedNames) { signature.addString(x); } } signature.addBool(this._unit != null); this._unit?.collectApiSignature(signature); if (this._definedTopLevelNames == null) { signature.addInt(0); } else { signature.addInt(this._definedTopLevelNames.length); for (var x in this._definedTopLevelNames) { signature.addString(x); } } if (this._definedClassMemberNames == null) { signature.addInt(0); } else { signature.addInt(this._definedClassMemberNames.length); for (var x in this._definedClassMemberNames) { signature.addString(x); } } if (this._subtypedNames == null) { signature.addInt(0); } else { signature.addInt(this._subtypedNames.length); for (var x in this._subtypedNames) { signature.addString(x); } } signature.addBool(this._unit2 != null); this._unit2?.collectApiSignature(signature); } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "ADUU"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_definedClassMemberNames; fb.Offset offset_definedTopLevelNames; fb.Offset offset_referencedNames; fb.Offset offset_subtypedNames; fb.Offset offset_unit; fb.Offset offset_unit2; if (!(_definedClassMemberNames == null || _definedClassMemberNames.isEmpty)) { offset_definedClassMemberNames = fbBuilder.writeList( _definedClassMemberNames .map((b) => fbBuilder.writeString(b)) .toList()); } if (!(_definedTopLevelNames == null || _definedTopLevelNames.isEmpty)) { offset_definedTopLevelNames = fbBuilder.writeList( _definedTopLevelNames.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_referencedNames == null || _referencedNames.isEmpty)) { offset_referencedNames = fbBuilder.writeList( _referencedNames.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_subtypedNames == null || _subtypedNames.isEmpty)) { offset_subtypedNames = fbBuilder.writeList( _subtypedNames.map((b) => fbBuilder.writeString(b)).toList()); } if (_unit != null) { offset_unit = _unit.finish(fbBuilder); } if (_unit2 != null) { offset_unit2 = _unit2.finish(fbBuilder); } fbBuilder.startTable(); if (offset_definedClassMemberNames != null) { fbBuilder.addOffset(3, offset_definedClassMemberNames); } if (offset_definedTopLevelNames != null) { fbBuilder.addOffset(2, offset_definedTopLevelNames); } if (offset_referencedNames != null) { fbBuilder.addOffset(0, offset_referencedNames); } if (offset_subtypedNames != null) { fbBuilder.addOffset(4, offset_subtypedNames); } if (offset_unit != null) { fbBuilder.addOffset(1, offset_unit); } if (offset_unit2 != null) { fbBuilder.addOffset(5, offset_unit2); } return fbBuilder.endTable(); } } idl.AnalysisDriverUnlinkedUnit readAnalysisDriverUnlinkedUnit( List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _AnalysisDriverUnlinkedUnitReader().read(rootRef, 0); } class _AnalysisDriverUnlinkedUnitReader extends fb.TableReader<_AnalysisDriverUnlinkedUnitImpl> { const _AnalysisDriverUnlinkedUnitReader(); @override _AnalysisDriverUnlinkedUnitImpl createObject( fb.BufferContext bc, int offset) => new _AnalysisDriverUnlinkedUnitImpl(bc, offset); } class _AnalysisDriverUnlinkedUnitImpl extends Object with _AnalysisDriverUnlinkedUnitMixin implements idl.AnalysisDriverUnlinkedUnit { final fb.BufferContext _bc; final int _bcOffset; _AnalysisDriverUnlinkedUnitImpl(this._bc, this._bcOffset); List<String> _definedClassMemberNames; List<String> _definedTopLevelNames; List<String> _referencedNames; List<String> _subtypedNames; idl.UnlinkedUnit _unit; idl.UnlinkedUnit2 _unit2; @override List<String> get definedClassMemberNames { _definedClassMemberNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 3, const <String>[]); return _definedClassMemberNames; } @override List<String> get definedTopLevelNames { _definedTopLevelNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 2, const <String>[]); return _definedTopLevelNames; } @override List<String> get referencedNames { _referencedNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 0, const <String>[]); return _referencedNames; } @override List<String> get subtypedNames { _subtypedNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 4, const <String>[]); return _subtypedNames; } @override idl.UnlinkedUnit get unit { _unit ??= const _UnlinkedUnitReader().vTableGet(_bc, _bcOffset, 1, null); return _unit; } @override idl.UnlinkedUnit2 get unit2 { _unit2 ??= const _UnlinkedUnit2Reader().vTableGet(_bc, _bcOffset, 5, null); return _unit2; } } abstract class _AnalysisDriverUnlinkedUnitMixin implements idl.AnalysisDriverUnlinkedUnit { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (definedClassMemberNames.isNotEmpty) _result["definedClassMemberNames"] = definedClassMemberNames; if (definedTopLevelNames.isNotEmpty) _result["definedTopLevelNames"] = definedTopLevelNames; if (referencedNames.isNotEmpty) _result["referencedNames"] = referencedNames; if (subtypedNames.isNotEmpty) _result["subtypedNames"] = subtypedNames; if (unit != null) _result["unit"] = unit.toJson(); if (unit2 != null) _result["unit2"] = unit2.toJson(); return _result; } @override Map<String, Object> toMap() => { "definedClassMemberNames": definedClassMemberNames, "definedTopLevelNames": definedTopLevelNames, "referencedNames": referencedNames, "subtypedNames": subtypedNames, "unit": unit, "unit2": unit2, }; @override String toString() => convert.json.encode(toJson()); } class AvailableDeclarationBuilder extends Object with _AvailableDeclarationMixin implements idl.AvailableDeclaration { List<AvailableDeclarationBuilder> _children; int _codeLength; int _codeOffset; String _defaultArgumentListString; List<int> _defaultArgumentListTextRanges; String _docComplete; String _docSummary; int _fieldMask; bool _isAbstract; bool _isConst; bool _isDeprecated; bool _isFinal; idl.AvailableDeclarationKind _kind; int _locationOffset; int _locationStartColumn; int _locationStartLine; String _name; List<String> _parameterNames; String _parameters; List<String> _parameterTypes; List<String> _relevanceTags; int _requiredParameterCount; String _returnType; String _typeParameters; @override List<AvailableDeclarationBuilder> get children => _children ??= <AvailableDeclarationBuilder>[]; set children(List<AvailableDeclarationBuilder> value) { this._children = value; } @override int get codeLength => _codeLength ??= 0; set codeLength(int value) { assert(value == null || value >= 0); this._codeLength = value; } @override int get codeOffset => _codeOffset ??= 0; set codeOffset(int value) { assert(value == null || value >= 0); this._codeOffset = value; } @override String get defaultArgumentListString => _defaultArgumentListString ??= ''; set defaultArgumentListString(String value) { this._defaultArgumentListString = value; } @override List<int> get defaultArgumentListTextRanges => _defaultArgumentListTextRanges ??= <int>[]; set defaultArgumentListTextRanges(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._defaultArgumentListTextRanges = value; } @override String get docComplete => _docComplete ??= ''; set docComplete(String value) { this._docComplete = value; } @override String get docSummary => _docSummary ??= ''; set docSummary(String value) { this._docSummary = value; } @override int get fieldMask => _fieldMask ??= 0; set fieldMask(int value) { assert(value == null || value >= 0); this._fieldMask = value; } @override bool get isAbstract => _isAbstract ??= false; set isAbstract(bool value) { this._isAbstract = value; } @override bool get isConst => _isConst ??= false; set isConst(bool value) { this._isConst = value; } @override bool get isDeprecated => _isDeprecated ??= false; set isDeprecated(bool value) { this._isDeprecated = value; } @override bool get isFinal => _isFinal ??= false; set isFinal(bool value) { this._isFinal = value; } @override idl.AvailableDeclarationKind get kind => _kind ??= idl.AvailableDeclarationKind.CLASS; /// The kind of the declaration. set kind(idl.AvailableDeclarationKind value) { this._kind = value; } @override int get locationOffset => _locationOffset ??= 0; set locationOffset(int value) { assert(value == null || value >= 0); this._locationOffset = value; } @override int get locationStartColumn => _locationStartColumn ??= 0; set locationStartColumn(int value) { assert(value == null || value >= 0); this._locationStartColumn = value; } @override int get locationStartLine => _locationStartLine ??= 0; set locationStartLine(int value) { assert(value == null || value >= 0); this._locationStartLine = value; } @override String get name => _name ??= ''; /// The first part of the declaration name, usually the only one, for example /// the name of a class like `MyClass`, or a function like `myFunction`. set name(String value) { this._name = value; } @override List<String> get parameterNames => _parameterNames ??= <String>[]; set parameterNames(List<String> value) { this._parameterNames = value; } @override String get parameters => _parameters ??= ''; set parameters(String value) { this._parameters = value; } @override List<String> get parameterTypes => _parameterTypes ??= <String>[]; set parameterTypes(List<String> value) { this._parameterTypes = value; } @override List<String> get relevanceTags => _relevanceTags ??= <String>[]; /// The partial list of relevance tags. Not every declaration has one (for /// example, function do not currently), and not every declaration has to /// store one (for classes it can be computed when we know the library that /// includes this file). set relevanceTags(List<String> value) { this._relevanceTags = value; } @override int get requiredParameterCount => _requiredParameterCount ??= 0; set requiredParameterCount(int value) { assert(value == null || value >= 0); this._requiredParameterCount = value; } @override String get returnType => _returnType ??= ''; set returnType(String value) { this._returnType = value; } @override String get typeParameters => _typeParameters ??= ''; set typeParameters(String value) { this._typeParameters = value; } AvailableDeclarationBuilder( {List<AvailableDeclarationBuilder> children, int codeLength, int codeOffset, String defaultArgumentListString, List<int> defaultArgumentListTextRanges, String docComplete, String docSummary, int fieldMask, bool isAbstract, bool isConst, bool isDeprecated, bool isFinal, idl.AvailableDeclarationKind kind, int locationOffset, int locationStartColumn, int locationStartLine, String name, List<String> parameterNames, String parameters, List<String> parameterTypes, List<String> relevanceTags, int requiredParameterCount, String returnType, String typeParameters}) : _children = children, _codeLength = codeLength, _codeOffset = codeOffset, _defaultArgumentListString = defaultArgumentListString, _defaultArgumentListTextRanges = defaultArgumentListTextRanges, _docComplete = docComplete, _docSummary = docSummary, _fieldMask = fieldMask, _isAbstract = isAbstract, _isConst = isConst, _isDeprecated = isDeprecated, _isFinal = isFinal, _kind = kind, _locationOffset = locationOffset, _locationStartColumn = locationStartColumn, _locationStartLine = locationStartLine, _name = name, _parameterNames = parameterNames, _parameters = parameters, _parameterTypes = parameterTypes, _relevanceTags = relevanceTags, _requiredParameterCount = requiredParameterCount, _returnType = returnType, _typeParameters = typeParameters; /// Flush [informative] data recursively. void flushInformative() { _children?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._children == null) { signature.addInt(0); } else { signature.addInt(this._children.length); for (var x in this._children) { x?.collectApiSignature(signature); } } signature.addInt(this._codeLength ?? 0); signature.addInt(this._codeOffset ?? 0); signature.addString(this._defaultArgumentListString ?? ''); if (this._defaultArgumentListTextRanges == null) { signature.addInt(0); } else { signature.addInt(this._defaultArgumentListTextRanges.length); for (var x in this._defaultArgumentListTextRanges) { signature.addInt(x); } } signature.addString(this._docComplete ?? ''); signature.addString(this._docSummary ?? ''); signature.addInt(this._fieldMask ?? 0); signature.addBool(this._isAbstract == true); signature.addBool(this._isConst == true); signature.addBool(this._isDeprecated == true); signature.addBool(this._isFinal == true); signature.addInt(this._kind == null ? 0 : this._kind.index); signature.addInt(this._locationOffset ?? 0); signature.addInt(this._locationStartColumn ?? 0); signature.addInt(this._locationStartLine ?? 0); signature.addString(this._name ?? ''); if (this._parameterNames == null) { signature.addInt(0); } else { signature.addInt(this._parameterNames.length); for (var x in this._parameterNames) { signature.addString(x); } } signature.addString(this._parameters ?? ''); if (this._parameterTypes == null) { signature.addInt(0); } else { signature.addInt(this._parameterTypes.length); for (var x in this._parameterTypes) { signature.addString(x); } } if (this._relevanceTags == null) { signature.addInt(0); } else { signature.addInt(this._relevanceTags.length); for (var x in this._relevanceTags) { signature.addString(x); } } signature.addInt(this._requiredParameterCount ?? 0); signature.addString(this._returnType ?? ''); signature.addString(this._typeParameters ?? ''); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_children; fb.Offset offset_defaultArgumentListString; fb.Offset offset_defaultArgumentListTextRanges; fb.Offset offset_docComplete; fb.Offset offset_docSummary; fb.Offset offset_name; fb.Offset offset_parameterNames; fb.Offset offset_parameters; fb.Offset offset_parameterTypes; fb.Offset offset_relevanceTags; fb.Offset offset_returnType; fb.Offset offset_typeParameters; if (!(_children == null || _children.isEmpty)) { offset_children = fbBuilder .writeList(_children.map((b) => b.finish(fbBuilder)).toList()); } if (_defaultArgumentListString != null) { offset_defaultArgumentListString = fbBuilder.writeString(_defaultArgumentListString); } if (!(_defaultArgumentListTextRanges == null || _defaultArgumentListTextRanges.isEmpty)) { offset_defaultArgumentListTextRanges = fbBuilder.writeListUint32(_defaultArgumentListTextRanges); } if (_docComplete != null) { offset_docComplete = fbBuilder.writeString(_docComplete); } if (_docSummary != null) { offset_docSummary = fbBuilder.writeString(_docSummary); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_parameterNames == null || _parameterNames.isEmpty)) { offset_parameterNames = fbBuilder.writeList( _parameterNames.map((b) => fbBuilder.writeString(b)).toList()); } if (_parameters != null) { offset_parameters = fbBuilder.writeString(_parameters); } if (!(_parameterTypes == null || _parameterTypes.isEmpty)) { offset_parameterTypes = fbBuilder.writeList( _parameterTypes.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_relevanceTags == null || _relevanceTags.isEmpty)) { offset_relevanceTags = fbBuilder.writeList( _relevanceTags.map((b) => fbBuilder.writeString(b)).toList()); } if (_returnType != null) { offset_returnType = fbBuilder.writeString(_returnType); } if (_typeParameters != null) { offset_typeParameters = fbBuilder.writeString(_typeParameters); } fbBuilder.startTable(); if (offset_children != null) { fbBuilder.addOffset(0, offset_children); } if (_codeLength != null && _codeLength != 0) { fbBuilder.addUint32(1, _codeLength); } if (_codeOffset != null && _codeOffset != 0) { fbBuilder.addUint32(2, _codeOffset); } if (offset_defaultArgumentListString != null) { fbBuilder.addOffset(3, offset_defaultArgumentListString); } if (offset_defaultArgumentListTextRanges != null) { fbBuilder.addOffset(4, offset_defaultArgumentListTextRanges); } if (offset_docComplete != null) { fbBuilder.addOffset(5, offset_docComplete); } if (offset_docSummary != null) { fbBuilder.addOffset(6, offset_docSummary); } if (_fieldMask != null && _fieldMask != 0) { fbBuilder.addUint32(7, _fieldMask); } if (_isAbstract == true) { fbBuilder.addBool(8, true); } if (_isConst == true) { fbBuilder.addBool(9, true); } if (_isDeprecated == true) { fbBuilder.addBool(10, true); } if (_isFinal == true) { fbBuilder.addBool(11, true); } if (_kind != null && _kind != idl.AvailableDeclarationKind.CLASS) { fbBuilder.addUint8(12, _kind.index); } if (_locationOffset != null && _locationOffset != 0) { fbBuilder.addUint32(13, _locationOffset); } if (_locationStartColumn != null && _locationStartColumn != 0) { fbBuilder.addUint32(14, _locationStartColumn); } if (_locationStartLine != null && _locationStartLine != 0) { fbBuilder.addUint32(15, _locationStartLine); } if (offset_name != null) { fbBuilder.addOffset(16, offset_name); } if (offset_parameterNames != null) { fbBuilder.addOffset(17, offset_parameterNames); } if (offset_parameters != null) { fbBuilder.addOffset(18, offset_parameters); } if (offset_parameterTypes != null) { fbBuilder.addOffset(19, offset_parameterTypes); } if (offset_relevanceTags != null) { fbBuilder.addOffset(20, offset_relevanceTags); } if (_requiredParameterCount != null && _requiredParameterCount != 0) { fbBuilder.addUint32(21, _requiredParameterCount); } if (offset_returnType != null) { fbBuilder.addOffset(22, offset_returnType); } if (offset_typeParameters != null) { fbBuilder.addOffset(23, offset_typeParameters); } return fbBuilder.endTable(); } } class _AvailableDeclarationReader extends fb.TableReader<_AvailableDeclarationImpl> { const _AvailableDeclarationReader(); @override _AvailableDeclarationImpl createObject(fb.BufferContext bc, int offset) => new _AvailableDeclarationImpl(bc, offset); } class _AvailableDeclarationImpl extends Object with _AvailableDeclarationMixin implements idl.AvailableDeclaration { final fb.BufferContext _bc; final int _bcOffset; _AvailableDeclarationImpl(this._bc, this._bcOffset); List<idl.AvailableDeclaration> _children; int _codeLength; int _codeOffset; String _defaultArgumentListString; List<int> _defaultArgumentListTextRanges; String _docComplete; String _docSummary; int _fieldMask; bool _isAbstract; bool _isConst; bool _isDeprecated; bool _isFinal; idl.AvailableDeclarationKind _kind; int _locationOffset; int _locationStartColumn; int _locationStartLine; String _name; List<String> _parameterNames; String _parameters; List<String> _parameterTypes; List<String> _relevanceTags; int _requiredParameterCount; String _returnType; String _typeParameters; @override List<idl.AvailableDeclaration> get children { _children ??= const fb.ListReader<idl.AvailableDeclaration>( const _AvailableDeclarationReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.AvailableDeclaration>[]); return _children; } @override int get codeLength { _codeLength ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _codeLength; } @override int get codeOffset { _codeOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _codeOffset; } @override String get defaultArgumentListString { _defaultArgumentListString ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 3, ''); return _defaultArgumentListString; } @override List<int> get defaultArgumentListTextRanges { _defaultArgumentListTextRanges ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 4, const <int>[]); return _defaultArgumentListTextRanges; } @override String get docComplete { _docComplete ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 5, ''); return _docComplete; } @override String get docSummary { _docSummary ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 6, ''); return _docSummary; } @override int get fieldMask { _fieldMask ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 7, 0); return _fieldMask; } @override bool get isAbstract { _isAbstract ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 8, false); return _isAbstract; } @override bool get isConst { _isConst ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 9, false); return _isConst; } @override bool get isDeprecated { _isDeprecated ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 10, false); return _isDeprecated; } @override bool get isFinal { _isFinal ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 11, false); return _isFinal; } @override idl.AvailableDeclarationKind get kind { _kind ??= const _AvailableDeclarationKindReader() .vTableGet(_bc, _bcOffset, 12, idl.AvailableDeclarationKind.CLASS); return _kind; } @override int get locationOffset { _locationOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 13, 0); return _locationOffset; } @override int get locationStartColumn { _locationStartColumn ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 14, 0); return _locationStartColumn; } @override int get locationStartLine { _locationStartLine ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _locationStartLine; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 16, ''); return _name; } @override List<String> get parameterNames { _parameterNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 17, const <String>[]); return _parameterNames; } @override String get parameters { _parameters ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 18, ''); return _parameters; } @override List<String> get parameterTypes { _parameterTypes ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 19, const <String>[]); return _parameterTypes; } @override List<String> get relevanceTags { _relevanceTags ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 20, const <String>[]); return _relevanceTags; } @override int get requiredParameterCount { _requiredParameterCount ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 21, 0); return _requiredParameterCount; } @override String get returnType { _returnType ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 22, ''); return _returnType; } @override String get typeParameters { _typeParameters ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 23, ''); return _typeParameters; } } abstract class _AvailableDeclarationMixin implements idl.AvailableDeclaration { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (children.isNotEmpty) _result["children"] = children.map((_value) => _value.toJson()).toList(); if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (defaultArgumentListString != '') _result["defaultArgumentListString"] = defaultArgumentListString; if (defaultArgumentListTextRanges.isNotEmpty) _result["defaultArgumentListTextRanges"] = defaultArgumentListTextRanges; if (docComplete != '') _result["docComplete"] = docComplete; if (docSummary != '') _result["docSummary"] = docSummary; if (fieldMask != 0) _result["fieldMask"] = fieldMask; if (isAbstract != false) _result["isAbstract"] = isAbstract; if (isConst != false) _result["isConst"] = isConst; if (isDeprecated != false) _result["isDeprecated"] = isDeprecated; if (isFinal != false) _result["isFinal"] = isFinal; if (kind != idl.AvailableDeclarationKind.CLASS) _result["kind"] = kind.toString().split('.')[1]; if (locationOffset != 0) _result["locationOffset"] = locationOffset; if (locationStartColumn != 0) _result["locationStartColumn"] = locationStartColumn; if (locationStartLine != 0) _result["locationStartLine"] = locationStartLine; if (name != '') _result["name"] = name; if (parameterNames.isNotEmpty) _result["parameterNames"] = parameterNames; if (parameters != '') _result["parameters"] = parameters; if (parameterTypes.isNotEmpty) _result["parameterTypes"] = parameterTypes; if (relevanceTags.isNotEmpty) _result["relevanceTags"] = relevanceTags; if (requiredParameterCount != 0) _result["requiredParameterCount"] = requiredParameterCount; if (returnType != '') _result["returnType"] = returnType; if (typeParameters != '') _result["typeParameters"] = typeParameters; return _result; } @override Map<String, Object> toMap() => { "children": children, "codeLength": codeLength, "codeOffset": codeOffset, "defaultArgumentListString": defaultArgumentListString, "defaultArgumentListTextRanges": defaultArgumentListTextRanges, "docComplete": docComplete, "docSummary": docSummary, "fieldMask": fieldMask, "isAbstract": isAbstract, "isConst": isConst, "isDeprecated": isDeprecated, "isFinal": isFinal, "kind": kind, "locationOffset": locationOffset, "locationStartColumn": locationStartColumn, "locationStartLine": locationStartLine, "name": name, "parameterNames": parameterNames, "parameters": parameters, "parameterTypes": parameterTypes, "relevanceTags": relevanceTags, "requiredParameterCount": requiredParameterCount, "returnType": returnType, "typeParameters": typeParameters, }; @override String toString() => convert.json.encode(toJson()); } class AvailableFileBuilder extends Object with _AvailableFileMixin implements idl.AvailableFile { List<AvailableDeclarationBuilder> _declarations; DirectiveInfoBuilder _directiveInfo; List<AvailableFileExportBuilder> _exports; bool _isLibrary; bool _isLibraryDeprecated; List<int> _lineStarts; List<String> _parts; @override List<AvailableDeclarationBuilder> get declarations => _declarations ??= <AvailableDeclarationBuilder>[]; /// Declarations of the file. set declarations(List<AvailableDeclarationBuilder> value) { this._declarations = value; } @override DirectiveInfoBuilder get directiveInfo => _directiveInfo; /// The Dartdoc directives in the file. set directiveInfo(DirectiveInfoBuilder value) { this._directiveInfo = value; } @override List<AvailableFileExportBuilder> get exports => _exports ??= <AvailableFileExportBuilder>[]; /// Exports directives of the file. set exports(List<AvailableFileExportBuilder> value) { this._exports = value; } @override bool get isLibrary => _isLibrary ??= false; /// Is `true` if this file is a library. set isLibrary(bool value) { this._isLibrary = value; } @override bool get isLibraryDeprecated => _isLibraryDeprecated ??= false; /// Is `true` if this file is a library, and it is deprecated. set isLibraryDeprecated(bool value) { this._isLibraryDeprecated = value; } @override List<int> get lineStarts => _lineStarts ??= <int>[]; /// Offsets of the first character of each line in the source code. set lineStarts(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._lineStarts = value; } @override List<String> get parts => _parts ??= <String>[]; /// URIs of `part` directives. set parts(List<String> value) { this._parts = value; } AvailableFileBuilder( {List<AvailableDeclarationBuilder> declarations, DirectiveInfoBuilder directiveInfo, List<AvailableFileExportBuilder> exports, bool isLibrary, bool isLibraryDeprecated, List<int> lineStarts, List<String> parts}) : _declarations = declarations, _directiveInfo = directiveInfo, _exports = exports, _isLibrary = isLibrary, _isLibraryDeprecated = isLibraryDeprecated, _lineStarts = lineStarts, _parts = parts; /// Flush [informative] data recursively. void flushInformative() { _declarations?.forEach((b) => b.flushInformative()); _directiveInfo?.flushInformative(); _exports?.forEach((b) => b.flushInformative()); _lineStarts = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._declarations == null) { signature.addInt(0); } else { signature.addInt(this._declarations.length); for (var x in this._declarations) { x?.collectApiSignature(signature); } } signature.addBool(this._directiveInfo != null); this._directiveInfo?.collectApiSignature(signature); if (this._exports == null) { signature.addInt(0); } else { signature.addInt(this._exports.length); for (var x in this._exports) { x?.collectApiSignature(signature); } } signature.addBool(this._isLibrary == true); signature.addBool(this._isLibraryDeprecated == true); if (this._parts == null) { signature.addInt(0); } else { signature.addInt(this._parts.length); for (var x in this._parts) { signature.addString(x); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "UICF"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_declarations; fb.Offset offset_directiveInfo; fb.Offset offset_exports; fb.Offset offset_lineStarts; fb.Offset offset_parts; if (!(_declarations == null || _declarations.isEmpty)) { offset_declarations = fbBuilder .writeList(_declarations.map((b) => b.finish(fbBuilder)).toList()); } if (_directiveInfo != null) { offset_directiveInfo = _directiveInfo.finish(fbBuilder); } if (!(_exports == null || _exports.isEmpty)) { offset_exports = fbBuilder .writeList(_exports.map((b) => b.finish(fbBuilder)).toList()); } if (!(_lineStarts == null || _lineStarts.isEmpty)) { offset_lineStarts = fbBuilder.writeListUint32(_lineStarts); } if (!(_parts == null || _parts.isEmpty)) { offset_parts = fbBuilder .writeList(_parts.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_declarations != null) { fbBuilder.addOffset(0, offset_declarations); } if (offset_directiveInfo != null) { fbBuilder.addOffset(1, offset_directiveInfo); } if (offset_exports != null) { fbBuilder.addOffset(2, offset_exports); } if (_isLibrary == true) { fbBuilder.addBool(3, true); } if (_isLibraryDeprecated == true) { fbBuilder.addBool(4, true); } if (offset_lineStarts != null) { fbBuilder.addOffset(5, offset_lineStarts); } if (offset_parts != null) { fbBuilder.addOffset(6, offset_parts); } return fbBuilder.endTable(); } } idl.AvailableFile readAvailableFile(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _AvailableFileReader().read(rootRef, 0); } class _AvailableFileReader extends fb.TableReader<_AvailableFileImpl> { const _AvailableFileReader(); @override _AvailableFileImpl createObject(fb.BufferContext bc, int offset) => new _AvailableFileImpl(bc, offset); } class _AvailableFileImpl extends Object with _AvailableFileMixin implements idl.AvailableFile { final fb.BufferContext _bc; final int _bcOffset; _AvailableFileImpl(this._bc, this._bcOffset); List<idl.AvailableDeclaration> _declarations; idl.DirectiveInfo _directiveInfo; List<idl.AvailableFileExport> _exports; bool _isLibrary; bool _isLibraryDeprecated; List<int> _lineStarts; List<String> _parts; @override List<idl.AvailableDeclaration> get declarations { _declarations ??= const fb.ListReader<idl.AvailableDeclaration>( const _AvailableDeclarationReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.AvailableDeclaration>[]); return _declarations; } @override idl.DirectiveInfo get directiveInfo { _directiveInfo ??= const _DirectiveInfoReader().vTableGet(_bc, _bcOffset, 1, null); return _directiveInfo; } @override List<idl.AvailableFileExport> get exports { _exports ??= const fb.ListReader<idl.AvailableFileExport>( const _AvailableFileExportReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.AvailableFileExport>[]); return _exports; } @override bool get isLibrary { _isLibrary ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 3, false); return _isLibrary; } @override bool get isLibraryDeprecated { _isLibraryDeprecated ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 4, false); return _isLibraryDeprecated; } @override List<int> get lineStarts { _lineStarts ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 5, const <int>[]); return _lineStarts; } @override List<String> get parts { _parts ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 6, const <String>[]); return _parts; } } abstract class _AvailableFileMixin implements idl.AvailableFile { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (declarations.isNotEmpty) _result["declarations"] = declarations.map((_value) => _value.toJson()).toList(); if (directiveInfo != null) _result["directiveInfo"] = directiveInfo.toJson(); if (exports.isNotEmpty) _result["exports"] = exports.map((_value) => _value.toJson()).toList(); if (isLibrary != false) _result["isLibrary"] = isLibrary; if (isLibraryDeprecated != false) _result["isLibraryDeprecated"] = isLibraryDeprecated; if (lineStarts.isNotEmpty) _result["lineStarts"] = lineStarts; if (parts.isNotEmpty) _result["parts"] = parts; return _result; } @override Map<String, Object> toMap() => { "declarations": declarations, "directiveInfo": directiveInfo, "exports": exports, "isLibrary": isLibrary, "isLibraryDeprecated": isLibraryDeprecated, "lineStarts": lineStarts, "parts": parts, }; @override String toString() => convert.json.encode(toJson()); } class AvailableFileExportBuilder extends Object with _AvailableFileExportMixin implements idl.AvailableFileExport { List<AvailableFileExportCombinatorBuilder> _combinators; String _uri; @override List<AvailableFileExportCombinatorBuilder> get combinators => _combinators ??= <AvailableFileExportCombinatorBuilder>[]; /// Combinators contained in this export directive. set combinators(List<AvailableFileExportCombinatorBuilder> value) { this._combinators = value; } @override String get uri => _uri ??= ''; /// URI of the exported library. set uri(String value) { this._uri = value; } AvailableFileExportBuilder( {List<AvailableFileExportCombinatorBuilder> combinators, String uri}) : _combinators = combinators, _uri = uri; /// Flush [informative] data recursively. void flushInformative() { _combinators?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._uri ?? ''); if (this._combinators == null) { signature.addInt(0); } else { signature.addInt(this._combinators.length); for (var x in this._combinators) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_combinators; fb.Offset offset_uri; if (!(_combinators == null || _combinators.isEmpty)) { offset_combinators = fbBuilder .writeList(_combinators.map((b) => b.finish(fbBuilder)).toList()); } if (_uri != null) { offset_uri = fbBuilder.writeString(_uri); } fbBuilder.startTable(); if (offset_combinators != null) { fbBuilder.addOffset(1, offset_combinators); } if (offset_uri != null) { fbBuilder.addOffset(0, offset_uri); } return fbBuilder.endTable(); } } class _AvailableFileExportReader extends fb.TableReader<_AvailableFileExportImpl> { const _AvailableFileExportReader(); @override _AvailableFileExportImpl createObject(fb.BufferContext bc, int offset) => new _AvailableFileExportImpl(bc, offset); } class _AvailableFileExportImpl extends Object with _AvailableFileExportMixin implements idl.AvailableFileExport { final fb.BufferContext _bc; final int _bcOffset; _AvailableFileExportImpl(this._bc, this._bcOffset); List<idl.AvailableFileExportCombinator> _combinators; String _uri; @override List<idl.AvailableFileExportCombinator> get combinators { _combinators ??= const fb.ListReader<idl.AvailableFileExportCombinator>( const _AvailableFileExportCombinatorReader()) .vTableGet( _bc, _bcOffset, 1, const <idl.AvailableFileExportCombinator>[]); return _combinators; } @override String get uri { _uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _uri; } } abstract class _AvailableFileExportMixin implements idl.AvailableFileExport { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (combinators.isNotEmpty) _result["combinators"] = combinators.map((_value) => _value.toJson()).toList(); if (uri != '') _result["uri"] = uri; return _result; } @override Map<String, Object> toMap() => { "combinators": combinators, "uri": uri, }; @override String toString() => convert.json.encode(toJson()); } class AvailableFileExportCombinatorBuilder extends Object with _AvailableFileExportCombinatorMixin implements idl.AvailableFileExportCombinator { List<String> _hides; List<String> _shows; @override List<String> get hides => _hides ??= <String>[]; /// List of names which are hidden. Empty if this is a `show` combinator. set hides(List<String> value) { this._hides = value; } @override List<String> get shows => _shows ??= <String>[]; /// List of names which are shown. Empty if this is a `hide` combinator. set shows(List<String> value) { this._shows = value; } AvailableFileExportCombinatorBuilder({List<String> hides, List<String> shows}) : _hides = hides, _shows = shows; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._shows == null) { signature.addInt(0); } else { signature.addInt(this._shows.length); for (var x in this._shows) { signature.addString(x); } } if (this._hides == null) { signature.addInt(0); } else { signature.addInt(this._hides.length); for (var x in this._hides) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_hides; fb.Offset offset_shows; if (!(_hides == null || _hides.isEmpty)) { offset_hides = fbBuilder .writeList(_hides.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_shows == null || _shows.isEmpty)) { offset_shows = fbBuilder .writeList(_shows.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_hides != null) { fbBuilder.addOffset(1, offset_hides); } if (offset_shows != null) { fbBuilder.addOffset(0, offset_shows); } return fbBuilder.endTable(); } } class _AvailableFileExportCombinatorReader extends fb.TableReader<_AvailableFileExportCombinatorImpl> { const _AvailableFileExportCombinatorReader(); @override _AvailableFileExportCombinatorImpl createObject( fb.BufferContext bc, int offset) => new _AvailableFileExportCombinatorImpl(bc, offset); } class _AvailableFileExportCombinatorImpl extends Object with _AvailableFileExportCombinatorMixin implements idl.AvailableFileExportCombinator { final fb.BufferContext _bc; final int _bcOffset; _AvailableFileExportCombinatorImpl(this._bc, this._bcOffset); List<String> _hides; List<String> _shows; @override List<String> get hides { _hides ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _hides; } @override List<String> get shows { _shows ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 0, const <String>[]); return _shows; } } abstract class _AvailableFileExportCombinatorMixin implements idl.AvailableFileExportCombinator { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (hides.isNotEmpty) _result["hides"] = hides; if (shows.isNotEmpty) _result["shows"] = shows; return _result; } @override Map<String, Object> toMap() => { "hides": hides, "shows": shows, }; @override String toString() => convert.json.encode(toJson()); } class CodeRangeBuilder extends Object with _CodeRangeMixin implements idl.CodeRange { int _length; int _offset; @override int get length => _length ??= 0; /// Length of the element code. set length(int value) { assert(value == null || value >= 0); this._length = value; } @override int get offset => _offset ??= 0; /// Offset of the element code relative to the beginning of the file. set offset(int value) { assert(value == null || value >= 0); this._offset = value; } CodeRangeBuilder({int length, int offset}) : _length = length, _offset = offset; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._offset ?? 0); signature.addInt(this._length ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fbBuilder.startTable(); if (_length != null && _length != 0) { fbBuilder.addUint32(1, _length); } if (_offset != null && _offset != 0) { fbBuilder.addUint32(0, _offset); } return fbBuilder.endTable(); } } class _CodeRangeReader extends fb.TableReader<_CodeRangeImpl> { const _CodeRangeReader(); @override _CodeRangeImpl createObject(fb.BufferContext bc, int offset) => new _CodeRangeImpl(bc, offset); } class _CodeRangeImpl extends Object with _CodeRangeMixin implements idl.CodeRange { final fb.BufferContext _bc; final int _bcOffset; _CodeRangeImpl(this._bc, this._bcOffset); int _length; int _offset; @override int get length { _length ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _length; } @override int get offset { _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _offset; } } abstract class _CodeRangeMixin implements idl.CodeRange { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (length != 0) _result["length"] = length; if (offset != 0) _result["offset"] = offset; return _result; } @override Map<String, Object> toMap() => { "length": length, "offset": offset, }; @override String toString() => convert.json.encode(toJson()); } class DiagnosticMessageBuilder extends Object with _DiagnosticMessageMixin implements idl.DiagnosticMessage { String _filePath; int _length; String _message; int _offset; @override String get filePath => _filePath ??= ''; /// The absolute and normalized path of the file associated with this message. set filePath(String value) { this._filePath = value; } @override int get length => _length ??= 0; /// The length of the source range associated with this message. set length(int value) { assert(value == null || value >= 0); this._length = value; } @override String get message => _message ??= ''; /// The text of the message. set message(String value) { this._message = value; } @override int get offset => _offset ??= 0; /// The zero-based offset from the start of the file to the beginning of the /// source range associated with this message. set offset(int value) { assert(value == null || value >= 0); this._offset = value; } DiagnosticMessageBuilder( {String filePath, int length, String message, int offset}) : _filePath = filePath, _length = length, _message = message, _offset = offset; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._filePath ?? ''); signature.addInt(this._length ?? 0); signature.addString(this._message ?? ''); signature.addInt(this._offset ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_filePath; fb.Offset offset_message; if (_filePath != null) { offset_filePath = fbBuilder.writeString(_filePath); } if (_message != null) { offset_message = fbBuilder.writeString(_message); } fbBuilder.startTable(); if (offset_filePath != null) { fbBuilder.addOffset(0, offset_filePath); } if (_length != null && _length != 0) { fbBuilder.addUint32(1, _length); } if (offset_message != null) { fbBuilder.addOffset(2, offset_message); } if (_offset != null && _offset != 0) { fbBuilder.addUint32(3, _offset); } return fbBuilder.endTable(); } } class _DiagnosticMessageReader extends fb.TableReader<_DiagnosticMessageImpl> { const _DiagnosticMessageReader(); @override _DiagnosticMessageImpl createObject(fb.BufferContext bc, int offset) => new _DiagnosticMessageImpl(bc, offset); } class _DiagnosticMessageImpl extends Object with _DiagnosticMessageMixin implements idl.DiagnosticMessage { final fb.BufferContext _bc; final int _bcOffset; _DiagnosticMessageImpl(this._bc, this._bcOffset); String _filePath; int _length; String _message; int _offset; @override String get filePath { _filePath ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _filePath; } @override int get length { _length ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _length; } @override String get message { _message ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 2, ''); return _message; } @override int get offset { _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _offset; } } abstract class _DiagnosticMessageMixin implements idl.DiagnosticMessage { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (filePath != '') _result["filePath"] = filePath; if (length != 0) _result["length"] = length; if (message != '') _result["message"] = message; if (offset != 0) _result["offset"] = offset; return _result; } @override Map<String, Object> toMap() => { "filePath": filePath, "length": length, "message": message, "offset": offset, }; @override String toString() => convert.json.encode(toJson()); } class DirectiveInfoBuilder extends Object with _DirectiveInfoMixin implements idl.DirectiveInfo { List<String> _templateNames; List<String> _templateValues; @override List<String> get templateNames => _templateNames ??= <String>[]; /// The names of the defined templates. set templateNames(List<String> value) { this._templateNames = value; } @override List<String> get templateValues => _templateValues ??= <String>[]; /// The values of the defined templates. set templateValues(List<String> value) { this._templateValues = value; } DirectiveInfoBuilder( {List<String> templateNames, List<String> templateValues}) : _templateNames = templateNames, _templateValues = templateValues; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._templateNames == null) { signature.addInt(0); } else { signature.addInt(this._templateNames.length); for (var x in this._templateNames) { signature.addString(x); } } if (this._templateValues == null) { signature.addInt(0); } else { signature.addInt(this._templateValues.length); for (var x in this._templateValues) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_templateNames; fb.Offset offset_templateValues; if (!(_templateNames == null || _templateNames.isEmpty)) { offset_templateNames = fbBuilder.writeList( _templateNames.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_templateValues == null || _templateValues.isEmpty)) { offset_templateValues = fbBuilder.writeList( _templateValues.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_templateNames != null) { fbBuilder.addOffset(0, offset_templateNames); } if (offset_templateValues != null) { fbBuilder.addOffset(1, offset_templateValues); } return fbBuilder.endTable(); } } class _DirectiveInfoReader extends fb.TableReader<_DirectiveInfoImpl> { const _DirectiveInfoReader(); @override _DirectiveInfoImpl createObject(fb.BufferContext bc, int offset) => new _DirectiveInfoImpl(bc, offset); } class _DirectiveInfoImpl extends Object with _DirectiveInfoMixin implements idl.DirectiveInfo { final fb.BufferContext _bc; final int _bcOffset; _DirectiveInfoImpl(this._bc, this._bcOffset); List<String> _templateNames; List<String> _templateValues; @override List<String> get templateNames { _templateNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 0, const <String>[]); return _templateNames; } @override List<String> get templateValues { _templateValues ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _templateValues; } } abstract class _DirectiveInfoMixin implements idl.DirectiveInfo { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (templateNames.isNotEmpty) _result["templateNames"] = templateNames; if (templateValues.isNotEmpty) _result["templateValues"] = templateValues; return _result; } @override Map<String, Object> toMap() => { "templateNames": templateNames, "templateValues": templateValues, }; @override String toString() => convert.json.encode(toJson()); } class EntityRefBuilder extends Object with _EntityRefMixin implements idl.EntityRef { idl.EntityRefKind _entityKind; List<int> _implicitFunctionTypeIndices; idl.EntityRefNullabilitySuffix _nullabilitySuffix; int _paramReference; int _reference; int _refinedSlot; int _slot; List<UnlinkedParamBuilder> _syntheticParams; EntityRefBuilder _syntheticReturnType; List<EntityRefBuilder> _typeArguments; List<UnlinkedTypeParamBuilder> _typeParameters; @override idl.EntityRefKind get entityKind => _entityKind ??= idl.EntityRefKind.named; /// The kind of entity being represented. set entityKind(idl.EntityRefKind value) { this._entityKind = value; } @override List<int> get implicitFunctionTypeIndices => _implicitFunctionTypeIndices ??= <int>[]; /// Notice: This will be deprecated. However, its not deprecated yet, as we're /// keeping it for backwards compatibilty, and marking it deprecated makes it /// unreadable. /// /// TODO(mfairhurst) mark this deprecated, and remove its logic. /// /// If this is a reference to a function type implicitly defined by a /// function-typed parameter, a list of zero-based indices indicating the path /// from the entity referred to by [reference] to the appropriate type /// parameter. Otherwise the empty list. /// /// If there are N indices in this list, then the entity being referred to is /// the function type implicitly defined by a function-typed parameter of a /// function-typed parameter, to N levels of nesting. The first index in the /// list refers to the outermost level of nesting; for example if [reference] /// refers to the entity defined by: /// /// void f(x, void g(y, z, int h(String w))) { ... } /// /// Then to refer to the function type implicitly defined by parameter `h` /// (which is parameter 2 of parameter 1 of `f`), then /// [implicitFunctionTypeIndices] should be [1, 2]. /// /// Note that if the entity being referred to is a generic method inside a /// generic class, then the type arguments in [typeArguments] are applied /// first to the class and then to the method. set implicitFunctionTypeIndices(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._implicitFunctionTypeIndices = value; } @override idl.EntityRefNullabilitySuffix get nullabilitySuffix => _nullabilitySuffix ??= idl.EntityRefNullabilitySuffix.starOrIrrelevant; /// If the reference represents a type, the nullability of the type. set nullabilitySuffix(idl.EntityRefNullabilitySuffix value) { this._nullabilitySuffix = value; } @override int get paramReference => _paramReference ??= 0; /// If this is a reference to a type parameter, one-based index into the list /// of [UnlinkedTypeParam]s currently in effect. Indexing is done using De /// Bruijn index conventions; that is, innermost parameters come first, and /// if a class or method has multiple parameters, they are indexed from right /// to left. So for instance, if the enclosing declaration is /// /// class C<T,U> { /// m<V,W> { /// ... /// } /// } /// /// Then [paramReference] values of 1, 2, 3, and 4 represent W, V, U, and T, /// respectively. /// /// If the type being referred to is not a type parameter, [paramReference] is /// zero. set paramReference(int value) { assert(value == null || value >= 0); this._paramReference = value; } @override int get reference => _reference ??= 0; /// Index into [UnlinkedUnit.references] for the entity being referred to, or /// zero if this is a reference to a type parameter. set reference(int value) { assert(value == null || value >= 0); this._reference = value; } @override int get refinedSlot => _refinedSlot ??= 0; /// If this [EntityRef] appears in a syntactic context where its type /// arguments might need to be inferred by a method other than /// instantiate-to-bounds, and [typeArguments] is empty, a slot id (which is /// unique within the compilation unit). If an entry appears in /// [LinkedUnit.types] whose [slot] matches this value, that entry will /// contain the complete inferred type. /// /// This is called `refinedSlot` to clarify that if it points to an inferred /// type, it points to a type that is a "refinement" of this one (one in which /// some type arguments have been inferred). set refinedSlot(int value) { assert(value == null || value >= 0); this._refinedSlot = value; } @override int get slot => _slot ??= 0; /// If this [EntityRef] is contained within [LinkedUnit.types], slot id (which /// is unique within the compilation unit) identifying the target of type /// propagation or type inference with which this [EntityRef] is associated. /// /// Otherwise zero. set slot(int value) { assert(value == null || value >= 0); this._slot = value; } @override List<UnlinkedParamBuilder> get syntheticParams => _syntheticParams ??= <UnlinkedParamBuilder>[]; /// If this [EntityRef] is a reference to a function type whose /// [FunctionElement] is not in any library (e.g. a function type that was /// synthesized by a LUB computation), the function parameters. Otherwise /// empty. set syntheticParams(List<UnlinkedParamBuilder> value) { this._syntheticParams = value; } @override EntityRefBuilder get syntheticReturnType => _syntheticReturnType; /// If this [EntityRef] is a reference to a function type whose /// [FunctionElement] is not in any library (e.g. a function type that was /// synthesized by a LUB computation), the return type of the function. /// Otherwise `null`. set syntheticReturnType(EntityRefBuilder value) { this._syntheticReturnType = value; } @override List<EntityRefBuilder> get typeArguments => _typeArguments ??= <EntityRefBuilder>[]; /// If this is an instantiation of a generic type or generic executable, the /// type arguments used to instantiate it (if any). set typeArguments(List<EntityRefBuilder> value) { this._typeArguments = value; } @override List<UnlinkedTypeParamBuilder> get typeParameters => _typeParameters ??= <UnlinkedTypeParamBuilder>[]; /// If this is a function type, the type parameters defined for the function /// type (if any). set typeParameters(List<UnlinkedTypeParamBuilder> value) { this._typeParameters = value; } EntityRefBuilder( {idl.EntityRefKind entityKind, List<int> implicitFunctionTypeIndices, idl.EntityRefNullabilitySuffix nullabilitySuffix, int paramReference, int reference, int refinedSlot, int slot, List<UnlinkedParamBuilder> syntheticParams, EntityRefBuilder syntheticReturnType, List<EntityRefBuilder> typeArguments, List<UnlinkedTypeParamBuilder> typeParameters}) : _entityKind = entityKind, _implicitFunctionTypeIndices = implicitFunctionTypeIndices, _nullabilitySuffix = nullabilitySuffix, _paramReference = paramReference, _reference = reference, _refinedSlot = refinedSlot, _slot = slot, _syntheticParams = syntheticParams, _syntheticReturnType = syntheticReturnType, _typeArguments = typeArguments, _typeParameters = typeParameters; /// Flush [informative] data recursively. void flushInformative() { _syntheticParams?.forEach((b) => b.flushInformative()); _syntheticReturnType?.flushInformative(); _typeArguments?.forEach((b) => b.flushInformative()); _typeParameters?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._reference ?? 0); if (this._typeArguments == null) { signature.addInt(0); } else { signature.addInt(this._typeArguments.length); for (var x in this._typeArguments) { x?.collectApiSignature(signature); } } signature.addInt(this._slot ?? 0); signature.addInt(this._paramReference ?? 0); if (this._implicitFunctionTypeIndices == null) { signature.addInt(0); } else { signature.addInt(this._implicitFunctionTypeIndices.length); for (var x in this._implicitFunctionTypeIndices) { signature.addInt(x); } } signature.addBool(this._syntheticReturnType != null); this._syntheticReturnType?.collectApiSignature(signature); if (this._syntheticParams == null) { signature.addInt(0); } else { signature.addInt(this._syntheticParams.length); for (var x in this._syntheticParams) { x?.collectApiSignature(signature); } } if (this._typeParameters == null) { signature.addInt(0); } else { signature.addInt(this._typeParameters.length); for (var x in this._typeParameters) { x?.collectApiSignature(signature); } } signature.addInt(this._entityKind == null ? 0 : this._entityKind.index); signature.addInt(this._refinedSlot ?? 0); signature.addInt( this._nullabilitySuffix == null ? 0 : this._nullabilitySuffix.index); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_implicitFunctionTypeIndices; fb.Offset offset_syntheticParams; fb.Offset offset_syntheticReturnType; fb.Offset offset_typeArguments; fb.Offset offset_typeParameters; if (!(_implicitFunctionTypeIndices == null || _implicitFunctionTypeIndices.isEmpty)) { offset_implicitFunctionTypeIndices = fbBuilder.writeListUint32(_implicitFunctionTypeIndices); } if (!(_syntheticParams == null || _syntheticParams.isEmpty)) { offset_syntheticParams = fbBuilder .writeList(_syntheticParams.map((b) => b.finish(fbBuilder)).toList()); } if (_syntheticReturnType != null) { offset_syntheticReturnType = _syntheticReturnType.finish(fbBuilder); } if (!(_typeArguments == null || _typeArguments.isEmpty)) { offset_typeArguments = fbBuilder .writeList(_typeArguments.map((b) => b.finish(fbBuilder)).toList()); } if (!(_typeParameters == null || _typeParameters.isEmpty)) { offset_typeParameters = fbBuilder .writeList(_typeParameters.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (_entityKind != null && _entityKind != idl.EntityRefKind.named) { fbBuilder.addUint8(8, _entityKind.index); } if (offset_implicitFunctionTypeIndices != null) { fbBuilder.addOffset(4, offset_implicitFunctionTypeIndices); } if (_nullabilitySuffix != null && _nullabilitySuffix != idl.EntityRefNullabilitySuffix.starOrIrrelevant) { fbBuilder.addUint8(10, _nullabilitySuffix.index); } if (_paramReference != null && _paramReference != 0) { fbBuilder.addUint32(3, _paramReference); } if (_reference != null && _reference != 0) { fbBuilder.addUint32(0, _reference); } if (_refinedSlot != null && _refinedSlot != 0) { fbBuilder.addUint32(9, _refinedSlot); } if (_slot != null && _slot != 0) { fbBuilder.addUint32(2, _slot); } if (offset_syntheticParams != null) { fbBuilder.addOffset(6, offset_syntheticParams); } if (offset_syntheticReturnType != null) { fbBuilder.addOffset(5, offset_syntheticReturnType); } if (offset_typeArguments != null) { fbBuilder.addOffset(1, offset_typeArguments); } if (offset_typeParameters != null) { fbBuilder.addOffset(7, offset_typeParameters); } return fbBuilder.endTable(); } } class _EntityRefReader extends fb.TableReader<_EntityRefImpl> { const _EntityRefReader(); @override _EntityRefImpl createObject(fb.BufferContext bc, int offset) => new _EntityRefImpl(bc, offset); } class _EntityRefImpl extends Object with _EntityRefMixin implements idl.EntityRef { final fb.BufferContext _bc; final int _bcOffset; _EntityRefImpl(this._bc, this._bcOffset); idl.EntityRefKind _entityKind; List<int> _implicitFunctionTypeIndices; idl.EntityRefNullabilitySuffix _nullabilitySuffix; int _paramReference; int _reference; int _refinedSlot; int _slot; List<idl.UnlinkedParam> _syntheticParams; idl.EntityRef _syntheticReturnType; List<idl.EntityRef> _typeArguments; List<idl.UnlinkedTypeParam> _typeParameters; @override idl.EntityRefKind get entityKind { _entityKind ??= const _EntityRefKindReader() .vTableGet(_bc, _bcOffset, 8, idl.EntityRefKind.named); return _entityKind; } @override List<int> get implicitFunctionTypeIndices { _implicitFunctionTypeIndices ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 4, const <int>[]); return _implicitFunctionTypeIndices; } @override idl.EntityRefNullabilitySuffix get nullabilitySuffix { _nullabilitySuffix ??= const _EntityRefNullabilitySuffixReader().vTableGet( _bc, _bcOffset, 10, idl.EntityRefNullabilitySuffix.starOrIrrelevant); return _nullabilitySuffix; } @override int get paramReference { _paramReference ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _paramReference; } @override int get reference { _reference ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _reference; } @override int get refinedSlot { _refinedSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 9, 0); return _refinedSlot; } @override int get slot { _slot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _slot; } @override List<idl.UnlinkedParam> get syntheticParams { _syntheticParams ??= const fb.ListReader<idl.UnlinkedParam>(const _UnlinkedParamReader()) .vTableGet(_bc, _bcOffset, 6, const <idl.UnlinkedParam>[]); return _syntheticParams; } @override idl.EntityRef get syntheticReturnType { _syntheticReturnType ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 5, null); return _syntheticReturnType; } @override List<idl.EntityRef> get typeArguments { _typeArguments ??= const fb.ListReader<idl.EntityRef>(const _EntityRefReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.EntityRef>[]); return _typeArguments; } @override List<idl.UnlinkedTypeParam> get typeParameters { _typeParameters ??= const fb.ListReader<idl.UnlinkedTypeParam>( const _UnlinkedTypeParamReader()) .vTableGet(_bc, _bcOffset, 7, const <idl.UnlinkedTypeParam>[]); return _typeParameters; } } abstract class _EntityRefMixin implements idl.EntityRef { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (entityKind != idl.EntityRefKind.named) _result["entityKind"] = entityKind.toString().split('.')[1]; if (implicitFunctionTypeIndices.isNotEmpty) _result["implicitFunctionTypeIndices"] = implicitFunctionTypeIndices; if (nullabilitySuffix != idl.EntityRefNullabilitySuffix.starOrIrrelevant) _result["nullabilitySuffix"] = nullabilitySuffix.toString().split('.')[1]; if (paramReference != 0) _result["paramReference"] = paramReference; if (reference != 0) _result["reference"] = reference; if (refinedSlot != 0) _result["refinedSlot"] = refinedSlot; if (slot != 0) _result["slot"] = slot; if (syntheticParams.isNotEmpty) _result["syntheticParams"] = syntheticParams.map((_value) => _value.toJson()).toList(); if (syntheticReturnType != null) _result["syntheticReturnType"] = syntheticReturnType.toJson(); if (typeArguments.isNotEmpty) _result["typeArguments"] = typeArguments.map((_value) => _value.toJson()).toList(); if (typeParameters.isNotEmpty) _result["typeParameters"] = typeParameters.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "entityKind": entityKind, "implicitFunctionTypeIndices": implicitFunctionTypeIndices, "nullabilitySuffix": nullabilitySuffix, "paramReference": paramReference, "reference": reference, "refinedSlot": refinedSlot, "slot": slot, "syntheticParams": syntheticParams, "syntheticReturnType": syntheticReturnType, "typeArguments": typeArguments, "typeParameters": typeParameters, }; @override String toString() => convert.json.encode(toJson()); } class LinkedDependencyBuilder extends Object with _LinkedDependencyMixin implements idl.LinkedDependency { List<String> _parts; String _uri; @override List<String> get parts => _parts ??= <String>[]; /// Absolute URI for the compilation units listed in the library's `part` /// declarations, empty string for invalid URI. set parts(List<String> value) { this._parts = value; } @override String get uri => _uri ??= ''; /// The absolute URI of the dependent library, e.g. `package:foo/bar.dart`. set uri(String value) { this._uri = value; } LinkedDependencyBuilder({List<String> parts, String uri}) : _parts = parts, _uri = uri; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._uri ?? ''); if (this._parts == null) { signature.addInt(0); } else { signature.addInt(this._parts.length); for (var x in this._parts) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_parts; fb.Offset offset_uri; if (!(_parts == null || _parts.isEmpty)) { offset_parts = fbBuilder .writeList(_parts.map((b) => fbBuilder.writeString(b)).toList()); } if (_uri != null) { offset_uri = fbBuilder.writeString(_uri); } fbBuilder.startTable(); if (offset_parts != null) { fbBuilder.addOffset(1, offset_parts); } if (offset_uri != null) { fbBuilder.addOffset(0, offset_uri); } return fbBuilder.endTable(); } } class _LinkedDependencyReader extends fb.TableReader<_LinkedDependencyImpl> { const _LinkedDependencyReader(); @override _LinkedDependencyImpl createObject(fb.BufferContext bc, int offset) => new _LinkedDependencyImpl(bc, offset); } class _LinkedDependencyImpl extends Object with _LinkedDependencyMixin implements idl.LinkedDependency { final fb.BufferContext _bc; final int _bcOffset; _LinkedDependencyImpl(this._bc, this._bcOffset); List<String> _parts; String _uri; @override List<String> get parts { _parts ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _parts; } @override String get uri { _uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _uri; } } abstract class _LinkedDependencyMixin implements idl.LinkedDependency { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (parts.isNotEmpty) _result["parts"] = parts; if (uri != '') _result["uri"] = uri; return _result; } @override Map<String, Object> toMap() => { "parts": parts, "uri": uri, }; @override String toString() => convert.json.encode(toJson()); } class LinkedExportNameBuilder extends Object with _LinkedExportNameMixin implements idl.LinkedExportName { int _dependency; idl.ReferenceKind _kind; String _name; int _unit; @override int get dependency => _dependency ??= 0; /// Index into [LinkedLibrary.dependencies] for the library in which the /// entity is defined. set dependency(int value) { assert(value == null || value >= 0); this._dependency = value; } @override idl.ReferenceKind get kind => _kind ??= idl.ReferenceKind.classOrEnum; /// The kind of the entity being referred to. set kind(idl.ReferenceKind value) { this._kind = value; } @override String get name => _name ??= ''; /// Name of the exported entity. For an exported setter, this name includes /// the trailing '='. set name(String value) { this._name = value; } @override int get unit => _unit ??= 0; /// Integer index indicating which unit in the exported library contains the /// definition of the entity. As with indices into [LinkedLibrary.units], /// zero represents the defining compilation unit, and nonzero values /// represent parts in the order of the corresponding `part` declarations. set unit(int value) { assert(value == null || value >= 0); this._unit = value; } LinkedExportNameBuilder( {int dependency, idl.ReferenceKind kind, String name, int unit}) : _dependency = dependency, _kind = kind, _name = name, _unit = unit; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._dependency ?? 0); signature.addString(this._name ?? ''); signature.addInt(this._unit ?? 0); signature.addInt(this._kind == null ? 0 : this._kind.index); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_name; if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (_dependency != null && _dependency != 0) { fbBuilder.addUint32(0, _dependency); } if (_kind != null && _kind != idl.ReferenceKind.classOrEnum) { fbBuilder.addUint8(3, _kind.index); } if (offset_name != null) { fbBuilder.addOffset(1, offset_name); } if (_unit != null && _unit != 0) { fbBuilder.addUint32(2, _unit); } return fbBuilder.endTable(); } } class _LinkedExportNameReader extends fb.TableReader<_LinkedExportNameImpl> { const _LinkedExportNameReader(); @override _LinkedExportNameImpl createObject(fb.BufferContext bc, int offset) => new _LinkedExportNameImpl(bc, offset); } class _LinkedExportNameImpl extends Object with _LinkedExportNameMixin implements idl.LinkedExportName { final fb.BufferContext _bc; final int _bcOffset; _LinkedExportNameImpl(this._bc, this._bcOffset); int _dependency; idl.ReferenceKind _kind; String _name; int _unit; @override int get dependency { _dependency ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _dependency; } @override idl.ReferenceKind get kind { _kind ??= const _ReferenceKindReader() .vTableGet(_bc, _bcOffset, 3, idl.ReferenceKind.classOrEnum); return _kind; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _name; } @override int get unit { _unit ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _unit; } } abstract class _LinkedExportNameMixin implements idl.LinkedExportName { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (dependency != 0) _result["dependency"] = dependency; if (kind != idl.ReferenceKind.classOrEnum) _result["kind"] = kind.toString().split('.')[1]; if (name != '') _result["name"] = name; if (unit != 0) _result["unit"] = unit; return _result; } @override Map<String, Object> toMap() => { "dependency": dependency, "kind": kind, "name": name, "unit": unit, }; @override String toString() => convert.json.encode(toJson()); } class LinkedLibraryBuilder extends Object with _LinkedLibraryMixin implements idl.LinkedLibrary { List<LinkedDependencyBuilder> _dependencies; List<int> _exportDependencies; List<LinkedExportNameBuilder> _exportNames; List<int> _importDependencies; int _numPrelinkedDependencies; List<LinkedUnitBuilder> _units; @override List<LinkedDependencyBuilder> get dependencies => _dependencies ??= <LinkedDependencyBuilder>[]; /// The libraries that this library depends on (either via an explicit import /// statement or via the implicit dependencies on `dart:core` and /// `dart:async`). The first element of this array is a pseudo-dependency /// representing the library itself (it is also used for `dynamic` and /// `void`). This is followed by elements representing "prelinked" /// dependencies (direct imports and the transitive closure of exports). /// After the prelinked dependencies are elements representing "linked" /// dependencies. /// /// A library is only included as a "linked" dependency if it is a true /// dependency (e.g. a propagated or inferred type or constant value /// implicitly refers to an element declared in the library) or /// anti-dependency (e.g. the result of type propagation or type inference /// depends on the lack of a certain declaration in the library). set dependencies(List<LinkedDependencyBuilder> value) { this._dependencies = value; } @override List<int> get exportDependencies => _exportDependencies ??= <int>[]; /// For each export in [UnlinkedUnit.exports], an index into [dependencies] /// of the library being exported. set exportDependencies(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._exportDependencies = value; } @override List<LinkedExportNameBuilder> get exportNames => _exportNames ??= <LinkedExportNameBuilder>[]; /// Information about entities in the export namespace of the library that are /// not in the public namespace of the library (that is, entities that are /// brought into the namespace via `export` directives). /// /// Sorted by name. set exportNames(List<LinkedExportNameBuilder> value) { this._exportNames = value; } @override Null get fallbackMode => throw new UnimplementedError('attempt to access deprecated field'); @override List<int> get importDependencies => _importDependencies ??= <int>[]; /// For each import in [UnlinkedUnit.imports], an index into [dependencies] /// of the library being imported. set importDependencies(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._importDependencies = value; } @override int get numPrelinkedDependencies => _numPrelinkedDependencies ??= 0; /// The number of elements in [dependencies] which are not "linked" /// dependencies (that is, the number of libraries in the direct imports plus /// the transitive closure of exports, plus the library itself). set numPrelinkedDependencies(int value) { assert(value == null || value >= 0); this._numPrelinkedDependencies = value; } @override List<LinkedUnitBuilder> get units => _units ??= <LinkedUnitBuilder>[]; /// The linked summary of all the compilation units constituting the /// library. The summary of the defining compilation unit is listed first, /// followed by the summary of each part, in the order of the `part` /// declarations in the defining compilation unit. set units(List<LinkedUnitBuilder> value) { this._units = value; } LinkedLibraryBuilder( {List<LinkedDependencyBuilder> dependencies, List<int> exportDependencies, List<LinkedExportNameBuilder> exportNames, List<int> importDependencies, int numPrelinkedDependencies, List<LinkedUnitBuilder> units}) : _dependencies = dependencies, _exportDependencies = exportDependencies, _exportNames = exportNames, _importDependencies = importDependencies, _numPrelinkedDependencies = numPrelinkedDependencies, _units = units; /// Flush [informative] data recursively. void flushInformative() { _dependencies?.forEach((b) => b.flushInformative()); _exportNames?.forEach((b) => b.flushInformative()); _units?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._dependencies == null) { signature.addInt(0); } else { signature.addInt(this._dependencies.length); for (var x in this._dependencies) { x?.collectApiSignature(signature); } } if (this._importDependencies == null) { signature.addInt(0); } else { signature.addInt(this._importDependencies.length); for (var x in this._importDependencies) { signature.addInt(x); } } signature.addInt(this._numPrelinkedDependencies ?? 0); if (this._units == null) { signature.addInt(0); } else { signature.addInt(this._units.length); for (var x in this._units) { x?.collectApiSignature(signature); } } if (this._exportNames == null) { signature.addInt(0); } else { signature.addInt(this._exportNames.length); for (var x in this._exportNames) { x?.collectApiSignature(signature); } } if (this._exportDependencies == null) { signature.addInt(0); } else { signature.addInt(this._exportDependencies.length); for (var x in this._exportDependencies) { signature.addInt(x); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "LLib"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_dependencies; fb.Offset offset_exportDependencies; fb.Offset offset_exportNames; fb.Offset offset_importDependencies; fb.Offset offset_units; if (!(_dependencies == null || _dependencies.isEmpty)) { offset_dependencies = fbBuilder .writeList(_dependencies.map((b) => b.finish(fbBuilder)).toList()); } if (!(_exportDependencies == null || _exportDependencies.isEmpty)) { offset_exportDependencies = fbBuilder.writeListUint32(_exportDependencies); } if (!(_exportNames == null || _exportNames.isEmpty)) { offset_exportNames = fbBuilder .writeList(_exportNames.map((b) => b.finish(fbBuilder)).toList()); } if (!(_importDependencies == null || _importDependencies.isEmpty)) { offset_importDependencies = fbBuilder.writeListUint32(_importDependencies); } if (!(_units == null || _units.isEmpty)) { offset_units = fbBuilder.writeList(_units.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_dependencies != null) { fbBuilder.addOffset(0, offset_dependencies); } if (offset_exportDependencies != null) { fbBuilder.addOffset(6, offset_exportDependencies); } if (offset_exportNames != null) { fbBuilder.addOffset(4, offset_exportNames); } if (offset_importDependencies != null) { fbBuilder.addOffset(1, offset_importDependencies); } if (_numPrelinkedDependencies != null && _numPrelinkedDependencies != 0) { fbBuilder.addUint32(2, _numPrelinkedDependencies); } if (offset_units != null) { fbBuilder.addOffset(3, offset_units); } return fbBuilder.endTable(); } } idl.LinkedLibrary readLinkedLibrary(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _LinkedLibraryReader().read(rootRef, 0); } class _LinkedLibraryReader extends fb.TableReader<_LinkedLibraryImpl> { const _LinkedLibraryReader(); @override _LinkedLibraryImpl createObject(fb.BufferContext bc, int offset) => new _LinkedLibraryImpl(bc, offset); } class _LinkedLibraryImpl extends Object with _LinkedLibraryMixin implements idl.LinkedLibrary { final fb.BufferContext _bc; final int _bcOffset; _LinkedLibraryImpl(this._bc, this._bcOffset); List<idl.LinkedDependency> _dependencies; List<int> _exportDependencies; List<idl.LinkedExportName> _exportNames; List<int> _importDependencies; int _numPrelinkedDependencies; List<idl.LinkedUnit> _units; @override List<idl.LinkedDependency> get dependencies { _dependencies ??= const fb.ListReader<idl.LinkedDependency>( const _LinkedDependencyReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.LinkedDependency>[]); return _dependencies; } @override List<int> get exportDependencies { _exportDependencies ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 6, const <int>[]); return _exportDependencies; } @override List<idl.LinkedExportName> get exportNames { _exportNames ??= const fb.ListReader<idl.LinkedExportName>( const _LinkedExportNameReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.LinkedExportName>[]); return _exportNames; } @override Null get fallbackMode => throw new UnimplementedError('attempt to access deprecated field'); @override List<int> get importDependencies { _importDependencies ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 1, const <int>[]); return _importDependencies; } @override int get numPrelinkedDependencies { _numPrelinkedDependencies ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _numPrelinkedDependencies; } @override List<idl.LinkedUnit> get units { _units ??= const fb.ListReader<idl.LinkedUnit>(const _LinkedUnitReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.LinkedUnit>[]); return _units; } } abstract class _LinkedLibraryMixin implements idl.LinkedLibrary { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (dependencies.isNotEmpty) _result["dependencies"] = dependencies.map((_value) => _value.toJson()).toList(); if (exportDependencies.isNotEmpty) _result["exportDependencies"] = exportDependencies; if (exportNames.isNotEmpty) _result["exportNames"] = exportNames.map((_value) => _value.toJson()).toList(); if (importDependencies.isNotEmpty) _result["importDependencies"] = importDependencies; if (numPrelinkedDependencies != 0) _result["numPrelinkedDependencies"] = numPrelinkedDependencies; if (units.isNotEmpty) _result["units"] = units.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "dependencies": dependencies, "exportDependencies": exportDependencies, "exportNames": exportNames, "importDependencies": importDependencies, "numPrelinkedDependencies": numPrelinkedDependencies, "units": units, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeBuilder extends Object with _LinkedNodeMixin implements idl.LinkedNode { LinkedNodeTypeBuilder _variantField_24; List<LinkedNodeBuilder> _variantField_2; List<LinkedNodeBuilder> _variantField_4; LinkedNodeBuilder _variantField_6; LinkedNodeBuilder _variantField_7; int _variantField_17; LinkedNodeBuilder _variantField_8; LinkedNodeTypeSubstitutionBuilder _variantField_38; int _variantField_15; idl.UnlinkedTokenType _variantField_28; bool _variantField_27; LinkedNodeBuilder _variantField_9; LinkedNodeBuilder _variantField_12; List<LinkedNodeBuilder> _variantField_5; LinkedNodeBuilder _variantField_13; List<String> _variantField_33; idl.LinkedNodeCommentType _variantField_29; List<LinkedNodeBuilder> _variantField_3; LinkedNodeBuilder _variantField_10; idl.LinkedNodeFormalParameterKind _variantField_26; double _variantField_21; LinkedNodeTypeBuilder _variantField_25; String _variantField_20; List<LinkedNodeTypeBuilder> _variantField_39; int _flags; String _variantField_1; int _variantField_36; int _variantField_16; String _variantField_30; LinkedNodeBuilder _variantField_14; idl.LinkedNodeKind _kind; List<String> _variantField_34; String _name; bool _variantField_31; idl.UnlinkedTokenType _variantField_35; TopLevelInferenceErrorBuilder _variantField_32; LinkedNodeTypeBuilder _variantField_23; LinkedNodeBuilder _variantField_11; String _variantField_22; int _variantField_19; @override LinkedNodeTypeBuilder get actualReturnType { assert(kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionExpression || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericFunctionType || kind == idl.LinkedNodeKind.methodDeclaration); return _variantField_24; } @override LinkedNodeTypeBuilder get actualType { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_24; } @override LinkedNodeTypeBuilder get binaryExpression_invokeType { assert(kind == idl.LinkedNodeKind.binaryExpression); return _variantField_24; } @override LinkedNodeTypeBuilder get extensionOverride_extendedType { assert(kind == idl.LinkedNodeKind.extensionOverride); return _variantField_24; } @override LinkedNodeTypeBuilder get invocationExpression_invokeType { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); return _variantField_24; } /// The explicit or inferred return type of a function typed node. set actualReturnType(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionExpression || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericFunctionType || kind == idl.LinkedNodeKind.methodDeclaration); _variantField_24 = value; } set actualType(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_24 = value; } set binaryExpression_invokeType(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_24 = value; } set extensionOverride_extendedType(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_24 = value; } set invocationExpression_invokeType(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); _variantField_24 = value; } @override List<LinkedNodeBuilder> get adjacentStrings_strings { assert(kind == idl.LinkedNodeKind.adjacentStrings); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get argumentList_arguments { assert(kind == idl.LinkedNodeKind.argumentList); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get block_statements { assert(kind == idl.LinkedNodeKind.block); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get cascadeExpression_sections { assert(kind == idl.LinkedNodeKind.cascadeExpression); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get comment_references { assert(kind == idl.LinkedNodeKind.comment); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get compilationUnit_declarations { assert(kind == idl.LinkedNodeKind.compilationUnit); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get constructorDeclaration_initializers { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get dottedName_components { assert(kind == idl.LinkedNodeKind.dottedName); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get enumDeclaration_constants { assert(kind == idl.LinkedNodeKind.enumDeclaration); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get extensionOverride_arguments { assert(kind == idl.LinkedNodeKind.extensionOverride); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get formalParameterList_parameters { assert(kind == idl.LinkedNodeKind.formalParameterList); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get implementsClause_interfaces { assert(kind == idl.LinkedNodeKind.implementsClause); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get instanceCreationExpression_arguments { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get labeledStatement_labels { assert(kind == idl.LinkedNodeKind.labeledStatement); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get libraryIdentifier_components { assert(kind == idl.LinkedNodeKind.libraryIdentifier); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get namespaceDirective_combinators { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get onClause_superclassConstraints { assert(kind == idl.LinkedNodeKind.onClause); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get stringInterpolation_elements { assert(kind == idl.LinkedNodeKind.stringInterpolation); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get switchStatement_members { assert(kind == idl.LinkedNodeKind.switchStatement); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get tryStatement_catchClauses { assert(kind == idl.LinkedNodeKind.tryStatement); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get typeArgumentList_arguments { assert(kind == idl.LinkedNodeKind.typeArgumentList); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get typedLiteral_typeArguments { assert(kind == idl.LinkedNodeKind.listLiteral || kind == idl.LinkedNodeKind.setOrMapLiteral); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get typeName_typeArguments { assert(kind == idl.LinkedNodeKind.typeName); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get typeParameterList_typeParameters { assert(kind == idl.LinkedNodeKind.typeParameterList); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get variableDeclarationList_variables { assert(kind == idl.LinkedNodeKind.variableDeclarationList); return _variantField_2 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get withClause_mixinTypes { assert(kind == idl.LinkedNodeKind.withClause); return _variantField_2 ??= <LinkedNodeBuilder>[]; } set adjacentStrings_strings(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.adjacentStrings); _variantField_2 = value; } set argumentList_arguments(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.argumentList); _variantField_2 = value; } set block_statements(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.block); _variantField_2 = value; } set cascadeExpression_sections(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.cascadeExpression); _variantField_2 = value; } set comment_references(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.comment); _variantField_2 = value; } set compilationUnit_declarations(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_2 = value; } set constructorDeclaration_initializers(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_2 = value; } set dottedName_components(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.dottedName); _variantField_2 = value; } set enumDeclaration_constants(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.enumDeclaration); _variantField_2 = value; } set extensionOverride_arguments(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_2 = value; } set formalParameterList_parameters(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.formalParameterList); _variantField_2 = value; } set implementsClause_interfaces(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.implementsClause); _variantField_2 = value; } set instanceCreationExpression_arguments(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); _variantField_2 = value; } set labeledStatement_labels(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.labeledStatement); _variantField_2 = value; } set libraryIdentifier_components(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.libraryIdentifier); _variantField_2 = value; } set namespaceDirective_combinators(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); _variantField_2 = value; } set onClause_superclassConstraints(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.onClause); _variantField_2 = value; } set stringInterpolation_elements(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.stringInterpolation); _variantField_2 = value; } set switchStatement_members(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.switchStatement); _variantField_2 = value; } set tryStatement_catchClauses(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.tryStatement); _variantField_2 = value; } set typeArgumentList_arguments(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.typeArgumentList); _variantField_2 = value; } set typedLiteral_typeArguments(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.listLiteral || kind == idl.LinkedNodeKind.setOrMapLiteral); _variantField_2 = value; } set typeName_typeArguments(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.typeName); _variantField_2 = value; } set typeParameterList_typeParameters(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.typeParameterList); _variantField_2 = value; } set variableDeclarationList_variables(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_2 = value; } set withClause_mixinTypes(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.withClause); _variantField_2 = value; } @override List<LinkedNodeBuilder> get annotatedNode_metadata { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.declaredIdentifier || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective || kind == idl.LinkedNodeKind.topLevelVariableDeclaration || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration || kind == idl.LinkedNodeKind.variableDeclarationList); return _variantField_4 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get normalFormalParameter_metadata { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter); return _variantField_4 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get switchMember_statements { assert(kind == idl.LinkedNodeKind.switchCase || kind == idl.LinkedNodeKind.switchDefault); return _variantField_4 ??= <LinkedNodeBuilder>[]; } set annotatedNode_metadata(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.declaredIdentifier || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective || kind == idl.LinkedNodeKind.topLevelVariableDeclaration || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration || kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_4 = value; } set normalFormalParameter_metadata(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter); _variantField_4 = value; } set switchMember_statements(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.switchCase || kind == idl.LinkedNodeKind.switchDefault); _variantField_4 = value; } @override LinkedNodeBuilder get annotation_arguments { assert(kind == idl.LinkedNodeKind.annotation); return _variantField_6; } @override LinkedNodeBuilder get asExpression_expression { assert(kind == idl.LinkedNodeKind.asExpression); return _variantField_6; } @override LinkedNodeBuilder get assertInitializer_condition { assert(kind == idl.LinkedNodeKind.assertInitializer); return _variantField_6; } @override LinkedNodeBuilder get assertStatement_condition { assert(kind == idl.LinkedNodeKind.assertStatement); return _variantField_6; } @override LinkedNodeBuilder get assignmentExpression_leftHandSide { assert(kind == idl.LinkedNodeKind.assignmentExpression); return _variantField_6; } @override LinkedNodeBuilder get awaitExpression_expression { assert(kind == idl.LinkedNodeKind.awaitExpression); return _variantField_6; } @override LinkedNodeBuilder get binaryExpression_leftOperand { assert(kind == idl.LinkedNodeKind.binaryExpression); return _variantField_6; } @override LinkedNodeBuilder get blockFunctionBody_block { assert(kind == idl.LinkedNodeKind.blockFunctionBody); return _variantField_6; } @override LinkedNodeBuilder get breakStatement_label { assert(kind == idl.LinkedNodeKind.breakStatement); return _variantField_6; } @override LinkedNodeBuilder get cascadeExpression_target { assert(kind == idl.LinkedNodeKind.cascadeExpression); return _variantField_6; } @override LinkedNodeBuilder get catchClause_body { assert(kind == idl.LinkedNodeKind.catchClause); return _variantField_6; } @override LinkedNodeBuilder get classDeclaration_extendsClause { assert(kind == idl.LinkedNodeKind.classDeclaration); return _variantField_6; } @override LinkedNodeBuilder get classTypeAlias_typeParameters { assert(kind == idl.LinkedNodeKind.classTypeAlias); return _variantField_6; } @override LinkedNodeBuilder get commentReference_identifier { assert(kind == idl.LinkedNodeKind.commentReference); return _variantField_6; } @override LinkedNodeBuilder get compilationUnit_scriptTag { assert(kind == idl.LinkedNodeKind.compilationUnit); return _variantField_6; } @override LinkedNodeBuilder get conditionalExpression_condition { assert(kind == idl.LinkedNodeKind.conditionalExpression); return _variantField_6; } @override LinkedNodeBuilder get configuration_name { assert(kind == idl.LinkedNodeKind.configuration); return _variantField_6; } @override LinkedNodeBuilder get constructorDeclaration_body { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_6; } @override LinkedNodeBuilder get constructorFieldInitializer_expression { assert(kind == idl.LinkedNodeKind.constructorFieldInitializer); return _variantField_6; } @override LinkedNodeBuilder get constructorName_name { assert(kind == idl.LinkedNodeKind.constructorName); return _variantField_6; } @override LinkedNodeBuilder get continueStatement_label { assert(kind == idl.LinkedNodeKind.continueStatement); return _variantField_6; } @override LinkedNodeBuilder get declaredIdentifier_identifier { assert(kind == idl.LinkedNodeKind.declaredIdentifier); return _variantField_6; } @override LinkedNodeBuilder get defaultFormalParameter_defaultValue { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); return _variantField_6; } @override LinkedNodeBuilder get doStatement_body { assert(kind == idl.LinkedNodeKind.doStatement); return _variantField_6; } @override LinkedNodeBuilder get expressionFunctionBody_expression { assert(kind == idl.LinkedNodeKind.expressionFunctionBody); return _variantField_6; } @override LinkedNodeBuilder get expressionStatement_expression { assert(kind == idl.LinkedNodeKind.expressionStatement); return _variantField_6; } @override LinkedNodeBuilder get extendsClause_superclass { assert(kind == idl.LinkedNodeKind.extendsClause); return _variantField_6; } @override LinkedNodeBuilder get extensionDeclaration_typeParameters { assert(kind == idl.LinkedNodeKind.extensionDeclaration); return _variantField_6; } @override LinkedNodeBuilder get fieldDeclaration_fields { assert(kind == idl.LinkedNodeKind.fieldDeclaration); return _variantField_6; } @override LinkedNodeBuilder get fieldFormalParameter_type { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); return _variantField_6; } @override LinkedNodeBuilder get forEachParts_iterable { assert(kind == idl.LinkedNodeKind.forEachPartsWithDeclaration || kind == idl.LinkedNodeKind.forEachPartsWithIdentifier); return _variantField_6; } @override LinkedNodeBuilder get forMixin_forLoopParts { assert(kind == idl.LinkedNodeKind.forElement || kind == idl.LinkedNodeKind.forStatement); return _variantField_6; } @override LinkedNodeBuilder get forParts_condition { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations || kind == idl.LinkedNodeKind.forPartsWithExpression); return _variantField_6; } @override LinkedNodeBuilder get functionDeclaration_functionExpression { assert(kind == idl.LinkedNodeKind.functionDeclaration); return _variantField_6; } @override LinkedNodeBuilder get functionDeclarationStatement_functionDeclaration { assert(kind == idl.LinkedNodeKind.functionDeclarationStatement); return _variantField_6; } @override LinkedNodeBuilder get functionExpression_body { assert(kind == idl.LinkedNodeKind.functionExpression); return _variantField_6; } @override LinkedNodeBuilder get functionExpressionInvocation_function { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation); return _variantField_6; } @override LinkedNodeBuilder get functionTypeAlias_formalParameters { assert(kind == idl.LinkedNodeKind.functionTypeAlias); return _variantField_6; } @override LinkedNodeBuilder get functionTypedFormalParameter_formalParameters { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); return _variantField_6; } @override LinkedNodeBuilder get genericFunctionType_typeParameters { assert(kind == idl.LinkedNodeKind.genericFunctionType); return _variantField_6; } @override LinkedNodeBuilder get genericTypeAlias_typeParameters { assert(kind == idl.LinkedNodeKind.genericTypeAlias); return _variantField_6; } @override LinkedNodeBuilder get ifMixin_condition { assert(kind == idl.LinkedNodeKind.ifElement || kind == idl.LinkedNodeKind.ifStatement); return _variantField_6; } @override LinkedNodeBuilder get indexExpression_index { assert(kind == idl.LinkedNodeKind.indexExpression); return _variantField_6; } @override LinkedNodeBuilder get interpolationExpression_expression { assert(kind == idl.LinkedNodeKind.interpolationExpression); return _variantField_6; } @override LinkedNodeBuilder get isExpression_expression { assert(kind == idl.LinkedNodeKind.isExpression); return _variantField_6; } @override LinkedNodeBuilder get label_label { assert(kind == idl.LinkedNodeKind.label); return _variantField_6; } @override LinkedNodeBuilder get labeledStatement_statement { assert(kind == idl.LinkedNodeKind.labeledStatement); return _variantField_6; } @override LinkedNodeBuilder get libraryDirective_name { assert(kind == idl.LinkedNodeKind.libraryDirective); return _variantField_6; } @override LinkedNodeBuilder get mapLiteralEntry_key { assert(kind == idl.LinkedNodeKind.mapLiteralEntry); return _variantField_6; } @override LinkedNodeBuilder get methodDeclaration_body { assert(kind == idl.LinkedNodeKind.methodDeclaration); return _variantField_6; } @override LinkedNodeBuilder get methodInvocation_methodName { assert(kind == idl.LinkedNodeKind.methodInvocation); return _variantField_6; } @override LinkedNodeBuilder get mixinDeclaration_onClause { assert(kind == idl.LinkedNodeKind.mixinDeclaration); return _variantField_6; } @override LinkedNodeBuilder get namedExpression_expression { assert(kind == idl.LinkedNodeKind.namedExpression); return _variantField_6; } @override LinkedNodeBuilder get nativeClause_name { assert(kind == idl.LinkedNodeKind.nativeClause); return _variantField_6; } @override LinkedNodeBuilder get nativeFunctionBody_stringLiteral { assert(kind == idl.LinkedNodeKind.nativeFunctionBody); return _variantField_6; } @override LinkedNodeBuilder get parenthesizedExpression_expression { assert(kind == idl.LinkedNodeKind.parenthesizedExpression); return _variantField_6; } @override LinkedNodeBuilder get partOfDirective_libraryName { assert(kind == idl.LinkedNodeKind.partOfDirective); return _variantField_6; } @override LinkedNodeBuilder get postfixExpression_operand { assert(kind == idl.LinkedNodeKind.postfixExpression); return _variantField_6; } @override LinkedNodeBuilder get prefixedIdentifier_identifier { assert(kind == idl.LinkedNodeKind.prefixedIdentifier); return _variantField_6; } @override LinkedNodeBuilder get prefixExpression_operand { assert(kind == idl.LinkedNodeKind.prefixExpression); return _variantField_6; } @override LinkedNodeBuilder get propertyAccess_propertyName { assert(kind == idl.LinkedNodeKind.propertyAccess); return _variantField_6; } @override LinkedNodeBuilder get redirectingConstructorInvocation_arguments { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); return _variantField_6; } @override LinkedNodeBuilder get returnStatement_expression { assert(kind == idl.LinkedNodeKind.returnStatement); return _variantField_6; } @override LinkedNodeBuilder get simpleFormalParameter_type { assert(kind == idl.LinkedNodeKind.simpleFormalParameter); return _variantField_6; } @override LinkedNodeBuilder get spreadElement_expression { assert(kind == idl.LinkedNodeKind.spreadElement); return _variantField_6; } @override LinkedNodeBuilder get superConstructorInvocation_arguments { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); return _variantField_6; } @override LinkedNodeBuilder get switchCase_expression { assert(kind == idl.LinkedNodeKind.switchCase); return _variantField_6; } @override LinkedNodeBuilder get throwExpression_expression { assert(kind == idl.LinkedNodeKind.throwExpression); return _variantField_6; } @override LinkedNodeBuilder get topLevelVariableDeclaration_variableList { assert(kind == idl.LinkedNodeKind.topLevelVariableDeclaration); return _variantField_6; } @override LinkedNodeBuilder get tryStatement_body { assert(kind == idl.LinkedNodeKind.tryStatement); return _variantField_6; } @override LinkedNodeBuilder get typeName_name { assert(kind == idl.LinkedNodeKind.typeName); return _variantField_6; } @override LinkedNodeBuilder get typeParameter_bound { assert(kind == idl.LinkedNodeKind.typeParameter); return _variantField_6; } @override LinkedNodeBuilder get variableDeclaration_initializer { assert(kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_6; } @override LinkedNodeBuilder get variableDeclarationList_type { assert(kind == idl.LinkedNodeKind.variableDeclarationList); return _variantField_6; } @override LinkedNodeBuilder get variableDeclarationStatement_variables { assert(kind == idl.LinkedNodeKind.variableDeclarationStatement); return _variantField_6; } @override LinkedNodeBuilder get whileStatement_body { assert(kind == idl.LinkedNodeKind.whileStatement); return _variantField_6; } @override LinkedNodeBuilder get yieldStatement_expression { assert(kind == idl.LinkedNodeKind.yieldStatement); return _variantField_6; } set annotation_arguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.annotation); _variantField_6 = value; } set asExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.asExpression); _variantField_6 = value; } set assertInitializer_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.assertInitializer); _variantField_6 = value; } set assertStatement_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.assertStatement); _variantField_6 = value; } set assignmentExpression_leftHandSide(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_6 = value; } set awaitExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.awaitExpression); _variantField_6 = value; } set binaryExpression_leftOperand(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_6 = value; } set blockFunctionBody_block(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.blockFunctionBody); _variantField_6 = value; } set breakStatement_label(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.breakStatement); _variantField_6 = value; } set cascadeExpression_target(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.cascadeExpression); _variantField_6 = value; } set catchClause_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_6 = value; } set classDeclaration_extendsClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_6 = value; } set classTypeAlias_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_6 = value; } set commentReference_identifier(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.commentReference); _variantField_6 = value; } set compilationUnit_scriptTag(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_6 = value; } set conditionalExpression_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.conditionalExpression); _variantField_6 = value; } set configuration_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.configuration); _variantField_6 = value; } set constructorDeclaration_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_6 = value; } set constructorFieldInitializer_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorFieldInitializer); _variantField_6 = value; } set constructorName_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_6 = value; } set continueStatement_label(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.continueStatement); _variantField_6 = value; } set declaredIdentifier_identifier(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.declaredIdentifier); _variantField_6 = value; } set defaultFormalParameter_defaultValue(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_6 = value; } set doStatement_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.doStatement); _variantField_6 = value; } set expressionFunctionBody_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.expressionFunctionBody); _variantField_6 = value; } set expressionStatement_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.expressionStatement); _variantField_6 = value; } set extendsClause_superclass(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.extendsClause); _variantField_6 = value; } set extensionDeclaration_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_6 = value; } set fieldDeclaration_fields(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.fieldDeclaration); _variantField_6 = value; } set fieldFormalParameter_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); _variantField_6 = value; } set forEachParts_iterable(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forEachPartsWithDeclaration || kind == idl.LinkedNodeKind.forEachPartsWithIdentifier); _variantField_6 = value; } set forMixin_forLoopParts(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forElement || kind == idl.LinkedNodeKind.forStatement); _variantField_6 = value; } set forParts_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations || kind == idl.LinkedNodeKind.forPartsWithExpression); _variantField_6 = value; } set functionDeclaration_functionExpression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionDeclaration); _variantField_6 = value; } set functionDeclarationStatement_functionDeclaration( LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionDeclarationStatement); _variantField_6 = value; } set functionExpression_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpression); _variantField_6 = value; } set functionExpressionInvocation_function(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation); _variantField_6 = value; } set functionTypeAlias_formalParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionTypeAlias); _variantField_6 = value; } set functionTypedFormalParameter_formalParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); _variantField_6 = value; } set genericFunctionType_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_6 = value; } set genericTypeAlias_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.genericTypeAlias); _variantField_6 = value; } set ifMixin_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.ifElement || kind == idl.LinkedNodeKind.ifStatement); _variantField_6 = value; } set indexExpression_index(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_6 = value; } set interpolationExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.interpolationExpression); _variantField_6 = value; } set isExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.isExpression); _variantField_6 = value; } set label_label(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.label); _variantField_6 = value; } set labeledStatement_statement(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.labeledStatement); _variantField_6 = value; } set libraryDirective_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.libraryDirective); _variantField_6 = value; } set mapLiteralEntry_key(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.mapLiteralEntry); _variantField_6 = value; } set methodDeclaration_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_6 = value; } set methodInvocation_methodName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.methodInvocation); _variantField_6 = value; } set mixinDeclaration_onClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_6 = value; } set namedExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.namedExpression); _variantField_6 = value; } set nativeClause_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.nativeClause); _variantField_6 = value; } set nativeFunctionBody_stringLiteral(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.nativeFunctionBody); _variantField_6 = value; } set parenthesizedExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.parenthesizedExpression); _variantField_6 = value; } set partOfDirective_libraryName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.partOfDirective); _variantField_6 = value; } set postfixExpression_operand(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_6 = value; } set prefixedIdentifier_identifier(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.prefixedIdentifier); _variantField_6 = value; } set prefixExpression_operand(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_6 = value; } set propertyAccess_propertyName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.propertyAccess); _variantField_6 = value; } set redirectingConstructorInvocation_arguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_6 = value; } set returnStatement_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.returnStatement); _variantField_6 = value; } set simpleFormalParameter_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.simpleFormalParameter); _variantField_6 = value; } set spreadElement_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.spreadElement); _variantField_6 = value; } set superConstructorInvocation_arguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_6 = value; } set switchCase_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.switchCase); _variantField_6 = value; } set throwExpression_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.throwExpression); _variantField_6 = value; } set topLevelVariableDeclaration_variableList(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.topLevelVariableDeclaration); _variantField_6 = value; } set tryStatement_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.tryStatement); _variantField_6 = value; } set typeName_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.typeName); _variantField_6 = value; } set typeParameter_bound(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.typeParameter); _variantField_6 = value; } set variableDeclaration_initializer(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.variableDeclaration); _variantField_6 = value; } set variableDeclarationList_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_6 = value; } set variableDeclarationStatement_variables(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.variableDeclarationStatement); _variantField_6 = value; } set whileStatement_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.whileStatement); _variantField_6 = value; } set yieldStatement_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.yieldStatement); _variantField_6 = value; } @override LinkedNodeBuilder get annotation_constructorName { assert(kind == idl.LinkedNodeKind.annotation); return _variantField_7; } @override LinkedNodeBuilder get asExpression_type { assert(kind == idl.LinkedNodeKind.asExpression); return _variantField_7; } @override LinkedNodeBuilder get assertInitializer_message { assert(kind == idl.LinkedNodeKind.assertInitializer); return _variantField_7; } @override LinkedNodeBuilder get assertStatement_message { assert(kind == idl.LinkedNodeKind.assertStatement); return _variantField_7; } @override LinkedNodeBuilder get assignmentExpression_rightHandSide { assert(kind == idl.LinkedNodeKind.assignmentExpression); return _variantField_7; } @override LinkedNodeBuilder get binaryExpression_rightOperand { assert(kind == idl.LinkedNodeKind.binaryExpression); return _variantField_7; } @override LinkedNodeBuilder get catchClause_exceptionParameter { assert(kind == idl.LinkedNodeKind.catchClause); return _variantField_7; } @override LinkedNodeBuilder get classDeclaration_withClause { assert(kind == idl.LinkedNodeKind.classDeclaration); return _variantField_7; } @override LinkedNodeBuilder get classTypeAlias_superclass { assert(kind == idl.LinkedNodeKind.classTypeAlias); return _variantField_7; } @override LinkedNodeBuilder get conditionalExpression_elseExpression { assert(kind == idl.LinkedNodeKind.conditionalExpression); return _variantField_7; } @override LinkedNodeBuilder get configuration_value { assert(kind == idl.LinkedNodeKind.configuration); return _variantField_7; } @override LinkedNodeBuilder get constructorFieldInitializer_fieldName { assert(kind == idl.LinkedNodeKind.constructorFieldInitializer); return _variantField_7; } @override LinkedNodeBuilder get constructorName_type { assert(kind == idl.LinkedNodeKind.constructorName); return _variantField_7; } @override LinkedNodeBuilder get declaredIdentifier_type { assert(kind == idl.LinkedNodeKind.declaredIdentifier); return _variantField_7; } @override LinkedNodeBuilder get defaultFormalParameter_parameter { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); return _variantField_7; } @override LinkedNodeBuilder get doStatement_condition { assert(kind == idl.LinkedNodeKind.doStatement); return _variantField_7; } @override LinkedNodeBuilder get extensionDeclaration_extendedType { assert(kind == idl.LinkedNodeKind.extensionDeclaration); return _variantField_7; } @override LinkedNodeBuilder get extensionOverride_extensionName { assert(kind == idl.LinkedNodeKind.extensionOverride); return _variantField_7; } @override LinkedNodeBuilder get fieldFormalParameter_typeParameters { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); return _variantField_7; } @override LinkedNodeBuilder get forEachPartsWithDeclaration_loopVariable { assert(kind == idl.LinkedNodeKind.forEachPartsWithDeclaration); return _variantField_7; } @override LinkedNodeBuilder get forEachPartsWithIdentifier_identifier { assert(kind == idl.LinkedNodeKind.forEachPartsWithIdentifier); return _variantField_7; } @override LinkedNodeBuilder get forElement_body { assert(kind == idl.LinkedNodeKind.forElement); return _variantField_7; } @override LinkedNodeBuilder get forPartsWithDeclarations_variables { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations); return _variantField_7; } @override LinkedNodeBuilder get forPartsWithExpression_initialization { assert(kind == idl.LinkedNodeKind.forPartsWithExpression); return _variantField_7; } @override LinkedNodeBuilder get forStatement_body { assert(kind == idl.LinkedNodeKind.forStatement); return _variantField_7; } @override LinkedNodeBuilder get functionDeclaration_returnType { assert(kind == idl.LinkedNodeKind.functionDeclaration); return _variantField_7; } @override LinkedNodeBuilder get functionExpression_formalParameters { assert(kind == idl.LinkedNodeKind.functionExpression); return _variantField_7; } @override LinkedNodeBuilder get functionTypeAlias_returnType { assert(kind == idl.LinkedNodeKind.functionTypeAlias); return _variantField_7; } @override LinkedNodeBuilder get functionTypedFormalParameter_returnType { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); return _variantField_7; } @override LinkedNodeBuilder get genericFunctionType_returnType { assert(kind == idl.LinkedNodeKind.genericFunctionType); return _variantField_7; } @override LinkedNodeBuilder get genericTypeAlias_functionType { assert(kind == idl.LinkedNodeKind.genericTypeAlias); return _variantField_7; } @override LinkedNodeBuilder get ifStatement_elseStatement { assert(kind == idl.LinkedNodeKind.ifStatement); return _variantField_7; } @override LinkedNodeBuilder get indexExpression_target { assert(kind == idl.LinkedNodeKind.indexExpression); return _variantField_7; } @override LinkedNodeBuilder get instanceCreationExpression_constructorName { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); return _variantField_7; } @override LinkedNodeBuilder get isExpression_type { assert(kind == idl.LinkedNodeKind.isExpression); return _variantField_7; } @override LinkedNodeBuilder get mapLiteralEntry_value { assert(kind == idl.LinkedNodeKind.mapLiteralEntry); return _variantField_7; } @override LinkedNodeBuilder get methodDeclaration_formalParameters { assert(kind == idl.LinkedNodeKind.methodDeclaration); return _variantField_7; } @override LinkedNodeBuilder get methodInvocation_target { assert(kind == idl.LinkedNodeKind.methodInvocation); return _variantField_7; } @override LinkedNodeBuilder get namedExpression_name { assert(kind == idl.LinkedNodeKind.namedExpression); return _variantField_7; } @override LinkedNodeBuilder get partOfDirective_uri { assert(kind == idl.LinkedNodeKind.partOfDirective); return _variantField_7; } @override LinkedNodeBuilder get prefixedIdentifier_prefix { assert(kind == idl.LinkedNodeKind.prefixedIdentifier); return _variantField_7; } @override LinkedNodeBuilder get propertyAccess_target { assert(kind == idl.LinkedNodeKind.propertyAccess); return _variantField_7; } @override LinkedNodeBuilder get redirectingConstructorInvocation_constructorName { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); return _variantField_7; } @override LinkedNodeBuilder get superConstructorInvocation_constructorName { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); return _variantField_7; } @override LinkedNodeBuilder get switchStatement_expression { assert(kind == idl.LinkedNodeKind.switchStatement); return _variantField_7; } @override LinkedNodeBuilder get tryStatement_finallyBlock { assert(kind == idl.LinkedNodeKind.tryStatement); return _variantField_7; } @override LinkedNodeBuilder get whileStatement_condition { assert(kind == idl.LinkedNodeKind.whileStatement); return _variantField_7; } set annotation_constructorName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.annotation); _variantField_7 = value; } set asExpression_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.asExpression); _variantField_7 = value; } set assertInitializer_message(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.assertInitializer); _variantField_7 = value; } set assertStatement_message(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.assertStatement); _variantField_7 = value; } set assignmentExpression_rightHandSide(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_7 = value; } set binaryExpression_rightOperand(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_7 = value; } set catchClause_exceptionParameter(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_7 = value; } set classDeclaration_withClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_7 = value; } set classTypeAlias_superclass(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_7 = value; } set conditionalExpression_elseExpression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.conditionalExpression); _variantField_7 = value; } set configuration_value(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.configuration); _variantField_7 = value; } set constructorFieldInitializer_fieldName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorFieldInitializer); _variantField_7 = value; } set constructorName_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_7 = value; } set declaredIdentifier_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.declaredIdentifier); _variantField_7 = value; } set defaultFormalParameter_parameter(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_7 = value; } set doStatement_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.doStatement); _variantField_7 = value; } set extensionDeclaration_extendedType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_7 = value; } set extensionOverride_extensionName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_7 = value; } set fieldFormalParameter_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); _variantField_7 = value; } set forEachPartsWithDeclaration_loopVariable(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forEachPartsWithDeclaration); _variantField_7 = value; } set forEachPartsWithIdentifier_identifier(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forEachPartsWithIdentifier); _variantField_7 = value; } set forElement_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forElement); _variantField_7 = value; } set forPartsWithDeclarations_variables(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations); _variantField_7 = value; } set forPartsWithExpression_initialization(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forPartsWithExpression); _variantField_7 = value; } set forStatement_body(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.forStatement); _variantField_7 = value; } set functionDeclaration_returnType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionDeclaration); _variantField_7 = value; } set functionExpression_formalParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpression); _variantField_7 = value; } set functionTypeAlias_returnType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionTypeAlias); _variantField_7 = value; } set functionTypedFormalParameter_returnType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); _variantField_7 = value; } set genericFunctionType_returnType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_7 = value; } set genericTypeAlias_functionType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.genericTypeAlias); _variantField_7 = value; } set ifStatement_elseStatement(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.ifStatement); _variantField_7 = value; } set indexExpression_target(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_7 = value; } set instanceCreationExpression_constructorName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); _variantField_7 = value; } set isExpression_type(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.isExpression); _variantField_7 = value; } set mapLiteralEntry_value(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.mapLiteralEntry); _variantField_7 = value; } set methodDeclaration_formalParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_7 = value; } set methodInvocation_target(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.methodInvocation); _variantField_7 = value; } set namedExpression_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.namedExpression); _variantField_7 = value; } set partOfDirective_uri(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.partOfDirective); _variantField_7 = value; } set prefixedIdentifier_prefix(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.prefixedIdentifier); _variantField_7 = value; } set propertyAccess_target(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.propertyAccess); _variantField_7 = value; } set redirectingConstructorInvocation_constructorName( LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_7 = value; } set superConstructorInvocation_constructorName(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_7 = value; } set switchStatement_expression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.switchStatement); _variantField_7 = value; } set tryStatement_finallyBlock(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.tryStatement); _variantField_7 = value; } set whileStatement_condition(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.whileStatement); _variantField_7 = value; } @override int get annotation_element { assert(kind == idl.LinkedNodeKind.annotation); return _variantField_17 ??= 0; } @override int get genericFunctionType_id { assert(kind == idl.LinkedNodeKind.genericFunctionType); return _variantField_17 ??= 0; } set annotation_element(int value) { assert(kind == idl.LinkedNodeKind.annotation); assert(value == null || value >= 0); _variantField_17 = value; } set genericFunctionType_id(int value) { assert(kind == idl.LinkedNodeKind.genericFunctionType); assert(value == null || value >= 0); _variantField_17 = value; } @override LinkedNodeBuilder get annotation_name { assert(kind == idl.LinkedNodeKind.annotation); return _variantField_8; } @override LinkedNodeBuilder get catchClause_exceptionType { assert(kind == idl.LinkedNodeKind.catchClause); return _variantField_8; } @override LinkedNodeBuilder get classDeclaration_nativeClause { assert(kind == idl.LinkedNodeKind.classDeclaration); return _variantField_8; } @override LinkedNodeBuilder get classTypeAlias_withClause { assert(kind == idl.LinkedNodeKind.classTypeAlias); return _variantField_8; } @override LinkedNodeBuilder get conditionalExpression_thenExpression { assert(kind == idl.LinkedNodeKind.conditionalExpression); return _variantField_8; } @override LinkedNodeBuilder get configuration_uri { assert(kind == idl.LinkedNodeKind.configuration); return _variantField_8; } @override LinkedNodeBuilder get constructorDeclaration_parameters { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_8; } @override LinkedNodeBuilder get extensionOverride_typeArguments { assert(kind == idl.LinkedNodeKind.extensionOverride); return _variantField_8; } @override LinkedNodeBuilder get fieldFormalParameter_formalParameters { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); return _variantField_8; } @override LinkedNodeBuilder get functionExpression_typeParameters { assert(kind == idl.LinkedNodeKind.functionExpression); return _variantField_8; } @override LinkedNodeBuilder get functionTypeAlias_typeParameters { assert(kind == idl.LinkedNodeKind.functionTypeAlias); return _variantField_8; } @override LinkedNodeBuilder get functionTypedFormalParameter_typeParameters { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); return _variantField_8; } @override LinkedNodeBuilder get genericFunctionType_formalParameters { assert(kind == idl.LinkedNodeKind.genericFunctionType); return _variantField_8; } @override LinkedNodeBuilder get ifElement_thenElement { assert(kind == idl.LinkedNodeKind.ifElement); return _variantField_8; } @override LinkedNodeBuilder get ifStatement_thenStatement { assert(kind == idl.LinkedNodeKind.ifStatement); return _variantField_8; } @override LinkedNodeBuilder get instanceCreationExpression_typeArguments { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); return _variantField_8; } @override LinkedNodeBuilder get methodDeclaration_returnType { assert(kind == idl.LinkedNodeKind.methodDeclaration); return _variantField_8; } set annotation_name(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.annotation); _variantField_8 = value; } set catchClause_exceptionType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_8 = value; } set classDeclaration_nativeClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_8 = value; } set classTypeAlias_withClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_8 = value; } set conditionalExpression_thenExpression(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.conditionalExpression); _variantField_8 = value; } set configuration_uri(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.configuration); _variantField_8 = value; } set constructorDeclaration_parameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_8 = value; } set extensionOverride_typeArguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_8 = value; } set fieldFormalParameter_formalParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); _variantField_8 = value; } set functionExpression_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpression); _variantField_8 = value; } set functionTypeAlias_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionTypeAlias); _variantField_8 = value; } set functionTypedFormalParameter_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); _variantField_8 = value; } set genericFunctionType_formalParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_8 = value; } set ifElement_thenElement(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.ifElement); _variantField_8 = value; } set ifStatement_thenStatement(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.ifStatement); _variantField_8 = value; } set instanceCreationExpression_typeArguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); _variantField_8 = value; } set methodDeclaration_returnType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_8 = value; } @override LinkedNodeTypeSubstitutionBuilder get annotation_substitution { assert(kind == idl.LinkedNodeKind.annotation); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get assignmentExpression_substitution { assert(kind == idl.LinkedNodeKind.assignmentExpression); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get binaryExpression_substitution { assert(kind == idl.LinkedNodeKind.binaryExpression); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get constructorName_substitution { assert(kind == idl.LinkedNodeKind.constructorName); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get indexExpression_substitution { assert(kind == idl.LinkedNodeKind.indexExpression); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get postfixExpression_substitution { assert(kind == idl.LinkedNodeKind.postfixExpression); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get prefixExpression_substitution { assert(kind == idl.LinkedNodeKind.prefixExpression); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get redirectingConstructorInvocation_substitution { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get simpleIdentifier_substitution { assert(kind == idl.LinkedNodeKind.simpleIdentifier); return _variantField_38; } @override LinkedNodeTypeSubstitutionBuilder get superConstructorInvocation_substitution { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); return _variantField_38; } set annotation_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.annotation); _variantField_38 = value; } set assignmentExpression_substitution( LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_38 = value; } set binaryExpression_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_38 = value; } set constructorName_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_38 = value; } set indexExpression_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_38 = value; } set postfixExpression_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_38 = value; } set prefixExpression_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_38 = value; } set redirectingConstructorInvocation_substitution( LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_38 = value; } set simpleIdentifier_substitution(LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.simpleIdentifier); _variantField_38 = value; } set superConstructorInvocation_substitution( LinkedNodeTypeSubstitutionBuilder value) { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_38 = value; } @override int get assignmentExpression_element { assert(kind == idl.LinkedNodeKind.assignmentExpression); return _variantField_15 ??= 0; } @override int get binaryExpression_element { assert(kind == idl.LinkedNodeKind.binaryExpression); return _variantField_15 ??= 0; } @override int get constructorName_element { assert(kind == idl.LinkedNodeKind.constructorName); return _variantField_15 ??= 0; } @override int get emptyFunctionBody_fake { assert(kind == idl.LinkedNodeKind.emptyFunctionBody); return _variantField_15 ??= 0; } @override int get emptyStatement_fake { assert(kind == idl.LinkedNodeKind.emptyStatement); return _variantField_15 ??= 0; } @override int get indexExpression_element { assert(kind == idl.LinkedNodeKind.indexExpression); return _variantField_15 ??= 0; } @override int get nullLiteral_fake { assert(kind == idl.LinkedNodeKind.nullLiteral); return _variantField_15 ??= 0; } @override int get postfixExpression_element { assert(kind == idl.LinkedNodeKind.postfixExpression); return _variantField_15 ??= 0; } @override int get prefixExpression_element { assert(kind == idl.LinkedNodeKind.prefixExpression); return _variantField_15 ??= 0; } @override int get redirectingConstructorInvocation_element { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); return _variantField_15 ??= 0; } @override int get simpleIdentifier_element { assert(kind == idl.LinkedNodeKind.simpleIdentifier); return _variantField_15 ??= 0; } @override int get superConstructorInvocation_element { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); return _variantField_15 ??= 0; } set assignmentExpression_element(int value) { assert(kind == idl.LinkedNodeKind.assignmentExpression); assert(value == null || value >= 0); _variantField_15 = value; } set binaryExpression_element(int value) { assert(kind == idl.LinkedNodeKind.binaryExpression); assert(value == null || value >= 0); _variantField_15 = value; } set constructorName_element(int value) { assert(kind == idl.LinkedNodeKind.constructorName); assert(value == null || value >= 0); _variantField_15 = value; } set emptyFunctionBody_fake(int value) { assert(kind == idl.LinkedNodeKind.emptyFunctionBody); assert(value == null || value >= 0); _variantField_15 = value; } set emptyStatement_fake(int value) { assert(kind == idl.LinkedNodeKind.emptyStatement); assert(value == null || value >= 0); _variantField_15 = value; } set indexExpression_element(int value) { assert(kind == idl.LinkedNodeKind.indexExpression); assert(value == null || value >= 0); _variantField_15 = value; } set nullLiteral_fake(int value) { assert(kind == idl.LinkedNodeKind.nullLiteral); assert(value == null || value >= 0); _variantField_15 = value; } set postfixExpression_element(int value) { assert(kind == idl.LinkedNodeKind.postfixExpression); assert(value == null || value >= 0); _variantField_15 = value; } set prefixExpression_element(int value) { assert(kind == idl.LinkedNodeKind.prefixExpression); assert(value == null || value >= 0); _variantField_15 = value; } set redirectingConstructorInvocation_element(int value) { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); assert(value == null || value >= 0); _variantField_15 = value; } set simpleIdentifier_element(int value) { assert(kind == idl.LinkedNodeKind.simpleIdentifier); assert(value == null || value >= 0); _variantField_15 = value; } set superConstructorInvocation_element(int value) { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); assert(value == null || value >= 0); _variantField_15 = value; } @override idl.UnlinkedTokenType get assignmentExpression_operator { assert(kind == idl.LinkedNodeKind.assignmentExpression); return _variantField_28 ??= idl.UnlinkedTokenType.NOTHING; } @override idl.UnlinkedTokenType get binaryExpression_operator { assert(kind == idl.LinkedNodeKind.binaryExpression); return _variantField_28 ??= idl.UnlinkedTokenType.NOTHING; } @override idl.UnlinkedTokenType get postfixExpression_operator { assert(kind == idl.LinkedNodeKind.postfixExpression); return _variantField_28 ??= idl.UnlinkedTokenType.NOTHING; } @override idl.UnlinkedTokenType get prefixExpression_operator { assert(kind == idl.LinkedNodeKind.prefixExpression); return _variantField_28 ??= idl.UnlinkedTokenType.NOTHING; } @override idl.UnlinkedTokenType get propertyAccess_operator { assert(kind == idl.LinkedNodeKind.propertyAccess); return _variantField_28 ??= idl.UnlinkedTokenType.NOTHING; } set assignmentExpression_operator(idl.UnlinkedTokenType value) { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_28 = value; } set binaryExpression_operator(idl.UnlinkedTokenType value) { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_28 = value; } set postfixExpression_operator(idl.UnlinkedTokenType value) { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_28 = value; } set prefixExpression_operator(idl.UnlinkedTokenType value) { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_28 = value; } set propertyAccess_operator(idl.UnlinkedTokenType value) { assert(kind == idl.LinkedNodeKind.propertyAccess); _variantField_28 = value; } @override bool get booleanLiteral_value { assert(kind == idl.LinkedNodeKind.booleanLiteral); return _variantField_27 ??= false; } @override bool get classDeclaration_isDartObject { assert(kind == idl.LinkedNodeKind.classDeclaration); return _variantField_27 ??= false; } @override bool get inheritsCovariant { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_27 ??= false; } @override bool get typeAlias_hasSelfReference { assert(kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias); return _variantField_27 ??= false; } set booleanLiteral_value(bool value) { assert(kind == idl.LinkedNodeKind.booleanLiteral); _variantField_27 = value; } set classDeclaration_isDartObject(bool value) { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_27 = value; } set inheritsCovariant(bool value) { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_27 = value; } set typeAlias_hasSelfReference(bool value) { assert(kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias); _variantField_27 = value; } @override LinkedNodeBuilder get catchClause_stackTraceParameter { assert(kind == idl.LinkedNodeKind.catchClause); return _variantField_9; } @override LinkedNodeBuilder get classTypeAlias_implementsClause { assert(kind == idl.LinkedNodeKind.classTypeAlias); return _variantField_9; } @override LinkedNodeBuilder get constructorDeclaration_redirectedConstructor { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_9; } @override LinkedNodeBuilder get ifElement_elseElement { assert(kind == idl.LinkedNodeKind.ifElement); return _variantField_9; } @override LinkedNodeBuilder get methodDeclaration_typeParameters { assert(kind == idl.LinkedNodeKind.methodDeclaration); return _variantField_9; } set catchClause_stackTraceParameter(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_9 = value; } set classTypeAlias_implementsClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_9 = value; } set constructorDeclaration_redirectedConstructor(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_9 = value; } set ifElement_elseElement(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.ifElement); _variantField_9 = value; } set methodDeclaration_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_9 = value; } @override LinkedNodeBuilder get classOrMixinDeclaration_implementsClause { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); return _variantField_12; } @override LinkedNodeBuilder get invocationExpression_typeArguments { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); return _variantField_12; } set classOrMixinDeclaration_implementsClause(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_12 = value; } set invocationExpression_typeArguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); _variantField_12 = value; } @override List<LinkedNodeBuilder> get classOrMixinDeclaration_members { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); return _variantField_5 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get extensionDeclaration_members { assert(kind == idl.LinkedNodeKind.extensionDeclaration); return _variantField_5 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get forParts_updaters { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations || kind == idl.LinkedNodeKind.forPartsWithExpression); return _variantField_5 ??= <LinkedNodeBuilder>[]; } set classOrMixinDeclaration_members(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_5 = value; } set extensionDeclaration_members(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_5 = value; } set forParts_updaters(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations || kind == idl.LinkedNodeKind.forPartsWithExpression); _variantField_5 = value; } @override LinkedNodeBuilder get classOrMixinDeclaration_typeParameters { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); return _variantField_13; } set classOrMixinDeclaration_typeParameters(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_13 = value; } @override List<String> get comment_tokens { assert(kind == idl.LinkedNodeKind.comment); return _variantField_33 ??= <String>[]; } set comment_tokens(List<String> value) { assert(kind == idl.LinkedNodeKind.comment); _variantField_33 = value; } @override idl.LinkedNodeCommentType get comment_type { assert(kind == idl.LinkedNodeKind.comment); return _variantField_29 ??= idl.LinkedNodeCommentType.block; } set comment_type(idl.LinkedNodeCommentType value) { assert(kind == idl.LinkedNodeKind.comment); _variantField_29 = value; } @override List<LinkedNodeBuilder> get compilationUnit_directives { assert(kind == idl.LinkedNodeKind.compilationUnit); return _variantField_3 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get listLiteral_elements { assert(kind == idl.LinkedNodeKind.listLiteral); return _variantField_3 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get namespaceDirective_configurations { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); return _variantField_3 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get setOrMapLiteral_elements { assert(kind == idl.LinkedNodeKind.setOrMapLiteral); return _variantField_3 ??= <LinkedNodeBuilder>[]; } @override List<LinkedNodeBuilder> get switchMember_labels { assert(kind == idl.LinkedNodeKind.switchCase || kind == idl.LinkedNodeKind.switchDefault); return _variantField_3 ??= <LinkedNodeBuilder>[]; } set compilationUnit_directives(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_3 = value; } set listLiteral_elements(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.listLiteral); _variantField_3 = value; } set namespaceDirective_configurations(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); _variantField_3 = value; } set setOrMapLiteral_elements(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.setOrMapLiteral); _variantField_3 = value; } set switchMember_labels(List<LinkedNodeBuilder> value) { assert(kind == idl.LinkedNodeKind.switchCase || kind == idl.LinkedNodeKind.switchDefault); _variantField_3 = value; } @override LinkedNodeBuilder get constructorDeclaration_returnType { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_10; } set constructorDeclaration_returnType(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_10 = value; } @override idl.LinkedNodeFormalParameterKind get defaultFormalParameter_kind { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); return _variantField_26 ??= idl.LinkedNodeFormalParameterKind.requiredPositional; } set defaultFormalParameter_kind(idl.LinkedNodeFormalParameterKind value) { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_26 = value; } @override double get doubleLiteral_value { assert(kind == idl.LinkedNodeKind.doubleLiteral); return _variantField_21 ??= 0.0; } set doubleLiteral_value(double value) { assert(kind == idl.LinkedNodeKind.doubleLiteral); _variantField_21 = value; } @override LinkedNodeTypeBuilder get expression_type { assert(kind == idl.LinkedNodeKind.assignmentExpression || kind == idl.LinkedNodeKind.asExpression || kind == idl.LinkedNodeKind.awaitExpression || kind == idl.LinkedNodeKind.binaryExpression || kind == idl.LinkedNodeKind.cascadeExpression || kind == idl.LinkedNodeKind.conditionalExpression || kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.indexExpression || kind == idl.LinkedNodeKind.instanceCreationExpression || kind == idl.LinkedNodeKind.integerLiteral || kind == idl.LinkedNodeKind.listLiteral || kind == idl.LinkedNodeKind.methodInvocation || kind == idl.LinkedNodeKind.nullLiteral || kind == idl.LinkedNodeKind.parenthesizedExpression || kind == idl.LinkedNodeKind.prefixExpression || kind == idl.LinkedNodeKind.prefixedIdentifier || kind == idl.LinkedNodeKind.propertyAccess || kind == idl.LinkedNodeKind.postfixExpression || kind == idl.LinkedNodeKind.rethrowExpression || kind == idl.LinkedNodeKind.setOrMapLiteral || kind == idl.LinkedNodeKind.simpleIdentifier || kind == idl.LinkedNodeKind.superExpression || kind == idl.LinkedNodeKind.symbolLiteral || kind == idl.LinkedNodeKind.thisExpression || kind == idl.LinkedNodeKind.throwExpression); return _variantField_25; } @override LinkedNodeTypeBuilder get genericFunctionType_type { assert(kind == idl.LinkedNodeKind.genericFunctionType); return _variantField_25; } set expression_type(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.assignmentExpression || kind == idl.LinkedNodeKind.asExpression || kind == idl.LinkedNodeKind.awaitExpression || kind == idl.LinkedNodeKind.binaryExpression || kind == idl.LinkedNodeKind.cascadeExpression || kind == idl.LinkedNodeKind.conditionalExpression || kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.indexExpression || kind == idl.LinkedNodeKind.instanceCreationExpression || kind == idl.LinkedNodeKind.integerLiteral || kind == idl.LinkedNodeKind.listLiteral || kind == idl.LinkedNodeKind.methodInvocation || kind == idl.LinkedNodeKind.nullLiteral || kind == idl.LinkedNodeKind.parenthesizedExpression || kind == idl.LinkedNodeKind.prefixExpression || kind == idl.LinkedNodeKind.prefixedIdentifier || kind == idl.LinkedNodeKind.propertyAccess || kind == idl.LinkedNodeKind.postfixExpression || kind == idl.LinkedNodeKind.rethrowExpression || kind == idl.LinkedNodeKind.setOrMapLiteral || kind == idl.LinkedNodeKind.simpleIdentifier || kind == idl.LinkedNodeKind.superExpression || kind == idl.LinkedNodeKind.symbolLiteral || kind == idl.LinkedNodeKind.thisExpression || kind == idl.LinkedNodeKind.throwExpression); _variantField_25 = value; } set genericFunctionType_type(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_25 = value; } @override String get extensionDeclaration_refName { assert(kind == idl.LinkedNodeKind.extensionDeclaration); return _variantField_20 ??= ''; } @override String get namespaceDirective_selectedUri { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); return _variantField_20 ??= ''; } @override String get simpleStringLiteral_value { assert(kind == idl.LinkedNodeKind.simpleStringLiteral); return _variantField_20 ??= ''; } set extensionDeclaration_refName(String value) { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_20 = value; } set namespaceDirective_selectedUri(String value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); _variantField_20 = value; } set simpleStringLiteral_value(String value) { assert(kind == idl.LinkedNodeKind.simpleStringLiteral); _variantField_20 = value; } @override List<LinkedNodeTypeBuilder> get extensionOverride_typeArgumentTypes { assert(kind == idl.LinkedNodeKind.extensionOverride); return _variantField_39 ??= <LinkedNodeTypeBuilder>[]; } set extensionOverride_typeArgumentTypes(List<LinkedNodeTypeBuilder> value) { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_39 = value; } @override int get flags => _flags ??= 0; set flags(int value) { assert(value == null || value >= 0); this._flags = value; } @override String get importDirective_prefix { assert(kind == idl.LinkedNodeKind.importDirective); return _variantField_1 ??= ''; } set importDirective_prefix(String value) { assert(kind == idl.LinkedNodeKind.importDirective); _variantField_1 = value; } @override int get informativeId { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective || kind == idl.LinkedNodeKind.showCombinator || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.topLevelVariableDeclaration || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration || kind == idl.LinkedNodeKind.variableDeclarationList); return _variantField_36 ??= 0; } set informativeId(int value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective || kind == idl.LinkedNodeKind.showCombinator || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.topLevelVariableDeclaration || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration || kind == idl.LinkedNodeKind.variableDeclarationList); assert(value == null || value >= 0); _variantField_36 = value; } @override int get integerLiteral_value { assert(kind == idl.LinkedNodeKind.integerLiteral); return _variantField_16 ??= 0; } set integerLiteral_value(int value) { assert(kind == idl.LinkedNodeKind.integerLiteral); assert(value == null || value >= 0); _variantField_16 = value; } @override String get interpolationString_value { assert(kind == idl.LinkedNodeKind.interpolationString); return _variantField_30 ??= ''; } set interpolationString_value(String value) { assert(kind == idl.LinkedNodeKind.interpolationString); _variantField_30 = value; } @override LinkedNodeBuilder get invocationExpression_arguments { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); return _variantField_14; } @override LinkedNodeBuilder get uriBasedDirective_uri { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); return _variantField_14; } set invocationExpression_arguments(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); _variantField_14 = value; } set uriBasedDirective_uri(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); _variantField_14 = value; } @override idl.LinkedNodeKind get kind => _kind ??= idl.LinkedNodeKind.adjacentStrings; set kind(idl.LinkedNodeKind value) { this._kind = value; } @override List<String> get mixinDeclaration_superInvokedNames { assert(kind == idl.LinkedNodeKind.mixinDeclaration); return _variantField_34 ??= <String>[]; } @override List<String> get names { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator || kind == idl.LinkedNodeKind.symbolLiteral); return _variantField_34 ??= <String>[]; } set mixinDeclaration_superInvokedNames(List<String> value) { assert(kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_34 = value; } set names(List<String> value) { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator || kind == idl.LinkedNodeKind.symbolLiteral); _variantField_34 = value; } @override String get name => _name ??= ''; set name(String value) { this._name = value; } @override bool get simplyBoundable_isSimplyBounded { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.mixinDeclaration); return _variantField_31 ??= false; } set simplyBoundable_isSimplyBounded(bool value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_31 = value; } @override idl.UnlinkedTokenType get spreadElement_spreadOperator { assert(kind == idl.LinkedNodeKind.spreadElement); return _variantField_35 ??= idl.UnlinkedTokenType.NOTHING; } set spreadElement_spreadOperator(idl.UnlinkedTokenType value) { assert(kind == idl.LinkedNodeKind.spreadElement); _variantField_35 = value; } @override TopLevelInferenceErrorBuilder get topLevelTypeInferenceError { assert(kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_32; } set topLevelTypeInferenceError(TopLevelInferenceErrorBuilder value) { assert(kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_32 = value; } @override LinkedNodeTypeBuilder get typeName_type { assert(kind == idl.LinkedNodeKind.typeName); return _variantField_23; } @override LinkedNodeTypeBuilder get typeParameter_defaultType { assert(kind == idl.LinkedNodeKind.typeParameter); return _variantField_23; } set typeName_type(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.typeName); _variantField_23 = value; } set typeParameter_defaultType(LinkedNodeTypeBuilder value) { assert(kind == idl.LinkedNodeKind.typeParameter); _variantField_23 = value; } @override LinkedNodeBuilder get unused11 { assert(kind == idl.LinkedNodeKind.classDeclaration); return _variantField_11; } set unused11(LinkedNodeBuilder value) { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_11 = value; } @override String get uriBasedDirective_uriContent { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); return _variantField_22 ??= ''; } set uriBasedDirective_uriContent(String value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); _variantField_22 = value; } @override int get uriBasedDirective_uriElement { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); return _variantField_19 ??= 0; } set uriBasedDirective_uriElement(int value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); assert(value == null || value >= 0); _variantField_19 = value; } LinkedNodeBuilder.adjacentStrings({ List<LinkedNodeBuilder> adjacentStrings_strings, }) : _kind = idl.LinkedNodeKind.adjacentStrings, _variantField_2 = adjacentStrings_strings; LinkedNodeBuilder.annotation({ LinkedNodeBuilder annotation_arguments, LinkedNodeBuilder annotation_constructorName, int annotation_element, LinkedNodeBuilder annotation_name, LinkedNodeTypeSubstitutionBuilder annotation_substitution, }) : _kind = idl.LinkedNodeKind.annotation, _variantField_6 = annotation_arguments, _variantField_7 = annotation_constructorName, _variantField_17 = annotation_element, _variantField_8 = annotation_name, _variantField_38 = annotation_substitution; LinkedNodeBuilder.argumentList({ List<LinkedNodeBuilder> argumentList_arguments, }) : _kind = idl.LinkedNodeKind.argumentList, _variantField_2 = argumentList_arguments; LinkedNodeBuilder.asExpression({ LinkedNodeBuilder asExpression_expression, LinkedNodeBuilder asExpression_type, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.asExpression, _variantField_6 = asExpression_expression, _variantField_7 = asExpression_type, _variantField_25 = expression_type; LinkedNodeBuilder.assertInitializer({ LinkedNodeBuilder assertInitializer_condition, LinkedNodeBuilder assertInitializer_message, }) : _kind = idl.LinkedNodeKind.assertInitializer, _variantField_6 = assertInitializer_condition, _variantField_7 = assertInitializer_message; LinkedNodeBuilder.assertStatement({ LinkedNodeBuilder assertStatement_condition, LinkedNodeBuilder assertStatement_message, }) : _kind = idl.LinkedNodeKind.assertStatement, _variantField_6 = assertStatement_condition, _variantField_7 = assertStatement_message; LinkedNodeBuilder.assignmentExpression({ LinkedNodeBuilder assignmentExpression_leftHandSide, LinkedNodeBuilder assignmentExpression_rightHandSide, LinkedNodeTypeSubstitutionBuilder assignmentExpression_substitution, int assignmentExpression_element, idl.UnlinkedTokenType assignmentExpression_operator, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.assignmentExpression, _variantField_6 = assignmentExpression_leftHandSide, _variantField_7 = assignmentExpression_rightHandSide, _variantField_38 = assignmentExpression_substitution, _variantField_15 = assignmentExpression_element, _variantField_28 = assignmentExpression_operator, _variantField_25 = expression_type; LinkedNodeBuilder.awaitExpression({ LinkedNodeBuilder awaitExpression_expression, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.awaitExpression, _variantField_6 = awaitExpression_expression, _variantField_25 = expression_type; LinkedNodeBuilder.binaryExpression({ LinkedNodeTypeBuilder binaryExpression_invokeType, LinkedNodeBuilder binaryExpression_leftOperand, LinkedNodeBuilder binaryExpression_rightOperand, LinkedNodeTypeSubstitutionBuilder binaryExpression_substitution, int binaryExpression_element, idl.UnlinkedTokenType binaryExpression_operator, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.binaryExpression, _variantField_24 = binaryExpression_invokeType, _variantField_6 = binaryExpression_leftOperand, _variantField_7 = binaryExpression_rightOperand, _variantField_38 = binaryExpression_substitution, _variantField_15 = binaryExpression_element, _variantField_28 = binaryExpression_operator, _variantField_25 = expression_type; LinkedNodeBuilder.block({ List<LinkedNodeBuilder> block_statements, }) : _kind = idl.LinkedNodeKind.block, _variantField_2 = block_statements; LinkedNodeBuilder.blockFunctionBody({ LinkedNodeBuilder blockFunctionBody_block, }) : _kind = idl.LinkedNodeKind.blockFunctionBody, _variantField_6 = blockFunctionBody_block; LinkedNodeBuilder.booleanLiteral({ bool booleanLiteral_value, }) : _kind = idl.LinkedNodeKind.booleanLiteral, _variantField_27 = booleanLiteral_value; LinkedNodeBuilder.breakStatement({ LinkedNodeBuilder breakStatement_label, }) : _kind = idl.LinkedNodeKind.breakStatement, _variantField_6 = breakStatement_label; LinkedNodeBuilder.cascadeExpression({ List<LinkedNodeBuilder> cascadeExpression_sections, LinkedNodeBuilder cascadeExpression_target, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.cascadeExpression, _variantField_2 = cascadeExpression_sections, _variantField_6 = cascadeExpression_target, _variantField_25 = expression_type; LinkedNodeBuilder.catchClause({ LinkedNodeBuilder catchClause_body, LinkedNodeBuilder catchClause_exceptionParameter, LinkedNodeBuilder catchClause_exceptionType, LinkedNodeBuilder catchClause_stackTraceParameter, }) : _kind = idl.LinkedNodeKind.catchClause, _variantField_6 = catchClause_body, _variantField_7 = catchClause_exceptionParameter, _variantField_8 = catchClause_exceptionType, _variantField_9 = catchClause_stackTraceParameter; LinkedNodeBuilder.classDeclaration({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder classDeclaration_extendsClause, LinkedNodeBuilder classDeclaration_withClause, LinkedNodeBuilder classDeclaration_nativeClause, bool classDeclaration_isDartObject, LinkedNodeBuilder classOrMixinDeclaration_implementsClause, List<LinkedNodeBuilder> classOrMixinDeclaration_members, LinkedNodeBuilder classOrMixinDeclaration_typeParameters, int informativeId, bool simplyBoundable_isSimplyBounded, LinkedNodeBuilder unused11, }) : _kind = idl.LinkedNodeKind.classDeclaration, _variantField_4 = annotatedNode_metadata, _variantField_6 = classDeclaration_extendsClause, _variantField_7 = classDeclaration_withClause, _variantField_8 = classDeclaration_nativeClause, _variantField_27 = classDeclaration_isDartObject, _variantField_12 = classOrMixinDeclaration_implementsClause, _variantField_5 = classOrMixinDeclaration_members, _variantField_13 = classOrMixinDeclaration_typeParameters, _variantField_36 = informativeId, _variantField_31 = simplyBoundable_isSimplyBounded, _variantField_11 = unused11; LinkedNodeBuilder.classTypeAlias({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder classTypeAlias_typeParameters, LinkedNodeBuilder classTypeAlias_superclass, LinkedNodeBuilder classTypeAlias_withClause, LinkedNodeBuilder classTypeAlias_implementsClause, int informativeId, bool simplyBoundable_isSimplyBounded, }) : _kind = idl.LinkedNodeKind.classTypeAlias, _variantField_4 = annotatedNode_metadata, _variantField_6 = classTypeAlias_typeParameters, _variantField_7 = classTypeAlias_superclass, _variantField_8 = classTypeAlias_withClause, _variantField_9 = classTypeAlias_implementsClause, _variantField_36 = informativeId, _variantField_31 = simplyBoundable_isSimplyBounded; LinkedNodeBuilder.comment({ List<LinkedNodeBuilder> comment_references, List<String> comment_tokens, idl.LinkedNodeCommentType comment_type, }) : _kind = idl.LinkedNodeKind.comment, _variantField_2 = comment_references, _variantField_33 = comment_tokens, _variantField_29 = comment_type; LinkedNodeBuilder.commentReference({ LinkedNodeBuilder commentReference_identifier, }) : _kind = idl.LinkedNodeKind.commentReference, _variantField_6 = commentReference_identifier; LinkedNodeBuilder.compilationUnit({ List<LinkedNodeBuilder> compilationUnit_declarations, LinkedNodeBuilder compilationUnit_scriptTag, List<LinkedNodeBuilder> compilationUnit_directives, int informativeId, }) : _kind = idl.LinkedNodeKind.compilationUnit, _variantField_2 = compilationUnit_declarations, _variantField_6 = compilationUnit_scriptTag, _variantField_3 = compilationUnit_directives, _variantField_36 = informativeId; LinkedNodeBuilder.conditionalExpression({ LinkedNodeBuilder conditionalExpression_condition, LinkedNodeBuilder conditionalExpression_elseExpression, LinkedNodeBuilder conditionalExpression_thenExpression, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.conditionalExpression, _variantField_6 = conditionalExpression_condition, _variantField_7 = conditionalExpression_elseExpression, _variantField_8 = conditionalExpression_thenExpression, _variantField_25 = expression_type; LinkedNodeBuilder.configuration({ LinkedNodeBuilder configuration_name, LinkedNodeBuilder configuration_value, LinkedNodeBuilder configuration_uri, }) : _kind = idl.LinkedNodeKind.configuration, _variantField_6 = configuration_name, _variantField_7 = configuration_value, _variantField_8 = configuration_uri; LinkedNodeBuilder.constructorDeclaration({ List<LinkedNodeBuilder> constructorDeclaration_initializers, List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder constructorDeclaration_body, LinkedNodeBuilder constructorDeclaration_parameters, LinkedNodeBuilder constructorDeclaration_redirectedConstructor, LinkedNodeBuilder constructorDeclaration_returnType, int informativeId, }) : _kind = idl.LinkedNodeKind.constructorDeclaration, _variantField_2 = constructorDeclaration_initializers, _variantField_4 = annotatedNode_metadata, _variantField_6 = constructorDeclaration_body, _variantField_8 = constructorDeclaration_parameters, _variantField_9 = constructorDeclaration_redirectedConstructor, _variantField_10 = constructorDeclaration_returnType, _variantField_36 = informativeId; LinkedNodeBuilder.constructorFieldInitializer({ LinkedNodeBuilder constructorFieldInitializer_expression, LinkedNodeBuilder constructorFieldInitializer_fieldName, }) : _kind = idl.LinkedNodeKind.constructorFieldInitializer, _variantField_6 = constructorFieldInitializer_expression, _variantField_7 = constructorFieldInitializer_fieldName; LinkedNodeBuilder.constructorName({ LinkedNodeBuilder constructorName_name, LinkedNodeBuilder constructorName_type, LinkedNodeTypeSubstitutionBuilder constructorName_substitution, int constructorName_element, }) : _kind = idl.LinkedNodeKind.constructorName, _variantField_6 = constructorName_name, _variantField_7 = constructorName_type, _variantField_38 = constructorName_substitution, _variantField_15 = constructorName_element; LinkedNodeBuilder.continueStatement({ LinkedNodeBuilder continueStatement_label, }) : _kind = idl.LinkedNodeKind.continueStatement, _variantField_6 = continueStatement_label; LinkedNodeBuilder.declaredIdentifier({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder declaredIdentifier_identifier, LinkedNodeBuilder declaredIdentifier_type, }) : _kind = idl.LinkedNodeKind.declaredIdentifier, _variantField_4 = annotatedNode_metadata, _variantField_6 = declaredIdentifier_identifier, _variantField_7 = declaredIdentifier_type; LinkedNodeBuilder.defaultFormalParameter({ LinkedNodeBuilder defaultFormalParameter_defaultValue, LinkedNodeBuilder defaultFormalParameter_parameter, idl.LinkedNodeFormalParameterKind defaultFormalParameter_kind, int informativeId, }) : _kind = idl.LinkedNodeKind.defaultFormalParameter, _variantField_6 = defaultFormalParameter_defaultValue, _variantField_7 = defaultFormalParameter_parameter, _variantField_26 = defaultFormalParameter_kind, _variantField_36 = informativeId; LinkedNodeBuilder.doStatement({ LinkedNodeBuilder doStatement_body, LinkedNodeBuilder doStatement_condition, }) : _kind = idl.LinkedNodeKind.doStatement, _variantField_6 = doStatement_body, _variantField_7 = doStatement_condition; LinkedNodeBuilder.dottedName({ List<LinkedNodeBuilder> dottedName_components, }) : _kind = idl.LinkedNodeKind.dottedName, _variantField_2 = dottedName_components; LinkedNodeBuilder.doubleLiteral({ double doubleLiteral_value, }) : _kind = idl.LinkedNodeKind.doubleLiteral, _variantField_21 = doubleLiteral_value; LinkedNodeBuilder.emptyFunctionBody({ int emptyFunctionBody_fake, }) : _kind = idl.LinkedNodeKind.emptyFunctionBody, _variantField_15 = emptyFunctionBody_fake; LinkedNodeBuilder.emptyStatement({ int emptyStatement_fake, }) : _kind = idl.LinkedNodeKind.emptyStatement, _variantField_15 = emptyStatement_fake; LinkedNodeBuilder.enumConstantDeclaration({ List<LinkedNodeBuilder> annotatedNode_metadata, int informativeId, }) : _kind = idl.LinkedNodeKind.enumConstantDeclaration, _variantField_4 = annotatedNode_metadata, _variantField_36 = informativeId; LinkedNodeBuilder.enumDeclaration({ List<LinkedNodeBuilder> enumDeclaration_constants, List<LinkedNodeBuilder> annotatedNode_metadata, int informativeId, }) : _kind = idl.LinkedNodeKind.enumDeclaration, _variantField_2 = enumDeclaration_constants, _variantField_4 = annotatedNode_metadata, _variantField_36 = informativeId; LinkedNodeBuilder.exportDirective({ List<LinkedNodeBuilder> namespaceDirective_combinators, List<LinkedNodeBuilder> annotatedNode_metadata, List<LinkedNodeBuilder> namespaceDirective_configurations, String namespaceDirective_selectedUri, int informativeId, LinkedNodeBuilder uriBasedDirective_uri, String uriBasedDirective_uriContent, int uriBasedDirective_uriElement, }) : _kind = idl.LinkedNodeKind.exportDirective, _variantField_2 = namespaceDirective_combinators, _variantField_4 = annotatedNode_metadata, _variantField_3 = namespaceDirective_configurations, _variantField_20 = namespaceDirective_selectedUri, _variantField_36 = informativeId, _variantField_14 = uriBasedDirective_uri, _variantField_22 = uriBasedDirective_uriContent, _variantField_19 = uriBasedDirective_uriElement; LinkedNodeBuilder.expressionFunctionBody({ LinkedNodeBuilder expressionFunctionBody_expression, }) : _kind = idl.LinkedNodeKind.expressionFunctionBody, _variantField_6 = expressionFunctionBody_expression; LinkedNodeBuilder.expressionStatement({ LinkedNodeBuilder expressionStatement_expression, }) : _kind = idl.LinkedNodeKind.expressionStatement, _variantField_6 = expressionStatement_expression; LinkedNodeBuilder.extendsClause({ LinkedNodeBuilder extendsClause_superclass, }) : _kind = idl.LinkedNodeKind.extendsClause, _variantField_6 = extendsClause_superclass; LinkedNodeBuilder.extensionDeclaration({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder extensionDeclaration_typeParameters, LinkedNodeBuilder extensionDeclaration_extendedType, List<LinkedNodeBuilder> extensionDeclaration_members, String extensionDeclaration_refName, int informativeId, }) : _kind = idl.LinkedNodeKind.extensionDeclaration, _variantField_4 = annotatedNode_metadata, _variantField_6 = extensionDeclaration_typeParameters, _variantField_7 = extensionDeclaration_extendedType, _variantField_5 = extensionDeclaration_members, _variantField_20 = extensionDeclaration_refName, _variantField_36 = informativeId; LinkedNodeBuilder.extensionOverride({ LinkedNodeTypeBuilder extensionOverride_extendedType, List<LinkedNodeBuilder> extensionOverride_arguments, LinkedNodeBuilder extensionOverride_extensionName, LinkedNodeBuilder extensionOverride_typeArguments, List<LinkedNodeTypeBuilder> extensionOverride_typeArgumentTypes, }) : _kind = idl.LinkedNodeKind.extensionOverride, _variantField_24 = extensionOverride_extendedType, _variantField_2 = extensionOverride_arguments, _variantField_7 = extensionOverride_extensionName, _variantField_8 = extensionOverride_typeArguments, _variantField_39 = extensionOverride_typeArgumentTypes; LinkedNodeBuilder.fieldDeclaration({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder fieldDeclaration_fields, int informativeId, }) : _kind = idl.LinkedNodeKind.fieldDeclaration, _variantField_4 = annotatedNode_metadata, _variantField_6 = fieldDeclaration_fields, _variantField_36 = informativeId; LinkedNodeBuilder.fieldFormalParameter({ LinkedNodeTypeBuilder actualType, List<LinkedNodeBuilder> normalFormalParameter_metadata, LinkedNodeBuilder fieldFormalParameter_type, LinkedNodeBuilder fieldFormalParameter_typeParameters, LinkedNodeBuilder fieldFormalParameter_formalParameters, bool inheritsCovariant, int informativeId, }) : _kind = idl.LinkedNodeKind.fieldFormalParameter, _variantField_24 = actualType, _variantField_4 = normalFormalParameter_metadata, _variantField_6 = fieldFormalParameter_type, _variantField_7 = fieldFormalParameter_typeParameters, _variantField_8 = fieldFormalParameter_formalParameters, _variantField_27 = inheritsCovariant, _variantField_36 = informativeId; LinkedNodeBuilder.forEachPartsWithDeclaration({ LinkedNodeBuilder forEachParts_iterable, LinkedNodeBuilder forEachPartsWithDeclaration_loopVariable, }) : _kind = idl.LinkedNodeKind.forEachPartsWithDeclaration, _variantField_6 = forEachParts_iterable, _variantField_7 = forEachPartsWithDeclaration_loopVariable; LinkedNodeBuilder.forEachPartsWithIdentifier({ LinkedNodeBuilder forEachParts_iterable, LinkedNodeBuilder forEachPartsWithIdentifier_identifier, }) : _kind = idl.LinkedNodeKind.forEachPartsWithIdentifier, _variantField_6 = forEachParts_iterable, _variantField_7 = forEachPartsWithIdentifier_identifier; LinkedNodeBuilder.forElement({ LinkedNodeBuilder forMixin_forLoopParts, LinkedNodeBuilder forElement_body, }) : _kind = idl.LinkedNodeKind.forElement, _variantField_6 = forMixin_forLoopParts, _variantField_7 = forElement_body; LinkedNodeBuilder.forPartsWithDeclarations({ LinkedNodeBuilder forParts_condition, LinkedNodeBuilder forPartsWithDeclarations_variables, List<LinkedNodeBuilder> forParts_updaters, }) : _kind = idl.LinkedNodeKind.forPartsWithDeclarations, _variantField_6 = forParts_condition, _variantField_7 = forPartsWithDeclarations_variables, _variantField_5 = forParts_updaters; LinkedNodeBuilder.forPartsWithExpression({ LinkedNodeBuilder forParts_condition, LinkedNodeBuilder forPartsWithExpression_initialization, List<LinkedNodeBuilder> forParts_updaters, }) : _kind = idl.LinkedNodeKind.forPartsWithExpression, _variantField_6 = forParts_condition, _variantField_7 = forPartsWithExpression_initialization, _variantField_5 = forParts_updaters; LinkedNodeBuilder.forStatement({ LinkedNodeBuilder forMixin_forLoopParts, LinkedNodeBuilder forStatement_body, }) : _kind = idl.LinkedNodeKind.forStatement, _variantField_6 = forMixin_forLoopParts, _variantField_7 = forStatement_body; LinkedNodeBuilder.formalParameterList({ List<LinkedNodeBuilder> formalParameterList_parameters, }) : _kind = idl.LinkedNodeKind.formalParameterList, _variantField_2 = formalParameterList_parameters; LinkedNodeBuilder.functionDeclaration({ LinkedNodeTypeBuilder actualReturnType, List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder functionDeclaration_functionExpression, LinkedNodeBuilder functionDeclaration_returnType, int informativeId, }) : _kind = idl.LinkedNodeKind.functionDeclaration, _variantField_24 = actualReturnType, _variantField_4 = annotatedNode_metadata, _variantField_6 = functionDeclaration_functionExpression, _variantField_7 = functionDeclaration_returnType, _variantField_36 = informativeId; LinkedNodeBuilder.functionDeclarationStatement({ LinkedNodeBuilder functionDeclarationStatement_functionDeclaration, }) : _kind = idl.LinkedNodeKind.functionDeclarationStatement, _variantField_6 = functionDeclarationStatement_functionDeclaration; LinkedNodeBuilder.functionExpression({ LinkedNodeTypeBuilder actualReturnType, LinkedNodeBuilder functionExpression_body, LinkedNodeBuilder functionExpression_formalParameters, LinkedNodeBuilder functionExpression_typeParameters, }) : _kind = idl.LinkedNodeKind.functionExpression, _variantField_24 = actualReturnType, _variantField_6 = functionExpression_body, _variantField_7 = functionExpression_formalParameters, _variantField_8 = functionExpression_typeParameters; LinkedNodeBuilder.functionExpressionInvocation({ LinkedNodeTypeBuilder invocationExpression_invokeType, LinkedNodeBuilder functionExpressionInvocation_function, LinkedNodeBuilder invocationExpression_typeArguments, LinkedNodeTypeBuilder expression_type, LinkedNodeBuilder invocationExpression_arguments, }) : _kind = idl.LinkedNodeKind.functionExpressionInvocation, _variantField_24 = invocationExpression_invokeType, _variantField_6 = functionExpressionInvocation_function, _variantField_12 = invocationExpression_typeArguments, _variantField_25 = expression_type, _variantField_14 = invocationExpression_arguments; LinkedNodeBuilder.functionTypeAlias({ LinkedNodeTypeBuilder actualReturnType, List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder functionTypeAlias_formalParameters, LinkedNodeBuilder functionTypeAlias_returnType, LinkedNodeBuilder functionTypeAlias_typeParameters, bool typeAlias_hasSelfReference, int informativeId, bool simplyBoundable_isSimplyBounded, }) : _kind = idl.LinkedNodeKind.functionTypeAlias, _variantField_24 = actualReturnType, _variantField_4 = annotatedNode_metadata, _variantField_6 = functionTypeAlias_formalParameters, _variantField_7 = functionTypeAlias_returnType, _variantField_8 = functionTypeAlias_typeParameters, _variantField_27 = typeAlias_hasSelfReference, _variantField_36 = informativeId, _variantField_31 = simplyBoundable_isSimplyBounded; LinkedNodeBuilder.functionTypedFormalParameter({ LinkedNodeTypeBuilder actualType, List<LinkedNodeBuilder> normalFormalParameter_metadata, LinkedNodeBuilder functionTypedFormalParameter_formalParameters, LinkedNodeBuilder functionTypedFormalParameter_returnType, LinkedNodeBuilder functionTypedFormalParameter_typeParameters, bool inheritsCovariant, int informativeId, }) : _kind = idl.LinkedNodeKind.functionTypedFormalParameter, _variantField_24 = actualType, _variantField_4 = normalFormalParameter_metadata, _variantField_6 = functionTypedFormalParameter_formalParameters, _variantField_7 = functionTypedFormalParameter_returnType, _variantField_8 = functionTypedFormalParameter_typeParameters, _variantField_27 = inheritsCovariant, _variantField_36 = informativeId; LinkedNodeBuilder.genericFunctionType({ LinkedNodeTypeBuilder actualReturnType, LinkedNodeBuilder genericFunctionType_typeParameters, LinkedNodeBuilder genericFunctionType_returnType, int genericFunctionType_id, LinkedNodeBuilder genericFunctionType_formalParameters, LinkedNodeTypeBuilder genericFunctionType_type, }) : _kind = idl.LinkedNodeKind.genericFunctionType, _variantField_24 = actualReturnType, _variantField_6 = genericFunctionType_typeParameters, _variantField_7 = genericFunctionType_returnType, _variantField_17 = genericFunctionType_id, _variantField_8 = genericFunctionType_formalParameters, _variantField_25 = genericFunctionType_type; LinkedNodeBuilder.genericTypeAlias({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder genericTypeAlias_typeParameters, LinkedNodeBuilder genericTypeAlias_functionType, bool typeAlias_hasSelfReference, int informativeId, bool simplyBoundable_isSimplyBounded, }) : _kind = idl.LinkedNodeKind.genericTypeAlias, _variantField_4 = annotatedNode_metadata, _variantField_6 = genericTypeAlias_typeParameters, _variantField_7 = genericTypeAlias_functionType, _variantField_27 = typeAlias_hasSelfReference, _variantField_36 = informativeId, _variantField_31 = simplyBoundable_isSimplyBounded; LinkedNodeBuilder.hideCombinator({ int informativeId, List<String> names, }) : _kind = idl.LinkedNodeKind.hideCombinator, _variantField_36 = informativeId, _variantField_34 = names; LinkedNodeBuilder.ifElement({ LinkedNodeBuilder ifMixin_condition, LinkedNodeBuilder ifElement_thenElement, LinkedNodeBuilder ifElement_elseElement, }) : _kind = idl.LinkedNodeKind.ifElement, _variantField_6 = ifMixin_condition, _variantField_8 = ifElement_thenElement, _variantField_9 = ifElement_elseElement; LinkedNodeBuilder.ifStatement({ LinkedNodeBuilder ifMixin_condition, LinkedNodeBuilder ifStatement_elseStatement, LinkedNodeBuilder ifStatement_thenStatement, }) : _kind = idl.LinkedNodeKind.ifStatement, _variantField_6 = ifMixin_condition, _variantField_7 = ifStatement_elseStatement, _variantField_8 = ifStatement_thenStatement; LinkedNodeBuilder.implementsClause({ List<LinkedNodeBuilder> implementsClause_interfaces, }) : _kind = idl.LinkedNodeKind.implementsClause, _variantField_2 = implementsClause_interfaces; LinkedNodeBuilder.importDirective({ List<LinkedNodeBuilder> namespaceDirective_combinators, List<LinkedNodeBuilder> annotatedNode_metadata, List<LinkedNodeBuilder> namespaceDirective_configurations, String namespaceDirective_selectedUri, String importDirective_prefix, int informativeId, LinkedNodeBuilder uriBasedDirective_uri, String uriBasedDirective_uriContent, int uriBasedDirective_uriElement, }) : _kind = idl.LinkedNodeKind.importDirective, _variantField_2 = namespaceDirective_combinators, _variantField_4 = annotatedNode_metadata, _variantField_3 = namespaceDirective_configurations, _variantField_20 = namespaceDirective_selectedUri, _variantField_1 = importDirective_prefix, _variantField_36 = informativeId, _variantField_14 = uriBasedDirective_uri, _variantField_22 = uriBasedDirective_uriContent, _variantField_19 = uriBasedDirective_uriElement; LinkedNodeBuilder.indexExpression({ LinkedNodeBuilder indexExpression_index, LinkedNodeBuilder indexExpression_target, LinkedNodeTypeSubstitutionBuilder indexExpression_substitution, int indexExpression_element, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.indexExpression, _variantField_6 = indexExpression_index, _variantField_7 = indexExpression_target, _variantField_38 = indexExpression_substitution, _variantField_15 = indexExpression_element, _variantField_25 = expression_type; LinkedNodeBuilder.instanceCreationExpression({ List<LinkedNodeBuilder> instanceCreationExpression_arguments, LinkedNodeBuilder instanceCreationExpression_constructorName, LinkedNodeBuilder instanceCreationExpression_typeArguments, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.instanceCreationExpression, _variantField_2 = instanceCreationExpression_arguments, _variantField_7 = instanceCreationExpression_constructorName, _variantField_8 = instanceCreationExpression_typeArguments, _variantField_25 = expression_type; LinkedNodeBuilder.integerLiteral({ LinkedNodeTypeBuilder expression_type, int integerLiteral_value, }) : _kind = idl.LinkedNodeKind.integerLiteral, _variantField_25 = expression_type, _variantField_16 = integerLiteral_value; LinkedNodeBuilder.interpolationExpression({ LinkedNodeBuilder interpolationExpression_expression, }) : _kind = idl.LinkedNodeKind.interpolationExpression, _variantField_6 = interpolationExpression_expression; LinkedNodeBuilder.interpolationString({ String interpolationString_value, }) : _kind = idl.LinkedNodeKind.interpolationString, _variantField_30 = interpolationString_value; LinkedNodeBuilder.isExpression({ LinkedNodeBuilder isExpression_expression, LinkedNodeBuilder isExpression_type, }) : _kind = idl.LinkedNodeKind.isExpression, _variantField_6 = isExpression_expression, _variantField_7 = isExpression_type; LinkedNodeBuilder.label({ LinkedNodeBuilder label_label, }) : _kind = idl.LinkedNodeKind.label, _variantField_6 = label_label; LinkedNodeBuilder.labeledStatement({ List<LinkedNodeBuilder> labeledStatement_labels, LinkedNodeBuilder labeledStatement_statement, }) : _kind = idl.LinkedNodeKind.labeledStatement, _variantField_2 = labeledStatement_labels, _variantField_6 = labeledStatement_statement; LinkedNodeBuilder.libraryDirective({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder libraryDirective_name, int informativeId, }) : _kind = idl.LinkedNodeKind.libraryDirective, _variantField_4 = annotatedNode_metadata, _variantField_6 = libraryDirective_name, _variantField_36 = informativeId; LinkedNodeBuilder.libraryIdentifier({ List<LinkedNodeBuilder> libraryIdentifier_components, }) : _kind = idl.LinkedNodeKind.libraryIdentifier, _variantField_2 = libraryIdentifier_components; LinkedNodeBuilder.listLiteral({ List<LinkedNodeBuilder> typedLiteral_typeArguments, List<LinkedNodeBuilder> listLiteral_elements, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.listLiteral, _variantField_2 = typedLiteral_typeArguments, _variantField_3 = listLiteral_elements, _variantField_25 = expression_type; LinkedNodeBuilder.mapLiteralEntry({ LinkedNodeBuilder mapLiteralEntry_key, LinkedNodeBuilder mapLiteralEntry_value, }) : _kind = idl.LinkedNodeKind.mapLiteralEntry, _variantField_6 = mapLiteralEntry_key, _variantField_7 = mapLiteralEntry_value; LinkedNodeBuilder.methodDeclaration({ LinkedNodeTypeBuilder actualReturnType, List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder methodDeclaration_body, LinkedNodeBuilder methodDeclaration_formalParameters, LinkedNodeBuilder methodDeclaration_returnType, LinkedNodeBuilder methodDeclaration_typeParameters, int informativeId, }) : _kind = idl.LinkedNodeKind.methodDeclaration, _variantField_24 = actualReturnType, _variantField_4 = annotatedNode_metadata, _variantField_6 = methodDeclaration_body, _variantField_7 = methodDeclaration_formalParameters, _variantField_8 = methodDeclaration_returnType, _variantField_9 = methodDeclaration_typeParameters, _variantField_36 = informativeId; LinkedNodeBuilder.methodInvocation({ LinkedNodeTypeBuilder invocationExpression_invokeType, LinkedNodeBuilder methodInvocation_methodName, LinkedNodeBuilder methodInvocation_target, LinkedNodeBuilder invocationExpression_typeArguments, LinkedNodeTypeBuilder expression_type, LinkedNodeBuilder invocationExpression_arguments, }) : _kind = idl.LinkedNodeKind.methodInvocation, _variantField_24 = invocationExpression_invokeType, _variantField_6 = methodInvocation_methodName, _variantField_7 = methodInvocation_target, _variantField_12 = invocationExpression_typeArguments, _variantField_25 = expression_type, _variantField_14 = invocationExpression_arguments; LinkedNodeBuilder.mixinDeclaration({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder mixinDeclaration_onClause, LinkedNodeBuilder classOrMixinDeclaration_implementsClause, List<LinkedNodeBuilder> classOrMixinDeclaration_members, LinkedNodeBuilder classOrMixinDeclaration_typeParameters, int informativeId, List<String> mixinDeclaration_superInvokedNames, bool simplyBoundable_isSimplyBounded, }) : _kind = idl.LinkedNodeKind.mixinDeclaration, _variantField_4 = annotatedNode_metadata, _variantField_6 = mixinDeclaration_onClause, _variantField_12 = classOrMixinDeclaration_implementsClause, _variantField_5 = classOrMixinDeclaration_members, _variantField_13 = classOrMixinDeclaration_typeParameters, _variantField_36 = informativeId, _variantField_34 = mixinDeclaration_superInvokedNames, _variantField_31 = simplyBoundable_isSimplyBounded; LinkedNodeBuilder.namedExpression({ LinkedNodeBuilder namedExpression_expression, LinkedNodeBuilder namedExpression_name, }) : _kind = idl.LinkedNodeKind.namedExpression, _variantField_6 = namedExpression_expression, _variantField_7 = namedExpression_name; LinkedNodeBuilder.nativeClause({ LinkedNodeBuilder nativeClause_name, }) : _kind = idl.LinkedNodeKind.nativeClause, _variantField_6 = nativeClause_name; LinkedNodeBuilder.nativeFunctionBody({ LinkedNodeBuilder nativeFunctionBody_stringLiteral, }) : _kind = idl.LinkedNodeKind.nativeFunctionBody, _variantField_6 = nativeFunctionBody_stringLiteral; LinkedNodeBuilder.nullLiteral({ int nullLiteral_fake, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.nullLiteral, _variantField_15 = nullLiteral_fake, _variantField_25 = expression_type; LinkedNodeBuilder.onClause({ List<LinkedNodeBuilder> onClause_superclassConstraints, }) : _kind = idl.LinkedNodeKind.onClause, _variantField_2 = onClause_superclassConstraints; LinkedNodeBuilder.parenthesizedExpression({ LinkedNodeBuilder parenthesizedExpression_expression, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.parenthesizedExpression, _variantField_6 = parenthesizedExpression_expression, _variantField_25 = expression_type; LinkedNodeBuilder.partDirective({ List<LinkedNodeBuilder> annotatedNode_metadata, int informativeId, LinkedNodeBuilder uriBasedDirective_uri, String uriBasedDirective_uriContent, int uriBasedDirective_uriElement, }) : _kind = idl.LinkedNodeKind.partDirective, _variantField_4 = annotatedNode_metadata, _variantField_36 = informativeId, _variantField_14 = uriBasedDirective_uri, _variantField_22 = uriBasedDirective_uriContent, _variantField_19 = uriBasedDirective_uriElement; LinkedNodeBuilder.partOfDirective({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder partOfDirective_libraryName, LinkedNodeBuilder partOfDirective_uri, int informativeId, }) : _kind = idl.LinkedNodeKind.partOfDirective, _variantField_4 = annotatedNode_metadata, _variantField_6 = partOfDirective_libraryName, _variantField_7 = partOfDirective_uri, _variantField_36 = informativeId; LinkedNodeBuilder.postfixExpression({ LinkedNodeBuilder postfixExpression_operand, LinkedNodeTypeSubstitutionBuilder postfixExpression_substitution, int postfixExpression_element, idl.UnlinkedTokenType postfixExpression_operator, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.postfixExpression, _variantField_6 = postfixExpression_operand, _variantField_38 = postfixExpression_substitution, _variantField_15 = postfixExpression_element, _variantField_28 = postfixExpression_operator, _variantField_25 = expression_type; LinkedNodeBuilder.prefixExpression({ LinkedNodeBuilder prefixExpression_operand, LinkedNodeTypeSubstitutionBuilder prefixExpression_substitution, int prefixExpression_element, idl.UnlinkedTokenType prefixExpression_operator, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.prefixExpression, _variantField_6 = prefixExpression_operand, _variantField_38 = prefixExpression_substitution, _variantField_15 = prefixExpression_element, _variantField_28 = prefixExpression_operator, _variantField_25 = expression_type; LinkedNodeBuilder.prefixedIdentifier({ LinkedNodeBuilder prefixedIdentifier_identifier, LinkedNodeBuilder prefixedIdentifier_prefix, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.prefixedIdentifier, _variantField_6 = prefixedIdentifier_identifier, _variantField_7 = prefixedIdentifier_prefix, _variantField_25 = expression_type; LinkedNodeBuilder.propertyAccess({ LinkedNodeBuilder propertyAccess_propertyName, LinkedNodeBuilder propertyAccess_target, idl.UnlinkedTokenType propertyAccess_operator, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.propertyAccess, _variantField_6 = propertyAccess_propertyName, _variantField_7 = propertyAccess_target, _variantField_28 = propertyAccess_operator, _variantField_25 = expression_type; LinkedNodeBuilder.redirectingConstructorInvocation({ LinkedNodeBuilder redirectingConstructorInvocation_arguments, LinkedNodeBuilder redirectingConstructorInvocation_constructorName, LinkedNodeTypeSubstitutionBuilder redirectingConstructorInvocation_substitution, int redirectingConstructorInvocation_element, }) : _kind = idl.LinkedNodeKind.redirectingConstructorInvocation, _variantField_6 = redirectingConstructorInvocation_arguments, _variantField_7 = redirectingConstructorInvocation_constructorName, _variantField_38 = redirectingConstructorInvocation_substitution, _variantField_15 = redirectingConstructorInvocation_element; LinkedNodeBuilder.rethrowExpression({ LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.rethrowExpression, _variantField_25 = expression_type; LinkedNodeBuilder.returnStatement({ LinkedNodeBuilder returnStatement_expression, }) : _kind = idl.LinkedNodeKind.returnStatement, _variantField_6 = returnStatement_expression; LinkedNodeBuilder.setOrMapLiteral({ List<LinkedNodeBuilder> typedLiteral_typeArguments, List<LinkedNodeBuilder> setOrMapLiteral_elements, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.setOrMapLiteral, _variantField_2 = typedLiteral_typeArguments, _variantField_3 = setOrMapLiteral_elements, _variantField_25 = expression_type; LinkedNodeBuilder.showCombinator({ int informativeId, List<String> names, }) : _kind = idl.LinkedNodeKind.showCombinator, _variantField_36 = informativeId, _variantField_34 = names; LinkedNodeBuilder.simpleFormalParameter({ LinkedNodeTypeBuilder actualType, List<LinkedNodeBuilder> normalFormalParameter_metadata, LinkedNodeBuilder simpleFormalParameter_type, bool inheritsCovariant, int informativeId, TopLevelInferenceErrorBuilder topLevelTypeInferenceError, }) : _kind = idl.LinkedNodeKind.simpleFormalParameter, _variantField_24 = actualType, _variantField_4 = normalFormalParameter_metadata, _variantField_6 = simpleFormalParameter_type, _variantField_27 = inheritsCovariant, _variantField_36 = informativeId, _variantField_32 = topLevelTypeInferenceError; LinkedNodeBuilder.simpleIdentifier({ LinkedNodeTypeSubstitutionBuilder simpleIdentifier_substitution, int simpleIdentifier_element, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.simpleIdentifier, _variantField_38 = simpleIdentifier_substitution, _variantField_15 = simpleIdentifier_element, _variantField_25 = expression_type; LinkedNodeBuilder.simpleStringLiteral({ String simpleStringLiteral_value, }) : _kind = idl.LinkedNodeKind.simpleStringLiteral, _variantField_20 = simpleStringLiteral_value; LinkedNodeBuilder.spreadElement({ LinkedNodeBuilder spreadElement_expression, idl.UnlinkedTokenType spreadElement_spreadOperator, }) : _kind = idl.LinkedNodeKind.spreadElement, _variantField_6 = spreadElement_expression, _variantField_35 = spreadElement_spreadOperator; LinkedNodeBuilder.stringInterpolation({ List<LinkedNodeBuilder> stringInterpolation_elements, }) : _kind = idl.LinkedNodeKind.stringInterpolation, _variantField_2 = stringInterpolation_elements; LinkedNodeBuilder.superConstructorInvocation({ LinkedNodeBuilder superConstructorInvocation_arguments, LinkedNodeBuilder superConstructorInvocation_constructorName, LinkedNodeTypeSubstitutionBuilder superConstructorInvocation_substitution, int superConstructorInvocation_element, }) : _kind = idl.LinkedNodeKind.superConstructorInvocation, _variantField_6 = superConstructorInvocation_arguments, _variantField_7 = superConstructorInvocation_constructorName, _variantField_38 = superConstructorInvocation_substitution, _variantField_15 = superConstructorInvocation_element; LinkedNodeBuilder.superExpression({ LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.superExpression, _variantField_25 = expression_type; LinkedNodeBuilder.switchCase({ List<LinkedNodeBuilder> switchMember_statements, LinkedNodeBuilder switchCase_expression, List<LinkedNodeBuilder> switchMember_labels, }) : _kind = idl.LinkedNodeKind.switchCase, _variantField_4 = switchMember_statements, _variantField_6 = switchCase_expression, _variantField_3 = switchMember_labels; LinkedNodeBuilder.switchDefault({ List<LinkedNodeBuilder> switchMember_statements, List<LinkedNodeBuilder> switchMember_labels, }) : _kind = idl.LinkedNodeKind.switchDefault, _variantField_4 = switchMember_statements, _variantField_3 = switchMember_labels; LinkedNodeBuilder.switchStatement({ List<LinkedNodeBuilder> switchStatement_members, LinkedNodeBuilder switchStatement_expression, }) : _kind = idl.LinkedNodeKind.switchStatement, _variantField_2 = switchStatement_members, _variantField_7 = switchStatement_expression; LinkedNodeBuilder.symbolLiteral({ LinkedNodeTypeBuilder expression_type, List<String> names, }) : _kind = idl.LinkedNodeKind.symbolLiteral, _variantField_25 = expression_type, _variantField_34 = names; LinkedNodeBuilder.thisExpression({ LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.thisExpression, _variantField_25 = expression_type; LinkedNodeBuilder.throwExpression({ LinkedNodeBuilder throwExpression_expression, LinkedNodeTypeBuilder expression_type, }) : _kind = idl.LinkedNodeKind.throwExpression, _variantField_6 = throwExpression_expression, _variantField_25 = expression_type; LinkedNodeBuilder.topLevelVariableDeclaration({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder topLevelVariableDeclaration_variableList, int informativeId, }) : _kind = idl.LinkedNodeKind.topLevelVariableDeclaration, _variantField_4 = annotatedNode_metadata, _variantField_6 = topLevelVariableDeclaration_variableList, _variantField_36 = informativeId; LinkedNodeBuilder.tryStatement({ List<LinkedNodeBuilder> tryStatement_catchClauses, LinkedNodeBuilder tryStatement_body, LinkedNodeBuilder tryStatement_finallyBlock, }) : _kind = idl.LinkedNodeKind.tryStatement, _variantField_2 = tryStatement_catchClauses, _variantField_6 = tryStatement_body, _variantField_7 = tryStatement_finallyBlock; LinkedNodeBuilder.typeArgumentList({ List<LinkedNodeBuilder> typeArgumentList_arguments, }) : _kind = idl.LinkedNodeKind.typeArgumentList, _variantField_2 = typeArgumentList_arguments; LinkedNodeBuilder.typeName({ List<LinkedNodeBuilder> typeName_typeArguments, LinkedNodeBuilder typeName_name, LinkedNodeTypeBuilder typeName_type, }) : _kind = idl.LinkedNodeKind.typeName, _variantField_2 = typeName_typeArguments, _variantField_6 = typeName_name, _variantField_23 = typeName_type; LinkedNodeBuilder.typeParameter({ List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder typeParameter_bound, int informativeId, LinkedNodeTypeBuilder typeParameter_defaultType, }) : _kind = idl.LinkedNodeKind.typeParameter, _variantField_4 = annotatedNode_metadata, _variantField_6 = typeParameter_bound, _variantField_36 = informativeId, _variantField_23 = typeParameter_defaultType; LinkedNodeBuilder.typeParameterList({ List<LinkedNodeBuilder> typeParameterList_typeParameters, }) : _kind = idl.LinkedNodeKind.typeParameterList, _variantField_2 = typeParameterList_typeParameters; LinkedNodeBuilder.variableDeclaration({ LinkedNodeTypeBuilder actualType, List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder variableDeclaration_initializer, bool inheritsCovariant, int informativeId, TopLevelInferenceErrorBuilder topLevelTypeInferenceError, }) : _kind = idl.LinkedNodeKind.variableDeclaration, _variantField_24 = actualType, _variantField_4 = annotatedNode_metadata, _variantField_6 = variableDeclaration_initializer, _variantField_27 = inheritsCovariant, _variantField_36 = informativeId, _variantField_32 = topLevelTypeInferenceError; LinkedNodeBuilder.variableDeclarationList({ List<LinkedNodeBuilder> variableDeclarationList_variables, List<LinkedNodeBuilder> annotatedNode_metadata, LinkedNodeBuilder variableDeclarationList_type, int informativeId, }) : _kind = idl.LinkedNodeKind.variableDeclarationList, _variantField_2 = variableDeclarationList_variables, _variantField_4 = annotatedNode_metadata, _variantField_6 = variableDeclarationList_type, _variantField_36 = informativeId; LinkedNodeBuilder.variableDeclarationStatement({ LinkedNodeBuilder variableDeclarationStatement_variables, }) : _kind = idl.LinkedNodeKind.variableDeclarationStatement, _variantField_6 = variableDeclarationStatement_variables; LinkedNodeBuilder.whileStatement({ LinkedNodeBuilder whileStatement_body, LinkedNodeBuilder whileStatement_condition, }) : _kind = idl.LinkedNodeKind.whileStatement, _variantField_6 = whileStatement_body, _variantField_7 = whileStatement_condition; LinkedNodeBuilder.withClause({ List<LinkedNodeBuilder> withClause_mixinTypes, }) : _kind = idl.LinkedNodeKind.withClause, _variantField_2 = withClause_mixinTypes; LinkedNodeBuilder.yieldStatement({ LinkedNodeBuilder yieldStatement_expression, }) : _kind = idl.LinkedNodeKind.yieldStatement, _variantField_6 = yieldStatement_expression; /// Flush [informative] data recursively. void flushInformative() { if (kind == idl.LinkedNodeKind.adjacentStrings) { adjacentStrings_strings?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.annotation) { annotation_arguments?.flushInformative(); annotation_constructorName?.flushInformative(); annotation_name?.flushInformative(); annotation_substitution?.flushInformative(); } else if (kind == idl.LinkedNodeKind.argumentList) { argumentList_arguments?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.asExpression) { asExpression_expression?.flushInformative(); asExpression_type?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.assertInitializer) { assertInitializer_condition?.flushInformative(); assertInitializer_message?.flushInformative(); } else if (kind == idl.LinkedNodeKind.assertStatement) { assertStatement_condition?.flushInformative(); assertStatement_message?.flushInformative(); } else if (kind == idl.LinkedNodeKind.assignmentExpression) { assignmentExpression_leftHandSide?.flushInformative(); assignmentExpression_rightHandSide?.flushInformative(); assignmentExpression_substitution?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.awaitExpression) { awaitExpression_expression?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.binaryExpression) { binaryExpression_invokeType?.flushInformative(); binaryExpression_leftOperand?.flushInformative(); binaryExpression_rightOperand?.flushInformative(); binaryExpression_substitution?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.block) { block_statements?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.blockFunctionBody) { blockFunctionBody_block?.flushInformative(); } else if (kind == idl.LinkedNodeKind.booleanLiteral) { } else if (kind == idl.LinkedNodeKind.breakStatement) { breakStatement_label?.flushInformative(); } else if (kind == idl.LinkedNodeKind.cascadeExpression) { cascadeExpression_sections?.forEach((b) => b.flushInformative()); cascadeExpression_target?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.catchClause) { catchClause_body?.flushInformative(); catchClause_exceptionParameter?.flushInformative(); catchClause_exceptionType?.flushInformative(); catchClause_stackTraceParameter?.flushInformative(); } else if (kind == idl.LinkedNodeKind.classDeclaration) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); classDeclaration_extendsClause?.flushInformative(); classDeclaration_withClause?.flushInformative(); classDeclaration_nativeClause?.flushInformative(); classOrMixinDeclaration_implementsClause?.flushInformative(); classOrMixinDeclaration_members?.forEach((b) => b.flushInformative()); classOrMixinDeclaration_typeParameters?.flushInformative(); informativeId = null; unused11?.flushInformative(); } else if (kind == idl.LinkedNodeKind.classTypeAlias) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); classTypeAlias_typeParameters?.flushInformative(); classTypeAlias_superclass?.flushInformative(); classTypeAlias_withClause?.flushInformative(); classTypeAlias_implementsClause?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.comment) { comment_references?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.commentReference) { commentReference_identifier?.flushInformative(); } else if (kind == idl.LinkedNodeKind.compilationUnit) { compilationUnit_declarations?.forEach((b) => b.flushInformative()); compilationUnit_scriptTag?.flushInformative(); compilationUnit_directives?.forEach((b) => b.flushInformative()); informativeId = null; } else if (kind == idl.LinkedNodeKind.conditionalExpression) { conditionalExpression_condition?.flushInformative(); conditionalExpression_elseExpression?.flushInformative(); conditionalExpression_thenExpression?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.configuration) { configuration_name?.flushInformative(); configuration_value?.flushInformative(); configuration_uri?.flushInformative(); } else if (kind == idl.LinkedNodeKind.constructorDeclaration) { constructorDeclaration_initializers?.forEach((b) => b.flushInformative()); annotatedNode_metadata?.forEach((b) => b.flushInformative()); constructorDeclaration_body?.flushInformative(); constructorDeclaration_parameters?.flushInformative(); constructorDeclaration_redirectedConstructor?.flushInformative(); constructorDeclaration_returnType?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.constructorFieldInitializer) { constructorFieldInitializer_expression?.flushInformative(); constructorFieldInitializer_fieldName?.flushInformative(); } else if (kind == idl.LinkedNodeKind.constructorName) { constructorName_name?.flushInformative(); constructorName_type?.flushInformative(); constructorName_substitution?.flushInformative(); } else if (kind == idl.LinkedNodeKind.continueStatement) { continueStatement_label?.flushInformative(); } else if (kind == idl.LinkedNodeKind.declaredIdentifier) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); declaredIdentifier_identifier?.flushInformative(); declaredIdentifier_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.defaultFormalParameter) { defaultFormalParameter_defaultValue?.flushInformative(); defaultFormalParameter_parameter?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.doStatement) { doStatement_body?.flushInformative(); doStatement_condition?.flushInformative(); } else if (kind == idl.LinkedNodeKind.dottedName) { dottedName_components?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.doubleLiteral) { } else if (kind == idl.LinkedNodeKind.emptyFunctionBody) { } else if (kind == idl.LinkedNodeKind.emptyStatement) { } else if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); informativeId = null; } else if (kind == idl.LinkedNodeKind.enumDeclaration) { enumDeclaration_constants?.forEach((b) => b.flushInformative()); annotatedNode_metadata?.forEach((b) => b.flushInformative()); informativeId = null; } else if (kind == idl.LinkedNodeKind.exportDirective) { namespaceDirective_combinators?.forEach((b) => b.flushInformative()); annotatedNode_metadata?.forEach((b) => b.flushInformative()); namespaceDirective_configurations?.forEach((b) => b.flushInformative()); informativeId = null; uriBasedDirective_uri?.flushInformative(); } else if (kind == idl.LinkedNodeKind.expressionFunctionBody) { expressionFunctionBody_expression?.flushInformative(); } else if (kind == idl.LinkedNodeKind.expressionStatement) { expressionStatement_expression?.flushInformative(); } else if (kind == idl.LinkedNodeKind.extendsClause) { extendsClause_superclass?.flushInformative(); } else if (kind == idl.LinkedNodeKind.extensionDeclaration) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); extensionDeclaration_typeParameters?.flushInformative(); extensionDeclaration_extendedType?.flushInformative(); extensionDeclaration_members?.forEach((b) => b.flushInformative()); informativeId = null; } else if (kind == idl.LinkedNodeKind.extensionOverride) { extensionOverride_extendedType?.flushInformative(); extensionOverride_arguments?.forEach((b) => b.flushInformative()); extensionOverride_extensionName?.flushInformative(); extensionOverride_typeArguments?.flushInformative(); extensionOverride_typeArgumentTypes?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.fieldDeclaration) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); fieldDeclaration_fields?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.fieldFormalParameter) { actualType?.flushInformative(); normalFormalParameter_metadata?.forEach((b) => b.flushInformative()); fieldFormalParameter_type?.flushInformative(); fieldFormalParameter_typeParameters?.flushInformative(); fieldFormalParameter_formalParameters?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.forEachPartsWithDeclaration) { forEachParts_iterable?.flushInformative(); forEachPartsWithDeclaration_loopVariable?.flushInformative(); } else if (kind == idl.LinkedNodeKind.forEachPartsWithIdentifier) { forEachParts_iterable?.flushInformative(); forEachPartsWithIdentifier_identifier?.flushInformative(); } else if (kind == idl.LinkedNodeKind.forElement) { forMixin_forLoopParts?.flushInformative(); forElement_body?.flushInformative(); } else if (kind == idl.LinkedNodeKind.forPartsWithDeclarations) { forParts_condition?.flushInformative(); forPartsWithDeclarations_variables?.flushInformative(); forParts_updaters?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.forPartsWithExpression) { forParts_condition?.flushInformative(); forPartsWithExpression_initialization?.flushInformative(); forParts_updaters?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.forStatement) { forMixin_forLoopParts?.flushInformative(); forStatement_body?.flushInformative(); } else if (kind == idl.LinkedNodeKind.formalParameterList) { formalParameterList_parameters?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.functionDeclaration) { actualReturnType?.flushInformative(); annotatedNode_metadata?.forEach((b) => b.flushInformative()); functionDeclaration_functionExpression?.flushInformative(); functionDeclaration_returnType?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.functionDeclarationStatement) { functionDeclarationStatement_functionDeclaration?.flushInformative(); } else if (kind == idl.LinkedNodeKind.functionExpression) { actualReturnType?.flushInformative(); functionExpression_body?.flushInformative(); functionExpression_formalParameters?.flushInformative(); functionExpression_typeParameters?.flushInformative(); } else if (kind == idl.LinkedNodeKind.functionExpressionInvocation) { invocationExpression_invokeType?.flushInformative(); functionExpressionInvocation_function?.flushInformative(); invocationExpression_typeArguments?.flushInformative(); expression_type?.flushInformative(); invocationExpression_arguments?.flushInformative(); } else if (kind == idl.LinkedNodeKind.functionTypeAlias) { actualReturnType?.flushInformative(); annotatedNode_metadata?.forEach((b) => b.flushInformative()); functionTypeAlias_formalParameters?.flushInformative(); functionTypeAlias_returnType?.flushInformative(); functionTypeAlias_typeParameters?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { actualType?.flushInformative(); normalFormalParameter_metadata?.forEach((b) => b.flushInformative()); functionTypedFormalParameter_formalParameters?.flushInformative(); functionTypedFormalParameter_returnType?.flushInformative(); functionTypedFormalParameter_typeParameters?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.genericFunctionType) { actualReturnType?.flushInformative(); genericFunctionType_typeParameters?.flushInformative(); genericFunctionType_returnType?.flushInformative(); genericFunctionType_formalParameters?.flushInformative(); genericFunctionType_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.genericTypeAlias) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); genericTypeAlias_typeParameters?.flushInformative(); genericTypeAlias_functionType?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.hideCombinator) { informativeId = null; } else if (kind == idl.LinkedNodeKind.ifElement) { ifMixin_condition?.flushInformative(); ifElement_thenElement?.flushInformative(); ifElement_elseElement?.flushInformative(); } else if (kind == idl.LinkedNodeKind.ifStatement) { ifMixin_condition?.flushInformative(); ifStatement_elseStatement?.flushInformative(); ifStatement_thenStatement?.flushInformative(); } else if (kind == idl.LinkedNodeKind.implementsClause) { implementsClause_interfaces?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.importDirective) { namespaceDirective_combinators?.forEach((b) => b.flushInformative()); annotatedNode_metadata?.forEach((b) => b.flushInformative()); namespaceDirective_configurations?.forEach((b) => b.flushInformative()); informativeId = null; uriBasedDirective_uri?.flushInformative(); } else if (kind == idl.LinkedNodeKind.indexExpression) { indexExpression_index?.flushInformative(); indexExpression_target?.flushInformative(); indexExpression_substitution?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.instanceCreationExpression) { instanceCreationExpression_arguments ?.forEach((b) => b.flushInformative()); instanceCreationExpression_constructorName?.flushInformative(); instanceCreationExpression_typeArguments?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.integerLiteral) { expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.interpolationExpression) { interpolationExpression_expression?.flushInformative(); } else if (kind == idl.LinkedNodeKind.interpolationString) { } else if (kind == idl.LinkedNodeKind.isExpression) { isExpression_expression?.flushInformative(); isExpression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.label) { label_label?.flushInformative(); } else if (kind == idl.LinkedNodeKind.labeledStatement) { labeledStatement_labels?.forEach((b) => b.flushInformative()); labeledStatement_statement?.flushInformative(); } else if (kind == idl.LinkedNodeKind.libraryDirective) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); libraryDirective_name?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.libraryIdentifier) { libraryIdentifier_components?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.listLiteral) { typedLiteral_typeArguments?.forEach((b) => b.flushInformative()); listLiteral_elements?.forEach((b) => b.flushInformative()); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.mapLiteralEntry) { mapLiteralEntry_key?.flushInformative(); mapLiteralEntry_value?.flushInformative(); } else if (kind == idl.LinkedNodeKind.methodDeclaration) { actualReturnType?.flushInformative(); annotatedNode_metadata?.forEach((b) => b.flushInformative()); methodDeclaration_body?.flushInformative(); methodDeclaration_formalParameters?.flushInformative(); methodDeclaration_returnType?.flushInformative(); methodDeclaration_typeParameters?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.methodInvocation) { invocationExpression_invokeType?.flushInformative(); methodInvocation_methodName?.flushInformative(); methodInvocation_target?.flushInformative(); invocationExpression_typeArguments?.flushInformative(); expression_type?.flushInformative(); invocationExpression_arguments?.flushInformative(); } else if (kind == idl.LinkedNodeKind.mixinDeclaration) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); mixinDeclaration_onClause?.flushInformative(); classOrMixinDeclaration_implementsClause?.flushInformative(); classOrMixinDeclaration_members?.forEach((b) => b.flushInformative()); classOrMixinDeclaration_typeParameters?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.namedExpression) { namedExpression_expression?.flushInformative(); namedExpression_name?.flushInformative(); } else if (kind == idl.LinkedNodeKind.nativeClause) { nativeClause_name?.flushInformative(); } else if (kind == idl.LinkedNodeKind.nativeFunctionBody) { nativeFunctionBody_stringLiteral?.flushInformative(); } else if (kind == idl.LinkedNodeKind.nullLiteral) { expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.onClause) { onClause_superclassConstraints?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.parenthesizedExpression) { parenthesizedExpression_expression?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.partDirective) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); informativeId = null; uriBasedDirective_uri?.flushInformative(); } else if (kind == idl.LinkedNodeKind.partOfDirective) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); partOfDirective_libraryName?.flushInformative(); partOfDirective_uri?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.postfixExpression) { postfixExpression_operand?.flushInformative(); postfixExpression_substitution?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.prefixExpression) { prefixExpression_operand?.flushInformative(); prefixExpression_substitution?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.prefixedIdentifier) { prefixedIdentifier_identifier?.flushInformative(); prefixedIdentifier_prefix?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.propertyAccess) { propertyAccess_propertyName?.flushInformative(); propertyAccess_target?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.redirectingConstructorInvocation) { redirectingConstructorInvocation_arguments?.flushInformative(); redirectingConstructorInvocation_constructorName?.flushInformative(); redirectingConstructorInvocation_substitution?.flushInformative(); } else if (kind == idl.LinkedNodeKind.rethrowExpression) { expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.returnStatement) { returnStatement_expression?.flushInformative(); } else if (kind == idl.LinkedNodeKind.setOrMapLiteral) { typedLiteral_typeArguments?.forEach((b) => b.flushInformative()); setOrMapLiteral_elements?.forEach((b) => b.flushInformative()); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.showCombinator) { informativeId = null; } else if (kind == idl.LinkedNodeKind.simpleFormalParameter) { actualType?.flushInformative(); normalFormalParameter_metadata?.forEach((b) => b.flushInformative()); simpleFormalParameter_type?.flushInformative(); informativeId = null; topLevelTypeInferenceError?.flushInformative(); } else if (kind == idl.LinkedNodeKind.simpleIdentifier) { simpleIdentifier_substitution?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.simpleStringLiteral) { } else if (kind == idl.LinkedNodeKind.spreadElement) { spreadElement_expression?.flushInformative(); } else if (kind == idl.LinkedNodeKind.stringInterpolation) { stringInterpolation_elements?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.superConstructorInvocation) { superConstructorInvocation_arguments?.flushInformative(); superConstructorInvocation_constructorName?.flushInformative(); superConstructorInvocation_substitution?.flushInformative(); } else if (kind == idl.LinkedNodeKind.superExpression) { expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.switchCase) { switchMember_statements?.forEach((b) => b.flushInformative()); switchCase_expression?.flushInformative(); switchMember_labels?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.switchDefault) { switchMember_statements?.forEach((b) => b.flushInformative()); switchMember_labels?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.switchStatement) { switchStatement_members?.forEach((b) => b.flushInformative()); switchStatement_expression?.flushInformative(); } else if (kind == idl.LinkedNodeKind.symbolLiteral) { expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.thisExpression) { expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.throwExpression) { throwExpression_expression?.flushInformative(); expression_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); topLevelVariableDeclaration_variableList?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.tryStatement) { tryStatement_catchClauses?.forEach((b) => b.flushInformative()); tryStatement_body?.flushInformative(); tryStatement_finallyBlock?.flushInformative(); } else if (kind == idl.LinkedNodeKind.typeArgumentList) { typeArgumentList_arguments?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.typeName) { typeName_typeArguments?.forEach((b) => b.flushInformative()); typeName_name?.flushInformative(); typeName_type?.flushInformative(); } else if (kind == idl.LinkedNodeKind.typeParameter) { annotatedNode_metadata?.forEach((b) => b.flushInformative()); typeParameter_bound?.flushInformative(); informativeId = null; typeParameter_defaultType?.flushInformative(); } else if (kind == idl.LinkedNodeKind.typeParameterList) { typeParameterList_typeParameters?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.variableDeclaration) { actualType?.flushInformative(); annotatedNode_metadata?.forEach((b) => b.flushInformative()); variableDeclaration_initializer?.flushInformative(); informativeId = null; topLevelTypeInferenceError?.flushInformative(); } else if (kind == idl.LinkedNodeKind.variableDeclarationList) { variableDeclarationList_variables?.forEach((b) => b.flushInformative()); annotatedNode_metadata?.forEach((b) => b.flushInformative()); variableDeclarationList_type?.flushInformative(); informativeId = null; } else if (kind == idl.LinkedNodeKind.variableDeclarationStatement) { variableDeclarationStatement_variables?.flushInformative(); } else if (kind == idl.LinkedNodeKind.whileStatement) { whileStatement_body?.flushInformative(); whileStatement_condition?.flushInformative(); } else if (kind == idl.LinkedNodeKind.withClause) { withClause_mixinTypes?.forEach((b) => b.flushInformative()); } else if (kind == idl.LinkedNodeKind.yieldStatement) { yieldStatement_expression?.flushInformative(); } } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (kind == idl.LinkedNodeKind.adjacentStrings) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.adjacentStrings_strings == null) { signature.addInt(0); } else { signature.addInt(this.adjacentStrings_strings.length); for (var x in this.adjacentStrings_strings) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.annotation) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.annotation_arguments != null); this.annotation_arguments?.collectApiSignature(signature); signature.addBool(this.annotation_constructorName != null); this.annotation_constructorName?.collectApiSignature(signature); signature.addBool(this.annotation_name != null); this.annotation_name?.collectApiSignature(signature); signature.addInt(this.annotation_element ?? 0); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); signature.addBool(this.annotation_substitution != null); this.annotation_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.argumentList) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.argumentList_arguments == null) { signature.addInt(0); } else { signature.addInt(this.argumentList_arguments.length); for (var x in this.argumentList_arguments) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.asExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.asExpression_expression != null); this.asExpression_expression?.collectApiSignature(signature); signature.addBool(this.asExpression_type != null); this.asExpression_type?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.assertInitializer) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.assertInitializer_condition != null); this.assertInitializer_condition?.collectApiSignature(signature); signature.addBool(this.assertInitializer_message != null); this.assertInitializer_message?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.assertStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.assertStatement_condition != null); this.assertStatement_condition?.collectApiSignature(signature); signature.addBool(this.assertStatement_message != null); this.assertStatement_message?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.assignmentExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.assignmentExpression_leftHandSide != null); this.assignmentExpression_leftHandSide?.collectApiSignature(signature); signature.addBool(this.assignmentExpression_rightHandSide != null); this.assignmentExpression_rightHandSide?.collectApiSignature(signature); signature.addInt(this.assignmentExpression_element ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addInt(this.assignmentExpression_operator == null ? 0 : this.assignmentExpression_operator.index); signature.addString(this.name ?? ''); signature.addBool(this.assignmentExpression_substitution != null); this.assignmentExpression_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.awaitExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.awaitExpression_expression != null); this.awaitExpression_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.binaryExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.binaryExpression_leftOperand != null); this.binaryExpression_leftOperand?.collectApiSignature(signature); signature.addBool(this.binaryExpression_rightOperand != null); this.binaryExpression_rightOperand?.collectApiSignature(signature); signature.addInt(this.binaryExpression_element ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.binaryExpression_invokeType != null); this.binaryExpression_invokeType?.collectApiSignature(signature); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addInt(this.binaryExpression_operator == null ? 0 : this.binaryExpression_operator.index); signature.addString(this.name ?? ''); signature.addBool(this.binaryExpression_substitution != null); this.binaryExpression_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.block) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.block_statements == null) { signature.addInt(0); } else { signature.addInt(this.block_statements.length); for (var x in this.block_statements) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.blockFunctionBody) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.blockFunctionBody_block != null); this.blockFunctionBody_block?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.booleanLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addBool(this.booleanLiteral_value == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.breakStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.breakStatement_label != null); this.breakStatement_label?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.cascadeExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.cascadeExpression_sections == null) { signature.addInt(0); } else { signature.addInt(this.cascadeExpression_sections.length); for (var x in this.cascadeExpression_sections) { x?.collectApiSignature(signature); } } signature.addBool(this.cascadeExpression_target != null); this.cascadeExpression_target?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.catchClause) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.catchClause_body != null); this.catchClause_body?.collectApiSignature(signature); signature.addBool(this.catchClause_exceptionParameter != null); this.catchClause_exceptionParameter?.collectApiSignature(signature); signature.addBool(this.catchClause_exceptionType != null); this.catchClause_exceptionType?.collectApiSignature(signature); signature.addBool(this.catchClause_stackTraceParameter != null); this.catchClause_stackTraceParameter?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.classDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } if (this.classOrMixinDeclaration_members == null) { signature.addInt(0); } else { signature.addInt(this.classOrMixinDeclaration_members.length); for (var x in this.classOrMixinDeclaration_members) { x?.collectApiSignature(signature); } } signature.addBool(this.classDeclaration_extendsClause != null); this.classDeclaration_extendsClause?.collectApiSignature(signature); signature.addBool(this.classDeclaration_withClause != null); this.classDeclaration_withClause?.collectApiSignature(signature); signature.addBool(this.classDeclaration_nativeClause != null); this.classDeclaration_nativeClause?.collectApiSignature(signature); signature.addBool(this.unused11 != null); this.unused11?.collectApiSignature(signature); signature.addBool(this.classOrMixinDeclaration_implementsClause != null); this .classOrMixinDeclaration_implementsClause ?.collectApiSignature(signature); signature.addBool(this.classOrMixinDeclaration_typeParameters != null); this .classOrMixinDeclaration_typeParameters ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.classDeclaration_isDartObject == true); signature.addBool(this.simplyBoundable_isSimplyBounded == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.classTypeAlias) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.classTypeAlias_typeParameters != null); this.classTypeAlias_typeParameters?.collectApiSignature(signature); signature.addBool(this.classTypeAlias_superclass != null); this.classTypeAlias_superclass?.collectApiSignature(signature); signature.addBool(this.classTypeAlias_withClause != null); this.classTypeAlias_withClause?.collectApiSignature(signature); signature.addBool(this.classTypeAlias_implementsClause != null); this.classTypeAlias_implementsClause?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.simplyBoundable_isSimplyBounded == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.comment) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.comment_references == null) { signature.addInt(0); } else { signature.addInt(this.comment_references.length); for (var x in this.comment_references) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addInt(this.comment_type == null ? 0 : this.comment_type.index); if (this.comment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.comment_tokens.length); for (var x in this.comment_tokens) { signature.addString(x); } } signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.commentReference) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.commentReference_identifier != null); this.commentReference_identifier?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.compilationUnit) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.compilationUnit_declarations == null) { signature.addInt(0); } else { signature.addInt(this.compilationUnit_declarations.length); for (var x in this.compilationUnit_declarations) { x?.collectApiSignature(signature); } } if (this.compilationUnit_directives == null) { signature.addInt(0); } else { signature.addInt(this.compilationUnit_directives.length); for (var x in this.compilationUnit_directives) { x?.collectApiSignature(signature); } } signature.addBool(this.compilationUnit_scriptTag != null); this.compilationUnit_scriptTag?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.conditionalExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.conditionalExpression_condition != null); this.conditionalExpression_condition?.collectApiSignature(signature); signature.addBool(this.conditionalExpression_elseExpression != null); this.conditionalExpression_elseExpression?.collectApiSignature(signature); signature.addBool(this.conditionalExpression_thenExpression != null); this.conditionalExpression_thenExpression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.configuration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.configuration_name != null); this.configuration_name?.collectApiSignature(signature); signature.addBool(this.configuration_value != null); this.configuration_value?.collectApiSignature(signature); signature.addBool(this.configuration_uri != null); this.configuration_uri?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.constructorDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.constructorDeclaration_initializers == null) { signature.addInt(0); } else { signature.addInt(this.constructorDeclaration_initializers.length); for (var x in this.constructorDeclaration_initializers) { x?.collectApiSignature(signature); } } if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.constructorDeclaration_body != null); this.constructorDeclaration_body?.collectApiSignature(signature); signature.addBool(this.constructorDeclaration_parameters != null); this.constructorDeclaration_parameters?.collectApiSignature(signature); signature .addBool(this.constructorDeclaration_redirectedConstructor != null); this .constructorDeclaration_redirectedConstructor ?.collectApiSignature(signature); signature.addBool(this.constructorDeclaration_returnType != null); this.constructorDeclaration_returnType?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.constructorFieldInitializer) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.constructorFieldInitializer_expression != null); this .constructorFieldInitializer_expression ?.collectApiSignature(signature); signature.addBool(this.constructorFieldInitializer_fieldName != null); this .constructorFieldInitializer_fieldName ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.constructorName) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.constructorName_name != null); this.constructorName_name?.collectApiSignature(signature); signature.addBool(this.constructorName_type != null); this.constructorName_type?.collectApiSignature(signature); signature.addInt(this.constructorName_element ?? 0); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); signature.addBool(this.constructorName_substitution != null); this.constructorName_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.continueStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.continueStatement_label != null); this.continueStatement_label?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.declaredIdentifier) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.declaredIdentifier_identifier != null); this.declaredIdentifier_identifier?.collectApiSignature(signature); signature.addBool(this.declaredIdentifier_type != null); this.declaredIdentifier_type?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.defaultFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.defaultFormalParameter_defaultValue != null); this.defaultFormalParameter_defaultValue?.collectApiSignature(signature); signature.addBool(this.defaultFormalParameter_parameter != null); this.defaultFormalParameter_parameter?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addInt(this.defaultFormalParameter_kind == null ? 0 : this.defaultFormalParameter_kind.index); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.doStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.doStatement_body != null); this.doStatement_body?.collectApiSignature(signature); signature.addBool(this.doStatement_condition != null); this.doStatement_condition?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.dottedName) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.dottedName_components == null) { signature.addInt(0); } else { signature.addInt(this.dottedName_components.length); for (var x in this.dottedName_components) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.doubleLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addDouble(this.doubleLiteral_value ?? 0.0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.emptyFunctionBody) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.emptyFunctionBody_fake ?? 0); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.emptyStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.emptyStatement_fake ?? 0); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.enumDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.enumDeclaration_constants == null) { signature.addInt(0); } else { signature.addInt(this.enumDeclaration_constants.length); for (var x in this.enumDeclaration_constants) { x?.collectApiSignature(signature); } } if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.exportDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.namespaceDirective_combinators == null) { signature.addInt(0); } else { signature.addInt(this.namespaceDirective_combinators.length); for (var x in this.namespaceDirective_combinators) { x?.collectApiSignature(signature); } } if (this.namespaceDirective_configurations == null) { signature.addInt(0); } else { signature.addInt(this.namespaceDirective_configurations.length); for (var x in this.namespaceDirective_configurations) { x?.collectApiSignature(signature); } } if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.uriBasedDirective_uri != null); this.uriBasedDirective_uri?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addInt(this.uriBasedDirective_uriElement ?? 0); signature.addString(this.namespaceDirective_selectedUri ?? ''); signature.addString(this.uriBasedDirective_uriContent ?? ''); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.expressionFunctionBody) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.expressionFunctionBody_expression != null); this.expressionFunctionBody_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.expressionStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.expressionStatement_expression != null); this.expressionStatement_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.extendsClause) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.extendsClause_superclass != null); this.extendsClause_superclass?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.extensionDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } if (this.extensionDeclaration_members == null) { signature.addInt(0); } else { signature.addInt(this.extensionDeclaration_members.length); for (var x in this.extensionDeclaration_members) { x?.collectApiSignature(signature); } } signature.addBool(this.extensionDeclaration_typeParameters != null); this.extensionDeclaration_typeParameters?.collectApiSignature(signature); signature.addBool(this.extensionDeclaration_extendedType != null); this.extensionDeclaration_extendedType?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.extensionDeclaration_refName ?? ''); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.extensionOverride) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.extensionOverride_arguments == null) { signature.addInt(0); } else { signature.addInt(this.extensionOverride_arguments.length); for (var x in this.extensionOverride_arguments) { x?.collectApiSignature(signature); } } signature.addBool(this.extensionOverride_extensionName != null); this.extensionOverride_extensionName?.collectApiSignature(signature); signature.addBool(this.extensionOverride_typeArguments != null); this.extensionOverride_typeArguments?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.extensionOverride_extendedType != null); this.extensionOverride_extendedType?.collectApiSignature(signature); signature.addString(this.name ?? ''); if (this.extensionOverride_typeArgumentTypes == null) { signature.addInt(0); } else { signature.addInt(this.extensionOverride_typeArgumentTypes.length); for (var x in this.extensionOverride_typeArgumentTypes) { x?.collectApiSignature(signature); } } } else if (kind == idl.LinkedNodeKind.fieldDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.fieldDeclaration_fields != null); this.fieldDeclaration_fields?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.fieldFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.normalFormalParameter_metadata == null) { signature.addInt(0); } else { signature.addInt(this.normalFormalParameter_metadata.length); for (var x in this.normalFormalParameter_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.fieldFormalParameter_type != null); this.fieldFormalParameter_type?.collectApiSignature(signature); signature.addBool(this.fieldFormalParameter_typeParameters != null); this.fieldFormalParameter_typeParameters?.collectApiSignature(signature); signature.addBool(this.fieldFormalParameter_formalParameters != null); this .fieldFormalParameter_formalParameters ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualType != null); this.actualType?.collectApiSignature(signature); signature.addBool(this.inheritsCovariant == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.forEachPartsWithDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.forEachParts_iterable != null); this.forEachParts_iterable?.collectApiSignature(signature); signature.addBool(this.forEachPartsWithDeclaration_loopVariable != null); this .forEachPartsWithDeclaration_loopVariable ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.forEachPartsWithIdentifier) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.forEachParts_iterable != null); this.forEachParts_iterable?.collectApiSignature(signature); signature.addBool(this.forEachPartsWithIdentifier_identifier != null); this .forEachPartsWithIdentifier_identifier ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.forElement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.forMixin_forLoopParts != null); this.forMixin_forLoopParts?.collectApiSignature(signature); signature.addBool(this.forElement_body != null); this.forElement_body?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.forPartsWithDeclarations) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.forParts_updaters == null) { signature.addInt(0); } else { signature.addInt(this.forParts_updaters.length); for (var x in this.forParts_updaters) { x?.collectApiSignature(signature); } } signature.addBool(this.forParts_condition != null); this.forParts_condition?.collectApiSignature(signature); signature.addBool(this.forPartsWithDeclarations_variables != null); this.forPartsWithDeclarations_variables?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.forPartsWithExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.forParts_updaters == null) { signature.addInt(0); } else { signature.addInt(this.forParts_updaters.length); for (var x in this.forParts_updaters) { x?.collectApiSignature(signature); } } signature.addBool(this.forParts_condition != null); this.forParts_condition?.collectApiSignature(signature); signature.addBool(this.forPartsWithExpression_initialization != null); this .forPartsWithExpression_initialization ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.forStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.forMixin_forLoopParts != null); this.forMixin_forLoopParts?.collectApiSignature(signature); signature.addBool(this.forStatement_body != null); this.forStatement_body?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.formalParameterList) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.formalParameterList_parameters == null) { signature.addInt(0); } else { signature.addInt(this.formalParameterList_parameters.length); for (var x in this.formalParameterList_parameters) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.functionDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.functionDeclaration_functionExpression != null); this .functionDeclaration_functionExpression ?.collectApiSignature(signature); signature.addBool(this.functionDeclaration_returnType != null); this.functionDeclaration_returnType?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualReturnType != null); this.actualReturnType?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.functionDeclarationStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool( this.functionDeclarationStatement_functionDeclaration != null); this .functionDeclarationStatement_functionDeclaration ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.functionExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.functionExpression_body != null); this.functionExpression_body?.collectApiSignature(signature); signature.addBool(this.functionExpression_formalParameters != null); this.functionExpression_formalParameters?.collectApiSignature(signature); signature.addBool(this.functionExpression_typeParameters != null); this.functionExpression_typeParameters?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualReturnType != null); this.actualReturnType?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.functionExpressionInvocation) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.functionExpressionInvocation_function != null); this .functionExpressionInvocation_function ?.collectApiSignature(signature); signature.addBool(this.invocationExpression_typeArguments != null); this.invocationExpression_typeArguments?.collectApiSignature(signature); signature.addBool(this.invocationExpression_arguments != null); this.invocationExpression_arguments?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.invocationExpression_invokeType != null); this.invocationExpression_invokeType?.collectApiSignature(signature); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.functionTypeAlias) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.functionTypeAlias_formalParameters != null); this.functionTypeAlias_formalParameters?.collectApiSignature(signature); signature.addBool(this.functionTypeAlias_returnType != null); this.functionTypeAlias_returnType?.collectApiSignature(signature); signature.addBool(this.functionTypeAlias_typeParameters != null); this.functionTypeAlias_typeParameters?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualReturnType != null); this.actualReturnType?.collectApiSignature(signature); signature.addBool(this.typeAlias_hasSelfReference == true); signature.addBool(this.simplyBoundable_isSimplyBounded == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.normalFormalParameter_metadata == null) { signature.addInt(0); } else { signature.addInt(this.normalFormalParameter_metadata.length); for (var x in this.normalFormalParameter_metadata) { x?.collectApiSignature(signature); } } signature .addBool(this.functionTypedFormalParameter_formalParameters != null); this .functionTypedFormalParameter_formalParameters ?.collectApiSignature(signature); signature.addBool(this.functionTypedFormalParameter_returnType != null); this .functionTypedFormalParameter_returnType ?.collectApiSignature(signature); signature .addBool(this.functionTypedFormalParameter_typeParameters != null); this .functionTypedFormalParameter_typeParameters ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualType != null); this.actualType?.collectApiSignature(signature); signature.addBool(this.inheritsCovariant == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.genericFunctionType) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.genericFunctionType_typeParameters != null); this.genericFunctionType_typeParameters?.collectApiSignature(signature); signature.addBool(this.genericFunctionType_returnType != null); this.genericFunctionType_returnType?.collectApiSignature(signature); signature.addBool(this.genericFunctionType_formalParameters != null); this.genericFunctionType_formalParameters?.collectApiSignature(signature); signature.addInt(this.genericFunctionType_id ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.actualReturnType != null); this.actualReturnType?.collectApiSignature(signature); signature.addBool(this.genericFunctionType_type != null); this.genericFunctionType_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.genericTypeAlias) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.genericTypeAlias_typeParameters != null); this.genericTypeAlias_typeParameters?.collectApiSignature(signature); signature.addBool(this.genericTypeAlias_functionType != null); this.genericTypeAlias_functionType?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.typeAlias_hasSelfReference == true); signature.addBool(this.simplyBoundable_isSimplyBounded == true); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.hideCombinator) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); if (this.names == null) { signature.addInt(0); } else { signature.addInt(this.names.length); for (var x in this.names) { signature.addString(x); } } signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.ifElement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.ifMixin_condition != null); this.ifMixin_condition?.collectApiSignature(signature); signature.addBool(this.ifElement_thenElement != null); this.ifElement_thenElement?.collectApiSignature(signature); signature.addBool(this.ifElement_elseElement != null); this.ifElement_elseElement?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.ifStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.ifMixin_condition != null); this.ifMixin_condition?.collectApiSignature(signature); signature.addBool(this.ifStatement_elseStatement != null); this.ifStatement_elseStatement?.collectApiSignature(signature); signature.addBool(this.ifStatement_thenStatement != null); this.ifStatement_thenStatement?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.implementsClause) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.implementsClause_interfaces == null) { signature.addInt(0); } else { signature.addInt(this.implementsClause_interfaces.length); for (var x in this.implementsClause_interfaces) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.importDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addString(this.importDirective_prefix ?? ''); if (this.namespaceDirective_combinators == null) { signature.addInt(0); } else { signature.addInt(this.namespaceDirective_combinators.length); for (var x in this.namespaceDirective_combinators) { x?.collectApiSignature(signature); } } if (this.namespaceDirective_configurations == null) { signature.addInt(0); } else { signature.addInt(this.namespaceDirective_configurations.length); for (var x in this.namespaceDirective_configurations) { x?.collectApiSignature(signature); } } if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.uriBasedDirective_uri != null); this.uriBasedDirective_uri?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addInt(this.uriBasedDirective_uriElement ?? 0); signature.addString(this.namespaceDirective_selectedUri ?? ''); signature.addString(this.uriBasedDirective_uriContent ?? ''); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.indexExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.indexExpression_index != null); this.indexExpression_index?.collectApiSignature(signature); signature.addBool(this.indexExpression_target != null); this.indexExpression_target?.collectApiSignature(signature); signature.addInt(this.indexExpression_element ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); signature.addBool(this.indexExpression_substitution != null); this.indexExpression_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.instanceCreationExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.instanceCreationExpression_arguments == null) { signature.addInt(0); } else { signature.addInt(this.instanceCreationExpression_arguments.length); for (var x in this.instanceCreationExpression_arguments) { x?.collectApiSignature(signature); } } signature .addBool(this.instanceCreationExpression_constructorName != null); this .instanceCreationExpression_constructorName ?.collectApiSignature(signature); signature.addBool(this.instanceCreationExpression_typeArguments != null); this .instanceCreationExpression_typeArguments ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.integerLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.integerLiteral_value ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.interpolationExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.interpolationExpression_expression != null); this.interpolationExpression_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.interpolationString) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addString(this.interpolationString_value ?? ''); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.isExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.isExpression_expression != null); this.isExpression_expression?.collectApiSignature(signature); signature.addBool(this.isExpression_type != null); this.isExpression_type?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.label) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.label_label != null); this.label_label?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.labeledStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.labeledStatement_labels == null) { signature.addInt(0); } else { signature.addInt(this.labeledStatement_labels.length); for (var x in this.labeledStatement_labels) { x?.collectApiSignature(signature); } } signature.addBool(this.labeledStatement_statement != null); this.labeledStatement_statement?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.libraryDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.libraryDirective_name != null); this.libraryDirective_name?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.libraryIdentifier) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.libraryIdentifier_components == null) { signature.addInt(0); } else { signature.addInt(this.libraryIdentifier_components.length); for (var x in this.libraryIdentifier_components) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.listLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.typedLiteral_typeArguments == null) { signature.addInt(0); } else { signature.addInt(this.typedLiteral_typeArguments.length); for (var x in this.typedLiteral_typeArguments) { x?.collectApiSignature(signature); } } if (this.listLiteral_elements == null) { signature.addInt(0); } else { signature.addInt(this.listLiteral_elements.length); for (var x in this.listLiteral_elements) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.mapLiteralEntry) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.mapLiteralEntry_key != null); this.mapLiteralEntry_key?.collectApiSignature(signature); signature.addBool(this.mapLiteralEntry_value != null); this.mapLiteralEntry_value?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.methodDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.methodDeclaration_body != null); this.methodDeclaration_body?.collectApiSignature(signature); signature.addBool(this.methodDeclaration_formalParameters != null); this.methodDeclaration_formalParameters?.collectApiSignature(signature); signature.addBool(this.methodDeclaration_returnType != null); this.methodDeclaration_returnType?.collectApiSignature(signature); signature.addBool(this.methodDeclaration_typeParameters != null); this.methodDeclaration_typeParameters?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualReturnType != null); this.actualReturnType?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.methodInvocation) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.methodInvocation_methodName != null); this.methodInvocation_methodName?.collectApiSignature(signature); signature.addBool(this.methodInvocation_target != null); this.methodInvocation_target?.collectApiSignature(signature); signature.addBool(this.invocationExpression_typeArguments != null); this.invocationExpression_typeArguments?.collectApiSignature(signature); signature.addBool(this.invocationExpression_arguments != null); this.invocationExpression_arguments?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.invocationExpression_invokeType != null); this.invocationExpression_invokeType?.collectApiSignature(signature); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.mixinDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } if (this.classOrMixinDeclaration_members == null) { signature.addInt(0); } else { signature.addInt(this.classOrMixinDeclaration_members.length); for (var x in this.classOrMixinDeclaration_members) { x?.collectApiSignature(signature); } } signature.addBool(this.mixinDeclaration_onClause != null); this.mixinDeclaration_onClause?.collectApiSignature(signature); signature.addBool(this.classOrMixinDeclaration_implementsClause != null); this .classOrMixinDeclaration_implementsClause ?.collectApiSignature(signature); signature.addBool(this.classOrMixinDeclaration_typeParameters != null); this .classOrMixinDeclaration_typeParameters ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.simplyBoundable_isSimplyBounded == true); if (this.mixinDeclaration_superInvokedNames == null) { signature.addInt(0); } else { signature.addInt(this.mixinDeclaration_superInvokedNames.length); for (var x in this.mixinDeclaration_superInvokedNames) { signature.addString(x); } } signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.namedExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.namedExpression_expression != null); this.namedExpression_expression?.collectApiSignature(signature); signature.addBool(this.namedExpression_name != null); this.namedExpression_name?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.nativeClause) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.nativeClause_name != null); this.nativeClause_name?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.nativeFunctionBody) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.nativeFunctionBody_stringLiteral != null); this.nativeFunctionBody_stringLiteral?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.nullLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nullLiteral_fake ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.onClause) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.onClause_superclassConstraints == null) { signature.addInt(0); } else { signature.addInt(this.onClause_superclassConstraints.length); for (var x in this.onClause_superclassConstraints) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.parenthesizedExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.parenthesizedExpression_expression != null); this.parenthesizedExpression_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.partDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.uriBasedDirective_uri != null); this.uriBasedDirective_uri?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addInt(this.uriBasedDirective_uriElement ?? 0); signature.addString(this.uriBasedDirective_uriContent ?? ''); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.partOfDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.partOfDirective_libraryName != null); this.partOfDirective_libraryName?.collectApiSignature(signature); signature.addBool(this.partOfDirective_uri != null); this.partOfDirective_uri?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.postfixExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.postfixExpression_operand != null); this.postfixExpression_operand?.collectApiSignature(signature); signature.addInt(this.postfixExpression_element ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addInt(this.postfixExpression_operator == null ? 0 : this.postfixExpression_operator.index); signature.addString(this.name ?? ''); signature.addBool(this.postfixExpression_substitution != null); this.postfixExpression_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.prefixExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.prefixExpression_operand != null); this.prefixExpression_operand?.collectApiSignature(signature); signature.addInt(this.prefixExpression_element ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addInt(this.prefixExpression_operator == null ? 0 : this.prefixExpression_operator.index); signature.addString(this.name ?? ''); signature.addBool(this.prefixExpression_substitution != null); this.prefixExpression_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.prefixedIdentifier) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.prefixedIdentifier_identifier != null); this.prefixedIdentifier_identifier?.collectApiSignature(signature); signature.addBool(this.prefixedIdentifier_prefix != null); this.prefixedIdentifier_prefix?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.propertyAccess) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.propertyAccess_propertyName != null); this.propertyAccess_propertyName?.collectApiSignature(signature); signature.addBool(this.propertyAccess_target != null); this.propertyAccess_target?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addInt(this.propertyAccess_operator == null ? 0 : this.propertyAccess_operator.index); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.redirectingConstructorInvocation) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature .addBool(this.redirectingConstructorInvocation_arguments != null); this .redirectingConstructorInvocation_arguments ?.collectApiSignature(signature); signature.addBool( this.redirectingConstructorInvocation_constructorName != null); this .redirectingConstructorInvocation_constructorName ?.collectApiSignature(signature); signature.addInt(this.redirectingConstructorInvocation_element ?? 0); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); signature .addBool(this.redirectingConstructorInvocation_substitution != null); this .redirectingConstructorInvocation_substitution ?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.rethrowExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.returnStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.returnStatement_expression != null); this.returnStatement_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.setOrMapLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.typedLiteral_typeArguments == null) { signature.addInt(0); } else { signature.addInt(this.typedLiteral_typeArguments.length); for (var x in this.typedLiteral_typeArguments) { x?.collectApiSignature(signature); } } if (this.setOrMapLiteral_elements == null) { signature.addInt(0); } else { signature.addInt(this.setOrMapLiteral_elements.length); for (var x in this.setOrMapLiteral_elements) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.showCombinator) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); if (this.names == null) { signature.addInt(0); } else { signature.addInt(this.names.length); for (var x in this.names) { signature.addString(x); } } signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.simpleFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.normalFormalParameter_metadata == null) { signature.addInt(0); } else { signature.addInt(this.normalFormalParameter_metadata.length); for (var x in this.normalFormalParameter_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.simpleFormalParameter_type != null); this.simpleFormalParameter_type?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualType != null); this.actualType?.collectApiSignature(signature); signature.addBool(this.inheritsCovariant == true); signature.addBool(this.topLevelTypeInferenceError != null); this.topLevelTypeInferenceError?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.simpleIdentifier) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.simpleIdentifier_element ?? 0); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); signature.addBool(this.simpleIdentifier_substitution != null); this.simpleIdentifier_substitution?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.simpleStringLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addString(this.simpleStringLiteral_value ?? ''); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.spreadElement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.spreadElement_expression != null); this.spreadElement_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addInt(this.spreadElement_spreadOperator == null ? 0 : this.spreadElement_spreadOperator.index); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.stringInterpolation) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.stringInterpolation_elements == null) { signature.addInt(0); } else { signature.addInt(this.stringInterpolation_elements.length); for (var x in this.stringInterpolation_elements) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.superConstructorInvocation) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.superConstructorInvocation_arguments != null); this.superConstructorInvocation_arguments?.collectApiSignature(signature); signature .addBool(this.superConstructorInvocation_constructorName != null); this .superConstructorInvocation_constructorName ?.collectApiSignature(signature); signature.addInt(this.superConstructorInvocation_element ?? 0); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); signature.addBool(this.superConstructorInvocation_substitution != null); this .superConstructorInvocation_substitution ?.collectApiSignature(signature); } else if (kind == idl.LinkedNodeKind.superExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.switchCase) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.switchMember_labels == null) { signature.addInt(0); } else { signature.addInt(this.switchMember_labels.length); for (var x in this.switchMember_labels) { x?.collectApiSignature(signature); } } if (this.switchMember_statements == null) { signature.addInt(0); } else { signature.addInt(this.switchMember_statements.length); for (var x in this.switchMember_statements) { x?.collectApiSignature(signature); } } signature.addBool(this.switchCase_expression != null); this.switchCase_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.switchDefault) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.switchMember_labels == null) { signature.addInt(0); } else { signature.addInt(this.switchMember_labels.length); for (var x in this.switchMember_labels) { x?.collectApiSignature(signature); } } if (this.switchMember_statements == null) { signature.addInt(0); } else { signature.addInt(this.switchMember_statements.length); for (var x in this.switchMember_statements) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.switchStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.switchStatement_members == null) { signature.addInt(0); } else { signature.addInt(this.switchStatement_members.length); for (var x in this.switchStatement_members) { x?.collectApiSignature(signature); } } signature.addBool(this.switchStatement_expression != null); this.switchStatement_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.symbolLiteral) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); if (this.names == null) { signature.addInt(0); } else { signature.addInt(this.names.length); for (var x in this.names) { signature.addString(x); } } signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.thisExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.throwExpression) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.throwExpression_expression != null); this.throwExpression_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.expression_type != null); this.expression_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.topLevelVariableDeclaration_variableList != null); this .topLevelVariableDeclaration_variableList ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.tryStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.tryStatement_catchClauses == null) { signature.addInt(0); } else { signature.addInt(this.tryStatement_catchClauses.length); for (var x in this.tryStatement_catchClauses) { x?.collectApiSignature(signature); } } signature.addBool(this.tryStatement_body != null); this.tryStatement_body?.collectApiSignature(signature); signature.addBool(this.tryStatement_finallyBlock != null); this.tryStatement_finallyBlock?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.typeArgumentList) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.typeArgumentList_arguments == null) { signature.addInt(0); } else { signature.addInt(this.typeArgumentList_arguments.length); for (var x in this.typeArgumentList_arguments) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.typeName) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.typeName_typeArguments == null) { signature.addInt(0); } else { signature.addInt(this.typeName_typeArguments.length); for (var x in this.typeName_typeArguments) { x?.collectApiSignature(signature); } } signature.addBool(this.typeName_name != null); this.typeName_name?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.typeName_type != null); this.typeName_type?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.typeParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.typeParameter_bound != null); this.typeParameter_bound?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.typeParameter_defaultType != null); this.typeParameter_defaultType?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.typeParameterList) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.typeParameterList_typeParameters == null) { signature.addInt(0); } else { signature.addInt(this.typeParameterList_typeParameters.length); for (var x in this.typeParameterList_typeParameters) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.variableDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.variableDeclaration_initializer != null); this.variableDeclaration_initializer?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addBool(this.actualType != null); this.actualType?.collectApiSignature(signature); signature.addBool(this.inheritsCovariant == true); signature.addBool(this.topLevelTypeInferenceError != null); this.topLevelTypeInferenceError?.collectApiSignature(signature); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.variableDeclarationList) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.variableDeclarationList_variables == null) { signature.addInt(0); } else { signature.addInt(this.variableDeclarationList_variables.length); for (var x in this.variableDeclarationList_variables) { x?.collectApiSignature(signature); } } if (this.annotatedNode_metadata == null) { signature.addInt(0); } else { signature.addInt(this.annotatedNode_metadata.length); for (var x in this.annotatedNode_metadata) { x?.collectApiSignature(signature); } } signature.addBool(this.variableDeclarationList_type != null); this.variableDeclarationList_type?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.variableDeclarationStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.variableDeclarationStatement_variables != null); this .variableDeclarationStatement_variables ?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.whileStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.whileStatement_body != null); this.whileStatement_body?.collectApiSignature(signature); signature.addBool(this.whileStatement_condition != null); this.whileStatement_condition?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.withClause) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.withClause_mixinTypes == null) { signature.addInt(0); } else { signature.addInt(this.withClause_mixinTypes.length); for (var x in this.withClause_mixinTypes) { x?.collectApiSignature(signature); } } signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } else if (kind == idl.LinkedNodeKind.yieldStatement) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addBool(this.yieldStatement_expression != null); this.yieldStatement_expression?.collectApiSignature(signature); signature.addInt(this.flags ?? 0); signature.addString(this.name ?? ''); } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_variantField_24; fb.Offset offset_variantField_2; fb.Offset offset_variantField_4; fb.Offset offset_variantField_6; fb.Offset offset_variantField_7; fb.Offset offset_variantField_8; fb.Offset offset_variantField_38; fb.Offset offset_variantField_9; fb.Offset offset_variantField_12; fb.Offset offset_variantField_5; fb.Offset offset_variantField_13; fb.Offset offset_variantField_33; fb.Offset offset_variantField_3; fb.Offset offset_variantField_10; fb.Offset offset_variantField_25; fb.Offset offset_variantField_20; fb.Offset offset_variantField_39; fb.Offset offset_variantField_1; fb.Offset offset_variantField_30; fb.Offset offset_variantField_14; fb.Offset offset_variantField_34; fb.Offset offset_name; fb.Offset offset_variantField_32; fb.Offset offset_variantField_23; fb.Offset offset_variantField_11; fb.Offset offset_variantField_22; if (_variantField_24 != null) { offset_variantField_24 = _variantField_24.finish(fbBuilder); } if (!(_variantField_2 == null || _variantField_2.isEmpty)) { offset_variantField_2 = fbBuilder .writeList(_variantField_2.map((b) => b.finish(fbBuilder)).toList()); } if (!(_variantField_4 == null || _variantField_4.isEmpty)) { offset_variantField_4 = fbBuilder .writeList(_variantField_4.map((b) => b.finish(fbBuilder)).toList()); } if (_variantField_6 != null) { offset_variantField_6 = _variantField_6.finish(fbBuilder); } if (_variantField_7 != null) { offset_variantField_7 = _variantField_7.finish(fbBuilder); } if (_variantField_8 != null) { offset_variantField_8 = _variantField_8.finish(fbBuilder); } if (_variantField_38 != null) { offset_variantField_38 = _variantField_38.finish(fbBuilder); } if (_variantField_9 != null) { offset_variantField_9 = _variantField_9.finish(fbBuilder); } if (_variantField_12 != null) { offset_variantField_12 = _variantField_12.finish(fbBuilder); } if (!(_variantField_5 == null || _variantField_5.isEmpty)) { offset_variantField_5 = fbBuilder .writeList(_variantField_5.map((b) => b.finish(fbBuilder)).toList()); } if (_variantField_13 != null) { offset_variantField_13 = _variantField_13.finish(fbBuilder); } if (!(_variantField_33 == null || _variantField_33.isEmpty)) { offset_variantField_33 = fbBuilder.writeList( _variantField_33.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_variantField_3 == null || _variantField_3.isEmpty)) { offset_variantField_3 = fbBuilder .writeList(_variantField_3.map((b) => b.finish(fbBuilder)).toList()); } if (_variantField_10 != null) { offset_variantField_10 = _variantField_10.finish(fbBuilder); } if (_variantField_25 != null) { offset_variantField_25 = _variantField_25.finish(fbBuilder); } if (_variantField_20 != null) { offset_variantField_20 = fbBuilder.writeString(_variantField_20); } if (!(_variantField_39 == null || _variantField_39.isEmpty)) { offset_variantField_39 = fbBuilder .writeList(_variantField_39.map((b) => b.finish(fbBuilder)).toList()); } if (_variantField_1 != null) { offset_variantField_1 = fbBuilder.writeString(_variantField_1); } if (_variantField_30 != null) { offset_variantField_30 = fbBuilder.writeString(_variantField_30); } if (_variantField_14 != null) { offset_variantField_14 = _variantField_14.finish(fbBuilder); } if (!(_variantField_34 == null || _variantField_34.isEmpty)) { offset_variantField_34 = fbBuilder.writeList( _variantField_34.map((b) => fbBuilder.writeString(b)).toList()); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (_variantField_32 != null) { offset_variantField_32 = _variantField_32.finish(fbBuilder); } if (_variantField_23 != null) { offset_variantField_23 = _variantField_23.finish(fbBuilder); } if (_variantField_11 != null) { offset_variantField_11 = _variantField_11.finish(fbBuilder); } if (_variantField_22 != null) { offset_variantField_22 = fbBuilder.writeString(_variantField_22); } fbBuilder.startTable(); if (offset_variantField_24 != null) { fbBuilder.addOffset(24, offset_variantField_24); } if (offset_variantField_2 != null) { fbBuilder.addOffset(2, offset_variantField_2); } if (offset_variantField_4 != null) { fbBuilder.addOffset(4, offset_variantField_4); } if (offset_variantField_6 != null) { fbBuilder.addOffset(6, offset_variantField_6); } if (offset_variantField_7 != null) { fbBuilder.addOffset(7, offset_variantField_7); } if (_variantField_17 != null && _variantField_17 != 0) { fbBuilder.addUint32(17, _variantField_17); } if (offset_variantField_8 != null) { fbBuilder.addOffset(8, offset_variantField_8); } if (offset_variantField_38 != null) { fbBuilder.addOffset(38, offset_variantField_38); } if (_variantField_15 != null && _variantField_15 != 0) { fbBuilder.addUint32(15, _variantField_15); } if (_variantField_28 != null && _variantField_28 != idl.UnlinkedTokenType.NOTHING) { fbBuilder.addUint8(28, _variantField_28.index); } if (_variantField_27 == true) { fbBuilder.addBool(27, true); } if (offset_variantField_9 != null) { fbBuilder.addOffset(9, offset_variantField_9); } if (offset_variantField_12 != null) { fbBuilder.addOffset(12, offset_variantField_12); } if (offset_variantField_5 != null) { fbBuilder.addOffset(5, offset_variantField_5); } if (offset_variantField_13 != null) { fbBuilder.addOffset(13, offset_variantField_13); } if (offset_variantField_33 != null) { fbBuilder.addOffset(33, offset_variantField_33); } if (_variantField_29 != null && _variantField_29 != idl.LinkedNodeCommentType.block) { fbBuilder.addUint8(29, _variantField_29.index); } if (offset_variantField_3 != null) { fbBuilder.addOffset(3, offset_variantField_3); } if (offset_variantField_10 != null) { fbBuilder.addOffset(10, offset_variantField_10); } if (_variantField_26 != null && _variantField_26 != idl.LinkedNodeFormalParameterKind.requiredPositional) { fbBuilder.addUint8(26, _variantField_26.index); } if (_variantField_21 != null && _variantField_21 != 0.0) { fbBuilder.addFloat64(21, _variantField_21); } if (offset_variantField_25 != null) { fbBuilder.addOffset(25, offset_variantField_25); } if (offset_variantField_20 != null) { fbBuilder.addOffset(20, offset_variantField_20); } if (offset_variantField_39 != null) { fbBuilder.addOffset(39, offset_variantField_39); } if (_flags != null && _flags != 0) { fbBuilder.addUint32(18, _flags); } if (offset_variantField_1 != null) { fbBuilder.addOffset(1, offset_variantField_1); } if (_variantField_36 != null && _variantField_36 != 0) { fbBuilder.addUint32(36, _variantField_36); } if (_variantField_16 != null && _variantField_16 != 0) { fbBuilder.addUint32(16, _variantField_16); } if (offset_variantField_30 != null) { fbBuilder.addOffset(30, offset_variantField_30); } if (offset_variantField_14 != null) { fbBuilder.addOffset(14, offset_variantField_14); } if (_kind != null && _kind != idl.LinkedNodeKind.adjacentStrings) { fbBuilder.addUint8(0, _kind.index); } if (offset_variantField_34 != null) { fbBuilder.addOffset(34, offset_variantField_34); } if (offset_name != null) { fbBuilder.addOffset(37, offset_name); } if (_variantField_31 == true) { fbBuilder.addBool(31, true); } if (_variantField_35 != null && _variantField_35 != idl.UnlinkedTokenType.NOTHING) { fbBuilder.addUint8(35, _variantField_35.index); } if (offset_variantField_32 != null) { fbBuilder.addOffset(32, offset_variantField_32); } if (offset_variantField_23 != null) { fbBuilder.addOffset(23, offset_variantField_23); } if (offset_variantField_11 != null) { fbBuilder.addOffset(11, offset_variantField_11); } if (offset_variantField_22 != null) { fbBuilder.addOffset(22, offset_variantField_22); } if (_variantField_19 != null && _variantField_19 != 0) { fbBuilder.addUint32(19, _variantField_19); } return fbBuilder.endTable(); } } class _LinkedNodeReader extends fb.TableReader<_LinkedNodeImpl> { const _LinkedNodeReader(); @override _LinkedNodeImpl createObject(fb.BufferContext bc, int offset) => new _LinkedNodeImpl(bc, offset); } class _LinkedNodeImpl extends Object with _LinkedNodeMixin implements idl.LinkedNode { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeImpl(this._bc, this._bcOffset); idl.LinkedNodeType _variantField_24; List<idl.LinkedNode> _variantField_2; List<idl.LinkedNode> _variantField_4; idl.LinkedNode _variantField_6; idl.LinkedNode _variantField_7; int _variantField_17; idl.LinkedNode _variantField_8; idl.LinkedNodeTypeSubstitution _variantField_38; int _variantField_15; idl.UnlinkedTokenType _variantField_28; bool _variantField_27; idl.LinkedNode _variantField_9; idl.LinkedNode _variantField_12; List<idl.LinkedNode> _variantField_5; idl.LinkedNode _variantField_13; List<String> _variantField_33; idl.LinkedNodeCommentType _variantField_29; List<idl.LinkedNode> _variantField_3; idl.LinkedNode _variantField_10; idl.LinkedNodeFormalParameterKind _variantField_26; double _variantField_21; idl.LinkedNodeType _variantField_25; String _variantField_20; List<idl.LinkedNodeType> _variantField_39; int _flags; String _variantField_1; int _variantField_36; int _variantField_16; String _variantField_30; idl.LinkedNode _variantField_14; idl.LinkedNodeKind _kind; List<String> _variantField_34; String _name; bool _variantField_31; idl.UnlinkedTokenType _variantField_35; idl.TopLevelInferenceError _variantField_32; idl.LinkedNodeType _variantField_23; idl.LinkedNode _variantField_11; String _variantField_22; int _variantField_19; @override idl.LinkedNodeType get actualReturnType { assert(kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionExpression || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericFunctionType || kind == idl.LinkedNodeKind.methodDeclaration); _variantField_24 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 24, null); return _variantField_24; } @override idl.LinkedNodeType get actualType { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_24 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 24, null); return _variantField_24; } @override idl.LinkedNodeType get binaryExpression_invokeType { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_24 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 24, null); return _variantField_24; } @override idl.LinkedNodeType get extensionOverride_extendedType { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_24 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 24, null); return _variantField_24; } @override idl.LinkedNodeType get invocationExpression_invokeType { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); _variantField_24 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 24, null); return _variantField_24; } @override List<idl.LinkedNode> get adjacentStrings_strings { assert(kind == idl.LinkedNodeKind.adjacentStrings); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get argumentList_arguments { assert(kind == idl.LinkedNodeKind.argumentList); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get block_statements { assert(kind == idl.LinkedNodeKind.block); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get cascadeExpression_sections { assert(kind == idl.LinkedNodeKind.cascadeExpression); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get comment_references { assert(kind == idl.LinkedNodeKind.comment); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get compilationUnit_declarations { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get constructorDeclaration_initializers { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get dottedName_components { assert(kind == idl.LinkedNodeKind.dottedName); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get enumDeclaration_constants { assert(kind == idl.LinkedNodeKind.enumDeclaration); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get extensionOverride_arguments { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get formalParameterList_parameters { assert(kind == idl.LinkedNodeKind.formalParameterList); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get implementsClause_interfaces { assert(kind == idl.LinkedNodeKind.implementsClause); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get instanceCreationExpression_arguments { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get labeledStatement_labels { assert(kind == idl.LinkedNodeKind.labeledStatement); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get libraryIdentifier_components { assert(kind == idl.LinkedNodeKind.libraryIdentifier); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get namespaceDirective_combinators { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get onClause_superclassConstraints { assert(kind == idl.LinkedNodeKind.onClause); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get stringInterpolation_elements { assert(kind == idl.LinkedNodeKind.stringInterpolation); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get switchStatement_members { assert(kind == idl.LinkedNodeKind.switchStatement); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get tryStatement_catchClauses { assert(kind == idl.LinkedNodeKind.tryStatement); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get typeArgumentList_arguments { assert(kind == idl.LinkedNodeKind.typeArgumentList); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get typedLiteral_typeArguments { assert(kind == idl.LinkedNodeKind.listLiteral || kind == idl.LinkedNodeKind.setOrMapLiteral); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get typeName_typeArguments { assert(kind == idl.LinkedNodeKind.typeName); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get typeParameterList_typeParameters { assert(kind == idl.LinkedNodeKind.typeParameterList); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get variableDeclarationList_variables { assert(kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get withClause_mixinTypes { assert(kind == idl.LinkedNodeKind.withClause); _variantField_2 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.LinkedNode>[]); return _variantField_2; } @override List<idl.LinkedNode> get annotatedNode_metadata { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.declaredIdentifier || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective || kind == idl.LinkedNodeKind.topLevelVariableDeclaration || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration || kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_4 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.LinkedNode>[]); return _variantField_4; } @override List<idl.LinkedNode> get normalFormalParameter_metadata { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter); _variantField_4 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.LinkedNode>[]); return _variantField_4; } @override List<idl.LinkedNode> get switchMember_statements { assert(kind == idl.LinkedNodeKind.switchCase || kind == idl.LinkedNodeKind.switchDefault); _variantField_4 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.LinkedNode>[]); return _variantField_4; } @override idl.LinkedNode get annotation_arguments { assert(kind == idl.LinkedNodeKind.annotation); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get asExpression_expression { assert(kind == idl.LinkedNodeKind.asExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get assertInitializer_condition { assert(kind == idl.LinkedNodeKind.assertInitializer); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get assertStatement_condition { assert(kind == idl.LinkedNodeKind.assertStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get assignmentExpression_leftHandSide { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get awaitExpression_expression { assert(kind == idl.LinkedNodeKind.awaitExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get binaryExpression_leftOperand { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get blockFunctionBody_block { assert(kind == idl.LinkedNodeKind.blockFunctionBody); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get breakStatement_label { assert(kind == idl.LinkedNodeKind.breakStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get cascadeExpression_target { assert(kind == idl.LinkedNodeKind.cascadeExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get catchClause_body { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get classDeclaration_extendsClause { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get classTypeAlias_typeParameters { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get commentReference_identifier { assert(kind == idl.LinkedNodeKind.commentReference); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get compilationUnit_scriptTag { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get conditionalExpression_condition { assert(kind == idl.LinkedNodeKind.conditionalExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get configuration_name { assert(kind == idl.LinkedNodeKind.configuration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get constructorDeclaration_body { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get constructorFieldInitializer_expression { assert(kind == idl.LinkedNodeKind.constructorFieldInitializer); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get constructorName_name { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get continueStatement_label { assert(kind == idl.LinkedNodeKind.continueStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get declaredIdentifier_identifier { assert(kind == idl.LinkedNodeKind.declaredIdentifier); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get defaultFormalParameter_defaultValue { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get doStatement_body { assert(kind == idl.LinkedNodeKind.doStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get expressionFunctionBody_expression { assert(kind == idl.LinkedNodeKind.expressionFunctionBody); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get expressionStatement_expression { assert(kind == idl.LinkedNodeKind.expressionStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get extendsClause_superclass { assert(kind == idl.LinkedNodeKind.extendsClause); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get extensionDeclaration_typeParameters { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get fieldDeclaration_fields { assert(kind == idl.LinkedNodeKind.fieldDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get fieldFormalParameter_type { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get forEachParts_iterable { assert(kind == idl.LinkedNodeKind.forEachPartsWithDeclaration || kind == idl.LinkedNodeKind.forEachPartsWithIdentifier); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get forMixin_forLoopParts { assert(kind == idl.LinkedNodeKind.forElement || kind == idl.LinkedNodeKind.forStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get forParts_condition { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations || kind == idl.LinkedNodeKind.forPartsWithExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get functionDeclaration_functionExpression { assert(kind == idl.LinkedNodeKind.functionDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get functionDeclarationStatement_functionDeclaration { assert(kind == idl.LinkedNodeKind.functionDeclarationStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get functionExpression_body { assert(kind == idl.LinkedNodeKind.functionExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get functionExpressionInvocation_function { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get functionTypeAlias_formalParameters { assert(kind == idl.LinkedNodeKind.functionTypeAlias); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get functionTypedFormalParameter_formalParameters { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get genericFunctionType_typeParameters { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get genericTypeAlias_typeParameters { assert(kind == idl.LinkedNodeKind.genericTypeAlias); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get ifMixin_condition { assert(kind == idl.LinkedNodeKind.ifElement || kind == idl.LinkedNodeKind.ifStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get indexExpression_index { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get interpolationExpression_expression { assert(kind == idl.LinkedNodeKind.interpolationExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get isExpression_expression { assert(kind == idl.LinkedNodeKind.isExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get label_label { assert(kind == idl.LinkedNodeKind.label); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get labeledStatement_statement { assert(kind == idl.LinkedNodeKind.labeledStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get libraryDirective_name { assert(kind == idl.LinkedNodeKind.libraryDirective); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get mapLiteralEntry_key { assert(kind == idl.LinkedNodeKind.mapLiteralEntry); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get methodDeclaration_body { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get methodInvocation_methodName { assert(kind == idl.LinkedNodeKind.methodInvocation); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get mixinDeclaration_onClause { assert(kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get namedExpression_expression { assert(kind == idl.LinkedNodeKind.namedExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get nativeClause_name { assert(kind == idl.LinkedNodeKind.nativeClause); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get nativeFunctionBody_stringLiteral { assert(kind == idl.LinkedNodeKind.nativeFunctionBody); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get parenthesizedExpression_expression { assert(kind == idl.LinkedNodeKind.parenthesizedExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get partOfDirective_libraryName { assert(kind == idl.LinkedNodeKind.partOfDirective); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get postfixExpression_operand { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get prefixedIdentifier_identifier { assert(kind == idl.LinkedNodeKind.prefixedIdentifier); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get prefixExpression_operand { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get propertyAccess_propertyName { assert(kind == idl.LinkedNodeKind.propertyAccess); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get redirectingConstructorInvocation_arguments { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get returnStatement_expression { assert(kind == idl.LinkedNodeKind.returnStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get simpleFormalParameter_type { assert(kind == idl.LinkedNodeKind.simpleFormalParameter); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get spreadElement_expression { assert(kind == idl.LinkedNodeKind.spreadElement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get superConstructorInvocation_arguments { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get switchCase_expression { assert(kind == idl.LinkedNodeKind.switchCase); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get throwExpression_expression { assert(kind == idl.LinkedNodeKind.throwExpression); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get topLevelVariableDeclaration_variableList { assert(kind == idl.LinkedNodeKind.topLevelVariableDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get tryStatement_body { assert(kind == idl.LinkedNodeKind.tryStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get typeName_name { assert(kind == idl.LinkedNodeKind.typeName); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get typeParameter_bound { assert(kind == idl.LinkedNodeKind.typeParameter); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get variableDeclaration_initializer { assert(kind == idl.LinkedNodeKind.variableDeclaration); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get variableDeclarationList_type { assert(kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get variableDeclarationStatement_variables { assert(kind == idl.LinkedNodeKind.variableDeclarationStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get whileStatement_body { assert(kind == idl.LinkedNodeKind.whileStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get yieldStatement_expression { assert(kind == idl.LinkedNodeKind.yieldStatement); _variantField_6 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 6, null); return _variantField_6; } @override idl.LinkedNode get annotation_constructorName { assert(kind == idl.LinkedNodeKind.annotation); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get asExpression_type { assert(kind == idl.LinkedNodeKind.asExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get assertInitializer_message { assert(kind == idl.LinkedNodeKind.assertInitializer); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get assertStatement_message { assert(kind == idl.LinkedNodeKind.assertStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get assignmentExpression_rightHandSide { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get binaryExpression_rightOperand { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get catchClause_exceptionParameter { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get classDeclaration_withClause { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get classTypeAlias_superclass { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get conditionalExpression_elseExpression { assert(kind == idl.LinkedNodeKind.conditionalExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get configuration_value { assert(kind == idl.LinkedNodeKind.configuration); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get constructorFieldInitializer_fieldName { assert(kind == idl.LinkedNodeKind.constructorFieldInitializer); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get constructorName_type { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get declaredIdentifier_type { assert(kind == idl.LinkedNodeKind.declaredIdentifier); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get defaultFormalParameter_parameter { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get doStatement_condition { assert(kind == idl.LinkedNodeKind.doStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get extensionDeclaration_extendedType { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get extensionOverride_extensionName { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get fieldFormalParameter_typeParameters { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get forEachPartsWithDeclaration_loopVariable { assert(kind == idl.LinkedNodeKind.forEachPartsWithDeclaration); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get forEachPartsWithIdentifier_identifier { assert(kind == idl.LinkedNodeKind.forEachPartsWithIdentifier); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get forElement_body { assert(kind == idl.LinkedNodeKind.forElement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get forPartsWithDeclarations_variables { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get forPartsWithExpression_initialization { assert(kind == idl.LinkedNodeKind.forPartsWithExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get forStatement_body { assert(kind == idl.LinkedNodeKind.forStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get functionDeclaration_returnType { assert(kind == idl.LinkedNodeKind.functionDeclaration); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get functionExpression_formalParameters { assert(kind == idl.LinkedNodeKind.functionExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get functionTypeAlias_returnType { assert(kind == idl.LinkedNodeKind.functionTypeAlias); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get functionTypedFormalParameter_returnType { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get genericFunctionType_returnType { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get genericTypeAlias_functionType { assert(kind == idl.LinkedNodeKind.genericTypeAlias); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get ifStatement_elseStatement { assert(kind == idl.LinkedNodeKind.ifStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get indexExpression_target { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get instanceCreationExpression_constructorName { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get isExpression_type { assert(kind == idl.LinkedNodeKind.isExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get mapLiteralEntry_value { assert(kind == idl.LinkedNodeKind.mapLiteralEntry); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get methodDeclaration_formalParameters { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get methodInvocation_target { assert(kind == idl.LinkedNodeKind.methodInvocation); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get namedExpression_name { assert(kind == idl.LinkedNodeKind.namedExpression); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get partOfDirective_uri { assert(kind == idl.LinkedNodeKind.partOfDirective); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get prefixedIdentifier_prefix { assert(kind == idl.LinkedNodeKind.prefixedIdentifier); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get propertyAccess_target { assert(kind == idl.LinkedNodeKind.propertyAccess); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get redirectingConstructorInvocation_constructorName { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get superConstructorInvocation_constructorName { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get switchStatement_expression { assert(kind == idl.LinkedNodeKind.switchStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get tryStatement_finallyBlock { assert(kind == idl.LinkedNodeKind.tryStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override idl.LinkedNode get whileStatement_condition { assert(kind == idl.LinkedNodeKind.whileStatement); _variantField_7 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 7, null); return _variantField_7; } @override int get annotation_element { assert(kind == idl.LinkedNodeKind.annotation); _variantField_17 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 17, 0); return _variantField_17; } @override int get genericFunctionType_id { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_17 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 17, 0); return _variantField_17; } @override idl.LinkedNode get annotation_name { assert(kind == idl.LinkedNodeKind.annotation); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get catchClause_exceptionType { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get classDeclaration_nativeClause { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get classTypeAlias_withClause { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get conditionalExpression_thenExpression { assert(kind == idl.LinkedNodeKind.conditionalExpression); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get configuration_uri { assert(kind == idl.LinkedNodeKind.configuration); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get constructorDeclaration_parameters { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get extensionOverride_typeArguments { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get fieldFormalParameter_formalParameters { assert(kind == idl.LinkedNodeKind.fieldFormalParameter); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get functionExpression_typeParameters { assert(kind == idl.LinkedNodeKind.functionExpression); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get functionTypeAlias_typeParameters { assert(kind == idl.LinkedNodeKind.functionTypeAlias); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get functionTypedFormalParameter_typeParameters { assert(kind == idl.LinkedNodeKind.functionTypedFormalParameter); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get genericFunctionType_formalParameters { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get ifElement_thenElement { assert(kind == idl.LinkedNodeKind.ifElement); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get ifStatement_thenStatement { assert(kind == idl.LinkedNodeKind.ifStatement); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get instanceCreationExpression_typeArguments { assert(kind == idl.LinkedNodeKind.instanceCreationExpression); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNode get methodDeclaration_returnType { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_8 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 8, null); return _variantField_8; } @override idl.LinkedNodeTypeSubstitution get annotation_substitution { assert(kind == idl.LinkedNodeKind.annotation); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get assignmentExpression_substitution { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get binaryExpression_substitution { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get constructorName_substitution { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get indexExpression_substitution { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get postfixExpression_substitution { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get prefixExpression_substitution { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get redirectingConstructorInvocation_substitution { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get simpleIdentifier_substitution { assert(kind == idl.LinkedNodeKind.simpleIdentifier); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override idl.LinkedNodeTypeSubstitution get superConstructorInvocation_substitution { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_38 ??= const _LinkedNodeTypeSubstitutionReader() .vTableGet(_bc, _bcOffset, 38, null); return _variantField_38; } @override int get assignmentExpression_element { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get binaryExpression_element { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get constructorName_element { assert(kind == idl.LinkedNodeKind.constructorName); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get emptyFunctionBody_fake { assert(kind == idl.LinkedNodeKind.emptyFunctionBody); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get emptyStatement_fake { assert(kind == idl.LinkedNodeKind.emptyStatement); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get indexExpression_element { assert(kind == idl.LinkedNodeKind.indexExpression); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get nullLiteral_fake { assert(kind == idl.LinkedNodeKind.nullLiteral); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get postfixExpression_element { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get prefixExpression_element { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get redirectingConstructorInvocation_element { assert(kind == idl.LinkedNodeKind.redirectingConstructorInvocation); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get simpleIdentifier_element { assert(kind == idl.LinkedNodeKind.simpleIdentifier); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override int get superConstructorInvocation_element { assert(kind == idl.LinkedNodeKind.superConstructorInvocation); _variantField_15 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _variantField_15; } @override idl.UnlinkedTokenType get assignmentExpression_operator { assert(kind == idl.LinkedNodeKind.assignmentExpression); _variantField_28 ??= const _UnlinkedTokenTypeReader() .vTableGet(_bc, _bcOffset, 28, idl.UnlinkedTokenType.NOTHING); return _variantField_28; } @override idl.UnlinkedTokenType get binaryExpression_operator { assert(kind == idl.LinkedNodeKind.binaryExpression); _variantField_28 ??= const _UnlinkedTokenTypeReader() .vTableGet(_bc, _bcOffset, 28, idl.UnlinkedTokenType.NOTHING); return _variantField_28; } @override idl.UnlinkedTokenType get postfixExpression_operator { assert(kind == idl.LinkedNodeKind.postfixExpression); _variantField_28 ??= const _UnlinkedTokenTypeReader() .vTableGet(_bc, _bcOffset, 28, idl.UnlinkedTokenType.NOTHING); return _variantField_28; } @override idl.UnlinkedTokenType get prefixExpression_operator { assert(kind == idl.LinkedNodeKind.prefixExpression); _variantField_28 ??= const _UnlinkedTokenTypeReader() .vTableGet(_bc, _bcOffset, 28, idl.UnlinkedTokenType.NOTHING); return _variantField_28; } @override idl.UnlinkedTokenType get propertyAccess_operator { assert(kind == idl.LinkedNodeKind.propertyAccess); _variantField_28 ??= const _UnlinkedTokenTypeReader() .vTableGet(_bc, _bcOffset, 28, idl.UnlinkedTokenType.NOTHING); return _variantField_28; } @override bool get booleanLiteral_value { assert(kind == idl.LinkedNodeKind.booleanLiteral); _variantField_27 ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 27, false); return _variantField_27; } @override bool get classDeclaration_isDartObject { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_27 ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 27, false); return _variantField_27; } @override bool get inheritsCovariant { assert(kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_27 ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 27, false); return _variantField_27; } @override bool get typeAlias_hasSelfReference { assert(kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias); _variantField_27 ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 27, false); return _variantField_27; } @override idl.LinkedNode get catchClause_stackTraceParameter { assert(kind == idl.LinkedNodeKind.catchClause); _variantField_9 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 9, null); return _variantField_9; } @override idl.LinkedNode get classTypeAlias_implementsClause { assert(kind == idl.LinkedNodeKind.classTypeAlias); _variantField_9 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 9, null); return _variantField_9; } @override idl.LinkedNode get constructorDeclaration_redirectedConstructor { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_9 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 9, null); return _variantField_9; } @override idl.LinkedNode get ifElement_elseElement { assert(kind == idl.LinkedNodeKind.ifElement); _variantField_9 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 9, null); return _variantField_9; } @override idl.LinkedNode get methodDeclaration_typeParameters { assert(kind == idl.LinkedNodeKind.methodDeclaration); _variantField_9 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 9, null); return _variantField_9; } @override idl.LinkedNode get classOrMixinDeclaration_implementsClause { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_12 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 12, null); return _variantField_12; } @override idl.LinkedNode get invocationExpression_typeArguments { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); _variantField_12 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 12, null); return _variantField_12; } @override List<idl.LinkedNode> get classOrMixinDeclaration_members { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_5 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.LinkedNode>[]); return _variantField_5; } @override List<idl.LinkedNode> get extensionDeclaration_members { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_5 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.LinkedNode>[]); return _variantField_5; } @override List<idl.LinkedNode> get forParts_updaters { assert(kind == idl.LinkedNodeKind.forPartsWithDeclarations || kind == idl.LinkedNodeKind.forPartsWithExpression); _variantField_5 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.LinkedNode>[]); return _variantField_5; } @override idl.LinkedNode get classOrMixinDeclaration_typeParameters { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_13 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 13, null); return _variantField_13; } @override List<String> get comment_tokens { assert(kind == idl.LinkedNodeKind.comment); _variantField_33 ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 33, const <String>[]); return _variantField_33; } @override idl.LinkedNodeCommentType get comment_type { assert(kind == idl.LinkedNodeKind.comment); _variantField_29 ??= const _LinkedNodeCommentTypeReader() .vTableGet(_bc, _bcOffset, 29, idl.LinkedNodeCommentType.block); return _variantField_29; } @override List<idl.LinkedNode> get compilationUnit_directives { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_3 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.LinkedNode>[]); return _variantField_3; } @override List<idl.LinkedNode> get listLiteral_elements { assert(kind == idl.LinkedNodeKind.listLiteral); _variantField_3 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.LinkedNode>[]); return _variantField_3; } @override List<idl.LinkedNode> get namespaceDirective_configurations { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); _variantField_3 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.LinkedNode>[]); return _variantField_3; } @override List<idl.LinkedNode> get setOrMapLiteral_elements { assert(kind == idl.LinkedNodeKind.setOrMapLiteral); _variantField_3 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.LinkedNode>[]); return _variantField_3; } @override List<idl.LinkedNode> get switchMember_labels { assert(kind == idl.LinkedNodeKind.switchCase || kind == idl.LinkedNodeKind.switchDefault); _variantField_3 ??= const fb.ListReader<idl.LinkedNode>(const _LinkedNodeReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.LinkedNode>[]); return _variantField_3; } @override idl.LinkedNode get constructorDeclaration_returnType { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_10 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 10, null); return _variantField_10; } @override idl.LinkedNodeFormalParameterKind get defaultFormalParameter_kind { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_26 ??= const _LinkedNodeFormalParameterKindReader().vTableGet( _bc, _bcOffset, 26, idl.LinkedNodeFormalParameterKind.requiredPositional); return _variantField_26; } @override double get doubleLiteral_value { assert(kind == idl.LinkedNodeKind.doubleLiteral); _variantField_21 ??= const fb.Float64Reader().vTableGet(_bc, _bcOffset, 21, 0.0); return _variantField_21; } @override idl.LinkedNodeType get expression_type { assert(kind == idl.LinkedNodeKind.assignmentExpression || kind == idl.LinkedNodeKind.asExpression || kind == idl.LinkedNodeKind.awaitExpression || kind == idl.LinkedNodeKind.binaryExpression || kind == idl.LinkedNodeKind.cascadeExpression || kind == idl.LinkedNodeKind.conditionalExpression || kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.indexExpression || kind == idl.LinkedNodeKind.instanceCreationExpression || kind == idl.LinkedNodeKind.integerLiteral || kind == idl.LinkedNodeKind.listLiteral || kind == idl.LinkedNodeKind.methodInvocation || kind == idl.LinkedNodeKind.nullLiteral || kind == idl.LinkedNodeKind.parenthesizedExpression || kind == idl.LinkedNodeKind.prefixExpression || kind == idl.LinkedNodeKind.prefixedIdentifier || kind == idl.LinkedNodeKind.propertyAccess || kind == idl.LinkedNodeKind.postfixExpression || kind == idl.LinkedNodeKind.rethrowExpression || kind == idl.LinkedNodeKind.setOrMapLiteral || kind == idl.LinkedNodeKind.simpleIdentifier || kind == idl.LinkedNodeKind.superExpression || kind == idl.LinkedNodeKind.symbolLiteral || kind == idl.LinkedNodeKind.thisExpression || kind == idl.LinkedNodeKind.throwExpression); _variantField_25 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 25, null); return _variantField_25; } @override idl.LinkedNodeType get genericFunctionType_type { assert(kind == idl.LinkedNodeKind.genericFunctionType); _variantField_25 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 25, null); return _variantField_25; } @override String get extensionDeclaration_refName { assert(kind == idl.LinkedNodeKind.extensionDeclaration); _variantField_20 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 20, ''); return _variantField_20; } @override String get namespaceDirective_selectedUri { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective); _variantField_20 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 20, ''); return _variantField_20; } @override String get simpleStringLiteral_value { assert(kind == idl.LinkedNodeKind.simpleStringLiteral); _variantField_20 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 20, ''); return _variantField_20; } @override List<idl.LinkedNodeType> get extensionOverride_typeArgumentTypes { assert(kind == idl.LinkedNodeKind.extensionOverride); _variantField_39 ??= const fb.ListReader<idl.LinkedNodeType>(const _LinkedNodeTypeReader()) .vTableGet(_bc, _bcOffset, 39, const <idl.LinkedNodeType>[]); return _variantField_39; } @override int get flags { _flags ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 18, 0); return _flags; } @override String get importDirective_prefix { assert(kind == idl.LinkedNodeKind.importDirective); _variantField_1 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _variantField_1; } @override int get informativeId { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective || kind == idl.LinkedNodeKind.showCombinator || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.topLevelVariableDeclaration || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration || kind == idl.LinkedNodeKind.variableDeclarationList); _variantField_36 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 36, 0); return _variantField_36; } @override int get integerLiteral_value { assert(kind == idl.LinkedNodeKind.integerLiteral); _variantField_16 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 16, 0); return _variantField_16; } @override String get interpolationString_value { assert(kind == idl.LinkedNodeKind.interpolationString); _variantField_30 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 30, ''); return _variantField_30; } @override idl.LinkedNode get invocationExpression_arguments { assert(kind == idl.LinkedNodeKind.functionExpressionInvocation || kind == idl.LinkedNodeKind.methodInvocation); _variantField_14 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 14, null); return _variantField_14; } @override idl.LinkedNode get uriBasedDirective_uri { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); _variantField_14 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 14, null); return _variantField_14; } @override idl.LinkedNodeKind get kind { _kind ??= const _LinkedNodeKindReader() .vTableGet(_bc, _bcOffset, 0, idl.LinkedNodeKind.adjacentStrings); return _kind; } @override List<String> get mixinDeclaration_superInvokedNames { assert(kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_34 ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 34, const <String>[]); return _variantField_34; } @override List<String> get names { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator || kind == idl.LinkedNodeKind.symbolLiteral); _variantField_34 ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 34, const <String>[]); return _variantField_34; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 37, ''); return _name; } @override bool get simplyBoundable_isSimplyBounded { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.mixinDeclaration); _variantField_31 ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 31, false); return _variantField_31; } @override idl.UnlinkedTokenType get spreadElement_spreadOperator { assert(kind == idl.LinkedNodeKind.spreadElement); _variantField_35 ??= const _UnlinkedTokenTypeReader() .vTableGet(_bc, _bcOffset, 35, idl.UnlinkedTokenType.NOTHING); return _variantField_35; } @override idl.TopLevelInferenceError get topLevelTypeInferenceError { assert(kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_32 ??= const _TopLevelInferenceErrorReader() .vTableGet(_bc, _bcOffset, 32, null); return _variantField_32; } @override idl.LinkedNodeType get typeName_type { assert(kind == idl.LinkedNodeKind.typeName); _variantField_23 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 23, null); return _variantField_23; } @override idl.LinkedNodeType get typeParameter_defaultType { assert(kind == idl.LinkedNodeKind.typeParameter); _variantField_23 ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 23, null); return _variantField_23; } @override idl.LinkedNode get unused11 { assert(kind == idl.LinkedNodeKind.classDeclaration); _variantField_11 ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 11, null); return _variantField_11; } @override String get uriBasedDirective_uriContent { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); _variantField_22 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 22, ''); return _variantField_22; } @override int get uriBasedDirective_uriElement { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.partDirective); _variantField_19 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 19, 0); return _variantField_19; } } abstract class _LinkedNodeMixin implements idl.LinkedNode { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (flags != 0) _result["flags"] = flags; if (kind != idl.LinkedNodeKind.adjacentStrings) _result["kind"] = kind.toString().split('.')[1]; if (name != '') _result["name"] = name; if (kind == idl.LinkedNodeKind.adjacentStrings) { if (adjacentStrings_strings.isNotEmpty) _result["adjacentStrings_strings"] = adjacentStrings_strings.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.annotation) { if (annotation_arguments != null) _result["annotation_arguments"] = annotation_arguments.toJson(); if (annotation_constructorName != null) _result["annotation_constructorName"] = annotation_constructorName.toJson(); if (annotation_element != 0) _result["annotation_element"] = annotation_element; if (annotation_name != null) _result["annotation_name"] = annotation_name.toJson(); if (annotation_substitution != null) _result["annotation_substitution"] = annotation_substitution.toJson(); } if (kind == idl.LinkedNodeKind.argumentList) { if (argumentList_arguments.isNotEmpty) _result["argumentList_arguments"] = argumentList_arguments.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.asExpression) { if (asExpression_expression != null) _result["asExpression_expression"] = asExpression_expression.toJson(); if (asExpression_type != null) _result["asExpression_type"] = asExpression_type.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.assertInitializer) { if (assertInitializer_condition != null) _result["assertInitializer_condition"] = assertInitializer_condition.toJson(); if (assertInitializer_message != null) _result["assertInitializer_message"] = assertInitializer_message.toJson(); } if (kind == idl.LinkedNodeKind.assertStatement) { if (assertStatement_condition != null) _result["assertStatement_condition"] = assertStatement_condition.toJson(); if (assertStatement_message != null) _result["assertStatement_message"] = assertStatement_message.toJson(); } if (kind == idl.LinkedNodeKind.assignmentExpression) { if (assignmentExpression_leftHandSide != null) _result["assignmentExpression_leftHandSide"] = assignmentExpression_leftHandSide.toJson(); if (assignmentExpression_rightHandSide != null) _result["assignmentExpression_rightHandSide"] = assignmentExpression_rightHandSide.toJson(); if (assignmentExpression_substitution != null) _result["assignmentExpression_substitution"] = assignmentExpression_substitution.toJson(); if (assignmentExpression_element != 0) _result["assignmentExpression_element"] = assignmentExpression_element; if (assignmentExpression_operator != idl.UnlinkedTokenType.NOTHING) _result["assignmentExpression_operator"] = assignmentExpression_operator.toString().split('.')[1]; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.awaitExpression) { if (awaitExpression_expression != null) _result["awaitExpression_expression"] = awaitExpression_expression.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.binaryExpression) { if (binaryExpression_invokeType != null) _result["binaryExpression_invokeType"] = binaryExpression_invokeType.toJson(); if (binaryExpression_leftOperand != null) _result["binaryExpression_leftOperand"] = binaryExpression_leftOperand.toJson(); if (binaryExpression_rightOperand != null) _result["binaryExpression_rightOperand"] = binaryExpression_rightOperand.toJson(); if (binaryExpression_substitution != null) _result["binaryExpression_substitution"] = binaryExpression_substitution.toJson(); if (binaryExpression_element != 0) _result["binaryExpression_element"] = binaryExpression_element; if (binaryExpression_operator != idl.UnlinkedTokenType.NOTHING) _result["binaryExpression_operator"] = binaryExpression_operator.toString().split('.')[1]; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.block) { if (block_statements.isNotEmpty) _result["block_statements"] = block_statements.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.blockFunctionBody) { if (blockFunctionBody_block != null) _result["blockFunctionBody_block"] = blockFunctionBody_block.toJson(); } if (kind == idl.LinkedNodeKind.booleanLiteral) { if (booleanLiteral_value != false) _result["booleanLiteral_value"] = booleanLiteral_value; } if (kind == idl.LinkedNodeKind.breakStatement) { if (breakStatement_label != null) _result["breakStatement_label"] = breakStatement_label.toJson(); } if (kind == idl.LinkedNodeKind.cascadeExpression) { if (cascadeExpression_sections.isNotEmpty) _result["cascadeExpression_sections"] = cascadeExpression_sections .map((_value) => _value.toJson()) .toList(); if (cascadeExpression_target != null) _result["cascadeExpression_target"] = cascadeExpression_target.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.catchClause) { if (catchClause_body != null) _result["catchClause_body"] = catchClause_body.toJson(); if (catchClause_exceptionParameter != null) _result["catchClause_exceptionParameter"] = catchClause_exceptionParameter.toJson(); if (catchClause_exceptionType != null) _result["catchClause_exceptionType"] = catchClause_exceptionType.toJson(); if (catchClause_stackTraceParameter != null) _result["catchClause_stackTraceParameter"] = catchClause_stackTraceParameter.toJson(); } if (kind == idl.LinkedNodeKind.classDeclaration) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (classDeclaration_extendsClause != null) _result["classDeclaration_extendsClause"] = classDeclaration_extendsClause.toJson(); if (classDeclaration_withClause != null) _result["classDeclaration_withClause"] = classDeclaration_withClause.toJson(); if (classDeclaration_nativeClause != null) _result["classDeclaration_nativeClause"] = classDeclaration_nativeClause.toJson(); if (classDeclaration_isDartObject != false) _result["classDeclaration_isDartObject"] = classDeclaration_isDartObject; if (classOrMixinDeclaration_implementsClause != null) _result["classOrMixinDeclaration_implementsClause"] = classOrMixinDeclaration_implementsClause.toJson(); if (classOrMixinDeclaration_members.isNotEmpty) _result["classOrMixinDeclaration_members"] = classOrMixinDeclaration_members .map((_value) => _value.toJson()) .toList(); if (classOrMixinDeclaration_typeParameters != null) _result["classOrMixinDeclaration_typeParameters"] = classOrMixinDeclaration_typeParameters.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; if (simplyBoundable_isSimplyBounded != false) _result["simplyBoundable_isSimplyBounded"] = simplyBoundable_isSimplyBounded; if (unused11 != null) _result["unused11"] = unused11.toJson(); } if (kind == idl.LinkedNodeKind.classTypeAlias) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (classTypeAlias_typeParameters != null) _result["classTypeAlias_typeParameters"] = classTypeAlias_typeParameters.toJson(); if (classTypeAlias_superclass != null) _result["classTypeAlias_superclass"] = classTypeAlias_superclass.toJson(); if (classTypeAlias_withClause != null) _result["classTypeAlias_withClause"] = classTypeAlias_withClause.toJson(); if (classTypeAlias_implementsClause != null) _result["classTypeAlias_implementsClause"] = classTypeAlias_implementsClause.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; if (simplyBoundable_isSimplyBounded != false) _result["simplyBoundable_isSimplyBounded"] = simplyBoundable_isSimplyBounded; } if (kind == idl.LinkedNodeKind.comment) { if (comment_references.isNotEmpty) _result["comment_references"] = comment_references.map((_value) => _value.toJson()).toList(); if (comment_tokens.isNotEmpty) _result["comment_tokens"] = comment_tokens; if (comment_type != idl.LinkedNodeCommentType.block) _result["comment_type"] = comment_type.toString().split('.')[1]; } if (kind == idl.LinkedNodeKind.commentReference) { if (commentReference_identifier != null) _result["commentReference_identifier"] = commentReference_identifier.toJson(); } if (kind == idl.LinkedNodeKind.compilationUnit) { if (compilationUnit_declarations.isNotEmpty) _result["compilationUnit_declarations"] = compilationUnit_declarations .map((_value) => _value.toJson()) .toList(); if (compilationUnit_scriptTag != null) _result["compilationUnit_scriptTag"] = compilationUnit_scriptTag.toJson(); if (compilationUnit_directives.isNotEmpty) _result["compilationUnit_directives"] = compilationUnit_directives .map((_value) => _value.toJson()) .toList(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.conditionalExpression) { if (conditionalExpression_condition != null) _result["conditionalExpression_condition"] = conditionalExpression_condition.toJson(); if (conditionalExpression_elseExpression != null) _result["conditionalExpression_elseExpression"] = conditionalExpression_elseExpression.toJson(); if (conditionalExpression_thenExpression != null) _result["conditionalExpression_thenExpression"] = conditionalExpression_thenExpression.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.configuration) { if (configuration_name != null) _result["configuration_name"] = configuration_name.toJson(); if (configuration_value != null) _result["configuration_value"] = configuration_value.toJson(); if (configuration_uri != null) _result["configuration_uri"] = configuration_uri.toJson(); } if (kind == idl.LinkedNodeKind.constructorDeclaration) { if (constructorDeclaration_initializers.isNotEmpty) _result["constructorDeclaration_initializers"] = constructorDeclaration_initializers .map((_value) => _value.toJson()) .toList(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (constructorDeclaration_body != null) _result["constructorDeclaration_body"] = constructorDeclaration_body.toJson(); if (constructorDeclaration_parameters != null) _result["constructorDeclaration_parameters"] = constructorDeclaration_parameters.toJson(); if (constructorDeclaration_redirectedConstructor != null) _result["constructorDeclaration_redirectedConstructor"] = constructorDeclaration_redirectedConstructor.toJson(); if (constructorDeclaration_returnType != null) _result["constructorDeclaration_returnType"] = constructorDeclaration_returnType.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.constructorFieldInitializer) { if (constructorFieldInitializer_expression != null) _result["constructorFieldInitializer_expression"] = constructorFieldInitializer_expression.toJson(); if (constructorFieldInitializer_fieldName != null) _result["constructorFieldInitializer_fieldName"] = constructorFieldInitializer_fieldName.toJson(); } if (kind == idl.LinkedNodeKind.constructorName) { if (constructorName_name != null) _result["constructorName_name"] = constructorName_name.toJson(); if (constructorName_type != null) _result["constructorName_type"] = constructorName_type.toJson(); if (constructorName_substitution != null) _result["constructorName_substitution"] = constructorName_substitution.toJson(); if (constructorName_element != 0) _result["constructorName_element"] = constructorName_element; } if (kind == idl.LinkedNodeKind.continueStatement) { if (continueStatement_label != null) _result["continueStatement_label"] = continueStatement_label.toJson(); } if (kind == idl.LinkedNodeKind.declaredIdentifier) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (declaredIdentifier_identifier != null) _result["declaredIdentifier_identifier"] = declaredIdentifier_identifier.toJson(); if (declaredIdentifier_type != null) _result["declaredIdentifier_type"] = declaredIdentifier_type.toJson(); } if (kind == idl.LinkedNodeKind.defaultFormalParameter) { if (defaultFormalParameter_defaultValue != null) _result["defaultFormalParameter_defaultValue"] = defaultFormalParameter_defaultValue.toJson(); if (defaultFormalParameter_parameter != null) _result["defaultFormalParameter_parameter"] = defaultFormalParameter_parameter.toJson(); if (defaultFormalParameter_kind != idl.LinkedNodeFormalParameterKind.requiredPositional) _result["defaultFormalParameter_kind"] = defaultFormalParameter_kind.toString().split('.')[1]; if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.doStatement) { if (doStatement_body != null) _result["doStatement_body"] = doStatement_body.toJson(); if (doStatement_condition != null) _result["doStatement_condition"] = doStatement_condition.toJson(); } if (kind == idl.LinkedNodeKind.dottedName) { if (dottedName_components.isNotEmpty) _result["dottedName_components"] = dottedName_components.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.doubleLiteral) { if (doubleLiteral_value != 0.0) _result["doubleLiteral_value"] = doubleLiteral_value.isFinite ? doubleLiteral_value : doubleLiteral_value.toString(); } if (kind == idl.LinkedNodeKind.emptyFunctionBody) { if (emptyFunctionBody_fake != 0) _result["emptyFunctionBody_fake"] = emptyFunctionBody_fake; } if (kind == idl.LinkedNodeKind.emptyStatement) { if (emptyStatement_fake != 0) _result["emptyStatement_fake"] = emptyStatement_fake; } if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.enumDeclaration) { if (enumDeclaration_constants.isNotEmpty) _result["enumDeclaration_constants"] = enumDeclaration_constants.map((_value) => _value.toJson()).toList(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.exportDirective) { if (namespaceDirective_combinators.isNotEmpty) _result["namespaceDirective_combinators"] = namespaceDirective_combinators .map((_value) => _value.toJson()) .toList(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (namespaceDirective_configurations.isNotEmpty) _result["namespaceDirective_configurations"] = namespaceDirective_configurations .map((_value) => _value.toJson()) .toList(); if (namespaceDirective_selectedUri != '') _result["namespaceDirective_selectedUri"] = namespaceDirective_selectedUri; if (informativeId != 0) _result["informativeId"] = informativeId; if (uriBasedDirective_uri != null) _result["uriBasedDirective_uri"] = uriBasedDirective_uri.toJson(); if (uriBasedDirective_uriContent != '') _result["uriBasedDirective_uriContent"] = uriBasedDirective_uriContent; if (uriBasedDirective_uriElement != 0) _result["uriBasedDirective_uriElement"] = uriBasedDirective_uriElement; } if (kind == idl.LinkedNodeKind.expressionFunctionBody) { if (expressionFunctionBody_expression != null) _result["expressionFunctionBody_expression"] = expressionFunctionBody_expression.toJson(); } if (kind == idl.LinkedNodeKind.expressionStatement) { if (expressionStatement_expression != null) _result["expressionStatement_expression"] = expressionStatement_expression.toJson(); } if (kind == idl.LinkedNodeKind.extendsClause) { if (extendsClause_superclass != null) _result["extendsClause_superclass"] = extendsClause_superclass.toJson(); } if (kind == idl.LinkedNodeKind.extensionDeclaration) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (extensionDeclaration_typeParameters != null) _result["extensionDeclaration_typeParameters"] = extensionDeclaration_typeParameters.toJson(); if (extensionDeclaration_extendedType != null) _result["extensionDeclaration_extendedType"] = extensionDeclaration_extendedType.toJson(); if (extensionDeclaration_members.isNotEmpty) _result["extensionDeclaration_members"] = extensionDeclaration_members .map((_value) => _value.toJson()) .toList(); if (extensionDeclaration_refName != '') _result["extensionDeclaration_refName"] = extensionDeclaration_refName; if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.extensionOverride) { if (extensionOverride_extendedType != null) _result["extensionOverride_extendedType"] = extensionOverride_extendedType.toJson(); if (extensionOverride_arguments.isNotEmpty) _result["extensionOverride_arguments"] = extensionOverride_arguments .map((_value) => _value.toJson()) .toList(); if (extensionOverride_extensionName != null) _result["extensionOverride_extensionName"] = extensionOverride_extensionName.toJson(); if (extensionOverride_typeArguments != null) _result["extensionOverride_typeArguments"] = extensionOverride_typeArguments.toJson(); if (extensionOverride_typeArgumentTypes.isNotEmpty) _result["extensionOverride_typeArgumentTypes"] = extensionOverride_typeArgumentTypes .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.fieldDeclaration) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (fieldDeclaration_fields != null) _result["fieldDeclaration_fields"] = fieldDeclaration_fields.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.fieldFormalParameter) { if (actualType != null) _result["actualType"] = actualType.toJson(); if (normalFormalParameter_metadata.isNotEmpty) _result["normalFormalParameter_metadata"] = normalFormalParameter_metadata .map((_value) => _value.toJson()) .toList(); if (fieldFormalParameter_type != null) _result["fieldFormalParameter_type"] = fieldFormalParameter_type.toJson(); if (fieldFormalParameter_typeParameters != null) _result["fieldFormalParameter_typeParameters"] = fieldFormalParameter_typeParameters.toJson(); if (fieldFormalParameter_formalParameters != null) _result["fieldFormalParameter_formalParameters"] = fieldFormalParameter_formalParameters.toJson(); if (inheritsCovariant != false) _result["inheritsCovariant"] = inheritsCovariant; if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.forEachPartsWithDeclaration) { if (forEachParts_iterable != null) _result["forEachParts_iterable"] = forEachParts_iterable.toJson(); if (forEachPartsWithDeclaration_loopVariable != null) _result["forEachPartsWithDeclaration_loopVariable"] = forEachPartsWithDeclaration_loopVariable.toJson(); } if (kind == idl.LinkedNodeKind.forEachPartsWithIdentifier) { if (forEachParts_iterable != null) _result["forEachParts_iterable"] = forEachParts_iterable.toJson(); if (forEachPartsWithIdentifier_identifier != null) _result["forEachPartsWithIdentifier_identifier"] = forEachPartsWithIdentifier_identifier.toJson(); } if (kind == idl.LinkedNodeKind.forElement) { if (forMixin_forLoopParts != null) _result["forMixin_forLoopParts"] = forMixin_forLoopParts.toJson(); if (forElement_body != null) _result["forElement_body"] = forElement_body.toJson(); } if (kind == idl.LinkedNodeKind.forPartsWithDeclarations) { if (forParts_condition != null) _result["forParts_condition"] = forParts_condition.toJson(); if (forPartsWithDeclarations_variables != null) _result["forPartsWithDeclarations_variables"] = forPartsWithDeclarations_variables.toJson(); if (forParts_updaters.isNotEmpty) _result["forParts_updaters"] = forParts_updaters.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.forPartsWithExpression) { if (forParts_condition != null) _result["forParts_condition"] = forParts_condition.toJson(); if (forPartsWithExpression_initialization != null) _result["forPartsWithExpression_initialization"] = forPartsWithExpression_initialization.toJson(); if (forParts_updaters.isNotEmpty) _result["forParts_updaters"] = forParts_updaters.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.forStatement) { if (forMixin_forLoopParts != null) _result["forMixin_forLoopParts"] = forMixin_forLoopParts.toJson(); if (forStatement_body != null) _result["forStatement_body"] = forStatement_body.toJson(); } if (kind == idl.LinkedNodeKind.formalParameterList) { if (formalParameterList_parameters.isNotEmpty) _result["formalParameterList_parameters"] = formalParameterList_parameters .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.functionDeclaration) { if (actualReturnType != null) _result["actualReturnType"] = actualReturnType.toJson(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (functionDeclaration_functionExpression != null) _result["functionDeclaration_functionExpression"] = functionDeclaration_functionExpression.toJson(); if (functionDeclaration_returnType != null) _result["functionDeclaration_returnType"] = functionDeclaration_returnType.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.functionDeclarationStatement) { if (functionDeclarationStatement_functionDeclaration != null) _result["functionDeclarationStatement_functionDeclaration"] = functionDeclarationStatement_functionDeclaration.toJson(); } if (kind == idl.LinkedNodeKind.functionExpression) { if (actualReturnType != null) _result["actualReturnType"] = actualReturnType.toJson(); if (functionExpression_body != null) _result["functionExpression_body"] = functionExpression_body.toJson(); if (functionExpression_formalParameters != null) _result["functionExpression_formalParameters"] = functionExpression_formalParameters.toJson(); if (functionExpression_typeParameters != null) _result["functionExpression_typeParameters"] = functionExpression_typeParameters.toJson(); } if (kind == idl.LinkedNodeKind.functionExpressionInvocation) { if (invocationExpression_invokeType != null) _result["invocationExpression_invokeType"] = invocationExpression_invokeType.toJson(); if (functionExpressionInvocation_function != null) _result["functionExpressionInvocation_function"] = functionExpressionInvocation_function.toJson(); if (invocationExpression_typeArguments != null) _result["invocationExpression_typeArguments"] = invocationExpression_typeArguments.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); if (invocationExpression_arguments != null) _result["invocationExpression_arguments"] = invocationExpression_arguments.toJson(); } if (kind == idl.LinkedNodeKind.functionTypeAlias) { if (actualReturnType != null) _result["actualReturnType"] = actualReturnType.toJson(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (functionTypeAlias_formalParameters != null) _result["functionTypeAlias_formalParameters"] = functionTypeAlias_formalParameters.toJson(); if (functionTypeAlias_returnType != null) _result["functionTypeAlias_returnType"] = functionTypeAlias_returnType.toJson(); if (functionTypeAlias_typeParameters != null) _result["functionTypeAlias_typeParameters"] = functionTypeAlias_typeParameters.toJson(); if (typeAlias_hasSelfReference != false) _result["typeAlias_hasSelfReference"] = typeAlias_hasSelfReference; if (informativeId != 0) _result["informativeId"] = informativeId; if (simplyBoundable_isSimplyBounded != false) _result["simplyBoundable_isSimplyBounded"] = simplyBoundable_isSimplyBounded; } if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { if (actualType != null) _result["actualType"] = actualType.toJson(); if (normalFormalParameter_metadata.isNotEmpty) _result["normalFormalParameter_metadata"] = normalFormalParameter_metadata .map((_value) => _value.toJson()) .toList(); if (functionTypedFormalParameter_formalParameters != null) _result["functionTypedFormalParameter_formalParameters"] = functionTypedFormalParameter_formalParameters.toJson(); if (functionTypedFormalParameter_returnType != null) _result["functionTypedFormalParameter_returnType"] = functionTypedFormalParameter_returnType.toJson(); if (functionTypedFormalParameter_typeParameters != null) _result["functionTypedFormalParameter_typeParameters"] = functionTypedFormalParameter_typeParameters.toJson(); if (inheritsCovariant != false) _result["inheritsCovariant"] = inheritsCovariant; if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.genericFunctionType) { if (actualReturnType != null) _result["actualReturnType"] = actualReturnType.toJson(); if (genericFunctionType_typeParameters != null) _result["genericFunctionType_typeParameters"] = genericFunctionType_typeParameters.toJson(); if (genericFunctionType_returnType != null) _result["genericFunctionType_returnType"] = genericFunctionType_returnType.toJson(); if (genericFunctionType_id != 0) _result["genericFunctionType_id"] = genericFunctionType_id; if (genericFunctionType_formalParameters != null) _result["genericFunctionType_formalParameters"] = genericFunctionType_formalParameters.toJson(); if (genericFunctionType_type != null) _result["genericFunctionType_type"] = genericFunctionType_type.toJson(); } if (kind == idl.LinkedNodeKind.genericTypeAlias) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (genericTypeAlias_typeParameters != null) _result["genericTypeAlias_typeParameters"] = genericTypeAlias_typeParameters.toJson(); if (genericTypeAlias_functionType != null) _result["genericTypeAlias_functionType"] = genericTypeAlias_functionType.toJson(); if (typeAlias_hasSelfReference != false) _result["typeAlias_hasSelfReference"] = typeAlias_hasSelfReference; if (informativeId != 0) _result["informativeId"] = informativeId; if (simplyBoundable_isSimplyBounded != false) _result["simplyBoundable_isSimplyBounded"] = simplyBoundable_isSimplyBounded; } if (kind == idl.LinkedNodeKind.hideCombinator) { if (informativeId != 0) _result["informativeId"] = informativeId; if (names.isNotEmpty) _result["names"] = names; } if (kind == idl.LinkedNodeKind.ifElement) { if (ifMixin_condition != null) _result["ifMixin_condition"] = ifMixin_condition.toJson(); if (ifElement_thenElement != null) _result["ifElement_thenElement"] = ifElement_thenElement.toJson(); if (ifElement_elseElement != null) _result["ifElement_elseElement"] = ifElement_elseElement.toJson(); } if (kind == idl.LinkedNodeKind.ifStatement) { if (ifMixin_condition != null) _result["ifMixin_condition"] = ifMixin_condition.toJson(); if (ifStatement_elseStatement != null) _result["ifStatement_elseStatement"] = ifStatement_elseStatement.toJson(); if (ifStatement_thenStatement != null) _result["ifStatement_thenStatement"] = ifStatement_thenStatement.toJson(); } if (kind == idl.LinkedNodeKind.implementsClause) { if (implementsClause_interfaces.isNotEmpty) _result["implementsClause_interfaces"] = implementsClause_interfaces .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.importDirective) { if (namespaceDirective_combinators.isNotEmpty) _result["namespaceDirective_combinators"] = namespaceDirective_combinators .map((_value) => _value.toJson()) .toList(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (namespaceDirective_configurations.isNotEmpty) _result["namespaceDirective_configurations"] = namespaceDirective_configurations .map((_value) => _value.toJson()) .toList(); if (namespaceDirective_selectedUri != '') _result["namespaceDirective_selectedUri"] = namespaceDirective_selectedUri; if (importDirective_prefix != '') _result["importDirective_prefix"] = importDirective_prefix; if (informativeId != 0) _result["informativeId"] = informativeId; if (uriBasedDirective_uri != null) _result["uriBasedDirective_uri"] = uriBasedDirective_uri.toJson(); if (uriBasedDirective_uriContent != '') _result["uriBasedDirective_uriContent"] = uriBasedDirective_uriContent; if (uriBasedDirective_uriElement != 0) _result["uriBasedDirective_uriElement"] = uriBasedDirective_uriElement; } if (kind == idl.LinkedNodeKind.indexExpression) { if (indexExpression_index != null) _result["indexExpression_index"] = indexExpression_index.toJson(); if (indexExpression_target != null) _result["indexExpression_target"] = indexExpression_target.toJson(); if (indexExpression_substitution != null) _result["indexExpression_substitution"] = indexExpression_substitution.toJson(); if (indexExpression_element != 0) _result["indexExpression_element"] = indexExpression_element; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.instanceCreationExpression) { if (instanceCreationExpression_arguments.isNotEmpty) _result["instanceCreationExpression_arguments"] = instanceCreationExpression_arguments .map((_value) => _value.toJson()) .toList(); if (instanceCreationExpression_constructorName != null) _result["instanceCreationExpression_constructorName"] = instanceCreationExpression_constructorName.toJson(); if (instanceCreationExpression_typeArguments != null) _result["instanceCreationExpression_typeArguments"] = instanceCreationExpression_typeArguments.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.integerLiteral) { if (expression_type != null) _result["expression_type"] = expression_type.toJson(); if (integerLiteral_value != 0) _result["integerLiteral_value"] = integerLiteral_value; } if (kind == idl.LinkedNodeKind.interpolationExpression) { if (interpolationExpression_expression != null) _result["interpolationExpression_expression"] = interpolationExpression_expression.toJson(); } if (kind == idl.LinkedNodeKind.interpolationString) { if (interpolationString_value != '') _result["interpolationString_value"] = interpolationString_value; } if (kind == idl.LinkedNodeKind.isExpression) { if (isExpression_expression != null) _result["isExpression_expression"] = isExpression_expression.toJson(); if (isExpression_type != null) _result["isExpression_type"] = isExpression_type.toJson(); } if (kind == idl.LinkedNodeKind.label) { if (label_label != null) _result["label_label"] = label_label.toJson(); } if (kind == idl.LinkedNodeKind.labeledStatement) { if (labeledStatement_labels.isNotEmpty) _result["labeledStatement_labels"] = labeledStatement_labels.map((_value) => _value.toJson()).toList(); if (labeledStatement_statement != null) _result["labeledStatement_statement"] = labeledStatement_statement.toJson(); } if (kind == idl.LinkedNodeKind.libraryDirective) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (libraryDirective_name != null) _result["libraryDirective_name"] = libraryDirective_name.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.libraryIdentifier) { if (libraryIdentifier_components.isNotEmpty) _result["libraryIdentifier_components"] = libraryIdentifier_components .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.listLiteral) { if (typedLiteral_typeArguments.isNotEmpty) _result["typedLiteral_typeArguments"] = typedLiteral_typeArguments .map((_value) => _value.toJson()) .toList(); if (listLiteral_elements.isNotEmpty) _result["listLiteral_elements"] = listLiteral_elements.map((_value) => _value.toJson()).toList(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.mapLiteralEntry) { if (mapLiteralEntry_key != null) _result["mapLiteralEntry_key"] = mapLiteralEntry_key.toJson(); if (mapLiteralEntry_value != null) _result["mapLiteralEntry_value"] = mapLiteralEntry_value.toJson(); } if (kind == idl.LinkedNodeKind.methodDeclaration) { if (actualReturnType != null) _result["actualReturnType"] = actualReturnType.toJson(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (methodDeclaration_body != null) _result["methodDeclaration_body"] = methodDeclaration_body.toJson(); if (methodDeclaration_formalParameters != null) _result["methodDeclaration_formalParameters"] = methodDeclaration_formalParameters.toJson(); if (methodDeclaration_returnType != null) _result["methodDeclaration_returnType"] = methodDeclaration_returnType.toJson(); if (methodDeclaration_typeParameters != null) _result["methodDeclaration_typeParameters"] = methodDeclaration_typeParameters.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.methodInvocation) { if (invocationExpression_invokeType != null) _result["invocationExpression_invokeType"] = invocationExpression_invokeType.toJson(); if (methodInvocation_methodName != null) _result["methodInvocation_methodName"] = methodInvocation_methodName.toJson(); if (methodInvocation_target != null) _result["methodInvocation_target"] = methodInvocation_target.toJson(); if (invocationExpression_typeArguments != null) _result["invocationExpression_typeArguments"] = invocationExpression_typeArguments.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); if (invocationExpression_arguments != null) _result["invocationExpression_arguments"] = invocationExpression_arguments.toJson(); } if (kind == idl.LinkedNodeKind.mixinDeclaration) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (mixinDeclaration_onClause != null) _result["mixinDeclaration_onClause"] = mixinDeclaration_onClause.toJson(); if (classOrMixinDeclaration_implementsClause != null) _result["classOrMixinDeclaration_implementsClause"] = classOrMixinDeclaration_implementsClause.toJson(); if (classOrMixinDeclaration_members.isNotEmpty) _result["classOrMixinDeclaration_members"] = classOrMixinDeclaration_members .map((_value) => _value.toJson()) .toList(); if (classOrMixinDeclaration_typeParameters != null) _result["classOrMixinDeclaration_typeParameters"] = classOrMixinDeclaration_typeParameters.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; if (mixinDeclaration_superInvokedNames.isNotEmpty) _result["mixinDeclaration_superInvokedNames"] = mixinDeclaration_superInvokedNames; if (simplyBoundable_isSimplyBounded != false) _result["simplyBoundable_isSimplyBounded"] = simplyBoundable_isSimplyBounded; } if (kind == idl.LinkedNodeKind.namedExpression) { if (namedExpression_expression != null) _result["namedExpression_expression"] = namedExpression_expression.toJson(); if (namedExpression_name != null) _result["namedExpression_name"] = namedExpression_name.toJson(); } if (kind == idl.LinkedNodeKind.nativeClause) { if (nativeClause_name != null) _result["nativeClause_name"] = nativeClause_name.toJson(); } if (kind == idl.LinkedNodeKind.nativeFunctionBody) { if (nativeFunctionBody_stringLiteral != null) _result["nativeFunctionBody_stringLiteral"] = nativeFunctionBody_stringLiteral.toJson(); } if (kind == idl.LinkedNodeKind.nullLiteral) { if (nullLiteral_fake != 0) _result["nullLiteral_fake"] = nullLiteral_fake; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.onClause) { if (onClause_superclassConstraints.isNotEmpty) _result["onClause_superclassConstraints"] = onClause_superclassConstraints .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.parenthesizedExpression) { if (parenthesizedExpression_expression != null) _result["parenthesizedExpression_expression"] = parenthesizedExpression_expression.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.partDirective) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (informativeId != 0) _result["informativeId"] = informativeId; if (uriBasedDirective_uri != null) _result["uriBasedDirective_uri"] = uriBasedDirective_uri.toJson(); if (uriBasedDirective_uriContent != '') _result["uriBasedDirective_uriContent"] = uriBasedDirective_uriContent; if (uriBasedDirective_uriElement != 0) _result["uriBasedDirective_uriElement"] = uriBasedDirective_uriElement; } if (kind == idl.LinkedNodeKind.partOfDirective) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (partOfDirective_libraryName != null) _result["partOfDirective_libraryName"] = partOfDirective_libraryName.toJson(); if (partOfDirective_uri != null) _result["partOfDirective_uri"] = partOfDirective_uri.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.postfixExpression) { if (postfixExpression_operand != null) _result["postfixExpression_operand"] = postfixExpression_operand.toJson(); if (postfixExpression_substitution != null) _result["postfixExpression_substitution"] = postfixExpression_substitution.toJson(); if (postfixExpression_element != 0) _result["postfixExpression_element"] = postfixExpression_element; if (postfixExpression_operator != idl.UnlinkedTokenType.NOTHING) _result["postfixExpression_operator"] = postfixExpression_operator.toString().split('.')[1]; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.prefixExpression) { if (prefixExpression_operand != null) _result["prefixExpression_operand"] = prefixExpression_operand.toJson(); if (prefixExpression_substitution != null) _result["prefixExpression_substitution"] = prefixExpression_substitution.toJson(); if (prefixExpression_element != 0) _result["prefixExpression_element"] = prefixExpression_element; if (prefixExpression_operator != idl.UnlinkedTokenType.NOTHING) _result["prefixExpression_operator"] = prefixExpression_operator.toString().split('.')[1]; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.prefixedIdentifier) { if (prefixedIdentifier_identifier != null) _result["prefixedIdentifier_identifier"] = prefixedIdentifier_identifier.toJson(); if (prefixedIdentifier_prefix != null) _result["prefixedIdentifier_prefix"] = prefixedIdentifier_prefix.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.propertyAccess) { if (propertyAccess_propertyName != null) _result["propertyAccess_propertyName"] = propertyAccess_propertyName.toJson(); if (propertyAccess_target != null) _result["propertyAccess_target"] = propertyAccess_target.toJson(); if (propertyAccess_operator != idl.UnlinkedTokenType.NOTHING) _result["propertyAccess_operator"] = propertyAccess_operator.toString().split('.')[1]; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.redirectingConstructorInvocation) { if (redirectingConstructorInvocation_arguments != null) _result["redirectingConstructorInvocation_arguments"] = redirectingConstructorInvocation_arguments.toJson(); if (redirectingConstructorInvocation_constructorName != null) _result["redirectingConstructorInvocation_constructorName"] = redirectingConstructorInvocation_constructorName.toJson(); if (redirectingConstructorInvocation_substitution != null) _result["redirectingConstructorInvocation_substitution"] = redirectingConstructorInvocation_substitution.toJson(); if (redirectingConstructorInvocation_element != 0) _result["redirectingConstructorInvocation_element"] = redirectingConstructorInvocation_element; } if (kind == idl.LinkedNodeKind.rethrowExpression) { if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.returnStatement) { if (returnStatement_expression != null) _result["returnStatement_expression"] = returnStatement_expression.toJson(); } if (kind == idl.LinkedNodeKind.setOrMapLiteral) { if (typedLiteral_typeArguments.isNotEmpty) _result["typedLiteral_typeArguments"] = typedLiteral_typeArguments .map((_value) => _value.toJson()) .toList(); if (setOrMapLiteral_elements.isNotEmpty) _result["setOrMapLiteral_elements"] = setOrMapLiteral_elements.map((_value) => _value.toJson()).toList(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.showCombinator) { if (informativeId != 0) _result["informativeId"] = informativeId; if (names.isNotEmpty) _result["names"] = names; } if (kind == idl.LinkedNodeKind.simpleFormalParameter) { if (actualType != null) _result["actualType"] = actualType.toJson(); if (normalFormalParameter_metadata.isNotEmpty) _result["normalFormalParameter_metadata"] = normalFormalParameter_metadata .map((_value) => _value.toJson()) .toList(); if (simpleFormalParameter_type != null) _result["simpleFormalParameter_type"] = simpleFormalParameter_type.toJson(); if (inheritsCovariant != false) _result["inheritsCovariant"] = inheritsCovariant; if (informativeId != 0) _result["informativeId"] = informativeId; if (topLevelTypeInferenceError != null) _result["topLevelTypeInferenceError"] = topLevelTypeInferenceError.toJson(); } if (kind == idl.LinkedNodeKind.simpleIdentifier) { if (simpleIdentifier_substitution != null) _result["simpleIdentifier_substitution"] = simpleIdentifier_substitution.toJson(); if (simpleIdentifier_element != 0) _result["simpleIdentifier_element"] = simpleIdentifier_element; if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.simpleStringLiteral) { if (simpleStringLiteral_value != '') _result["simpleStringLiteral_value"] = simpleStringLiteral_value; } if (kind == idl.LinkedNodeKind.spreadElement) { if (spreadElement_expression != null) _result["spreadElement_expression"] = spreadElement_expression.toJson(); if (spreadElement_spreadOperator != idl.UnlinkedTokenType.NOTHING) _result["spreadElement_spreadOperator"] = spreadElement_spreadOperator.toString().split('.')[1]; } if (kind == idl.LinkedNodeKind.stringInterpolation) { if (stringInterpolation_elements.isNotEmpty) _result["stringInterpolation_elements"] = stringInterpolation_elements .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.superConstructorInvocation) { if (superConstructorInvocation_arguments != null) _result["superConstructorInvocation_arguments"] = superConstructorInvocation_arguments.toJson(); if (superConstructorInvocation_constructorName != null) _result["superConstructorInvocation_constructorName"] = superConstructorInvocation_constructorName.toJson(); if (superConstructorInvocation_substitution != null) _result["superConstructorInvocation_substitution"] = superConstructorInvocation_substitution.toJson(); if (superConstructorInvocation_element != 0) _result["superConstructorInvocation_element"] = superConstructorInvocation_element; } if (kind == idl.LinkedNodeKind.superExpression) { if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.switchCase) { if (switchMember_statements.isNotEmpty) _result["switchMember_statements"] = switchMember_statements.map((_value) => _value.toJson()).toList(); if (switchCase_expression != null) _result["switchCase_expression"] = switchCase_expression.toJson(); if (switchMember_labels.isNotEmpty) _result["switchMember_labels"] = switchMember_labels.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.switchDefault) { if (switchMember_statements.isNotEmpty) _result["switchMember_statements"] = switchMember_statements.map((_value) => _value.toJson()).toList(); if (switchMember_labels.isNotEmpty) _result["switchMember_labels"] = switchMember_labels.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.switchStatement) { if (switchStatement_members.isNotEmpty) _result["switchStatement_members"] = switchStatement_members.map((_value) => _value.toJson()).toList(); if (switchStatement_expression != null) _result["switchStatement_expression"] = switchStatement_expression.toJson(); } if (kind == idl.LinkedNodeKind.symbolLiteral) { if (expression_type != null) _result["expression_type"] = expression_type.toJson(); if (names.isNotEmpty) _result["names"] = names; } if (kind == idl.LinkedNodeKind.thisExpression) { if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.throwExpression) { if (throwExpression_expression != null) _result["throwExpression_expression"] = throwExpression_expression.toJson(); if (expression_type != null) _result["expression_type"] = expression_type.toJson(); } if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (topLevelVariableDeclaration_variableList != null) _result["topLevelVariableDeclaration_variableList"] = topLevelVariableDeclaration_variableList.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.tryStatement) { if (tryStatement_catchClauses.isNotEmpty) _result["tryStatement_catchClauses"] = tryStatement_catchClauses.map((_value) => _value.toJson()).toList(); if (tryStatement_body != null) _result["tryStatement_body"] = tryStatement_body.toJson(); if (tryStatement_finallyBlock != null) _result["tryStatement_finallyBlock"] = tryStatement_finallyBlock.toJson(); } if (kind == idl.LinkedNodeKind.typeArgumentList) { if (typeArgumentList_arguments.isNotEmpty) _result["typeArgumentList_arguments"] = typeArgumentList_arguments .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.typeName) { if (typeName_typeArguments.isNotEmpty) _result["typeName_typeArguments"] = typeName_typeArguments.map((_value) => _value.toJson()).toList(); if (typeName_name != null) _result["typeName_name"] = typeName_name.toJson(); if (typeName_type != null) _result["typeName_type"] = typeName_type.toJson(); } if (kind == idl.LinkedNodeKind.typeParameter) { if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (typeParameter_bound != null) _result["typeParameter_bound"] = typeParameter_bound.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; if (typeParameter_defaultType != null) _result["typeParameter_defaultType"] = typeParameter_defaultType.toJson(); } if (kind == idl.LinkedNodeKind.typeParameterList) { if (typeParameterList_typeParameters.isNotEmpty) _result["typeParameterList_typeParameters"] = typeParameterList_typeParameters .map((_value) => _value.toJson()) .toList(); } if (kind == idl.LinkedNodeKind.variableDeclaration) { if (actualType != null) _result["actualType"] = actualType.toJson(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (variableDeclaration_initializer != null) _result["variableDeclaration_initializer"] = variableDeclaration_initializer.toJson(); if (inheritsCovariant != false) _result["inheritsCovariant"] = inheritsCovariant; if (informativeId != 0) _result["informativeId"] = informativeId; if (topLevelTypeInferenceError != null) _result["topLevelTypeInferenceError"] = topLevelTypeInferenceError.toJson(); } if (kind == idl.LinkedNodeKind.variableDeclarationList) { if (variableDeclarationList_variables.isNotEmpty) _result["variableDeclarationList_variables"] = variableDeclarationList_variables .map((_value) => _value.toJson()) .toList(); if (annotatedNode_metadata.isNotEmpty) _result["annotatedNode_metadata"] = annotatedNode_metadata.map((_value) => _value.toJson()).toList(); if (variableDeclarationList_type != null) _result["variableDeclarationList_type"] = variableDeclarationList_type.toJson(); if (informativeId != 0) _result["informativeId"] = informativeId; } if (kind == idl.LinkedNodeKind.variableDeclarationStatement) { if (variableDeclarationStatement_variables != null) _result["variableDeclarationStatement_variables"] = variableDeclarationStatement_variables.toJson(); } if (kind == idl.LinkedNodeKind.whileStatement) { if (whileStatement_body != null) _result["whileStatement_body"] = whileStatement_body.toJson(); if (whileStatement_condition != null) _result["whileStatement_condition"] = whileStatement_condition.toJson(); } if (kind == idl.LinkedNodeKind.withClause) { if (withClause_mixinTypes.isNotEmpty) _result["withClause_mixinTypes"] = withClause_mixinTypes.map((_value) => _value.toJson()).toList(); } if (kind == idl.LinkedNodeKind.yieldStatement) { if (yieldStatement_expression != null) _result["yieldStatement_expression"] = yieldStatement_expression.toJson(); } return _result; } @override Map<String, Object> toMap() { if (kind == idl.LinkedNodeKind.adjacentStrings) { return { "adjacentStrings_strings": adjacentStrings_strings, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.annotation) { return { "annotation_arguments": annotation_arguments, "annotation_constructorName": annotation_constructorName, "annotation_element": annotation_element, "annotation_name": annotation_name, "annotation_substitution": annotation_substitution, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.argumentList) { return { "argumentList_arguments": argumentList_arguments, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.asExpression) { return { "asExpression_expression": asExpression_expression, "asExpression_type": asExpression_type, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.assertInitializer) { return { "assertInitializer_condition": assertInitializer_condition, "assertInitializer_message": assertInitializer_message, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.assertStatement) { return { "assertStatement_condition": assertStatement_condition, "assertStatement_message": assertStatement_message, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.assignmentExpression) { return { "assignmentExpression_leftHandSide": assignmentExpression_leftHandSide, "assignmentExpression_rightHandSide": assignmentExpression_rightHandSide, "assignmentExpression_substitution": assignmentExpression_substitution, "assignmentExpression_element": assignmentExpression_element, "assignmentExpression_operator": assignmentExpression_operator, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.awaitExpression) { return { "awaitExpression_expression": awaitExpression_expression, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.binaryExpression) { return { "binaryExpression_invokeType": binaryExpression_invokeType, "binaryExpression_leftOperand": binaryExpression_leftOperand, "binaryExpression_rightOperand": binaryExpression_rightOperand, "binaryExpression_substitution": binaryExpression_substitution, "binaryExpression_element": binaryExpression_element, "binaryExpression_operator": binaryExpression_operator, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.block) { return { "block_statements": block_statements, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.blockFunctionBody) { return { "blockFunctionBody_block": blockFunctionBody_block, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.booleanLiteral) { return { "booleanLiteral_value": booleanLiteral_value, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.breakStatement) { return { "breakStatement_label": breakStatement_label, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.cascadeExpression) { return { "cascadeExpression_sections": cascadeExpression_sections, "cascadeExpression_target": cascadeExpression_target, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.catchClause) { return { "catchClause_body": catchClause_body, "catchClause_exceptionParameter": catchClause_exceptionParameter, "catchClause_exceptionType": catchClause_exceptionType, "catchClause_stackTraceParameter": catchClause_stackTraceParameter, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.classDeclaration) { return { "annotatedNode_metadata": annotatedNode_metadata, "classDeclaration_extendsClause": classDeclaration_extendsClause, "classDeclaration_withClause": classDeclaration_withClause, "classDeclaration_nativeClause": classDeclaration_nativeClause, "classDeclaration_isDartObject": classDeclaration_isDartObject, "classOrMixinDeclaration_implementsClause": classOrMixinDeclaration_implementsClause, "classOrMixinDeclaration_members": classOrMixinDeclaration_members, "classOrMixinDeclaration_typeParameters": classOrMixinDeclaration_typeParameters, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "simplyBoundable_isSimplyBounded": simplyBoundable_isSimplyBounded, "unused11": unused11, }; } if (kind == idl.LinkedNodeKind.classTypeAlias) { return { "annotatedNode_metadata": annotatedNode_metadata, "classTypeAlias_typeParameters": classTypeAlias_typeParameters, "classTypeAlias_superclass": classTypeAlias_superclass, "classTypeAlias_withClause": classTypeAlias_withClause, "classTypeAlias_implementsClause": classTypeAlias_implementsClause, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "simplyBoundable_isSimplyBounded": simplyBoundable_isSimplyBounded, }; } if (kind == idl.LinkedNodeKind.comment) { return { "comment_references": comment_references, "comment_tokens": comment_tokens, "comment_type": comment_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.commentReference) { return { "commentReference_identifier": commentReference_identifier, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.compilationUnit) { return { "compilationUnit_declarations": compilationUnit_declarations, "compilationUnit_scriptTag": compilationUnit_scriptTag, "compilationUnit_directives": compilationUnit_directives, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.conditionalExpression) { return { "conditionalExpression_condition": conditionalExpression_condition, "conditionalExpression_elseExpression": conditionalExpression_elseExpression, "conditionalExpression_thenExpression": conditionalExpression_thenExpression, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.configuration) { return { "configuration_name": configuration_name, "configuration_value": configuration_value, "configuration_uri": configuration_uri, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.constructorDeclaration) { return { "constructorDeclaration_initializers": constructorDeclaration_initializers, "annotatedNode_metadata": annotatedNode_metadata, "constructorDeclaration_body": constructorDeclaration_body, "constructorDeclaration_parameters": constructorDeclaration_parameters, "constructorDeclaration_redirectedConstructor": constructorDeclaration_redirectedConstructor, "constructorDeclaration_returnType": constructorDeclaration_returnType, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.constructorFieldInitializer) { return { "constructorFieldInitializer_expression": constructorFieldInitializer_expression, "constructorFieldInitializer_fieldName": constructorFieldInitializer_fieldName, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.constructorName) { return { "constructorName_name": constructorName_name, "constructorName_type": constructorName_type, "constructorName_substitution": constructorName_substitution, "constructorName_element": constructorName_element, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.continueStatement) { return { "continueStatement_label": continueStatement_label, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.declaredIdentifier) { return { "annotatedNode_metadata": annotatedNode_metadata, "declaredIdentifier_identifier": declaredIdentifier_identifier, "declaredIdentifier_type": declaredIdentifier_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.defaultFormalParameter) { return { "defaultFormalParameter_defaultValue": defaultFormalParameter_defaultValue, "defaultFormalParameter_parameter": defaultFormalParameter_parameter, "defaultFormalParameter_kind": defaultFormalParameter_kind, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.doStatement) { return { "doStatement_body": doStatement_body, "doStatement_condition": doStatement_condition, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.dottedName) { return { "dottedName_components": dottedName_components, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.doubleLiteral) { return { "doubleLiteral_value": doubleLiteral_value, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.emptyFunctionBody) { return { "emptyFunctionBody_fake": emptyFunctionBody_fake, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.emptyStatement) { return { "emptyStatement_fake": emptyStatement_fake, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { return { "annotatedNode_metadata": annotatedNode_metadata, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.enumDeclaration) { return { "enumDeclaration_constants": enumDeclaration_constants, "annotatedNode_metadata": annotatedNode_metadata, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.exportDirective) { return { "namespaceDirective_combinators": namespaceDirective_combinators, "annotatedNode_metadata": annotatedNode_metadata, "namespaceDirective_configurations": namespaceDirective_configurations, "namespaceDirective_selectedUri": namespaceDirective_selectedUri, "flags": flags, "informativeId": informativeId, "uriBasedDirective_uri": uriBasedDirective_uri, "kind": kind, "name": name, "uriBasedDirective_uriContent": uriBasedDirective_uriContent, "uriBasedDirective_uriElement": uriBasedDirective_uriElement, }; } if (kind == idl.LinkedNodeKind.expressionFunctionBody) { return { "expressionFunctionBody_expression": expressionFunctionBody_expression, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.expressionStatement) { return { "expressionStatement_expression": expressionStatement_expression, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.extendsClause) { return { "extendsClause_superclass": extendsClause_superclass, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.extensionDeclaration) { return { "annotatedNode_metadata": annotatedNode_metadata, "extensionDeclaration_typeParameters": extensionDeclaration_typeParameters, "extensionDeclaration_extendedType": extensionDeclaration_extendedType, "extensionDeclaration_members": extensionDeclaration_members, "extensionDeclaration_refName": extensionDeclaration_refName, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.extensionOverride) { return { "extensionOverride_extendedType": extensionOverride_extendedType, "extensionOverride_arguments": extensionOverride_arguments, "extensionOverride_extensionName": extensionOverride_extensionName, "extensionOverride_typeArguments": extensionOverride_typeArguments, "extensionOverride_typeArgumentTypes": extensionOverride_typeArgumentTypes, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.fieldDeclaration) { return { "annotatedNode_metadata": annotatedNode_metadata, "fieldDeclaration_fields": fieldDeclaration_fields, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.fieldFormalParameter) { return { "actualType": actualType, "normalFormalParameter_metadata": normalFormalParameter_metadata, "fieldFormalParameter_type": fieldFormalParameter_type, "fieldFormalParameter_typeParameters": fieldFormalParameter_typeParameters, "fieldFormalParameter_formalParameters": fieldFormalParameter_formalParameters, "inheritsCovariant": inheritsCovariant, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.forEachPartsWithDeclaration) { return { "forEachParts_iterable": forEachParts_iterable, "forEachPartsWithDeclaration_loopVariable": forEachPartsWithDeclaration_loopVariable, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.forEachPartsWithIdentifier) { return { "forEachParts_iterable": forEachParts_iterable, "forEachPartsWithIdentifier_identifier": forEachPartsWithIdentifier_identifier, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.forElement) { return { "forMixin_forLoopParts": forMixin_forLoopParts, "forElement_body": forElement_body, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.forPartsWithDeclarations) { return { "forParts_condition": forParts_condition, "forPartsWithDeclarations_variables": forPartsWithDeclarations_variables, "forParts_updaters": forParts_updaters, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.forPartsWithExpression) { return { "forParts_condition": forParts_condition, "forPartsWithExpression_initialization": forPartsWithExpression_initialization, "forParts_updaters": forParts_updaters, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.forStatement) { return { "forMixin_forLoopParts": forMixin_forLoopParts, "forStatement_body": forStatement_body, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.formalParameterList) { return { "formalParameterList_parameters": formalParameterList_parameters, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.functionDeclaration) { return { "actualReturnType": actualReturnType, "annotatedNode_metadata": annotatedNode_metadata, "functionDeclaration_functionExpression": functionDeclaration_functionExpression, "functionDeclaration_returnType": functionDeclaration_returnType, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.functionDeclarationStatement) { return { "functionDeclarationStatement_functionDeclaration": functionDeclarationStatement_functionDeclaration, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.functionExpression) { return { "actualReturnType": actualReturnType, "functionExpression_body": functionExpression_body, "functionExpression_formalParameters": functionExpression_formalParameters, "functionExpression_typeParameters": functionExpression_typeParameters, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.functionExpressionInvocation) { return { "invocationExpression_invokeType": invocationExpression_invokeType, "functionExpressionInvocation_function": functionExpressionInvocation_function, "invocationExpression_typeArguments": invocationExpression_typeArguments, "expression_type": expression_type, "flags": flags, "invocationExpression_arguments": invocationExpression_arguments, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.functionTypeAlias) { return { "actualReturnType": actualReturnType, "annotatedNode_metadata": annotatedNode_metadata, "functionTypeAlias_formalParameters": functionTypeAlias_formalParameters, "functionTypeAlias_returnType": functionTypeAlias_returnType, "functionTypeAlias_typeParameters": functionTypeAlias_typeParameters, "typeAlias_hasSelfReference": typeAlias_hasSelfReference, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "simplyBoundable_isSimplyBounded": simplyBoundable_isSimplyBounded, }; } if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { return { "actualType": actualType, "normalFormalParameter_metadata": normalFormalParameter_metadata, "functionTypedFormalParameter_formalParameters": functionTypedFormalParameter_formalParameters, "functionTypedFormalParameter_returnType": functionTypedFormalParameter_returnType, "functionTypedFormalParameter_typeParameters": functionTypedFormalParameter_typeParameters, "inheritsCovariant": inheritsCovariant, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.genericFunctionType) { return { "actualReturnType": actualReturnType, "genericFunctionType_typeParameters": genericFunctionType_typeParameters, "genericFunctionType_returnType": genericFunctionType_returnType, "genericFunctionType_id": genericFunctionType_id, "genericFunctionType_formalParameters": genericFunctionType_formalParameters, "genericFunctionType_type": genericFunctionType_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.genericTypeAlias) { return { "annotatedNode_metadata": annotatedNode_metadata, "genericTypeAlias_typeParameters": genericTypeAlias_typeParameters, "genericTypeAlias_functionType": genericTypeAlias_functionType, "typeAlias_hasSelfReference": typeAlias_hasSelfReference, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "simplyBoundable_isSimplyBounded": simplyBoundable_isSimplyBounded, }; } if (kind == idl.LinkedNodeKind.hideCombinator) { return { "flags": flags, "informativeId": informativeId, "kind": kind, "names": names, "name": name, }; } if (kind == idl.LinkedNodeKind.ifElement) { return { "ifMixin_condition": ifMixin_condition, "ifElement_thenElement": ifElement_thenElement, "ifElement_elseElement": ifElement_elseElement, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.ifStatement) { return { "ifMixin_condition": ifMixin_condition, "ifStatement_elseStatement": ifStatement_elseStatement, "ifStatement_thenStatement": ifStatement_thenStatement, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.implementsClause) { return { "implementsClause_interfaces": implementsClause_interfaces, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.importDirective) { return { "namespaceDirective_combinators": namespaceDirective_combinators, "annotatedNode_metadata": annotatedNode_metadata, "namespaceDirective_configurations": namespaceDirective_configurations, "namespaceDirective_selectedUri": namespaceDirective_selectedUri, "flags": flags, "importDirective_prefix": importDirective_prefix, "informativeId": informativeId, "uriBasedDirective_uri": uriBasedDirective_uri, "kind": kind, "name": name, "uriBasedDirective_uriContent": uriBasedDirective_uriContent, "uriBasedDirective_uriElement": uriBasedDirective_uriElement, }; } if (kind == idl.LinkedNodeKind.indexExpression) { return { "indexExpression_index": indexExpression_index, "indexExpression_target": indexExpression_target, "indexExpression_substitution": indexExpression_substitution, "indexExpression_element": indexExpression_element, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.instanceCreationExpression) { return { "instanceCreationExpression_arguments": instanceCreationExpression_arguments, "instanceCreationExpression_constructorName": instanceCreationExpression_constructorName, "instanceCreationExpression_typeArguments": instanceCreationExpression_typeArguments, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.integerLiteral) { return { "expression_type": expression_type, "flags": flags, "integerLiteral_value": integerLiteral_value, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.interpolationExpression) { return { "interpolationExpression_expression": interpolationExpression_expression, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.interpolationString) { return { "flags": flags, "interpolationString_value": interpolationString_value, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.isExpression) { return { "isExpression_expression": isExpression_expression, "isExpression_type": isExpression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.label) { return { "label_label": label_label, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.labeledStatement) { return { "labeledStatement_labels": labeledStatement_labels, "labeledStatement_statement": labeledStatement_statement, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.libraryDirective) { return { "annotatedNode_metadata": annotatedNode_metadata, "libraryDirective_name": libraryDirective_name, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.libraryIdentifier) { return { "libraryIdentifier_components": libraryIdentifier_components, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.listLiteral) { return { "typedLiteral_typeArguments": typedLiteral_typeArguments, "listLiteral_elements": listLiteral_elements, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.mapLiteralEntry) { return { "mapLiteralEntry_key": mapLiteralEntry_key, "mapLiteralEntry_value": mapLiteralEntry_value, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.methodDeclaration) { return { "actualReturnType": actualReturnType, "annotatedNode_metadata": annotatedNode_metadata, "methodDeclaration_body": methodDeclaration_body, "methodDeclaration_formalParameters": methodDeclaration_formalParameters, "methodDeclaration_returnType": methodDeclaration_returnType, "methodDeclaration_typeParameters": methodDeclaration_typeParameters, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.methodInvocation) { return { "invocationExpression_invokeType": invocationExpression_invokeType, "methodInvocation_methodName": methodInvocation_methodName, "methodInvocation_target": methodInvocation_target, "invocationExpression_typeArguments": invocationExpression_typeArguments, "expression_type": expression_type, "flags": flags, "invocationExpression_arguments": invocationExpression_arguments, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.mixinDeclaration) { return { "annotatedNode_metadata": annotatedNode_metadata, "mixinDeclaration_onClause": mixinDeclaration_onClause, "classOrMixinDeclaration_implementsClause": classOrMixinDeclaration_implementsClause, "classOrMixinDeclaration_members": classOrMixinDeclaration_members, "classOrMixinDeclaration_typeParameters": classOrMixinDeclaration_typeParameters, "flags": flags, "informativeId": informativeId, "kind": kind, "mixinDeclaration_superInvokedNames": mixinDeclaration_superInvokedNames, "name": name, "simplyBoundable_isSimplyBounded": simplyBoundable_isSimplyBounded, }; } if (kind == idl.LinkedNodeKind.namedExpression) { return { "namedExpression_expression": namedExpression_expression, "namedExpression_name": namedExpression_name, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.nativeClause) { return { "nativeClause_name": nativeClause_name, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.nativeFunctionBody) { return { "nativeFunctionBody_stringLiteral": nativeFunctionBody_stringLiteral, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.nullLiteral) { return { "nullLiteral_fake": nullLiteral_fake, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.onClause) { return { "onClause_superclassConstraints": onClause_superclassConstraints, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.parenthesizedExpression) { return { "parenthesizedExpression_expression": parenthesizedExpression_expression, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.partDirective) { return { "annotatedNode_metadata": annotatedNode_metadata, "flags": flags, "informativeId": informativeId, "uriBasedDirective_uri": uriBasedDirective_uri, "kind": kind, "name": name, "uriBasedDirective_uriContent": uriBasedDirective_uriContent, "uriBasedDirective_uriElement": uriBasedDirective_uriElement, }; } if (kind == idl.LinkedNodeKind.partOfDirective) { return { "annotatedNode_metadata": annotatedNode_metadata, "partOfDirective_libraryName": partOfDirective_libraryName, "partOfDirective_uri": partOfDirective_uri, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.postfixExpression) { return { "postfixExpression_operand": postfixExpression_operand, "postfixExpression_substitution": postfixExpression_substitution, "postfixExpression_element": postfixExpression_element, "postfixExpression_operator": postfixExpression_operator, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.prefixExpression) { return { "prefixExpression_operand": prefixExpression_operand, "prefixExpression_substitution": prefixExpression_substitution, "prefixExpression_element": prefixExpression_element, "prefixExpression_operator": prefixExpression_operator, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.prefixedIdentifier) { return { "prefixedIdentifier_identifier": prefixedIdentifier_identifier, "prefixedIdentifier_prefix": prefixedIdentifier_prefix, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.propertyAccess) { return { "propertyAccess_propertyName": propertyAccess_propertyName, "propertyAccess_target": propertyAccess_target, "propertyAccess_operator": propertyAccess_operator, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.redirectingConstructorInvocation) { return { "redirectingConstructorInvocation_arguments": redirectingConstructorInvocation_arguments, "redirectingConstructorInvocation_constructorName": redirectingConstructorInvocation_constructorName, "redirectingConstructorInvocation_substitution": redirectingConstructorInvocation_substitution, "redirectingConstructorInvocation_element": redirectingConstructorInvocation_element, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.rethrowExpression) { return { "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.returnStatement) { return { "returnStatement_expression": returnStatement_expression, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.setOrMapLiteral) { return { "typedLiteral_typeArguments": typedLiteral_typeArguments, "setOrMapLiteral_elements": setOrMapLiteral_elements, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.showCombinator) { return { "flags": flags, "informativeId": informativeId, "kind": kind, "names": names, "name": name, }; } if (kind == idl.LinkedNodeKind.simpleFormalParameter) { return { "actualType": actualType, "normalFormalParameter_metadata": normalFormalParameter_metadata, "simpleFormalParameter_type": simpleFormalParameter_type, "inheritsCovariant": inheritsCovariant, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "topLevelTypeInferenceError": topLevelTypeInferenceError, }; } if (kind == idl.LinkedNodeKind.simpleIdentifier) { return { "simpleIdentifier_substitution": simpleIdentifier_substitution, "simpleIdentifier_element": simpleIdentifier_element, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.simpleStringLiteral) { return { "simpleStringLiteral_value": simpleStringLiteral_value, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.spreadElement) { return { "spreadElement_expression": spreadElement_expression, "flags": flags, "kind": kind, "name": name, "spreadElement_spreadOperator": spreadElement_spreadOperator, }; } if (kind == idl.LinkedNodeKind.stringInterpolation) { return { "stringInterpolation_elements": stringInterpolation_elements, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.superConstructorInvocation) { return { "superConstructorInvocation_arguments": superConstructorInvocation_arguments, "superConstructorInvocation_constructorName": superConstructorInvocation_constructorName, "superConstructorInvocation_substitution": superConstructorInvocation_substitution, "superConstructorInvocation_element": superConstructorInvocation_element, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.superExpression) { return { "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.switchCase) { return { "switchMember_statements": switchMember_statements, "switchCase_expression": switchCase_expression, "switchMember_labels": switchMember_labels, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.switchDefault) { return { "switchMember_statements": switchMember_statements, "switchMember_labels": switchMember_labels, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.switchStatement) { return { "switchStatement_members": switchStatement_members, "switchStatement_expression": switchStatement_expression, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.symbolLiteral) { return { "expression_type": expression_type, "flags": flags, "kind": kind, "names": names, "name": name, }; } if (kind == idl.LinkedNodeKind.thisExpression) { return { "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.throwExpression) { return { "throwExpression_expression": throwExpression_expression, "expression_type": expression_type, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { return { "annotatedNode_metadata": annotatedNode_metadata, "topLevelVariableDeclaration_variableList": topLevelVariableDeclaration_variableList, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.tryStatement) { return { "tryStatement_catchClauses": tryStatement_catchClauses, "tryStatement_body": tryStatement_body, "tryStatement_finallyBlock": tryStatement_finallyBlock, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.typeArgumentList) { return { "typeArgumentList_arguments": typeArgumentList_arguments, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.typeName) { return { "typeName_typeArguments": typeName_typeArguments, "typeName_name": typeName_name, "flags": flags, "kind": kind, "name": name, "typeName_type": typeName_type, }; } if (kind == idl.LinkedNodeKind.typeParameter) { return { "annotatedNode_metadata": annotatedNode_metadata, "typeParameter_bound": typeParameter_bound, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "typeParameter_defaultType": typeParameter_defaultType, }; } if (kind == idl.LinkedNodeKind.typeParameterList) { return { "typeParameterList_typeParameters": typeParameterList_typeParameters, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.variableDeclaration) { return { "actualType": actualType, "annotatedNode_metadata": annotatedNode_metadata, "variableDeclaration_initializer": variableDeclaration_initializer, "inheritsCovariant": inheritsCovariant, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, "topLevelTypeInferenceError": topLevelTypeInferenceError, }; } if (kind == idl.LinkedNodeKind.variableDeclarationList) { return { "variableDeclarationList_variables": variableDeclarationList_variables, "annotatedNode_metadata": annotatedNode_metadata, "variableDeclarationList_type": variableDeclarationList_type, "flags": flags, "informativeId": informativeId, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.variableDeclarationStatement) { return { "variableDeclarationStatement_variables": variableDeclarationStatement_variables, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.whileStatement) { return { "whileStatement_body": whileStatement_body, "whileStatement_condition": whileStatement_condition, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.withClause) { return { "withClause_mixinTypes": withClause_mixinTypes, "flags": flags, "kind": kind, "name": name, }; } if (kind == idl.LinkedNodeKind.yieldStatement) { return { "yieldStatement_expression": yieldStatement_expression, "flags": flags, "kind": kind, "name": name, }; } throw StateError("Unexpected $kind"); } @override String toString() => convert.json.encode(toJson()); } class LinkedNodeBundleBuilder extends Object with _LinkedNodeBundleMixin implements idl.LinkedNodeBundle { List<LinkedNodeLibraryBuilder> _libraries; LinkedNodeReferencesBuilder _references; @override List<LinkedNodeLibraryBuilder> get libraries => _libraries ??= <LinkedNodeLibraryBuilder>[]; set libraries(List<LinkedNodeLibraryBuilder> value) { this._libraries = value; } @override LinkedNodeReferencesBuilder get references => _references; /// The shared list of references used in the [libraries]. set references(LinkedNodeReferencesBuilder value) { this._references = value; } LinkedNodeBundleBuilder( {List<LinkedNodeLibraryBuilder> libraries, LinkedNodeReferencesBuilder references}) : _libraries = libraries, _references = references; /// Flush [informative] data recursively. void flushInformative() { _libraries?.forEach((b) => b.flushInformative()); _references?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addBool(this._references != null); this._references?.collectApiSignature(signature); if (this._libraries == null) { signature.addInt(0); } else { signature.addInt(this._libraries.length); for (var x in this._libraries) { x?.collectApiSignature(signature); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "LNBn"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_libraries; fb.Offset offset_references; if (!(_libraries == null || _libraries.isEmpty)) { offset_libraries = fbBuilder .writeList(_libraries.map((b) => b.finish(fbBuilder)).toList()); } if (_references != null) { offset_references = _references.finish(fbBuilder); } fbBuilder.startTable(); if (offset_libraries != null) { fbBuilder.addOffset(1, offset_libraries); } if (offset_references != null) { fbBuilder.addOffset(0, offset_references); } return fbBuilder.endTable(); } } idl.LinkedNodeBundle readLinkedNodeBundle(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _LinkedNodeBundleReader().read(rootRef, 0); } class _LinkedNodeBundleReader extends fb.TableReader<_LinkedNodeBundleImpl> { const _LinkedNodeBundleReader(); @override _LinkedNodeBundleImpl createObject(fb.BufferContext bc, int offset) => new _LinkedNodeBundleImpl(bc, offset); } class _LinkedNodeBundleImpl extends Object with _LinkedNodeBundleMixin implements idl.LinkedNodeBundle { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeBundleImpl(this._bc, this._bcOffset); List<idl.LinkedNodeLibrary> _libraries; idl.LinkedNodeReferences _references; @override List<idl.LinkedNodeLibrary> get libraries { _libraries ??= const fb.ListReader<idl.LinkedNodeLibrary>( const _LinkedNodeLibraryReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.LinkedNodeLibrary>[]); return _libraries; } @override idl.LinkedNodeReferences get references { _references ??= const _LinkedNodeReferencesReader().vTableGet(_bc, _bcOffset, 0, null); return _references; } } abstract class _LinkedNodeBundleMixin implements idl.LinkedNodeBundle { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (libraries.isNotEmpty) _result["libraries"] = libraries.map((_value) => _value.toJson()).toList(); if (references != null) _result["references"] = references.toJson(); return _result; } @override Map<String, Object> toMap() => { "libraries": libraries, "references": references, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeLibraryBuilder extends Object with _LinkedNodeLibraryMixin implements idl.LinkedNodeLibrary { List<int> _exports; String _name; int _nameLength; int _nameOffset; List<LinkedNodeUnitBuilder> _units; String _uriStr; @override List<int> get exports => _exports ??= <int>[]; set exports(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._exports = value; } @override String get name => _name ??= ''; set name(String value) { this._name = value; } @override int get nameLength => _nameLength ??= 0; set nameLength(int value) { assert(value == null || value >= 0); this._nameLength = value; } @override int get nameOffset => _nameOffset ??= 0; set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override List<LinkedNodeUnitBuilder> get units => _units ??= <LinkedNodeUnitBuilder>[]; set units(List<LinkedNodeUnitBuilder> value) { this._units = value; } @override String get uriStr => _uriStr ??= ''; set uriStr(String value) { this._uriStr = value; } LinkedNodeLibraryBuilder( {List<int> exports, String name, int nameLength, int nameOffset, List<LinkedNodeUnitBuilder> units, String uriStr}) : _exports = exports, _name = name, _nameLength = nameLength, _nameOffset = nameOffset, _units = units, _uriStr = uriStr; /// Flush [informative] data recursively. void flushInformative() { _units?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._uriStr ?? ''); if (this._units == null) { signature.addInt(0); } else { signature.addInt(this._units.length); for (var x in this._units) { x?.collectApiSignature(signature); } } if (this._exports == null) { signature.addInt(0); } else { signature.addInt(this._exports.length); for (var x in this._exports) { signature.addInt(x); } } signature.addString(this._name ?? ''); signature.addInt(this._nameOffset ?? 0); signature.addInt(this._nameLength ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_exports; fb.Offset offset_name; fb.Offset offset_units; fb.Offset offset_uriStr; if (!(_exports == null || _exports.isEmpty)) { offset_exports = fbBuilder.writeListUint32(_exports); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_units == null || _units.isEmpty)) { offset_units = fbBuilder.writeList(_units.map((b) => b.finish(fbBuilder)).toList()); } if (_uriStr != null) { offset_uriStr = fbBuilder.writeString(_uriStr); } fbBuilder.startTable(); if (offset_exports != null) { fbBuilder.addOffset(2, offset_exports); } if (offset_name != null) { fbBuilder.addOffset(3, offset_name); } if (_nameLength != null && _nameLength != 0) { fbBuilder.addUint32(5, _nameLength); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(4, _nameOffset); } if (offset_units != null) { fbBuilder.addOffset(1, offset_units); } if (offset_uriStr != null) { fbBuilder.addOffset(0, offset_uriStr); } return fbBuilder.endTable(); } } class _LinkedNodeLibraryReader extends fb.TableReader<_LinkedNodeLibraryImpl> { const _LinkedNodeLibraryReader(); @override _LinkedNodeLibraryImpl createObject(fb.BufferContext bc, int offset) => new _LinkedNodeLibraryImpl(bc, offset); } class _LinkedNodeLibraryImpl extends Object with _LinkedNodeLibraryMixin implements idl.LinkedNodeLibrary { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeLibraryImpl(this._bc, this._bcOffset); List<int> _exports; String _name; int _nameLength; int _nameOffset; List<idl.LinkedNodeUnit> _units; String _uriStr; @override List<int> get exports { _exports ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 2, const <int>[]); return _exports; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 3, ''); return _name; } @override int get nameLength { _nameLength ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 5, 0); return _nameLength; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 4, 0); return _nameOffset; } @override List<idl.LinkedNodeUnit> get units { _units ??= const fb.ListReader<idl.LinkedNodeUnit>(const _LinkedNodeUnitReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.LinkedNodeUnit>[]); return _units; } @override String get uriStr { _uriStr ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _uriStr; } } abstract class _LinkedNodeLibraryMixin implements idl.LinkedNodeLibrary { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (exports.isNotEmpty) _result["exports"] = exports; if (name != '') _result["name"] = name; if (nameLength != 0) _result["nameLength"] = nameLength; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (units.isNotEmpty) _result["units"] = units.map((_value) => _value.toJson()).toList(); if (uriStr != '') _result["uriStr"] = uriStr; return _result; } @override Map<String, Object> toMap() => { "exports": exports, "name": name, "nameLength": nameLength, "nameOffset": nameOffset, "units": units, "uriStr": uriStr, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeReferencesBuilder extends Object with _LinkedNodeReferencesMixin implements idl.LinkedNodeReferences { List<String> _name; List<int> _parent; @override List<String> get name => _name ??= <String>[]; set name(List<String> value) { this._name = value; } @override List<int> get parent => _parent ??= <int>[]; set parent(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._parent = value; } LinkedNodeReferencesBuilder({List<String> name, List<int> parent}) : _name = name, _parent = parent; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._parent == null) { signature.addInt(0); } else { signature.addInt(this._parent.length); for (var x in this._parent) { signature.addInt(x); } } if (this._name == null) { signature.addInt(0); } else { signature.addInt(this._name.length); for (var x in this._name) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_name; fb.Offset offset_parent; if (!(_name == null || _name.isEmpty)) { offset_name = fbBuilder .writeList(_name.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_parent == null || _parent.isEmpty)) { offset_parent = fbBuilder.writeListUint32(_parent); } fbBuilder.startTable(); if (offset_name != null) { fbBuilder.addOffset(1, offset_name); } if (offset_parent != null) { fbBuilder.addOffset(0, offset_parent); } return fbBuilder.endTable(); } } class _LinkedNodeReferencesReader extends fb.TableReader<_LinkedNodeReferencesImpl> { const _LinkedNodeReferencesReader(); @override _LinkedNodeReferencesImpl createObject(fb.BufferContext bc, int offset) => new _LinkedNodeReferencesImpl(bc, offset); } class _LinkedNodeReferencesImpl extends Object with _LinkedNodeReferencesMixin implements idl.LinkedNodeReferences { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeReferencesImpl(this._bc, this._bcOffset); List<String> _name; List<int> _parent; @override List<String> get name { _name ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _name; } @override List<int> get parent { _parent ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 0, const <int>[]); return _parent; } } abstract class _LinkedNodeReferencesMixin implements idl.LinkedNodeReferences { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (name.isNotEmpty) _result["name"] = name; if (parent.isNotEmpty) _result["parent"] = parent; return _result; } @override Map<String, Object> toMap() => { "name": name, "parent": parent, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeTypeBuilder extends Object with _LinkedNodeTypeMixin implements idl.LinkedNodeType { List<LinkedNodeTypeFormalParameterBuilder> _functionFormalParameters; LinkedNodeTypeBuilder _functionReturnType; int _functionTypedef; List<LinkedNodeTypeBuilder> _functionTypedefTypeArguments; List<LinkedNodeTypeTypeParameterBuilder> _functionTypeParameters; int _interfaceClass; List<LinkedNodeTypeBuilder> _interfaceTypeArguments; idl.LinkedNodeTypeKind _kind; idl.EntityRefNullabilitySuffix _nullabilitySuffix; int _typeParameterElement; int _typeParameterId; @override List<LinkedNodeTypeFormalParameterBuilder> get functionFormalParameters => _functionFormalParameters ??= <LinkedNodeTypeFormalParameterBuilder>[]; set functionFormalParameters( List<LinkedNodeTypeFormalParameterBuilder> value) { this._functionFormalParameters = value; } @override LinkedNodeTypeBuilder get functionReturnType => _functionReturnType; set functionReturnType(LinkedNodeTypeBuilder value) { this._functionReturnType = value; } @override int get functionTypedef => _functionTypedef ??= 0; /// The typedef this function type is created for. set functionTypedef(int value) { assert(value == null || value >= 0); this._functionTypedef = value; } @override List<LinkedNodeTypeBuilder> get functionTypedefTypeArguments => _functionTypedefTypeArguments ??= <LinkedNodeTypeBuilder>[]; set functionTypedefTypeArguments(List<LinkedNodeTypeBuilder> value) { this._functionTypedefTypeArguments = value; } @override List<LinkedNodeTypeTypeParameterBuilder> get functionTypeParameters => _functionTypeParameters ??= <LinkedNodeTypeTypeParameterBuilder>[]; set functionTypeParameters(List<LinkedNodeTypeTypeParameterBuilder> value) { this._functionTypeParameters = value; } @override int get interfaceClass => _interfaceClass ??= 0; /// Reference to a [LinkedNodeReferences]. set interfaceClass(int value) { assert(value == null || value >= 0); this._interfaceClass = value; } @override List<LinkedNodeTypeBuilder> get interfaceTypeArguments => _interfaceTypeArguments ??= <LinkedNodeTypeBuilder>[]; set interfaceTypeArguments(List<LinkedNodeTypeBuilder> value) { this._interfaceTypeArguments = value; } @override idl.LinkedNodeTypeKind get kind => _kind ??= idl.LinkedNodeTypeKind.bottom; set kind(idl.LinkedNodeTypeKind value) { this._kind = value; } @override idl.EntityRefNullabilitySuffix get nullabilitySuffix => _nullabilitySuffix ??= idl.EntityRefNullabilitySuffix.starOrIrrelevant; set nullabilitySuffix(idl.EntityRefNullabilitySuffix value) { this._nullabilitySuffix = value; } @override int get typeParameterElement => _typeParameterElement ??= 0; set typeParameterElement(int value) { assert(value == null || value >= 0); this._typeParameterElement = value; } @override int get typeParameterId => _typeParameterId ??= 0; set typeParameterId(int value) { assert(value == null || value >= 0); this._typeParameterId = value; } LinkedNodeTypeBuilder( {List<LinkedNodeTypeFormalParameterBuilder> functionFormalParameters, LinkedNodeTypeBuilder functionReturnType, int functionTypedef, List<LinkedNodeTypeBuilder> functionTypedefTypeArguments, List<LinkedNodeTypeTypeParameterBuilder> functionTypeParameters, int interfaceClass, List<LinkedNodeTypeBuilder> interfaceTypeArguments, idl.LinkedNodeTypeKind kind, idl.EntityRefNullabilitySuffix nullabilitySuffix, int typeParameterElement, int typeParameterId}) : _functionFormalParameters = functionFormalParameters, _functionReturnType = functionReturnType, _functionTypedef = functionTypedef, _functionTypedefTypeArguments = functionTypedefTypeArguments, _functionTypeParameters = functionTypeParameters, _interfaceClass = interfaceClass, _interfaceTypeArguments = interfaceTypeArguments, _kind = kind, _nullabilitySuffix = nullabilitySuffix, _typeParameterElement = typeParameterElement, _typeParameterId = typeParameterId; /// Flush [informative] data recursively. void flushInformative() { _functionFormalParameters?.forEach((b) => b.flushInformative()); _functionReturnType?.flushInformative(); _functionTypedefTypeArguments?.forEach((b) => b.flushInformative()); _functionTypeParameters?.forEach((b) => b.flushInformative()); _interfaceTypeArguments?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._functionFormalParameters == null) { signature.addInt(0); } else { signature.addInt(this._functionFormalParameters.length); for (var x in this._functionFormalParameters) { x?.collectApiSignature(signature); } } signature.addBool(this._functionReturnType != null); this._functionReturnType?.collectApiSignature(signature); if (this._functionTypeParameters == null) { signature.addInt(0); } else { signature.addInt(this._functionTypeParameters.length); for (var x in this._functionTypeParameters) { x?.collectApiSignature(signature); } } signature.addInt(this._interfaceClass ?? 0); if (this._interfaceTypeArguments == null) { signature.addInt(0); } else { signature.addInt(this._interfaceTypeArguments.length); for (var x in this._interfaceTypeArguments) { x?.collectApiSignature(signature); } } signature.addInt(this._kind == null ? 0 : this._kind.index); signature.addInt(this._typeParameterElement ?? 0); signature.addInt(this._typeParameterId ?? 0); signature.addInt( this._nullabilitySuffix == null ? 0 : this._nullabilitySuffix.index); signature.addInt(this._functionTypedef ?? 0); if (this._functionTypedefTypeArguments == null) { signature.addInt(0); } else { signature.addInt(this._functionTypedefTypeArguments.length); for (var x in this._functionTypedefTypeArguments) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_functionFormalParameters; fb.Offset offset_functionReturnType; fb.Offset offset_functionTypedefTypeArguments; fb.Offset offset_functionTypeParameters; fb.Offset offset_interfaceTypeArguments; if (!(_functionFormalParameters == null || _functionFormalParameters.isEmpty)) { offset_functionFormalParameters = fbBuilder.writeList( _functionFormalParameters.map((b) => b.finish(fbBuilder)).toList()); } if (_functionReturnType != null) { offset_functionReturnType = _functionReturnType.finish(fbBuilder); } if (!(_functionTypedefTypeArguments == null || _functionTypedefTypeArguments.isEmpty)) { offset_functionTypedefTypeArguments = fbBuilder.writeList( _functionTypedefTypeArguments .map((b) => b.finish(fbBuilder)) .toList()); } if (!(_functionTypeParameters == null || _functionTypeParameters.isEmpty)) { offset_functionTypeParameters = fbBuilder.writeList( _functionTypeParameters.map((b) => b.finish(fbBuilder)).toList()); } if (!(_interfaceTypeArguments == null || _interfaceTypeArguments.isEmpty)) { offset_interfaceTypeArguments = fbBuilder.writeList( _interfaceTypeArguments.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_functionFormalParameters != null) { fbBuilder.addOffset(0, offset_functionFormalParameters); } if (offset_functionReturnType != null) { fbBuilder.addOffset(1, offset_functionReturnType); } if (_functionTypedef != null && _functionTypedef != 0) { fbBuilder.addUint32(9, _functionTypedef); } if (offset_functionTypedefTypeArguments != null) { fbBuilder.addOffset(10, offset_functionTypedefTypeArguments); } if (offset_functionTypeParameters != null) { fbBuilder.addOffset(2, offset_functionTypeParameters); } if (_interfaceClass != null && _interfaceClass != 0) { fbBuilder.addUint32(3, _interfaceClass); } if (offset_interfaceTypeArguments != null) { fbBuilder.addOffset(4, offset_interfaceTypeArguments); } if (_kind != null && _kind != idl.LinkedNodeTypeKind.bottom) { fbBuilder.addUint8(5, _kind.index); } if (_nullabilitySuffix != null && _nullabilitySuffix != idl.EntityRefNullabilitySuffix.starOrIrrelevant) { fbBuilder.addUint8(8, _nullabilitySuffix.index); } if (_typeParameterElement != null && _typeParameterElement != 0) { fbBuilder.addUint32(6, _typeParameterElement); } if (_typeParameterId != null && _typeParameterId != 0) { fbBuilder.addUint32(7, _typeParameterId); } return fbBuilder.endTable(); } } class _LinkedNodeTypeReader extends fb.TableReader<_LinkedNodeTypeImpl> { const _LinkedNodeTypeReader(); @override _LinkedNodeTypeImpl createObject(fb.BufferContext bc, int offset) => new _LinkedNodeTypeImpl(bc, offset); } class _LinkedNodeTypeImpl extends Object with _LinkedNodeTypeMixin implements idl.LinkedNodeType { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeTypeImpl(this._bc, this._bcOffset); List<idl.LinkedNodeTypeFormalParameter> _functionFormalParameters; idl.LinkedNodeType _functionReturnType; int _functionTypedef; List<idl.LinkedNodeType> _functionTypedefTypeArguments; List<idl.LinkedNodeTypeTypeParameter> _functionTypeParameters; int _interfaceClass; List<idl.LinkedNodeType> _interfaceTypeArguments; idl.LinkedNodeTypeKind _kind; idl.EntityRefNullabilitySuffix _nullabilitySuffix; int _typeParameterElement; int _typeParameterId; @override List<idl.LinkedNodeTypeFormalParameter> get functionFormalParameters { _functionFormalParameters ??= const fb.ListReader<idl.LinkedNodeTypeFormalParameter>( const _LinkedNodeTypeFormalParameterReader()) .vTableGet( _bc, _bcOffset, 0, const <idl.LinkedNodeTypeFormalParameter>[]); return _functionFormalParameters; } @override idl.LinkedNodeType get functionReturnType { _functionReturnType ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 1, null); return _functionReturnType; } @override int get functionTypedef { _functionTypedef ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 9, 0); return _functionTypedef; } @override List<idl.LinkedNodeType> get functionTypedefTypeArguments { _functionTypedefTypeArguments ??= const fb.ListReader<idl.LinkedNodeType>(const _LinkedNodeTypeReader()) .vTableGet(_bc, _bcOffset, 10, const <idl.LinkedNodeType>[]); return _functionTypedefTypeArguments; } @override List<idl.LinkedNodeTypeTypeParameter> get functionTypeParameters { _functionTypeParameters ??= const fb.ListReader<idl.LinkedNodeTypeTypeParameter>( const _LinkedNodeTypeTypeParameterReader()) .vTableGet( _bc, _bcOffset, 2, const <idl.LinkedNodeTypeTypeParameter>[]); return _functionTypeParameters; } @override int get interfaceClass { _interfaceClass ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _interfaceClass; } @override List<idl.LinkedNodeType> get interfaceTypeArguments { _interfaceTypeArguments ??= const fb.ListReader<idl.LinkedNodeType>(const _LinkedNodeTypeReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.LinkedNodeType>[]); return _interfaceTypeArguments; } @override idl.LinkedNodeTypeKind get kind { _kind ??= const _LinkedNodeTypeKindReader() .vTableGet(_bc, _bcOffset, 5, idl.LinkedNodeTypeKind.bottom); return _kind; } @override idl.EntityRefNullabilitySuffix get nullabilitySuffix { _nullabilitySuffix ??= const _EntityRefNullabilitySuffixReader().vTableGet( _bc, _bcOffset, 8, idl.EntityRefNullabilitySuffix.starOrIrrelevant); return _nullabilitySuffix; } @override int get typeParameterElement { _typeParameterElement ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 6, 0); return _typeParameterElement; } @override int get typeParameterId { _typeParameterId ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 7, 0); return _typeParameterId; } } abstract class _LinkedNodeTypeMixin implements idl.LinkedNodeType { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (functionFormalParameters.isNotEmpty) _result["functionFormalParameters"] = functionFormalParameters.map((_value) => _value.toJson()).toList(); if (functionReturnType != null) _result["functionReturnType"] = functionReturnType.toJson(); if (functionTypedef != 0) _result["functionTypedef"] = functionTypedef; if (functionTypedefTypeArguments.isNotEmpty) _result["functionTypedefTypeArguments"] = functionTypedefTypeArguments .map((_value) => _value.toJson()) .toList(); if (functionTypeParameters.isNotEmpty) _result["functionTypeParameters"] = functionTypeParameters.map((_value) => _value.toJson()).toList(); if (interfaceClass != 0) _result["interfaceClass"] = interfaceClass; if (interfaceTypeArguments.isNotEmpty) _result["interfaceTypeArguments"] = interfaceTypeArguments.map((_value) => _value.toJson()).toList(); if (kind != idl.LinkedNodeTypeKind.bottom) _result["kind"] = kind.toString().split('.')[1]; if (nullabilitySuffix != idl.EntityRefNullabilitySuffix.starOrIrrelevant) _result["nullabilitySuffix"] = nullabilitySuffix.toString().split('.')[1]; if (typeParameterElement != 0) _result["typeParameterElement"] = typeParameterElement; if (typeParameterId != 0) _result["typeParameterId"] = typeParameterId; return _result; } @override Map<String, Object> toMap() => { "functionFormalParameters": functionFormalParameters, "functionReturnType": functionReturnType, "functionTypedef": functionTypedef, "functionTypedefTypeArguments": functionTypedefTypeArguments, "functionTypeParameters": functionTypeParameters, "interfaceClass": interfaceClass, "interfaceTypeArguments": interfaceTypeArguments, "kind": kind, "nullabilitySuffix": nullabilitySuffix, "typeParameterElement": typeParameterElement, "typeParameterId": typeParameterId, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeTypeFormalParameterBuilder extends Object with _LinkedNodeTypeFormalParameterMixin implements idl.LinkedNodeTypeFormalParameter { idl.LinkedNodeFormalParameterKind _kind; String _name; LinkedNodeTypeBuilder _type; @override idl.LinkedNodeFormalParameterKind get kind => _kind ??= idl.LinkedNodeFormalParameterKind.requiredPositional; set kind(idl.LinkedNodeFormalParameterKind value) { this._kind = value; } @override String get name => _name ??= ''; set name(String value) { this._name = value; } @override LinkedNodeTypeBuilder get type => _type; set type(LinkedNodeTypeBuilder value) { this._type = value; } LinkedNodeTypeFormalParameterBuilder( {idl.LinkedNodeFormalParameterKind kind, String name, LinkedNodeTypeBuilder type}) : _kind = kind, _name = name, _type = type; /// Flush [informative] data recursively. void flushInformative() { _type?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._kind == null ? 0 : this._kind.index); signature.addString(this._name ?? ''); signature.addBool(this._type != null); this._type?.collectApiSignature(signature); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_name; fb.Offset offset_type; if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (_type != null) { offset_type = _type.finish(fbBuilder); } fbBuilder.startTable(); if (_kind != null && _kind != idl.LinkedNodeFormalParameterKind.requiredPositional) { fbBuilder.addUint8(0, _kind.index); } if (offset_name != null) { fbBuilder.addOffset(1, offset_name); } if (offset_type != null) { fbBuilder.addOffset(2, offset_type); } return fbBuilder.endTable(); } } class _LinkedNodeTypeFormalParameterReader extends fb.TableReader<_LinkedNodeTypeFormalParameterImpl> { const _LinkedNodeTypeFormalParameterReader(); @override _LinkedNodeTypeFormalParameterImpl createObject( fb.BufferContext bc, int offset) => new _LinkedNodeTypeFormalParameterImpl(bc, offset); } class _LinkedNodeTypeFormalParameterImpl extends Object with _LinkedNodeTypeFormalParameterMixin implements idl.LinkedNodeTypeFormalParameter { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeTypeFormalParameterImpl(this._bc, this._bcOffset); idl.LinkedNodeFormalParameterKind _kind; String _name; idl.LinkedNodeType _type; @override idl.LinkedNodeFormalParameterKind get kind { _kind ??= const _LinkedNodeFormalParameterKindReader().vTableGet(_bc, _bcOffset, 0, idl.LinkedNodeFormalParameterKind.requiredPositional); return _kind; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _name; } @override idl.LinkedNodeType get type { _type ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 2, null); return _type; } } abstract class _LinkedNodeTypeFormalParameterMixin implements idl.LinkedNodeTypeFormalParameter { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (kind != idl.LinkedNodeFormalParameterKind.requiredPositional) _result["kind"] = kind.toString().split('.')[1]; if (name != '') _result["name"] = name; if (type != null) _result["type"] = type.toJson(); return _result; } @override Map<String, Object> toMap() => { "kind": kind, "name": name, "type": type, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeTypeSubstitutionBuilder extends Object with _LinkedNodeTypeSubstitutionMixin implements idl.LinkedNodeTypeSubstitution { List<LinkedNodeTypeBuilder> _typeArguments; List<int> _typeParameters; @override List<LinkedNodeTypeBuilder> get typeArguments => _typeArguments ??= <LinkedNodeTypeBuilder>[]; set typeArguments(List<LinkedNodeTypeBuilder> value) { this._typeArguments = value; } @override List<int> get typeParameters => _typeParameters ??= <int>[]; set typeParameters(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._typeParameters = value; } LinkedNodeTypeSubstitutionBuilder( {List<LinkedNodeTypeBuilder> typeArguments, List<int> typeParameters}) : _typeArguments = typeArguments, _typeParameters = typeParameters; /// Flush [informative] data recursively. void flushInformative() { _typeArguments?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._typeParameters == null) { signature.addInt(0); } else { signature.addInt(this._typeParameters.length); for (var x in this._typeParameters) { signature.addInt(x); } } if (this._typeArguments == null) { signature.addInt(0); } else { signature.addInt(this._typeArguments.length); for (var x in this._typeArguments) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_typeArguments; fb.Offset offset_typeParameters; if (!(_typeArguments == null || _typeArguments.isEmpty)) { offset_typeArguments = fbBuilder .writeList(_typeArguments.map((b) => b.finish(fbBuilder)).toList()); } if (!(_typeParameters == null || _typeParameters.isEmpty)) { offset_typeParameters = fbBuilder.writeListUint32(_typeParameters); } fbBuilder.startTable(); if (offset_typeArguments != null) { fbBuilder.addOffset(1, offset_typeArguments); } if (offset_typeParameters != null) { fbBuilder.addOffset(0, offset_typeParameters); } return fbBuilder.endTable(); } } class _LinkedNodeTypeSubstitutionReader extends fb.TableReader<_LinkedNodeTypeSubstitutionImpl> { const _LinkedNodeTypeSubstitutionReader(); @override _LinkedNodeTypeSubstitutionImpl createObject( fb.BufferContext bc, int offset) => new _LinkedNodeTypeSubstitutionImpl(bc, offset); } class _LinkedNodeTypeSubstitutionImpl extends Object with _LinkedNodeTypeSubstitutionMixin implements idl.LinkedNodeTypeSubstitution { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeTypeSubstitutionImpl(this._bc, this._bcOffset); List<idl.LinkedNodeType> _typeArguments; List<int> _typeParameters; @override List<idl.LinkedNodeType> get typeArguments { _typeArguments ??= const fb.ListReader<idl.LinkedNodeType>(const _LinkedNodeTypeReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.LinkedNodeType>[]); return _typeArguments; } @override List<int> get typeParameters { _typeParameters ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 0, const <int>[]); return _typeParameters; } } abstract class _LinkedNodeTypeSubstitutionMixin implements idl.LinkedNodeTypeSubstitution { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (typeArguments.isNotEmpty) _result["typeArguments"] = typeArguments.map((_value) => _value.toJson()).toList(); if (typeParameters.isNotEmpty) _result["typeParameters"] = typeParameters; return _result; } @override Map<String, Object> toMap() => { "typeArguments": typeArguments, "typeParameters": typeParameters, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeTypeTypeParameterBuilder extends Object with _LinkedNodeTypeTypeParameterMixin implements idl.LinkedNodeTypeTypeParameter { LinkedNodeTypeBuilder _bound; String _name; @override LinkedNodeTypeBuilder get bound => _bound; set bound(LinkedNodeTypeBuilder value) { this._bound = value; } @override String get name => _name ??= ''; set name(String value) { this._name = value; } LinkedNodeTypeTypeParameterBuilder({LinkedNodeTypeBuilder bound, String name}) : _bound = bound, _name = name; /// Flush [informative] data recursively. void flushInformative() { _bound?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addBool(this._bound != null); this._bound?.collectApiSignature(signature); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_bound; fb.Offset offset_name; if (_bound != null) { offset_bound = _bound.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (offset_bound != null) { fbBuilder.addOffset(1, offset_bound); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } return fbBuilder.endTable(); } } class _LinkedNodeTypeTypeParameterReader extends fb.TableReader<_LinkedNodeTypeTypeParameterImpl> { const _LinkedNodeTypeTypeParameterReader(); @override _LinkedNodeTypeTypeParameterImpl createObject( fb.BufferContext bc, int offset) => new _LinkedNodeTypeTypeParameterImpl(bc, offset); } class _LinkedNodeTypeTypeParameterImpl extends Object with _LinkedNodeTypeTypeParameterMixin implements idl.LinkedNodeTypeTypeParameter { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeTypeTypeParameterImpl(this._bc, this._bcOffset); idl.LinkedNodeType _bound; String _name; @override idl.LinkedNodeType get bound { _bound ??= const _LinkedNodeTypeReader().vTableGet(_bc, _bcOffset, 1, null); return _bound; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } } abstract class _LinkedNodeTypeTypeParameterMixin implements idl.LinkedNodeTypeTypeParameter { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (bound != null) _result["bound"] = bound.toJson(); if (name != '') _result["name"] = name; return _result; } @override Map<String, Object> toMap() => { "bound": bound, "name": name, }; @override String toString() => convert.json.encode(toJson()); } class LinkedNodeUnitBuilder extends Object with _LinkedNodeUnitMixin implements idl.LinkedNodeUnit { bool _isNNBD; bool _isSynthetic; LinkedNodeBuilder _node; String _partUriStr; UnlinkedTokensBuilder _tokens; String _uriStr; @override bool get isNNBD => _isNNBD ??= false; set isNNBD(bool value) { this._isNNBD = value; } @override bool get isSynthetic => _isSynthetic ??= false; set isSynthetic(bool value) { this._isSynthetic = value; } @override LinkedNodeBuilder get node => _node; set node(LinkedNodeBuilder value) { this._node = value; } @override String get partUriStr => _partUriStr ??= ''; /// If the unit is a part, the URI specified in the `part` directive. /// Otherwise empty. set partUriStr(String value) { this._partUriStr = value; } @override UnlinkedTokensBuilder get tokens => _tokens; set tokens(UnlinkedTokensBuilder value) { this._tokens = value; } @override String get uriStr => _uriStr ??= ''; /// The absolute URI. set uriStr(String value) { this._uriStr = value; } LinkedNodeUnitBuilder( {bool isNNBD, bool isSynthetic, LinkedNodeBuilder node, String partUriStr, UnlinkedTokensBuilder tokens, String uriStr}) : _isNNBD = isNNBD, _isSynthetic = isSynthetic, _node = node, _partUriStr = partUriStr, _tokens = tokens, _uriStr = uriStr; /// Flush [informative] data recursively. void flushInformative() { _node?.flushInformative(); _tokens?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._uriStr ?? ''); signature.addBool(this._tokens != null); this._tokens?.collectApiSignature(signature); signature.addBool(this._node != null); this._node?.collectApiSignature(signature); signature.addBool(this._isSynthetic == true); signature.addBool(this._isNNBD == true); signature.addString(this._partUriStr ?? ''); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_node; fb.Offset offset_partUriStr; fb.Offset offset_tokens; fb.Offset offset_uriStr; if (_node != null) { offset_node = _node.finish(fbBuilder); } if (_partUriStr != null) { offset_partUriStr = fbBuilder.writeString(_partUriStr); } if (_tokens != null) { offset_tokens = _tokens.finish(fbBuilder); } if (_uriStr != null) { offset_uriStr = fbBuilder.writeString(_uriStr); } fbBuilder.startTable(); if (_isNNBD == true) { fbBuilder.addBool(4, true); } if (_isSynthetic == true) { fbBuilder.addBool(3, true); } if (offset_node != null) { fbBuilder.addOffset(2, offset_node); } if (offset_partUriStr != null) { fbBuilder.addOffset(5, offset_partUriStr); } if (offset_tokens != null) { fbBuilder.addOffset(1, offset_tokens); } if (offset_uriStr != null) { fbBuilder.addOffset(0, offset_uriStr); } return fbBuilder.endTable(); } } class _LinkedNodeUnitReader extends fb.TableReader<_LinkedNodeUnitImpl> { const _LinkedNodeUnitReader(); @override _LinkedNodeUnitImpl createObject(fb.BufferContext bc, int offset) => new _LinkedNodeUnitImpl(bc, offset); } class _LinkedNodeUnitImpl extends Object with _LinkedNodeUnitMixin implements idl.LinkedNodeUnit { final fb.BufferContext _bc; final int _bcOffset; _LinkedNodeUnitImpl(this._bc, this._bcOffset); bool _isNNBD; bool _isSynthetic; idl.LinkedNode _node; String _partUriStr; idl.UnlinkedTokens _tokens; String _uriStr; @override bool get isNNBD { _isNNBD ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 4, false); return _isNNBD; } @override bool get isSynthetic { _isSynthetic ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 3, false); return _isSynthetic; } @override idl.LinkedNode get node { _node ??= const _LinkedNodeReader().vTableGet(_bc, _bcOffset, 2, null); return _node; } @override String get partUriStr { _partUriStr ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 5, ''); return _partUriStr; } @override idl.UnlinkedTokens get tokens { _tokens ??= const _UnlinkedTokensReader().vTableGet(_bc, _bcOffset, 1, null); return _tokens; } @override String get uriStr { _uriStr ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _uriStr; } } abstract class _LinkedNodeUnitMixin implements idl.LinkedNodeUnit { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (isNNBD != false) _result["isNNBD"] = isNNBD; if (isSynthetic != false) _result["isSynthetic"] = isSynthetic; if (node != null) _result["node"] = node.toJson(); if (partUriStr != '') _result["partUriStr"] = partUriStr; if (tokens != null) _result["tokens"] = tokens.toJson(); if (uriStr != '') _result["uriStr"] = uriStr; return _result; } @override Map<String, Object> toMap() => { "isNNBD": isNNBD, "isSynthetic": isSynthetic, "node": node, "partUriStr": partUriStr, "tokens": tokens, "uriStr": uriStr, }; @override String toString() => convert.json.encode(toJson()); } class LinkedReferenceBuilder extends Object with _LinkedReferenceMixin implements idl.LinkedReference { int _containingReference; int _dependency; idl.ReferenceKind _kind; String _name; int _numTypeParameters; int _unit; @override int get containingReference => _containingReference ??= 0; /// If this [LinkedReference] doesn't have an associated [UnlinkedReference], /// and the entity being referred to is contained within another entity, index /// of the containing entity. This behaves similarly to /// [UnlinkedReference.prefixReference], however it is only used for class /// members, not for prefixed imports. /// /// Containing references must always point backward; that is, for all i, if /// LinkedUnit.references[i].containingReference != 0, then /// LinkedUnit.references[i].containingReference < i. set containingReference(int value) { assert(value == null || value >= 0); this._containingReference = value; } @override int get dependency => _dependency ??= 0; /// Index into [LinkedLibrary.dependencies] indicating which imported library /// declares the entity being referred to. /// /// Zero if this entity is contained within another entity (e.g. a class /// member), or if [kind] is [ReferenceKind.prefix]. set dependency(int value) { assert(value == null || value >= 0); this._dependency = value; } @override idl.ReferenceKind get kind => _kind ??= idl.ReferenceKind.classOrEnum; /// The kind of the entity being referred to. For the pseudo-types `dynamic` /// and `void`, the kind is [ReferenceKind.classOrEnum]. set kind(idl.ReferenceKind value) { this._kind = value; } @override Null get localIndex => throw new UnimplementedError('attempt to access deprecated field'); @override String get name => _name ??= ''; /// If this [LinkedReference] doesn't have an associated [UnlinkedReference], /// name of the entity being referred to. For the pseudo-type `dynamic`, the /// string is "dynamic". For the pseudo-type `void`, the string is "void". set name(String value) { this._name = value; } @override int get numTypeParameters => _numTypeParameters ??= 0; /// If the entity being referred to is generic, the number of type parameters /// it declares (does not include type parameters of enclosing entities). /// Otherwise zero. set numTypeParameters(int value) { assert(value == null || value >= 0); this._numTypeParameters = value; } @override int get unit => _unit ??= 0; /// Integer index indicating which unit in the imported library contains the /// definition of the entity. As with indices into [LinkedLibrary.units], /// zero represents the defining compilation unit, and nonzero values /// represent parts in the order of the corresponding `part` declarations. /// /// Zero if this entity is contained within another entity (e.g. a class /// member). set unit(int value) { assert(value == null || value >= 0); this._unit = value; } LinkedReferenceBuilder( {int containingReference, int dependency, idl.ReferenceKind kind, String name, int numTypeParameters, int unit}) : _containingReference = containingReference, _dependency = dependency, _kind = kind, _name = name, _numTypeParameters = numTypeParameters, _unit = unit; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._unit ?? 0); signature.addInt(this._dependency ?? 0); signature.addInt(this._kind == null ? 0 : this._kind.index); signature.addString(this._name ?? ''); signature.addInt(this._numTypeParameters ?? 0); signature.addInt(this._containingReference ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_name; if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (_containingReference != null && _containingReference != 0) { fbBuilder.addUint32(5, _containingReference); } if (_dependency != null && _dependency != 0) { fbBuilder.addUint32(1, _dependency); } if (_kind != null && _kind != idl.ReferenceKind.classOrEnum) { fbBuilder.addUint8(2, _kind.index); } if (offset_name != null) { fbBuilder.addOffset(3, offset_name); } if (_numTypeParameters != null && _numTypeParameters != 0) { fbBuilder.addUint32(4, _numTypeParameters); } if (_unit != null && _unit != 0) { fbBuilder.addUint32(0, _unit); } return fbBuilder.endTable(); } } class _LinkedReferenceReader extends fb.TableReader<_LinkedReferenceImpl> { const _LinkedReferenceReader(); @override _LinkedReferenceImpl createObject(fb.BufferContext bc, int offset) => new _LinkedReferenceImpl(bc, offset); } class _LinkedReferenceImpl extends Object with _LinkedReferenceMixin implements idl.LinkedReference { final fb.BufferContext _bc; final int _bcOffset; _LinkedReferenceImpl(this._bc, this._bcOffset); int _containingReference; int _dependency; idl.ReferenceKind _kind; String _name; int _numTypeParameters; int _unit; @override int get containingReference { _containingReference ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 5, 0); return _containingReference; } @override int get dependency { _dependency ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _dependency; } @override idl.ReferenceKind get kind { _kind ??= const _ReferenceKindReader() .vTableGet(_bc, _bcOffset, 2, idl.ReferenceKind.classOrEnum); return _kind; } @override Null get localIndex => throw new UnimplementedError('attempt to access deprecated field'); @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 3, ''); return _name; } @override int get numTypeParameters { _numTypeParameters ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 4, 0); return _numTypeParameters; } @override int get unit { _unit ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _unit; } } abstract class _LinkedReferenceMixin implements idl.LinkedReference { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (containingReference != 0) _result["containingReference"] = containingReference; if (dependency != 0) _result["dependency"] = dependency; if (kind != idl.ReferenceKind.classOrEnum) _result["kind"] = kind.toString().split('.')[1]; if (name != '') _result["name"] = name; if (numTypeParameters != 0) _result["numTypeParameters"] = numTypeParameters; if (unit != 0) _result["unit"] = unit; return _result; } @override Map<String, Object> toMap() => { "containingReference": containingReference, "dependency": dependency, "kind": kind, "name": name, "numTypeParameters": numTypeParameters, "unit": unit, }; @override String toString() => convert.json.encode(toJson()); } class LinkedUnitBuilder extends Object with _LinkedUnitMixin implements idl.LinkedUnit { List<int> _constCycles; List<int> _notSimplyBounded; List<int> _parametersInheritingCovariant; List<LinkedReferenceBuilder> _references; List<TopLevelInferenceErrorBuilder> _topLevelInferenceErrors; List<EntityRefBuilder> _types; @override List<int> get constCycles => _constCycles ??= <int>[]; /// List of slot ids (referring to [UnlinkedExecutable.constCycleSlot]) /// corresponding to const constructors that are part of cycles. set constCycles(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._constCycles = value; } @override List<int> get notSimplyBounded => _notSimplyBounded ??= <int>[]; /// List of slot ids (referring to [UnlinkedClass.notSimplyBoundedSlot] or /// [UnlinkedTypedef.notSimplyBoundedSlot]) corresponding to classes and /// typedefs that are not simply bounded. set notSimplyBounded(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._notSimplyBounded = value; } @override List<int> get parametersInheritingCovariant => _parametersInheritingCovariant ??= <int>[]; /// List of slot ids (referring to [UnlinkedParam.inheritsCovariantSlot] or /// [UnlinkedVariable.inheritsCovariantSlot]) corresponding to parameters /// that inherit `@covariant` behavior from a base class. set parametersInheritingCovariant(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._parametersInheritingCovariant = value; } @override List<LinkedReferenceBuilder> get references => _references ??= <LinkedReferenceBuilder>[]; /// Information about the resolution of references within the compilation /// unit. Each element of [UnlinkedUnit.references] has a corresponding /// element in this list (at the same index). If this list has additional /// elements beyond the number of elements in [UnlinkedUnit.references], those /// additional elements are references that are only referred to implicitly /// (e.g. elements involved in inferred or propagated types). set references(List<LinkedReferenceBuilder> value) { this._references = value; } @override List<TopLevelInferenceErrorBuilder> get topLevelInferenceErrors => _topLevelInferenceErrors ??= <TopLevelInferenceErrorBuilder>[]; /// The list of type inference errors. set topLevelInferenceErrors(List<TopLevelInferenceErrorBuilder> value) { this._topLevelInferenceErrors = value; } @override List<EntityRefBuilder> get types => _types ??= <EntityRefBuilder>[]; /// List associating slot ids found inside the unlinked summary for the /// compilation unit with propagated and inferred types. set types(List<EntityRefBuilder> value) { this._types = value; } LinkedUnitBuilder( {List<int> constCycles, List<int> notSimplyBounded, List<int> parametersInheritingCovariant, List<LinkedReferenceBuilder> references, List<TopLevelInferenceErrorBuilder> topLevelInferenceErrors, List<EntityRefBuilder> types}) : _constCycles = constCycles, _notSimplyBounded = notSimplyBounded, _parametersInheritingCovariant = parametersInheritingCovariant, _references = references, _topLevelInferenceErrors = topLevelInferenceErrors, _types = types; /// Flush [informative] data recursively. void flushInformative() { _references?.forEach((b) => b.flushInformative()); _topLevelInferenceErrors?.forEach((b) => b.flushInformative()); _types?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._references == null) { signature.addInt(0); } else { signature.addInt(this._references.length); for (var x in this._references) { x?.collectApiSignature(signature); } } if (this._types == null) { signature.addInt(0); } else { signature.addInt(this._types.length); for (var x in this._types) { x?.collectApiSignature(signature); } } if (this._constCycles == null) { signature.addInt(0); } else { signature.addInt(this._constCycles.length); for (var x in this._constCycles) { signature.addInt(x); } } if (this._parametersInheritingCovariant == null) { signature.addInt(0); } else { signature.addInt(this._parametersInheritingCovariant.length); for (var x in this._parametersInheritingCovariant) { signature.addInt(x); } } if (this._topLevelInferenceErrors == null) { signature.addInt(0); } else { signature.addInt(this._topLevelInferenceErrors.length); for (var x in this._topLevelInferenceErrors) { x?.collectApiSignature(signature); } } if (this._notSimplyBounded == null) { signature.addInt(0); } else { signature.addInt(this._notSimplyBounded.length); for (var x in this._notSimplyBounded) { signature.addInt(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_constCycles; fb.Offset offset_notSimplyBounded; fb.Offset offset_parametersInheritingCovariant; fb.Offset offset_references; fb.Offset offset_topLevelInferenceErrors; fb.Offset offset_types; if (!(_constCycles == null || _constCycles.isEmpty)) { offset_constCycles = fbBuilder.writeListUint32(_constCycles); } if (!(_notSimplyBounded == null || _notSimplyBounded.isEmpty)) { offset_notSimplyBounded = fbBuilder.writeListUint32(_notSimplyBounded); } if (!(_parametersInheritingCovariant == null || _parametersInheritingCovariant.isEmpty)) { offset_parametersInheritingCovariant = fbBuilder.writeListUint32(_parametersInheritingCovariant); } if (!(_references == null || _references.isEmpty)) { offset_references = fbBuilder .writeList(_references.map((b) => b.finish(fbBuilder)).toList()); } if (!(_topLevelInferenceErrors == null || _topLevelInferenceErrors.isEmpty)) { offset_topLevelInferenceErrors = fbBuilder.writeList( _topLevelInferenceErrors.map((b) => b.finish(fbBuilder)).toList()); } if (!(_types == null || _types.isEmpty)) { offset_types = fbBuilder.writeList(_types.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_constCycles != null) { fbBuilder.addOffset(2, offset_constCycles); } if (offset_notSimplyBounded != null) { fbBuilder.addOffset(5, offset_notSimplyBounded); } if (offset_parametersInheritingCovariant != null) { fbBuilder.addOffset(3, offset_parametersInheritingCovariant); } if (offset_references != null) { fbBuilder.addOffset(0, offset_references); } if (offset_topLevelInferenceErrors != null) { fbBuilder.addOffset(4, offset_topLevelInferenceErrors); } if (offset_types != null) { fbBuilder.addOffset(1, offset_types); } return fbBuilder.endTable(); } } class _LinkedUnitReader extends fb.TableReader<_LinkedUnitImpl> { const _LinkedUnitReader(); @override _LinkedUnitImpl createObject(fb.BufferContext bc, int offset) => new _LinkedUnitImpl(bc, offset); } class _LinkedUnitImpl extends Object with _LinkedUnitMixin implements idl.LinkedUnit { final fb.BufferContext _bc; final int _bcOffset; _LinkedUnitImpl(this._bc, this._bcOffset); List<int> _constCycles; List<int> _notSimplyBounded; List<int> _parametersInheritingCovariant; List<idl.LinkedReference> _references; List<idl.TopLevelInferenceError> _topLevelInferenceErrors; List<idl.EntityRef> _types; @override List<int> get constCycles { _constCycles ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 2, const <int>[]); return _constCycles; } @override List<int> get notSimplyBounded { _notSimplyBounded ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 5, const <int>[]); return _notSimplyBounded; } @override List<int> get parametersInheritingCovariant { _parametersInheritingCovariant ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 3, const <int>[]); return _parametersInheritingCovariant; } @override List<idl.LinkedReference> get references { _references ??= const fb.ListReader<idl.LinkedReference>(const _LinkedReferenceReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.LinkedReference>[]); return _references; } @override List<idl.TopLevelInferenceError> get topLevelInferenceErrors { _topLevelInferenceErrors ??= const fb.ListReader<idl.TopLevelInferenceError>( const _TopLevelInferenceErrorReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.TopLevelInferenceError>[]); return _topLevelInferenceErrors; } @override List<idl.EntityRef> get types { _types ??= const fb.ListReader<idl.EntityRef>(const _EntityRefReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.EntityRef>[]); return _types; } } abstract class _LinkedUnitMixin implements idl.LinkedUnit { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (constCycles.isNotEmpty) _result["constCycles"] = constCycles; if (notSimplyBounded.isNotEmpty) _result["notSimplyBounded"] = notSimplyBounded; if (parametersInheritingCovariant.isNotEmpty) _result["parametersInheritingCovariant"] = parametersInheritingCovariant; if (references.isNotEmpty) _result["references"] = references.map((_value) => _value.toJson()).toList(); if (topLevelInferenceErrors.isNotEmpty) _result["topLevelInferenceErrors"] = topLevelInferenceErrors.map((_value) => _value.toJson()).toList(); if (types.isNotEmpty) _result["types"] = types.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "constCycles": constCycles, "notSimplyBounded": notSimplyBounded, "parametersInheritingCovariant": parametersInheritingCovariant, "references": references, "topLevelInferenceErrors": topLevelInferenceErrors, "types": types, }; @override String toString() => convert.json.encode(toJson()); } class PackageBundleBuilder extends Object with _PackageBundleMixin implements idl.PackageBundle { LinkedNodeBundleBuilder _bundle2; List<LinkedLibraryBuilder> _linkedLibraries; List<String> _linkedLibraryUris; int _majorVersion; int _minorVersion; List<UnlinkedUnitBuilder> _unlinkedUnits; List<String> _unlinkedUnitUris; @override Null get apiSignature => throw new UnimplementedError('attempt to access deprecated field'); @override LinkedNodeBundleBuilder get bundle2 => _bundle2; /// The version 2 of the summary. set bundle2(LinkedNodeBundleBuilder value) { this._bundle2 = value; } @override Null get dependencies => throw new UnimplementedError('attempt to access deprecated field'); @override List<LinkedLibraryBuilder> get linkedLibraries => _linkedLibraries ??= <LinkedLibraryBuilder>[]; /// Linked libraries. set linkedLibraries(List<LinkedLibraryBuilder> value) { this._linkedLibraries = value; } @override List<String> get linkedLibraryUris => _linkedLibraryUris ??= <String>[]; /// The list of URIs of items in [linkedLibraries], e.g. `dart:core` or /// `package:foo/bar.dart`. set linkedLibraryUris(List<String> value) { this._linkedLibraryUris = value; } @override int get majorVersion => _majorVersion ??= 0; /// Major version of the summary format. See /// [PackageBundleAssembler.currentMajorVersion]. set majorVersion(int value) { assert(value == null || value >= 0); this._majorVersion = value; } @override int get minorVersion => _minorVersion ??= 0; /// Minor version of the summary format. See /// [PackageBundleAssembler.currentMinorVersion]. set minorVersion(int value) { assert(value == null || value >= 0); this._minorVersion = value; } @override Null get unlinkedUnitHashes => throw new UnimplementedError('attempt to access deprecated field'); @override List<UnlinkedUnitBuilder> get unlinkedUnits => _unlinkedUnits ??= <UnlinkedUnitBuilder>[]; /// Unlinked information for the compilation units constituting the package. set unlinkedUnits(List<UnlinkedUnitBuilder> value) { this._unlinkedUnits = value; } @override List<String> get unlinkedUnitUris => _unlinkedUnitUris ??= <String>[]; /// The list of URIs of items in [unlinkedUnits], e.g. `dart:core/bool.dart`. set unlinkedUnitUris(List<String> value) { this._unlinkedUnitUris = value; } PackageBundleBuilder( {LinkedNodeBundleBuilder bundle2, List<LinkedLibraryBuilder> linkedLibraries, List<String> linkedLibraryUris, int majorVersion, int minorVersion, List<UnlinkedUnitBuilder> unlinkedUnits, List<String> unlinkedUnitUris}) : _bundle2 = bundle2, _linkedLibraries = linkedLibraries, _linkedLibraryUris = linkedLibraryUris, _majorVersion = majorVersion, _minorVersion = minorVersion, _unlinkedUnits = unlinkedUnits, _unlinkedUnitUris = unlinkedUnitUris; /// Flush [informative] data recursively. void flushInformative() { _bundle2?.flushInformative(); _linkedLibraries?.forEach((b) => b.flushInformative()); _unlinkedUnits?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._linkedLibraries == null) { signature.addInt(0); } else { signature.addInt(this._linkedLibraries.length); for (var x in this._linkedLibraries) { x?.collectApiSignature(signature); } } if (this._linkedLibraryUris == null) { signature.addInt(0); } else { signature.addInt(this._linkedLibraryUris.length); for (var x in this._linkedLibraryUris) { signature.addString(x); } } if (this._unlinkedUnits == null) { signature.addInt(0); } else { signature.addInt(this._unlinkedUnits.length); for (var x in this._unlinkedUnits) { x?.collectApiSignature(signature); } } if (this._unlinkedUnitUris == null) { signature.addInt(0); } else { signature.addInt(this._unlinkedUnitUris.length); for (var x in this._unlinkedUnitUris) { signature.addString(x); } } signature.addInt(this._majorVersion ?? 0); signature.addInt(this._minorVersion ?? 0); signature.addBool(this._bundle2 != null); this._bundle2?.collectApiSignature(signature); } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "PBdl"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_bundle2; fb.Offset offset_linkedLibraries; fb.Offset offset_linkedLibraryUris; fb.Offset offset_unlinkedUnits; fb.Offset offset_unlinkedUnitUris; if (_bundle2 != null) { offset_bundle2 = _bundle2.finish(fbBuilder); } if (!(_linkedLibraries == null || _linkedLibraries.isEmpty)) { offset_linkedLibraries = fbBuilder .writeList(_linkedLibraries.map((b) => b.finish(fbBuilder)).toList()); } if (!(_linkedLibraryUris == null || _linkedLibraryUris.isEmpty)) { offset_linkedLibraryUris = fbBuilder.writeList( _linkedLibraryUris.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_unlinkedUnits == null || _unlinkedUnits.isEmpty)) { offset_unlinkedUnits = fbBuilder .writeList(_unlinkedUnits.map((b) => b.finish(fbBuilder)).toList()); } if (!(_unlinkedUnitUris == null || _unlinkedUnitUris.isEmpty)) { offset_unlinkedUnitUris = fbBuilder.writeList( _unlinkedUnitUris.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_bundle2 != null) { fbBuilder.addOffset(9, offset_bundle2); } if (offset_linkedLibraries != null) { fbBuilder.addOffset(0, offset_linkedLibraries); } if (offset_linkedLibraryUris != null) { fbBuilder.addOffset(1, offset_linkedLibraryUris); } if (_majorVersion != null && _majorVersion != 0) { fbBuilder.addUint32(5, _majorVersion); } if (_minorVersion != null && _minorVersion != 0) { fbBuilder.addUint32(6, _minorVersion); } if (offset_unlinkedUnits != null) { fbBuilder.addOffset(2, offset_unlinkedUnits); } if (offset_unlinkedUnitUris != null) { fbBuilder.addOffset(3, offset_unlinkedUnitUris); } return fbBuilder.endTable(); } } idl.PackageBundle readPackageBundle(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _PackageBundleReader().read(rootRef, 0); } class _PackageBundleReader extends fb.TableReader<_PackageBundleImpl> { const _PackageBundleReader(); @override _PackageBundleImpl createObject(fb.BufferContext bc, int offset) => new _PackageBundleImpl(bc, offset); } class _PackageBundleImpl extends Object with _PackageBundleMixin implements idl.PackageBundle { final fb.BufferContext _bc; final int _bcOffset; _PackageBundleImpl(this._bc, this._bcOffset); idl.LinkedNodeBundle _bundle2; List<idl.LinkedLibrary> _linkedLibraries; List<String> _linkedLibraryUris; int _majorVersion; int _minorVersion; List<idl.UnlinkedUnit> _unlinkedUnits; List<String> _unlinkedUnitUris; @override Null get apiSignature => throw new UnimplementedError('attempt to access deprecated field'); @override idl.LinkedNodeBundle get bundle2 { _bundle2 ??= const _LinkedNodeBundleReader().vTableGet(_bc, _bcOffset, 9, null); return _bundle2; } @override Null get dependencies => throw new UnimplementedError('attempt to access deprecated field'); @override List<idl.LinkedLibrary> get linkedLibraries { _linkedLibraries ??= const fb.ListReader<idl.LinkedLibrary>(const _LinkedLibraryReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.LinkedLibrary>[]); return _linkedLibraries; } @override List<String> get linkedLibraryUris { _linkedLibraryUris ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _linkedLibraryUris; } @override int get majorVersion { _majorVersion ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 5, 0); return _majorVersion; } @override int get minorVersion { _minorVersion ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 6, 0); return _minorVersion; } @override Null get unlinkedUnitHashes => throw new UnimplementedError('attempt to access deprecated field'); @override List<idl.UnlinkedUnit> get unlinkedUnits { _unlinkedUnits ??= const fb.ListReader<idl.UnlinkedUnit>(const _UnlinkedUnitReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedUnit>[]); return _unlinkedUnits; } @override List<String> get unlinkedUnitUris { _unlinkedUnitUris ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 3, const <String>[]); return _unlinkedUnitUris; } } abstract class _PackageBundleMixin implements idl.PackageBundle { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (bundle2 != null) _result["bundle2"] = bundle2.toJson(); if (linkedLibraries.isNotEmpty) _result["linkedLibraries"] = linkedLibraries.map((_value) => _value.toJson()).toList(); if (linkedLibraryUris.isNotEmpty) _result["linkedLibraryUris"] = linkedLibraryUris; if (majorVersion != 0) _result["majorVersion"] = majorVersion; if (minorVersion != 0) _result["minorVersion"] = minorVersion; if (unlinkedUnits.isNotEmpty) _result["unlinkedUnits"] = unlinkedUnits.map((_value) => _value.toJson()).toList(); if (unlinkedUnitUris.isNotEmpty) _result["unlinkedUnitUris"] = unlinkedUnitUris; return _result; } @override Map<String, Object> toMap() => { "bundle2": bundle2, "linkedLibraries": linkedLibraries, "linkedLibraryUris": linkedLibraryUris, "majorVersion": majorVersion, "minorVersion": minorVersion, "unlinkedUnits": unlinkedUnits, "unlinkedUnitUris": unlinkedUnitUris, }; @override String toString() => convert.json.encode(toJson()); } class PackageIndexBuilder extends Object with _PackageIndexMixin implements idl.PackageIndex { List<idl.IndexSyntheticElementKind> _elementKinds; List<int> _elementNameClassMemberIds; List<int> _elementNameParameterIds; List<int> _elementNameUnitMemberIds; List<int> _elementUnits; List<String> _strings; List<int> _unitLibraryUris; List<UnitIndexBuilder> _units; List<int> _unitUnitUris; @override List<idl.IndexSyntheticElementKind> get elementKinds => _elementKinds ??= <idl.IndexSyntheticElementKind>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the kind of the synthetic element. set elementKinds(List<idl.IndexSyntheticElementKind> value) { this._elementKinds = value; } @override List<int> get elementNameClassMemberIds => _elementNameClassMemberIds ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the class member element name, or `null` if the element /// is a top-level element. The list is sorted in ascending order, so that /// the client can quickly check whether an element is referenced in this /// [PackageIndex]. set elementNameClassMemberIds(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementNameClassMemberIds = value; } @override List<int> get elementNameParameterIds => _elementNameParameterIds ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the named parameter name, or `null` if the element is /// not a named parameter. The list is sorted in ascending order, so that the /// client can quickly check whether an element is referenced in this /// [PackageIndex]. set elementNameParameterIds(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementNameParameterIds = value; } @override List<int> get elementNameUnitMemberIds => _elementNameUnitMemberIds ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the identifier of the top-level element name, or `null` if the element is /// the unit. The list is sorted in ascending order, so that the client can /// quickly check whether an element is referenced in this [PackageIndex]. set elementNameUnitMemberIds(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementNameUnitMemberIds = value; } @override List<int> get elementUnits => _elementUnits ??= <int>[]; /// Each item of this list corresponds to a unique referenced element. It is /// the index into [unitLibraryUris] and [unitUnitUris] for the library /// specific unit where the element is declared. set elementUnits(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._elementUnits = value; } @override List<String> get strings => _strings ??= <String>[]; /// List of unique element strings used in this [PackageIndex]. The list is /// sorted in ascending order, so that the client can quickly check the /// presence of a string in this [PackageIndex]. set strings(List<String> value) { this._strings = value; } @override List<int> get unitLibraryUris => _unitLibraryUris ??= <int>[]; /// Each item of this list corresponds to the library URI of a unique library /// specific unit referenced in the [PackageIndex]. It is an index into /// [strings] list. set unitLibraryUris(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._unitLibraryUris = value; } @override List<UnitIndexBuilder> get units => _units ??= <UnitIndexBuilder>[]; /// List of indexes of each unit in this [PackageIndex]. set units(List<UnitIndexBuilder> value) { this._units = value; } @override List<int> get unitUnitUris => _unitUnitUris ??= <int>[]; /// Each item of this list corresponds to the unit URI of a unique library /// specific unit referenced in the [PackageIndex]. It is an index into /// [strings] list. set unitUnitUris(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._unitUnitUris = value; } PackageIndexBuilder( {List<idl.IndexSyntheticElementKind> elementKinds, List<int> elementNameClassMemberIds, List<int> elementNameParameterIds, List<int> elementNameUnitMemberIds, List<int> elementUnits, List<String> strings, List<int> unitLibraryUris, List<UnitIndexBuilder> units, List<int> unitUnitUris}) : _elementKinds = elementKinds, _elementNameClassMemberIds = elementNameClassMemberIds, _elementNameParameterIds = elementNameParameterIds, _elementNameUnitMemberIds = elementNameUnitMemberIds, _elementUnits = elementUnits, _strings = strings, _unitLibraryUris = unitLibraryUris, _units = units, _unitUnitUris = unitUnitUris; /// Flush [informative] data recursively. void flushInformative() { _units?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._elementUnits == null) { signature.addInt(0); } else { signature.addInt(this._elementUnits.length); for (var x in this._elementUnits) { signature.addInt(x); } } if (this._elementNameUnitMemberIds == null) { signature.addInt(0); } else { signature.addInt(this._elementNameUnitMemberIds.length); for (var x in this._elementNameUnitMemberIds) { signature.addInt(x); } } if (this._unitLibraryUris == null) { signature.addInt(0); } else { signature.addInt(this._unitLibraryUris.length); for (var x in this._unitLibraryUris) { signature.addInt(x); } } if (this._unitUnitUris == null) { signature.addInt(0); } else { signature.addInt(this._unitUnitUris.length); for (var x in this._unitUnitUris) { signature.addInt(x); } } if (this._units == null) { signature.addInt(0); } else { signature.addInt(this._units.length); for (var x in this._units) { x?.collectApiSignature(signature); } } if (this._elementKinds == null) { signature.addInt(0); } else { signature.addInt(this._elementKinds.length); for (var x in this._elementKinds) { signature.addInt(x.index); } } if (this._strings == null) { signature.addInt(0); } else { signature.addInt(this._strings.length); for (var x in this._strings) { signature.addString(x); } } if (this._elementNameClassMemberIds == null) { signature.addInt(0); } else { signature.addInt(this._elementNameClassMemberIds.length); for (var x in this._elementNameClassMemberIds) { signature.addInt(x); } } if (this._elementNameParameterIds == null) { signature.addInt(0); } else { signature.addInt(this._elementNameParameterIds.length); for (var x in this._elementNameParameterIds) { signature.addInt(x); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "Indx"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_elementKinds; fb.Offset offset_elementNameClassMemberIds; fb.Offset offset_elementNameParameterIds; fb.Offset offset_elementNameUnitMemberIds; fb.Offset offset_elementUnits; fb.Offset offset_strings; fb.Offset offset_unitLibraryUris; fb.Offset offset_units; fb.Offset offset_unitUnitUris; if (!(_elementKinds == null || _elementKinds.isEmpty)) { offset_elementKinds = fbBuilder.writeListUint8(_elementKinds.map((b) => b.index).toList()); } if (!(_elementNameClassMemberIds == null || _elementNameClassMemberIds.isEmpty)) { offset_elementNameClassMemberIds = fbBuilder.writeListUint32(_elementNameClassMemberIds); } if (!(_elementNameParameterIds == null || _elementNameParameterIds.isEmpty)) { offset_elementNameParameterIds = fbBuilder.writeListUint32(_elementNameParameterIds); } if (!(_elementNameUnitMemberIds == null || _elementNameUnitMemberIds.isEmpty)) { offset_elementNameUnitMemberIds = fbBuilder.writeListUint32(_elementNameUnitMemberIds); } if (!(_elementUnits == null || _elementUnits.isEmpty)) { offset_elementUnits = fbBuilder.writeListUint32(_elementUnits); } if (!(_strings == null || _strings.isEmpty)) { offset_strings = fbBuilder .writeList(_strings.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_unitLibraryUris == null || _unitLibraryUris.isEmpty)) { offset_unitLibraryUris = fbBuilder.writeListUint32(_unitLibraryUris); } if (!(_units == null || _units.isEmpty)) { offset_units = fbBuilder.writeList(_units.map((b) => b.finish(fbBuilder)).toList()); } if (!(_unitUnitUris == null || _unitUnitUris.isEmpty)) { offset_unitUnitUris = fbBuilder.writeListUint32(_unitUnitUris); } fbBuilder.startTable(); if (offset_elementKinds != null) { fbBuilder.addOffset(5, offset_elementKinds); } if (offset_elementNameClassMemberIds != null) { fbBuilder.addOffset(7, offset_elementNameClassMemberIds); } if (offset_elementNameParameterIds != null) { fbBuilder.addOffset(8, offset_elementNameParameterIds); } if (offset_elementNameUnitMemberIds != null) { fbBuilder.addOffset(1, offset_elementNameUnitMemberIds); } if (offset_elementUnits != null) { fbBuilder.addOffset(0, offset_elementUnits); } if (offset_strings != null) { fbBuilder.addOffset(6, offset_strings); } if (offset_unitLibraryUris != null) { fbBuilder.addOffset(2, offset_unitLibraryUris); } if (offset_units != null) { fbBuilder.addOffset(4, offset_units); } if (offset_unitUnitUris != null) { fbBuilder.addOffset(3, offset_unitUnitUris); } return fbBuilder.endTable(); } } idl.PackageIndex readPackageIndex(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _PackageIndexReader().read(rootRef, 0); } class _PackageIndexReader extends fb.TableReader<_PackageIndexImpl> { const _PackageIndexReader(); @override _PackageIndexImpl createObject(fb.BufferContext bc, int offset) => new _PackageIndexImpl(bc, offset); } class _PackageIndexImpl extends Object with _PackageIndexMixin implements idl.PackageIndex { final fb.BufferContext _bc; final int _bcOffset; _PackageIndexImpl(this._bc, this._bcOffset); List<idl.IndexSyntheticElementKind> _elementKinds; List<int> _elementNameClassMemberIds; List<int> _elementNameParameterIds; List<int> _elementNameUnitMemberIds; List<int> _elementUnits; List<String> _strings; List<int> _unitLibraryUris; List<idl.UnitIndex> _units; List<int> _unitUnitUris; @override List<idl.IndexSyntheticElementKind> get elementKinds { _elementKinds ??= const fb.ListReader<idl.IndexSyntheticElementKind>( const _IndexSyntheticElementKindReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.IndexSyntheticElementKind>[]); return _elementKinds; } @override List<int> get elementNameClassMemberIds { _elementNameClassMemberIds ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 7, const <int>[]); return _elementNameClassMemberIds; } @override List<int> get elementNameParameterIds { _elementNameParameterIds ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 8, const <int>[]); return _elementNameParameterIds; } @override List<int> get elementNameUnitMemberIds { _elementNameUnitMemberIds ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 1, const <int>[]); return _elementNameUnitMemberIds; } @override List<int> get elementUnits { _elementUnits ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 0, const <int>[]); return _elementUnits; } @override List<String> get strings { _strings ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 6, const <String>[]); return _strings; } @override List<int> get unitLibraryUris { _unitLibraryUris ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 2, const <int>[]); return _unitLibraryUris; } @override List<idl.UnitIndex> get units { _units ??= const fb.ListReader<idl.UnitIndex>(const _UnitIndexReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnitIndex>[]); return _units; } @override List<int> get unitUnitUris { _unitUnitUris ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 3, const <int>[]); return _unitUnitUris; } } abstract class _PackageIndexMixin implements idl.PackageIndex { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (elementKinds.isNotEmpty) _result["elementKinds"] = elementKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (elementNameClassMemberIds.isNotEmpty) _result["elementNameClassMemberIds"] = elementNameClassMemberIds; if (elementNameParameterIds.isNotEmpty) _result["elementNameParameterIds"] = elementNameParameterIds; if (elementNameUnitMemberIds.isNotEmpty) _result["elementNameUnitMemberIds"] = elementNameUnitMemberIds; if (elementUnits.isNotEmpty) _result["elementUnits"] = elementUnits; if (strings.isNotEmpty) _result["strings"] = strings; if (unitLibraryUris.isNotEmpty) _result["unitLibraryUris"] = unitLibraryUris; if (units.isNotEmpty) _result["units"] = units.map((_value) => _value.toJson()).toList(); if (unitUnitUris.isNotEmpty) _result["unitUnitUris"] = unitUnitUris; return _result; } @override Map<String, Object> toMap() => { "elementKinds": elementKinds, "elementNameClassMemberIds": elementNameClassMemberIds, "elementNameParameterIds": elementNameParameterIds, "elementNameUnitMemberIds": elementNameUnitMemberIds, "elementUnits": elementUnits, "strings": strings, "unitLibraryUris": unitLibraryUris, "units": units, "unitUnitUris": unitUnitUris, }; @override String toString() => convert.json.encode(toJson()); } class TopLevelInferenceErrorBuilder extends Object with _TopLevelInferenceErrorMixin implements idl.TopLevelInferenceError { List<String> _arguments; idl.TopLevelInferenceErrorKind _kind; int _slot; @override List<String> get arguments => _arguments ??= <String>[]; /// The [kind] specific arguments. set arguments(List<String> value) { this._arguments = value; } @override idl.TopLevelInferenceErrorKind get kind => _kind ??= idl.TopLevelInferenceErrorKind.assignment; /// The kind of the error. set kind(idl.TopLevelInferenceErrorKind value) { this._kind = value; } @override int get slot => _slot ??= 0; /// The slot id (which is unique within the compilation unit) identifying the /// target of type inference with which this [TopLevelInferenceError] is /// associated. set slot(int value) { assert(value == null || value >= 0); this._slot = value; } TopLevelInferenceErrorBuilder( {List<String> arguments, idl.TopLevelInferenceErrorKind kind, int slot}) : _arguments = arguments, _kind = kind, _slot = slot; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._slot ?? 0); signature.addInt(this._kind == null ? 0 : this._kind.index); if (this._arguments == null) { signature.addInt(0); } else { signature.addInt(this._arguments.length); for (var x in this._arguments) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_arguments; if (!(_arguments == null || _arguments.isEmpty)) { offset_arguments = fbBuilder .writeList(_arguments.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_arguments != null) { fbBuilder.addOffset(2, offset_arguments); } if (_kind != null && _kind != idl.TopLevelInferenceErrorKind.assignment) { fbBuilder.addUint8(1, _kind.index); } if (_slot != null && _slot != 0) { fbBuilder.addUint32(0, _slot); } return fbBuilder.endTable(); } } class _TopLevelInferenceErrorReader extends fb.TableReader<_TopLevelInferenceErrorImpl> { const _TopLevelInferenceErrorReader(); @override _TopLevelInferenceErrorImpl createObject(fb.BufferContext bc, int offset) => new _TopLevelInferenceErrorImpl(bc, offset); } class _TopLevelInferenceErrorImpl extends Object with _TopLevelInferenceErrorMixin implements idl.TopLevelInferenceError { final fb.BufferContext _bc; final int _bcOffset; _TopLevelInferenceErrorImpl(this._bc, this._bcOffset); List<String> _arguments; idl.TopLevelInferenceErrorKind _kind; int _slot; @override List<String> get arguments { _arguments ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 2, const <String>[]); return _arguments; } @override idl.TopLevelInferenceErrorKind get kind { _kind ??= const _TopLevelInferenceErrorKindReader().vTableGet( _bc, _bcOffset, 1, idl.TopLevelInferenceErrorKind.assignment); return _kind; } @override int get slot { _slot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _slot; } } abstract class _TopLevelInferenceErrorMixin implements idl.TopLevelInferenceError { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (arguments.isNotEmpty) _result["arguments"] = arguments; if (kind != idl.TopLevelInferenceErrorKind.assignment) _result["kind"] = kind.toString().split('.')[1]; if (slot != 0) _result["slot"] = slot; return _result; } @override Map<String, Object> toMap() => { "arguments": arguments, "kind": kind, "slot": slot, }; @override String toString() => convert.json.encode(toJson()); } class UnitIndexBuilder extends Object with _UnitIndexMixin implements idl.UnitIndex { List<idl.IndexNameKind> _definedNameKinds; List<int> _definedNameOffsets; List<int> _definedNames; int _unit; List<bool> _usedElementIsQualifiedFlags; List<idl.IndexRelationKind> _usedElementKinds; List<int> _usedElementLengths; List<int> _usedElementOffsets; List<int> _usedElements; List<bool> _usedNameIsQualifiedFlags; List<idl.IndexRelationKind> _usedNameKinds; List<int> _usedNameOffsets; List<int> _usedNames; @override List<idl.IndexNameKind> get definedNameKinds => _definedNameKinds ??= <idl.IndexNameKind>[]; /// Each item of this list is the kind of an element defined in this unit. set definedNameKinds(List<idl.IndexNameKind> value) { this._definedNameKinds = value; } @override List<int> get definedNameOffsets => _definedNameOffsets ??= <int>[]; /// Each item of this list is the name offset of an element defined in this /// unit relative to the beginning of the file. set definedNameOffsets(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._definedNameOffsets = value; } @override List<int> get definedNames => _definedNames ??= <int>[]; /// Each item of this list corresponds to an element defined in this unit. It /// is an index into [PackageIndex.strings] list. The list is sorted in /// ascending order, so that the client can quickly find name definitions in /// this [UnitIndex]. set definedNames(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._definedNames = value; } @override int get unit => _unit ??= 0; /// Index into [PackageIndex.unitLibraryUris] and [PackageIndex.unitUnitUris] /// for the library specific unit that corresponds to this [UnitIndex]. set unit(int value) { assert(value == null || value >= 0); this._unit = value; } @override List<bool> get usedElementIsQualifiedFlags => _usedElementIsQualifiedFlags ??= <bool>[]; /// Each item of this list is the `true` if the corresponding element usage /// is qualified with some prefix. set usedElementIsQualifiedFlags(List<bool> value) { this._usedElementIsQualifiedFlags = value; } @override List<idl.IndexRelationKind> get usedElementKinds => _usedElementKinds ??= <idl.IndexRelationKind>[]; /// Each item of this list is the kind of the element usage. set usedElementKinds(List<idl.IndexRelationKind> value) { this._usedElementKinds = value; } @override List<int> get usedElementLengths => _usedElementLengths ??= <int>[]; /// Each item of this list is the length of the element usage. set usedElementLengths(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedElementLengths = value; } @override List<int> get usedElementOffsets => _usedElementOffsets ??= <int>[]; /// Each item of this list is the offset of the element usage relative to the /// beginning of the file. set usedElementOffsets(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedElementOffsets = value; } @override List<int> get usedElements => _usedElements ??= <int>[]; /// Each item of this list is the index into [PackageIndex.elementUnits] and /// [PackageIndex.elementOffsets]. The list is sorted in ascending order, so /// that the client can quickly find element references in this [UnitIndex]. set usedElements(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedElements = value; } @override List<bool> get usedNameIsQualifiedFlags => _usedNameIsQualifiedFlags ??= <bool>[]; /// Each item of this list is the `true` if the corresponding name usage /// is qualified with some prefix. set usedNameIsQualifiedFlags(List<bool> value) { this._usedNameIsQualifiedFlags = value; } @override List<idl.IndexRelationKind> get usedNameKinds => _usedNameKinds ??= <idl.IndexRelationKind>[]; /// Each item of this list is the kind of the name usage. set usedNameKinds(List<idl.IndexRelationKind> value) { this._usedNameKinds = value; } @override List<int> get usedNameOffsets => _usedNameOffsets ??= <int>[]; /// Each item of this list is the offset of the name usage relative to the /// beginning of the file. set usedNameOffsets(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedNameOffsets = value; } @override List<int> get usedNames => _usedNames ??= <int>[]; /// Each item of this list is the index into [PackageIndex.strings] for a /// used name. The list is sorted in ascending order, so that the client can /// quickly find name uses in this [UnitIndex]. set usedNames(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._usedNames = value; } UnitIndexBuilder( {List<idl.IndexNameKind> definedNameKinds, List<int> definedNameOffsets, List<int> definedNames, int unit, List<bool> usedElementIsQualifiedFlags, List<idl.IndexRelationKind> usedElementKinds, List<int> usedElementLengths, List<int> usedElementOffsets, List<int> usedElements, List<bool> usedNameIsQualifiedFlags, List<idl.IndexRelationKind> usedNameKinds, List<int> usedNameOffsets, List<int> usedNames}) : _definedNameKinds = definedNameKinds, _definedNameOffsets = definedNameOffsets, _definedNames = definedNames, _unit = unit, _usedElementIsQualifiedFlags = usedElementIsQualifiedFlags, _usedElementKinds = usedElementKinds, _usedElementLengths = usedElementLengths, _usedElementOffsets = usedElementOffsets, _usedElements = usedElements, _usedNameIsQualifiedFlags = usedNameIsQualifiedFlags, _usedNameKinds = usedNameKinds, _usedNameOffsets = usedNameOffsets, _usedNames = usedNames; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addInt(this._unit ?? 0); if (this._usedElementLengths == null) { signature.addInt(0); } else { signature.addInt(this._usedElementLengths.length); for (var x in this._usedElementLengths) { signature.addInt(x); } } if (this._usedElementOffsets == null) { signature.addInt(0); } else { signature.addInt(this._usedElementOffsets.length); for (var x in this._usedElementOffsets) { signature.addInt(x); } } if (this._usedElements == null) { signature.addInt(0); } else { signature.addInt(this._usedElements.length); for (var x in this._usedElements) { signature.addInt(x); } } if (this._usedElementKinds == null) { signature.addInt(0); } else { signature.addInt(this._usedElementKinds.length); for (var x in this._usedElementKinds) { signature.addInt(x.index); } } if (this._definedNames == null) { signature.addInt(0); } else { signature.addInt(this._definedNames.length); for (var x in this._definedNames) { signature.addInt(x); } } if (this._definedNameKinds == null) { signature.addInt(0); } else { signature.addInt(this._definedNameKinds.length); for (var x in this._definedNameKinds) { signature.addInt(x.index); } } if (this._definedNameOffsets == null) { signature.addInt(0); } else { signature.addInt(this._definedNameOffsets.length); for (var x in this._definedNameOffsets) { signature.addInt(x); } } if (this._usedNames == null) { signature.addInt(0); } else { signature.addInt(this._usedNames.length); for (var x in this._usedNames) { signature.addInt(x); } } if (this._usedNameOffsets == null) { signature.addInt(0); } else { signature.addInt(this._usedNameOffsets.length); for (var x in this._usedNameOffsets) { signature.addInt(x); } } if (this._usedNameKinds == null) { signature.addInt(0); } else { signature.addInt(this._usedNameKinds.length); for (var x in this._usedNameKinds) { signature.addInt(x.index); } } if (this._usedElementIsQualifiedFlags == null) { signature.addInt(0); } else { signature.addInt(this._usedElementIsQualifiedFlags.length); for (var x in this._usedElementIsQualifiedFlags) { signature.addBool(x); } } if (this._usedNameIsQualifiedFlags == null) { signature.addInt(0); } else { signature.addInt(this._usedNameIsQualifiedFlags.length); for (var x in this._usedNameIsQualifiedFlags) { signature.addBool(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_definedNameKinds; fb.Offset offset_definedNameOffsets; fb.Offset offset_definedNames; fb.Offset offset_usedElementIsQualifiedFlags; fb.Offset offset_usedElementKinds; fb.Offset offset_usedElementLengths; fb.Offset offset_usedElementOffsets; fb.Offset offset_usedElements; fb.Offset offset_usedNameIsQualifiedFlags; fb.Offset offset_usedNameKinds; fb.Offset offset_usedNameOffsets; fb.Offset offset_usedNames; if (!(_definedNameKinds == null || _definedNameKinds.isEmpty)) { offset_definedNameKinds = fbBuilder .writeListUint8(_definedNameKinds.map((b) => b.index).toList()); } if (!(_definedNameOffsets == null || _definedNameOffsets.isEmpty)) { offset_definedNameOffsets = fbBuilder.writeListUint32(_definedNameOffsets); } if (!(_definedNames == null || _definedNames.isEmpty)) { offset_definedNames = fbBuilder.writeListUint32(_definedNames); } if (!(_usedElementIsQualifiedFlags == null || _usedElementIsQualifiedFlags.isEmpty)) { offset_usedElementIsQualifiedFlags = fbBuilder.writeListBool(_usedElementIsQualifiedFlags); } if (!(_usedElementKinds == null || _usedElementKinds.isEmpty)) { offset_usedElementKinds = fbBuilder .writeListUint8(_usedElementKinds.map((b) => b.index).toList()); } if (!(_usedElementLengths == null || _usedElementLengths.isEmpty)) { offset_usedElementLengths = fbBuilder.writeListUint32(_usedElementLengths); } if (!(_usedElementOffsets == null || _usedElementOffsets.isEmpty)) { offset_usedElementOffsets = fbBuilder.writeListUint32(_usedElementOffsets); } if (!(_usedElements == null || _usedElements.isEmpty)) { offset_usedElements = fbBuilder.writeListUint32(_usedElements); } if (!(_usedNameIsQualifiedFlags == null || _usedNameIsQualifiedFlags.isEmpty)) { offset_usedNameIsQualifiedFlags = fbBuilder.writeListBool(_usedNameIsQualifiedFlags); } if (!(_usedNameKinds == null || _usedNameKinds.isEmpty)) { offset_usedNameKinds = fbBuilder.writeListUint8(_usedNameKinds.map((b) => b.index).toList()); } if (!(_usedNameOffsets == null || _usedNameOffsets.isEmpty)) { offset_usedNameOffsets = fbBuilder.writeListUint32(_usedNameOffsets); } if (!(_usedNames == null || _usedNames.isEmpty)) { offset_usedNames = fbBuilder.writeListUint32(_usedNames); } fbBuilder.startTable(); if (offset_definedNameKinds != null) { fbBuilder.addOffset(6, offset_definedNameKinds); } if (offset_definedNameOffsets != null) { fbBuilder.addOffset(7, offset_definedNameOffsets); } if (offset_definedNames != null) { fbBuilder.addOffset(5, offset_definedNames); } if (_unit != null && _unit != 0) { fbBuilder.addUint32(0, _unit); } if (offset_usedElementIsQualifiedFlags != null) { fbBuilder.addOffset(11, offset_usedElementIsQualifiedFlags); } if (offset_usedElementKinds != null) { fbBuilder.addOffset(4, offset_usedElementKinds); } if (offset_usedElementLengths != null) { fbBuilder.addOffset(1, offset_usedElementLengths); } if (offset_usedElementOffsets != null) { fbBuilder.addOffset(2, offset_usedElementOffsets); } if (offset_usedElements != null) { fbBuilder.addOffset(3, offset_usedElements); } if (offset_usedNameIsQualifiedFlags != null) { fbBuilder.addOffset(12, offset_usedNameIsQualifiedFlags); } if (offset_usedNameKinds != null) { fbBuilder.addOffset(10, offset_usedNameKinds); } if (offset_usedNameOffsets != null) { fbBuilder.addOffset(9, offset_usedNameOffsets); } if (offset_usedNames != null) { fbBuilder.addOffset(8, offset_usedNames); } return fbBuilder.endTable(); } } class _UnitIndexReader extends fb.TableReader<_UnitIndexImpl> { const _UnitIndexReader(); @override _UnitIndexImpl createObject(fb.BufferContext bc, int offset) => new _UnitIndexImpl(bc, offset); } class _UnitIndexImpl extends Object with _UnitIndexMixin implements idl.UnitIndex { final fb.BufferContext _bc; final int _bcOffset; _UnitIndexImpl(this._bc, this._bcOffset); List<idl.IndexNameKind> _definedNameKinds; List<int> _definedNameOffsets; List<int> _definedNames; int _unit; List<bool> _usedElementIsQualifiedFlags; List<idl.IndexRelationKind> _usedElementKinds; List<int> _usedElementLengths; List<int> _usedElementOffsets; List<int> _usedElements; List<bool> _usedNameIsQualifiedFlags; List<idl.IndexRelationKind> _usedNameKinds; List<int> _usedNameOffsets; List<int> _usedNames; @override List<idl.IndexNameKind> get definedNameKinds { _definedNameKinds ??= const fb.ListReader<idl.IndexNameKind>(const _IndexNameKindReader()) .vTableGet(_bc, _bcOffset, 6, const <idl.IndexNameKind>[]); return _definedNameKinds; } @override List<int> get definedNameOffsets { _definedNameOffsets ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 7, const <int>[]); return _definedNameOffsets; } @override List<int> get definedNames { _definedNames ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 5, const <int>[]); return _definedNames; } @override int get unit { _unit ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _unit; } @override List<bool> get usedElementIsQualifiedFlags { _usedElementIsQualifiedFlags ??= const fb.BoolListReader().vTableGet(_bc, _bcOffset, 11, const <bool>[]); return _usedElementIsQualifiedFlags; } @override List<idl.IndexRelationKind> get usedElementKinds { _usedElementKinds ??= const fb.ListReader<idl.IndexRelationKind>( const _IndexRelationKindReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.IndexRelationKind>[]); return _usedElementKinds; } @override List<int> get usedElementLengths { _usedElementLengths ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 1, const <int>[]); return _usedElementLengths; } @override List<int> get usedElementOffsets { _usedElementOffsets ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 2, const <int>[]); return _usedElementOffsets; } @override List<int> get usedElements { _usedElements ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 3, const <int>[]); return _usedElements; } @override List<bool> get usedNameIsQualifiedFlags { _usedNameIsQualifiedFlags ??= const fb.BoolListReader().vTableGet(_bc, _bcOffset, 12, const <bool>[]); return _usedNameIsQualifiedFlags; } @override List<idl.IndexRelationKind> get usedNameKinds { _usedNameKinds ??= const fb.ListReader<idl.IndexRelationKind>( const _IndexRelationKindReader()) .vTableGet(_bc, _bcOffset, 10, const <idl.IndexRelationKind>[]); return _usedNameKinds; } @override List<int> get usedNameOffsets { _usedNameOffsets ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 9, const <int>[]); return _usedNameOffsets; } @override List<int> get usedNames { _usedNames ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 8, const <int>[]); return _usedNames; } } abstract class _UnitIndexMixin implements idl.UnitIndex { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (definedNameKinds.isNotEmpty) _result["definedNameKinds"] = definedNameKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (definedNameOffsets.isNotEmpty) _result["definedNameOffsets"] = definedNameOffsets; if (definedNames.isNotEmpty) _result["definedNames"] = definedNames; if (unit != 0) _result["unit"] = unit; if (usedElementIsQualifiedFlags.isNotEmpty) _result["usedElementIsQualifiedFlags"] = usedElementIsQualifiedFlags; if (usedElementKinds.isNotEmpty) _result["usedElementKinds"] = usedElementKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (usedElementLengths.isNotEmpty) _result["usedElementLengths"] = usedElementLengths; if (usedElementOffsets.isNotEmpty) _result["usedElementOffsets"] = usedElementOffsets; if (usedElements.isNotEmpty) _result["usedElements"] = usedElements; if (usedNameIsQualifiedFlags.isNotEmpty) _result["usedNameIsQualifiedFlags"] = usedNameIsQualifiedFlags; if (usedNameKinds.isNotEmpty) _result["usedNameKinds"] = usedNameKinds .map((_value) => _value.toString().split('.')[1]) .toList(); if (usedNameOffsets.isNotEmpty) _result["usedNameOffsets"] = usedNameOffsets; if (usedNames.isNotEmpty) _result["usedNames"] = usedNames; return _result; } @override Map<String, Object> toMap() => { "definedNameKinds": definedNameKinds, "definedNameOffsets": definedNameOffsets, "definedNames": definedNames, "unit": unit, "usedElementIsQualifiedFlags": usedElementIsQualifiedFlags, "usedElementKinds": usedElementKinds, "usedElementLengths": usedElementLengths, "usedElementOffsets": usedElementOffsets, "usedElements": usedElements, "usedNameIsQualifiedFlags": usedNameIsQualifiedFlags, "usedNameKinds": usedNameKinds, "usedNameOffsets": usedNameOffsets, "usedNames": usedNames, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedClassBuilder extends Object with _UnlinkedClassMixin implements idl.UnlinkedClass { List<UnlinkedExprBuilder> _annotations; CodeRangeBuilder _codeRange; UnlinkedDocumentationCommentBuilder _documentationComment; List<UnlinkedExecutableBuilder> _executables; List<UnlinkedVariableBuilder> _fields; bool _hasNoSupertype; List<EntityRefBuilder> _interfaces; bool _isAbstract; bool _isMixinApplication; List<EntityRefBuilder> _mixins; String _name; int _nameOffset; int _notSimplyBoundedSlot; List<EntityRefBuilder> _superclassConstraints; List<String> _superInvokedNames; EntityRefBuilder _supertype; List<UnlinkedTypeParamBuilder> _typeParameters; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this class. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the class. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the class, or `null` if there is no /// documentation comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override List<UnlinkedExecutableBuilder> get executables => _executables ??= <UnlinkedExecutableBuilder>[]; /// Executable objects (methods, getters, and setters) contained in the class. set executables(List<UnlinkedExecutableBuilder> value) { this._executables = value; } @override List<UnlinkedVariableBuilder> get fields => _fields ??= <UnlinkedVariableBuilder>[]; /// Field declarations contained in the class. set fields(List<UnlinkedVariableBuilder> value) { this._fields = value; } @override bool get hasNoSupertype => _hasNoSupertype ??= false; /// Indicates whether this class is the core "Object" class (and hence has no /// supertype) set hasNoSupertype(bool value) { this._hasNoSupertype = value; } @override List<EntityRefBuilder> get interfaces => _interfaces ??= <EntityRefBuilder>[]; /// Interfaces appearing in an `implements` clause, if any. set interfaces(List<EntityRefBuilder> value) { this._interfaces = value; } @override bool get isAbstract => _isAbstract ??= false; /// Indicates whether the class is declared with the `abstract` keyword. set isAbstract(bool value) { this._isAbstract = value; } @override bool get isMixinApplication => _isMixinApplication ??= false; /// Indicates whether the class is declared using mixin application syntax. set isMixinApplication(bool value) { this._isMixinApplication = value; } @override List<EntityRefBuilder> get mixins => _mixins ??= <EntityRefBuilder>[]; /// Mixins appearing in a `with` clause, if any. set mixins(List<EntityRefBuilder> value) { this._mixins = value; } @override String get name => _name ??= ''; /// Name of the class. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the class name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override int get notSimplyBoundedSlot => _notSimplyBoundedSlot ??= 0; /// If the class might not be simply bounded, a nonzero slot id which is unique /// within this compilation unit. If this id is found in /// [LinkedUnit.notSimplyBounded], then at least one of this class's type /// parameters is not simply bounded, hence this class can't be used as a raw /// type when specifying the bound of a type parameter. /// /// Otherwise, zero. set notSimplyBoundedSlot(int value) { assert(value == null || value >= 0); this._notSimplyBoundedSlot = value; } @override List<EntityRefBuilder> get superclassConstraints => _superclassConstraints ??= <EntityRefBuilder>[]; /// Superclass constraints for this mixin declaration. The list will be empty /// if this class is not a mixin declaration, or if the declaration does not /// have an `on` clause (in which case the type `Object` is implied). set superclassConstraints(List<EntityRefBuilder> value) { this._superclassConstraints = value; } @override List<String> get superInvokedNames => _superInvokedNames ??= <String>[]; /// Names of methods, getters, setters, and operators that this mixin /// declaration super-invokes. For setters this includes the trailing "=". /// The list will be empty if this class is not a mixin declaration. set superInvokedNames(List<String> value) { this._superInvokedNames = value; } @override EntityRefBuilder get supertype => _supertype; /// Supertype of the class, or `null` if either (a) the class doesn't /// explicitly declare a supertype (and hence has supertype `Object`), or (b) /// the class *is* `Object` (and hence has no supertype). set supertype(EntityRefBuilder value) { this._supertype = value; } @override List<UnlinkedTypeParamBuilder> get typeParameters => _typeParameters ??= <UnlinkedTypeParamBuilder>[]; /// Type parameters of the class, if any. set typeParameters(List<UnlinkedTypeParamBuilder> value) { this._typeParameters = value; } UnlinkedClassBuilder( {List<UnlinkedExprBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, List<UnlinkedExecutableBuilder> executables, List<UnlinkedVariableBuilder> fields, bool hasNoSupertype, List<EntityRefBuilder> interfaces, bool isAbstract, bool isMixinApplication, List<EntityRefBuilder> mixins, String name, int nameOffset, int notSimplyBoundedSlot, List<EntityRefBuilder> superclassConstraints, List<String> superInvokedNames, EntityRefBuilder supertype, List<UnlinkedTypeParamBuilder> typeParameters}) : _annotations = annotations, _codeRange = codeRange, _documentationComment = documentationComment, _executables = executables, _fields = fields, _hasNoSupertype = hasNoSupertype, _interfaces = interfaces, _isAbstract = isAbstract, _isMixinApplication = isMixinApplication, _mixins = mixins, _name = name, _nameOffset = nameOffset, _notSimplyBoundedSlot = notSimplyBoundedSlot, _superclassConstraints = superclassConstraints, _superInvokedNames = superInvokedNames, _supertype = supertype, _typeParameters = typeParameters; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _codeRange = null; _documentationComment = null; _executables?.forEach((b) => b.flushInformative()); _fields?.forEach((b) => b.flushInformative()); _interfaces?.forEach((b) => b.flushInformative()); _mixins?.forEach((b) => b.flushInformative()); _nameOffset = null; _superclassConstraints?.forEach((b) => b.flushInformative()); _supertype?.flushInformative(); _typeParameters?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); if (this._executables == null) { signature.addInt(0); } else { signature.addInt(this._executables.length); for (var x in this._executables) { x?.collectApiSignature(signature); } } signature.addBool(this._supertype != null); this._supertype?.collectApiSignature(signature); if (this._fields == null) { signature.addInt(0); } else { signature.addInt(this._fields.length); for (var x in this._fields) { x?.collectApiSignature(signature); } } if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } if (this._interfaces == null) { signature.addInt(0); } else { signature.addInt(this._interfaces.length); for (var x in this._interfaces) { x?.collectApiSignature(signature); } } signature.addBool(this._isAbstract == true); if (this._typeParameters == null) { signature.addInt(0); } else { signature.addInt(this._typeParameters.length); for (var x in this._typeParameters) { x?.collectApiSignature(signature); } } if (this._mixins == null) { signature.addInt(0); } else { signature.addInt(this._mixins.length); for (var x in this._mixins) { x?.collectApiSignature(signature); } } signature.addBool(this._isMixinApplication == true); signature.addBool(this._hasNoSupertype == true); if (this._superclassConstraints == null) { signature.addInt(0); } else { signature.addInt(this._superclassConstraints.length); for (var x in this._superclassConstraints) { x?.collectApiSignature(signature); } } if (this._superInvokedNames == null) { signature.addInt(0); } else { signature.addInt(this._superInvokedNames.length); for (var x in this._superInvokedNames) { signature.addString(x); } } signature.addInt(this._notSimplyBoundedSlot ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_codeRange; fb.Offset offset_documentationComment; fb.Offset offset_executables; fb.Offset offset_fields; fb.Offset offset_interfaces; fb.Offset offset_mixins; fb.Offset offset_name; fb.Offset offset_superclassConstraints; fb.Offset offset_superInvokedNames; fb.Offset offset_supertype; fb.Offset offset_typeParameters; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (!(_executables == null || _executables.isEmpty)) { offset_executables = fbBuilder .writeList(_executables.map((b) => b.finish(fbBuilder)).toList()); } if (!(_fields == null || _fields.isEmpty)) { offset_fields = fbBuilder.writeList(_fields.map((b) => b.finish(fbBuilder)).toList()); } if (!(_interfaces == null || _interfaces.isEmpty)) { offset_interfaces = fbBuilder .writeList(_interfaces.map((b) => b.finish(fbBuilder)).toList()); } if (!(_mixins == null || _mixins.isEmpty)) { offset_mixins = fbBuilder.writeList(_mixins.map((b) => b.finish(fbBuilder)).toList()); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_superclassConstraints == null || _superclassConstraints.isEmpty)) { offset_superclassConstraints = fbBuilder.writeList( _superclassConstraints.map((b) => b.finish(fbBuilder)).toList()); } if (!(_superInvokedNames == null || _superInvokedNames.isEmpty)) { offset_superInvokedNames = fbBuilder.writeList( _superInvokedNames.map((b) => fbBuilder.writeString(b)).toList()); } if (_supertype != null) { offset_supertype = _supertype.finish(fbBuilder); } if (!(_typeParameters == null || _typeParameters.isEmpty)) { offset_typeParameters = fbBuilder .writeList(_typeParameters.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(5, offset_annotations); } if (offset_codeRange != null) { fbBuilder.addOffset(13, offset_codeRange); } if (offset_documentationComment != null) { fbBuilder.addOffset(6, offset_documentationComment); } if (offset_executables != null) { fbBuilder.addOffset(2, offset_executables); } if (offset_fields != null) { fbBuilder.addOffset(4, offset_fields); } if (_hasNoSupertype == true) { fbBuilder.addBool(12, true); } if (offset_interfaces != null) { fbBuilder.addOffset(7, offset_interfaces); } if (_isAbstract == true) { fbBuilder.addBool(8, true); } if (_isMixinApplication == true) { fbBuilder.addBool(11, true); } if (offset_mixins != null) { fbBuilder.addOffset(10, offset_mixins); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } if (_notSimplyBoundedSlot != null && _notSimplyBoundedSlot != 0) { fbBuilder.addUint32(16, _notSimplyBoundedSlot); } if (offset_superclassConstraints != null) { fbBuilder.addOffset(14, offset_superclassConstraints); } if (offset_superInvokedNames != null) { fbBuilder.addOffset(15, offset_superInvokedNames); } if (offset_supertype != null) { fbBuilder.addOffset(3, offset_supertype); } if (offset_typeParameters != null) { fbBuilder.addOffset(9, offset_typeParameters); } return fbBuilder.endTable(); } } class _UnlinkedClassReader extends fb.TableReader<_UnlinkedClassImpl> { const _UnlinkedClassReader(); @override _UnlinkedClassImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedClassImpl(bc, offset); } class _UnlinkedClassImpl extends Object with _UnlinkedClassMixin implements idl.UnlinkedClass { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedClassImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.CodeRange _codeRange; idl.UnlinkedDocumentationComment _documentationComment; List<idl.UnlinkedExecutable> _executables; List<idl.UnlinkedVariable> _fields; bool _hasNoSupertype; List<idl.EntityRef> _interfaces; bool _isAbstract; bool _isMixinApplication; List<idl.EntityRef> _mixins; String _name; int _nameOffset; int _notSimplyBoundedSlot; List<idl.EntityRef> _superclassConstraints; List<String> _superInvokedNames; idl.EntityRef _supertype; List<idl.UnlinkedTypeParam> _typeParameters; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 13, null); return _codeRange; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 6, null); return _documentationComment; } @override List<idl.UnlinkedExecutable> get executables { _executables ??= const fb.ListReader<idl.UnlinkedExecutable>( const _UnlinkedExecutableReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedExecutable>[]); return _executables; } @override List<idl.UnlinkedVariable> get fields { _fields ??= const fb.ListReader<idl.UnlinkedVariable>( const _UnlinkedVariableReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnlinkedVariable>[]); return _fields; } @override bool get hasNoSupertype { _hasNoSupertype ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 12, false); return _hasNoSupertype; } @override List<idl.EntityRef> get interfaces { _interfaces ??= const fb.ListReader<idl.EntityRef>(const _EntityRefReader()) .vTableGet(_bc, _bcOffset, 7, const <idl.EntityRef>[]); return _interfaces; } @override bool get isAbstract { _isAbstract ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 8, false); return _isAbstract; } @override bool get isMixinApplication { _isMixinApplication ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 11, false); return _isMixinApplication; } @override List<idl.EntityRef> get mixins { _mixins ??= const fb.ListReader<idl.EntityRef>(const _EntityRefReader()) .vTableGet(_bc, _bcOffset, 10, const <idl.EntityRef>[]); return _mixins; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } @override int get notSimplyBoundedSlot { _notSimplyBoundedSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 16, 0); return _notSimplyBoundedSlot; } @override List<idl.EntityRef> get superclassConstraints { _superclassConstraints ??= const fb.ListReader<idl.EntityRef>(const _EntityRefReader()) .vTableGet(_bc, _bcOffset, 14, const <idl.EntityRef>[]); return _superclassConstraints; } @override List<String> get superInvokedNames { _superInvokedNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 15, const <String>[]); return _superInvokedNames; } @override idl.EntityRef get supertype { _supertype ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 3, null); return _supertype; } @override List<idl.UnlinkedTypeParam> get typeParameters { _typeParameters ??= const fb.ListReader<idl.UnlinkedTypeParam>( const _UnlinkedTypeParamReader()) .vTableGet(_bc, _bcOffset, 9, const <idl.UnlinkedTypeParam>[]); return _typeParameters; } } abstract class _UnlinkedClassMixin implements idl.UnlinkedClass { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (executables.isNotEmpty) _result["executables"] = executables.map((_value) => _value.toJson()).toList(); if (fields.isNotEmpty) _result["fields"] = fields.map((_value) => _value.toJson()).toList(); if (hasNoSupertype != false) _result["hasNoSupertype"] = hasNoSupertype; if (interfaces.isNotEmpty) _result["interfaces"] = interfaces.map((_value) => _value.toJson()).toList(); if (isAbstract != false) _result["isAbstract"] = isAbstract; if (isMixinApplication != false) _result["isMixinApplication"] = isMixinApplication; if (mixins.isNotEmpty) _result["mixins"] = mixins.map((_value) => _value.toJson()).toList(); if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (notSimplyBoundedSlot != 0) _result["notSimplyBoundedSlot"] = notSimplyBoundedSlot; if (superclassConstraints.isNotEmpty) _result["superclassConstraints"] = superclassConstraints.map((_value) => _value.toJson()).toList(); if (superInvokedNames.isNotEmpty) _result["superInvokedNames"] = superInvokedNames; if (supertype != null) _result["supertype"] = supertype.toJson(); if (typeParameters.isNotEmpty) _result["typeParameters"] = typeParameters.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "codeRange": codeRange, "documentationComment": documentationComment, "executables": executables, "fields": fields, "hasNoSupertype": hasNoSupertype, "interfaces": interfaces, "isAbstract": isAbstract, "isMixinApplication": isMixinApplication, "mixins": mixins, "name": name, "nameOffset": nameOffset, "notSimplyBoundedSlot": notSimplyBoundedSlot, "superclassConstraints": superclassConstraints, "superInvokedNames": superInvokedNames, "supertype": supertype, "typeParameters": typeParameters, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedCombinatorBuilder extends Object with _UnlinkedCombinatorMixin implements idl.UnlinkedCombinator { int _end; List<String> _hides; int _offset; List<String> _shows; @override int get end => _end ??= 0; /// If this is a `show` combinator, offset of the end of the list of shown /// names. Otherwise zero. set end(int value) { assert(value == null || value >= 0); this._end = value; } @override List<String> get hides => _hides ??= <String>[]; /// List of names which are hidden. Empty if this is a `show` combinator. set hides(List<String> value) { this._hides = value; } @override int get offset => _offset ??= 0; /// If this is a `show` combinator, offset of the `show` keyword. Otherwise /// zero. set offset(int value) { assert(value == null || value >= 0); this._offset = value; } @override List<String> get shows => _shows ??= <String>[]; /// List of names which are shown. Empty if this is a `hide` combinator. set shows(List<String> value) { this._shows = value; } UnlinkedCombinatorBuilder( {int end, List<String> hides, int offset, List<String> shows}) : _end = end, _hides = hides, _offset = offset, _shows = shows; /// Flush [informative] data recursively. void flushInformative() { _end = null; _offset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._shows == null) { signature.addInt(0); } else { signature.addInt(this._shows.length); for (var x in this._shows) { signature.addString(x); } } if (this._hides == null) { signature.addInt(0); } else { signature.addInt(this._hides.length); for (var x in this._hides) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_hides; fb.Offset offset_shows; if (!(_hides == null || _hides.isEmpty)) { offset_hides = fbBuilder .writeList(_hides.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_shows == null || _shows.isEmpty)) { offset_shows = fbBuilder .writeList(_shows.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (_end != null && _end != 0) { fbBuilder.addUint32(3, _end); } if (offset_hides != null) { fbBuilder.addOffset(1, offset_hides); } if (_offset != null && _offset != 0) { fbBuilder.addUint32(2, _offset); } if (offset_shows != null) { fbBuilder.addOffset(0, offset_shows); } return fbBuilder.endTable(); } } class _UnlinkedCombinatorReader extends fb.TableReader<_UnlinkedCombinatorImpl> { const _UnlinkedCombinatorReader(); @override _UnlinkedCombinatorImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedCombinatorImpl(bc, offset); } class _UnlinkedCombinatorImpl extends Object with _UnlinkedCombinatorMixin implements idl.UnlinkedCombinator { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedCombinatorImpl(this._bc, this._bcOffset); int _end; List<String> _hides; int _offset; List<String> _shows; @override int get end { _end ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _end; } @override List<String> get hides { _hides ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _hides; } @override int get offset { _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _offset; } @override List<String> get shows { _shows ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 0, const <String>[]); return _shows; } } abstract class _UnlinkedCombinatorMixin implements idl.UnlinkedCombinator { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (end != 0) _result["end"] = end; if (hides.isNotEmpty) _result["hides"] = hides; if (offset != 0) _result["offset"] = offset; if (shows.isNotEmpty) _result["shows"] = shows; return _result; } @override Map<String, Object> toMap() => { "end": end, "hides": hides, "offset": offset, "shows": shows, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedConfigurationBuilder extends Object with _UnlinkedConfigurationMixin implements idl.UnlinkedConfiguration { String _name; String _uri; String _value; @override String get name => _name ??= ''; /// The name of the declared variable whose value is being used in the /// condition. set name(String value) { this._name = value; } @override String get uri => _uri ??= ''; /// The URI of the implementation library to be used if the condition is true. set uri(String value) { this._uri = value; } @override String get value => _value ??= ''; /// The value to which the value of the declared variable will be compared, /// or `true` if the condition does not include an equality test. set value(String value) { this._value = value; } UnlinkedConfigurationBuilder({String name, String uri, String value}) : _name = name, _uri = uri, _value = value; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addString(this._value ?? ''); signature.addString(this._uri ?? ''); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_name; fb.Offset offset_uri; fb.Offset offset_value; if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (_uri != null) { offset_uri = fbBuilder.writeString(_uri); } if (_value != null) { offset_value = fbBuilder.writeString(_value); } fbBuilder.startTable(); if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (offset_uri != null) { fbBuilder.addOffset(2, offset_uri); } if (offset_value != null) { fbBuilder.addOffset(1, offset_value); } return fbBuilder.endTable(); } } class _UnlinkedConfigurationReader extends fb.TableReader<_UnlinkedConfigurationImpl> { const _UnlinkedConfigurationReader(); @override _UnlinkedConfigurationImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedConfigurationImpl(bc, offset); } class _UnlinkedConfigurationImpl extends Object with _UnlinkedConfigurationMixin implements idl.UnlinkedConfiguration { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedConfigurationImpl(this._bc, this._bcOffset); String _name; String _uri; String _value; @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override String get uri { _uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 2, ''); return _uri; } @override String get value { _value ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _value; } } abstract class _UnlinkedConfigurationMixin implements idl.UnlinkedConfiguration { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (name != '') _result["name"] = name; if (uri != '') _result["uri"] = uri; if (value != '') _result["value"] = value; return _result; } @override Map<String, Object> toMap() => { "name": name, "uri": uri, "value": value, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedConstructorInitializerBuilder extends Object with _UnlinkedConstructorInitializerMixin implements idl.UnlinkedConstructorInitializer { List<String> _argumentNames; List<UnlinkedExprBuilder> _arguments; UnlinkedExprBuilder _expression; idl.UnlinkedConstructorInitializerKind _kind; String _name; @override List<String> get argumentNames => _argumentNames ??= <String>[]; /// If there are `m` [arguments] and `n` [argumentNames], then each argument /// from [arguments] with index `i` such that `n + i - m >= 0`, should be used /// with the name at `n + i - m`. set argumentNames(List<String> value) { this._argumentNames = value; } @override List<UnlinkedExprBuilder> get arguments => _arguments ??= <UnlinkedExprBuilder>[]; /// If [kind] is `thisInvocation` or `superInvocation`, the arguments of the /// invocation. Otherwise empty. set arguments(List<UnlinkedExprBuilder> value) { this._arguments = value; } @override UnlinkedExprBuilder get expression => _expression; /// If [kind] is `field`, the expression of the field initializer. /// Otherwise `null`. set expression(UnlinkedExprBuilder value) { this._expression = value; } @override idl.UnlinkedConstructorInitializerKind get kind => _kind ??= idl.UnlinkedConstructorInitializerKind.field; /// The kind of the constructor initializer (field, redirect, super). set kind(idl.UnlinkedConstructorInitializerKind value) { this._kind = value; } @override String get name => _name ??= ''; /// If [kind] is `field`, the name of the field declared in the class. If /// [kind] is `thisInvocation`, the name of the constructor, declared in this /// class, to redirect to. If [kind] is `superInvocation`, the name of the /// constructor, declared in the superclass, to invoke. set name(String value) { this._name = value; } UnlinkedConstructorInitializerBuilder( {List<String> argumentNames, List<UnlinkedExprBuilder> arguments, UnlinkedExprBuilder expression, idl.UnlinkedConstructorInitializerKind kind, String name}) : _argumentNames = argumentNames, _arguments = arguments, _expression = expression, _kind = kind, _name = name; /// Flush [informative] data recursively. void flushInformative() { _arguments?.forEach((b) => b.flushInformative()); _expression?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addBool(this._expression != null); this._expression?.collectApiSignature(signature); signature.addInt(this._kind == null ? 0 : this._kind.index); if (this._arguments == null) { signature.addInt(0); } else { signature.addInt(this._arguments.length); for (var x in this._arguments) { x?.collectApiSignature(signature); } } if (this._argumentNames == null) { signature.addInt(0); } else { signature.addInt(this._argumentNames.length); for (var x in this._argumentNames) { signature.addString(x); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_argumentNames; fb.Offset offset_arguments; fb.Offset offset_expression; fb.Offset offset_name; if (!(_argumentNames == null || _argumentNames.isEmpty)) { offset_argumentNames = fbBuilder.writeList( _argumentNames.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_arguments == null || _arguments.isEmpty)) { offset_arguments = fbBuilder .writeList(_arguments.map((b) => b.finish(fbBuilder)).toList()); } if (_expression != null) { offset_expression = _expression.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (offset_argumentNames != null) { fbBuilder.addOffset(4, offset_argumentNames); } if (offset_arguments != null) { fbBuilder.addOffset(3, offset_arguments); } if (offset_expression != null) { fbBuilder.addOffset(1, offset_expression); } if (_kind != null && _kind != idl.UnlinkedConstructorInitializerKind.field) { fbBuilder.addUint8(2, _kind.index); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } return fbBuilder.endTable(); } } class _UnlinkedConstructorInitializerReader extends fb.TableReader<_UnlinkedConstructorInitializerImpl> { const _UnlinkedConstructorInitializerReader(); @override _UnlinkedConstructorInitializerImpl createObject( fb.BufferContext bc, int offset) => new _UnlinkedConstructorInitializerImpl(bc, offset); } class _UnlinkedConstructorInitializerImpl extends Object with _UnlinkedConstructorInitializerMixin implements idl.UnlinkedConstructorInitializer { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedConstructorInitializerImpl(this._bc, this._bcOffset); List<String> _argumentNames; List<idl.UnlinkedExpr> _arguments; idl.UnlinkedExpr _expression; idl.UnlinkedConstructorInitializerKind _kind; String _name; @override List<String> get argumentNames { _argumentNames ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 4, const <String>[]); return _argumentNames; } @override List<idl.UnlinkedExpr> get arguments { _arguments ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.UnlinkedExpr>[]); return _arguments; } @override idl.UnlinkedExpr get expression { _expression ??= const _UnlinkedExprReader().vTableGet(_bc, _bcOffset, 1, null); return _expression; } @override idl.UnlinkedConstructorInitializerKind get kind { _kind ??= const _UnlinkedConstructorInitializerKindReader().vTableGet( _bc, _bcOffset, 2, idl.UnlinkedConstructorInitializerKind.field); return _kind; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } } abstract class _UnlinkedConstructorInitializerMixin implements idl.UnlinkedConstructorInitializer { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (argumentNames.isNotEmpty) _result["argumentNames"] = argumentNames; if (arguments.isNotEmpty) _result["arguments"] = arguments.map((_value) => _value.toJson()).toList(); if (expression != null) _result["expression"] = expression.toJson(); if (kind != idl.UnlinkedConstructorInitializerKind.field) _result["kind"] = kind.toString().split('.')[1]; if (name != '') _result["name"] = name; return _result; } @override Map<String, Object> toMap() => { "argumentNames": argumentNames, "arguments": arguments, "expression": expression, "kind": kind, "name": name, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedDocumentationCommentBuilder extends Object with _UnlinkedDocumentationCommentMixin implements idl.UnlinkedDocumentationComment { String _text; @override Null get length => throw new UnimplementedError('attempt to access deprecated field'); @override Null get offset => throw new UnimplementedError('attempt to access deprecated field'); @override String get text => _text ??= ''; /// Text of the documentation comment, with '\r\n' replaced by '\n'. /// /// References appearing within the doc comment in square brackets are not /// specially encoded. set text(String value) { this._text = value; } UnlinkedDocumentationCommentBuilder({String text}) : _text = text; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._text ?? ''); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_text; if (_text != null) { offset_text = fbBuilder.writeString(_text); } fbBuilder.startTable(); if (offset_text != null) { fbBuilder.addOffset(1, offset_text); } return fbBuilder.endTable(); } } class _UnlinkedDocumentationCommentReader extends fb.TableReader<_UnlinkedDocumentationCommentImpl> { const _UnlinkedDocumentationCommentReader(); @override _UnlinkedDocumentationCommentImpl createObject( fb.BufferContext bc, int offset) => new _UnlinkedDocumentationCommentImpl(bc, offset); } class _UnlinkedDocumentationCommentImpl extends Object with _UnlinkedDocumentationCommentMixin implements idl.UnlinkedDocumentationComment { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedDocumentationCommentImpl(this._bc, this._bcOffset); String _text; @override Null get length => throw new UnimplementedError('attempt to access deprecated field'); @override Null get offset => throw new UnimplementedError('attempt to access deprecated field'); @override String get text { _text ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _text; } } abstract class _UnlinkedDocumentationCommentMixin implements idl.UnlinkedDocumentationComment { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (text != '') _result["text"] = text; return _result; } @override Map<String, Object> toMap() => { "text": text, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedEnumBuilder extends Object with _UnlinkedEnumMixin implements idl.UnlinkedEnum { List<UnlinkedExprBuilder> _annotations; CodeRangeBuilder _codeRange; UnlinkedDocumentationCommentBuilder _documentationComment; String _name; int _nameOffset; List<UnlinkedEnumValueBuilder> _values; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this enum. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the enum. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the enum, or `null` if there is no documentation /// comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override String get name => _name ??= ''; /// Name of the enum type. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the enum name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override List<UnlinkedEnumValueBuilder> get values => _values ??= <UnlinkedEnumValueBuilder>[]; /// Values listed in the enum declaration, in declaration order. set values(List<UnlinkedEnumValueBuilder> value) { this._values = value; } UnlinkedEnumBuilder( {List<UnlinkedExprBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, String name, int nameOffset, List<UnlinkedEnumValueBuilder> values}) : _annotations = annotations, _codeRange = codeRange, _documentationComment = documentationComment, _name = name, _nameOffset = nameOffset, _values = values; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _codeRange = null; _documentationComment = null; _nameOffset = null; _values?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); if (this._values == null) { signature.addInt(0); } else { signature.addInt(this._values.length); for (var x in this._values) { x?.collectApiSignature(signature); } } if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_codeRange; fb.Offset offset_documentationComment; fb.Offset offset_name; fb.Offset offset_values; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_values == null || _values.isEmpty)) { offset_values = fbBuilder.writeList(_values.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(4, offset_annotations); } if (offset_codeRange != null) { fbBuilder.addOffset(5, offset_codeRange); } if (offset_documentationComment != null) { fbBuilder.addOffset(3, offset_documentationComment); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } if (offset_values != null) { fbBuilder.addOffset(2, offset_values); } return fbBuilder.endTable(); } } class _UnlinkedEnumReader extends fb.TableReader<_UnlinkedEnumImpl> { const _UnlinkedEnumReader(); @override _UnlinkedEnumImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedEnumImpl(bc, offset); } class _UnlinkedEnumImpl extends Object with _UnlinkedEnumMixin implements idl.UnlinkedEnum { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedEnumImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.CodeRange _codeRange; idl.UnlinkedDocumentationComment _documentationComment; String _name; int _nameOffset; List<idl.UnlinkedEnumValue> _values; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 5, null); return _codeRange; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 3, null); return _documentationComment; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } @override List<idl.UnlinkedEnumValue> get values { _values ??= const fb.ListReader<idl.UnlinkedEnumValue>( const _UnlinkedEnumValueReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedEnumValue>[]); return _values; } } abstract class _UnlinkedEnumMixin implements idl.UnlinkedEnum { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (values.isNotEmpty) _result["values"] = values.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "codeRange": codeRange, "documentationComment": documentationComment, "name": name, "nameOffset": nameOffset, "values": values, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedEnumValueBuilder extends Object with _UnlinkedEnumValueMixin implements idl.UnlinkedEnumValue { List<UnlinkedExprBuilder> _annotations; UnlinkedDocumentationCommentBuilder _documentationComment; String _name; int _nameOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this value. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the enum value, or `null` if there is no /// documentation comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override String get name => _name ??= ''; /// Name of the enumerated value. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the enum value name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } UnlinkedEnumValueBuilder( {List<UnlinkedExprBuilder> annotations, UnlinkedDocumentationCommentBuilder documentationComment, String name, int nameOffset}) : _annotations = annotations, _documentationComment = documentationComment, _name = name, _nameOffset = nameOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _documentationComment = null; _nameOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_documentationComment; fb.Offset offset_name; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(3, offset_annotations); } if (offset_documentationComment != null) { fbBuilder.addOffset(2, offset_documentationComment); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } return fbBuilder.endTable(); } } class _UnlinkedEnumValueReader extends fb.TableReader<_UnlinkedEnumValueImpl> { const _UnlinkedEnumValueReader(); @override _UnlinkedEnumValueImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedEnumValueImpl(bc, offset); } class _UnlinkedEnumValueImpl extends Object with _UnlinkedEnumValueMixin implements idl.UnlinkedEnumValue { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedEnumValueImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.UnlinkedDocumentationComment _documentationComment; String _name; int _nameOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 2, null); return _documentationComment; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } } abstract class _UnlinkedEnumValueMixin implements idl.UnlinkedEnumValue { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "documentationComment": documentationComment, "name": name, "nameOffset": nameOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedExecutableBuilder extends Object with _UnlinkedExecutableMixin implements idl.UnlinkedExecutable { List<UnlinkedExprBuilder> _annotations; UnlinkedExprBuilder _bodyExpr; CodeRangeBuilder _codeRange; List<UnlinkedConstructorInitializerBuilder> _constantInitializers; int _constCycleSlot; UnlinkedDocumentationCommentBuilder _documentationComment; int _inferredReturnTypeSlot; bool _isAbstract; bool _isAsynchronous; bool _isConst; bool _isExternal; bool _isFactory; bool _isGenerator; bool _isRedirectedConstructor; bool _isStatic; idl.UnlinkedExecutableKind _kind; List<UnlinkedExecutableBuilder> _localFunctions; String _name; int _nameEnd; int _nameOffset; List<UnlinkedParamBuilder> _parameters; int _periodOffset; EntityRefBuilder _redirectedConstructor; String _redirectedConstructorName; EntityRefBuilder _returnType; List<UnlinkedTypeParamBuilder> _typeParameters; int _visibleLength; int _visibleOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this executable. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override UnlinkedExprBuilder get bodyExpr => _bodyExpr; /// If this executable's function body is declared using `=>`, the expression /// to the right of the `=>`. May be omitted if neither type inference nor /// constant evaluation depends on the function body. set bodyExpr(UnlinkedExprBuilder value) { this._bodyExpr = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the executable. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override List<UnlinkedConstructorInitializerBuilder> get constantInitializers => _constantInitializers ??= <UnlinkedConstructorInitializerBuilder>[]; /// If a constant [UnlinkedExecutableKind.constructor], the constructor /// initializers. Otherwise empty. set constantInitializers(List<UnlinkedConstructorInitializerBuilder> value) { this._constantInitializers = value; } @override int get constCycleSlot => _constCycleSlot ??= 0; /// If [kind] is [UnlinkedExecutableKind.constructor] and [isConst] is `true`, /// a nonzero slot id which is unique within this compilation unit. If this /// id is found in [LinkedUnit.constCycles], then this constructor is part of /// a cycle. /// /// Otherwise, zero. set constCycleSlot(int value) { assert(value == null || value >= 0); this._constCycleSlot = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the executable, or `null` if there is no /// documentation comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override int get inferredReturnTypeSlot => _inferredReturnTypeSlot ??= 0; /// If this executable's return type is inferable, nonzero slot id /// identifying which entry in [LinkedUnit.types] contains the inferred /// return type. If there is no matching entry in [LinkedUnit.types], then /// no return type was inferred for this variable, so its static type is /// `dynamic`. set inferredReturnTypeSlot(int value) { assert(value == null || value >= 0); this._inferredReturnTypeSlot = value; } @override bool get isAbstract => _isAbstract ??= false; /// Indicates whether the executable is declared using the `abstract` keyword. set isAbstract(bool value) { this._isAbstract = value; } @override bool get isAsynchronous => _isAsynchronous ??= false; /// Indicates whether the executable has body marked as being asynchronous. set isAsynchronous(bool value) { this._isAsynchronous = value; } @override bool get isConst => _isConst ??= false; /// Indicates whether the executable is declared using the `const` keyword. set isConst(bool value) { this._isConst = value; } @override bool get isExternal => _isExternal ??= false; /// Indicates whether the executable is declared using the `external` keyword. set isExternal(bool value) { this._isExternal = value; } @override bool get isFactory => _isFactory ??= false; /// Indicates whether the executable is declared using the `factory` keyword. set isFactory(bool value) { this._isFactory = value; } @override bool get isGenerator => _isGenerator ??= false; /// Indicates whether the executable has body marked as being a generator. set isGenerator(bool value) { this._isGenerator = value; } @override bool get isRedirectedConstructor => _isRedirectedConstructor ??= false; /// Indicates whether the executable is a redirected constructor. set isRedirectedConstructor(bool value) { this._isRedirectedConstructor = value; } @override bool get isStatic => _isStatic ??= false; /// Indicates whether the executable is declared using the `static` keyword. /// /// Note that for top level executables, this flag is false, since they are /// not declared using the `static` keyword (even though they are considered /// static for semantic purposes). set isStatic(bool value) { this._isStatic = value; } @override idl.UnlinkedExecutableKind get kind => _kind ??= idl.UnlinkedExecutableKind.functionOrMethod; /// The kind of the executable (function/method, getter, setter, or /// constructor). set kind(idl.UnlinkedExecutableKind value) { this._kind = value; } @override List<UnlinkedExecutableBuilder> get localFunctions => _localFunctions ??= <UnlinkedExecutableBuilder>[]; /// The list of local functions. set localFunctions(List<UnlinkedExecutableBuilder> value) { this._localFunctions = value; } @override Null get localLabels => throw new UnimplementedError('attempt to access deprecated field'); @override Null get localVariables => throw new UnimplementedError('attempt to access deprecated field'); @override String get name => _name ??= ''; /// Name of the executable. For setters, this includes the trailing "=". For /// named constructors, this excludes the class name and excludes the ".". /// For unnamed constructors, this is the empty string. set name(String value) { this._name = value; } @override int get nameEnd => _nameEnd ??= 0; /// If [kind] is [UnlinkedExecutableKind.constructor] and [name] is not empty, /// the offset of the end of the constructor name. Otherwise zero. set nameEnd(int value) { assert(value == null || value >= 0); this._nameEnd = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the executable name relative to the beginning of the file. For /// named constructors, this excludes the class name and excludes the ".". /// For unnamed constructors, this is the offset of the class name (i.e. the /// offset of the second "C" in "class C { C(); }"). set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override List<UnlinkedParamBuilder> get parameters => _parameters ??= <UnlinkedParamBuilder>[]; /// Parameters of the executable, if any. Note that getters have no /// parameters (hence this will be the empty list), and setters have a single /// parameter. set parameters(List<UnlinkedParamBuilder> value) { this._parameters = value; } @override int get periodOffset => _periodOffset ??= 0; /// If [kind] is [UnlinkedExecutableKind.constructor] and [name] is not empty, /// the offset of the period before the constructor name. Otherwise zero. set periodOffset(int value) { assert(value == null || value >= 0); this._periodOffset = value; } @override EntityRefBuilder get redirectedConstructor => _redirectedConstructor; /// If [isRedirectedConstructor] and [isFactory] are both `true`, the /// constructor to which this constructor redirects; otherwise empty. set redirectedConstructor(EntityRefBuilder value) { this._redirectedConstructor = value; } @override String get redirectedConstructorName => _redirectedConstructorName ??= ''; /// If [isRedirectedConstructor] is `true` and [isFactory] is `false`, the /// name of the constructor that this constructor redirects to; otherwise /// empty. set redirectedConstructorName(String value) { this._redirectedConstructorName = value; } @override EntityRefBuilder get returnType => _returnType; /// Declared return type of the executable. Absent if the executable is a /// constructor or the return type is implicit. Absent for executables /// associated with variable initializers and closures, since these /// executables may have return types that are not accessible via direct /// imports. set returnType(EntityRefBuilder value) { this._returnType = value; } @override List<UnlinkedTypeParamBuilder> get typeParameters => _typeParameters ??= <UnlinkedTypeParamBuilder>[]; /// Type parameters of the executable, if any. Empty if support for generic /// method syntax is disabled. set typeParameters(List<UnlinkedTypeParamBuilder> value) { this._typeParameters = value; } @override int get visibleLength => _visibleLength ??= 0; /// If a local function, the length of the visible range; zero otherwise. set visibleLength(int value) { assert(value == null || value >= 0); this._visibleLength = value; } @override int get visibleOffset => _visibleOffset ??= 0; /// If a local function, the beginning of the visible range; zero otherwise. set visibleOffset(int value) { assert(value == null || value >= 0); this._visibleOffset = value; } UnlinkedExecutableBuilder( {List<UnlinkedExprBuilder> annotations, UnlinkedExprBuilder bodyExpr, CodeRangeBuilder codeRange, List<UnlinkedConstructorInitializerBuilder> constantInitializers, int constCycleSlot, UnlinkedDocumentationCommentBuilder documentationComment, int inferredReturnTypeSlot, bool isAbstract, bool isAsynchronous, bool isConst, bool isExternal, bool isFactory, bool isGenerator, bool isRedirectedConstructor, bool isStatic, idl.UnlinkedExecutableKind kind, List<UnlinkedExecutableBuilder> localFunctions, String name, int nameEnd, int nameOffset, List<UnlinkedParamBuilder> parameters, int periodOffset, EntityRefBuilder redirectedConstructor, String redirectedConstructorName, EntityRefBuilder returnType, List<UnlinkedTypeParamBuilder> typeParameters, int visibleLength, int visibleOffset}) : _annotations = annotations, _bodyExpr = bodyExpr, _codeRange = codeRange, _constantInitializers = constantInitializers, _constCycleSlot = constCycleSlot, _documentationComment = documentationComment, _inferredReturnTypeSlot = inferredReturnTypeSlot, _isAbstract = isAbstract, _isAsynchronous = isAsynchronous, _isConst = isConst, _isExternal = isExternal, _isFactory = isFactory, _isGenerator = isGenerator, _isRedirectedConstructor = isRedirectedConstructor, _isStatic = isStatic, _kind = kind, _localFunctions = localFunctions, _name = name, _nameEnd = nameEnd, _nameOffset = nameOffset, _parameters = parameters, _periodOffset = periodOffset, _redirectedConstructor = redirectedConstructor, _redirectedConstructorName = redirectedConstructorName, _returnType = returnType, _typeParameters = typeParameters, _visibleLength = visibleLength, _visibleOffset = visibleOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _bodyExpr?.flushInformative(); _codeRange = null; _constantInitializers?.forEach((b) => b.flushInformative()); _documentationComment = null; _isAsynchronous = null; _isGenerator = null; _localFunctions?.forEach((b) => b.flushInformative()); _nameEnd = null; _nameOffset = null; _parameters?.forEach((b) => b.flushInformative()); _periodOffset = null; _redirectedConstructor?.flushInformative(); _returnType?.flushInformative(); _typeParameters?.forEach((b) => b.flushInformative()); _visibleLength = null; _visibleOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); if (this._parameters == null) { signature.addInt(0); } else { signature.addInt(this._parameters.length); for (var x in this._parameters) { x?.collectApiSignature(signature); } } signature.addBool(this._returnType != null); this._returnType?.collectApiSignature(signature); signature.addInt(this._kind == null ? 0 : this._kind.index); signature.addInt(this._inferredReturnTypeSlot ?? 0); if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } signature.addBool(this._isFactory == true); signature.addBool(this._isStatic == true); signature.addBool(this._isAbstract == true); signature.addBool(this._isExternal == true); signature.addBool(this._isConst == true); signature.addBool(this._isRedirectedConstructor == true); if (this._constantInitializers == null) { signature.addInt(0); } else { signature.addInt(this._constantInitializers.length); for (var x in this._constantInitializers) { x?.collectApiSignature(signature); } } signature.addBool(this._redirectedConstructor != null); this._redirectedConstructor?.collectApiSignature(signature); if (this._typeParameters == null) { signature.addInt(0); } else { signature.addInt(this._typeParameters.length); for (var x in this._typeParameters) { x?.collectApiSignature(signature); } } signature.addString(this._redirectedConstructorName ?? ''); if (this._localFunctions == null) { signature.addInt(0); } else { signature.addInt(this._localFunctions.length); for (var x in this._localFunctions) { x?.collectApiSignature(signature); } } signature.addInt(this._constCycleSlot ?? 0); signature.addBool(this._bodyExpr != null); this._bodyExpr?.collectApiSignature(signature); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_bodyExpr; fb.Offset offset_codeRange; fb.Offset offset_constantInitializers; fb.Offset offset_documentationComment; fb.Offset offset_localFunctions; fb.Offset offset_name; fb.Offset offset_parameters; fb.Offset offset_redirectedConstructor; fb.Offset offset_redirectedConstructorName; fb.Offset offset_returnType; fb.Offset offset_typeParameters; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_bodyExpr != null) { offset_bodyExpr = _bodyExpr.finish(fbBuilder); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (!(_constantInitializers == null || _constantInitializers.isEmpty)) { offset_constantInitializers = fbBuilder.writeList( _constantInitializers.map((b) => b.finish(fbBuilder)).toList()); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (!(_localFunctions == null || _localFunctions.isEmpty)) { offset_localFunctions = fbBuilder .writeList(_localFunctions.map((b) => b.finish(fbBuilder)).toList()); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_parameters == null || _parameters.isEmpty)) { offset_parameters = fbBuilder .writeList(_parameters.map((b) => b.finish(fbBuilder)).toList()); } if (_redirectedConstructor != null) { offset_redirectedConstructor = _redirectedConstructor.finish(fbBuilder); } if (_redirectedConstructorName != null) { offset_redirectedConstructorName = fbBuilder.writeString(_redirectedConstructorName); } if (_returnType != null) { offset_returnType = _returnType.finish(fbBuilder); } if (!(_typeParameters == null || _typeParameters.isEmpty)) { offset_typeParameters = fbBuilder .writeList(_typeParameters.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(6, offset_annotations); } if (offset_bodyExpr != null) { fbBuilder.addOffset(29, offset_bodyExpr); } if (offset_codeRange != null) { fbBuilder.addOffset(26, offset_codeRange); } if (offset_constantInitializers != null) { fbBuilder.addOffset(14, offset_constantInitializers); } if (_constCycleSlot != null && _constCycleSlot != 0) { fbBuilder.addUint32(25, _constCycleSlot); } if (offset_documentationComment != null) { fbBuilder.addOffset(7, offset_documentationComment); } if (_inferredReturnTypeSlot != null && _inferredReturnTypeSlot != 0) { fbBuilder.addUint32(5, _inferredReturnTypeSlot); } if (_isAbstract == true) { fbBuilder.addBool(10, true); } if (_isAsynchronous == true) { fbBuilder.addBool(27, true); } if (_isConst == true) { fbBuilder.addBool(12, true); } if (_isExternal == true) { fbBuilder.addBool(11, true); } if (_isFactory == true) { fbBuilder.addBool(8, true); } if (_isGenerator == true) { fbBuilder.addBool(28, true); } if (_isRedirectedConstructor == true) { fbBuilder.addBool(13, true); } if (_isStatic == true) { fbBuilder.addBool(9, true); } if (_kind != null && _kind != idl.UnlinkedExecutableKind.functionOrMethod) { fbBuilder.addUint8(4, _kind.index); } if (offset_localFunctions != null) { fbBuilder.addOffset(18, offset_localFunctions); } if (offset_name != null) { fbBuilder.addOffset(1, offset_name); } if (_nameEnd != null && _nameEnd != 0) { fbBuilder.addUint32(23, _nameEnd); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(0, _nameOffset); } if (offset_parameters != null) { fbBuilder.addOffset(2, offset_parameters); } if (_periodOffset != null && _periodOffset != 0) { fbBuilder.addUint32(24, _periodOffset); } if (offset_redirectedConstructor != null) { fbBuilder.addOffset(15, offset_redirectedConstructor); } if (offset_redirectedConstructorName != null) { fbBuilder.addOffset(17, offset_redirectedConstructorName); } if (offset_returnType != null) { fbBuilder.addOffset(3, offset_returnType); } if (offset_typeParameters != null) { fbBuilder.addOffset(16, offset_typeParameters); } if (_visibleLength != null && _visibleLength != 0) { fbBuilder.addUint32(20, _visibleLength); } if (_visibleOffset != null && _visibleOffset != 0) { fbBuilder.addUint32(21, _visibleOffset); } return fbBuilder.endTable(); } } class _UnlinkedExecutableReader extends fb.TableReader<_UnlinkedExecutableImpl> { const _UnlinkedExecutableReader(); @override _UnlinkedExecutableImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedExecutableImpl(bc, offset); } class _UnlinkedExecutableImpl extends Object with _UnlinkedExecutableMixin implements idl.UnlinkedExecutable { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedExecutableImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.UnlinkedExpr _bodyExpr; idl.CodeRange _codeRange; List<idl.UnlinkedConstructorInitializer> _constantInitializers; int _constCycleSlot; idl.UnlinkedDocumentationComment _documentationComment; int _inferredReturnTypeSlot; bool _isAbstract; bool _isAsynchronous; bool _isConst; bool _isExternal; bool _isFactory; bool _isGenerator; bool _isRedirectedConstructor; bool _isStatic; idl.UnlinkedExecutableKind _kind; List<idl.UnlinkedExecutable> _localFunctions; String _name; int _nameEnd; int _nameOffset; List<idl.UnlinkedParam> _parameters; int _periodOffset; idl.EntityRef _redirectedConstructor; String _redirectedConstructorName; idl.EntityRef _returnType; List<idl.UnlinkedTypeParam> _typeParameters; int _visibleLength; int _visibleOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 6, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.UnlinkedExpr get bodyExpr { _bodyExpr ??= const _UnlinkedExprReader().vTableGet(_bc, _bcOffset, 29, null); return _bodyExpr; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 26, null); return _codeRange; } @override List<idl.UnlinkedConstructorInitializer> get constantInitializers { _constantInitializers ??= const fb.ListReader<idl.UnlinkedConstructorInitializer>( const _UnlinkedConstructorInitializerReader()) .vTableGet(_bc, _bcOffset, 14, const <idl.UnlinkedConstructorInitializer>[]); return _constantInitializers; } @override int get constCycleSlot { _constCycleSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 25, 0); return _constCycleSlot; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 7, null); return _documentationComment; } @override int get inferredReturnTypeSlot { _inferredReturnTypeSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 5, 0); return _inferredReturnTypeSlot; } @override bool get isAbstract { _isAbstract ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 10, false); return _isAbstract; } @override bool get isAsynchronous { _isAsynchronous ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 27, false); return _isAsynchronous; } @override bool get isConst { _isConst ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 12, false); return _isConst; } @override bool get isExternal { _isExternal ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 11, false); return _isExternal; } @override bool get isFactory { _isFactory ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 8, false); return _isFactory; } @override bool get isGenerator { _isGenerator ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 28, false); return _isGenerator; } @override bool get isRedirectedConstructor { _isRedirectedConstructor ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 13, false); return _isRedirectedConstructor; } @override bool get isStatic { _isStatic ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 9, false); return _isStatic; } @override idl.UnlinkedExecutableKind get kind { _kind ??= const _UnlinkedExecutableKindReader().vTableGet( _bc, _bcOffset, 4, idl.UnlinkedExecutableKind.functionOrMethod); return _kind; } @override List<idl.UnlinkedExecutable> get localFunctions { _localFunctions ??= const fb.ListReader<idl.UnlinkedExecutable>( const _UnlinkedExecutableReader()) .vTableGet(_bc, _bcOffset, 18, const <idl.UnlinkedExecutable>[]); return _localFunctions; } @override Null get localLabels => throw new UnimplementedError('attempt to access deprecated field'); @override Null get localVariables => throw new UnimplementedError('attempt to access deprecated field'); @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _name; } @override int get nameEnd { _nameEnd ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 23, 0); return _nameEnd; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _nameOffset; } @override List<idl.UnlinkedParam> get parameters { _parameters ??= const fb.ListReader<idl.UnlinkedParam>(const _UnlinkedParamReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedParam>[]); return _parameters; } @override int get periodOffset { _periodOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 24, 0); return _periodOffset; } @override idl.EntityRef get redirectedConstructor { _redirectedConstructor ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 15, null); return _redirectedConstructor; } @override String get redirectedConstructorName { _redirectedConstructorName ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 17, ''); return _redirectedConstructorName; } @override idl.EntityRef get returnType { _returnType ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 3, null); return _returnType; } @override List<idl.UnlinkedTypeParam> get typeParameters { _typeParameters ??= const fb.ListReader<idl.UnlinkedTypeParam>( const _UnlinkedTypeParamReader()) .vTableGet(_bc, _bcOffset, 16, const <idl.UnlinkedTypeParam>[]); return _typeParameters; } @override int get visibleLength { _visibleLength ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 20, 0); return _visibleLength; } @override int get visibleOffset { _visibleOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 21, 0); return _visibleOffset; } } abstract class _UnlinkedExecutableMixin implements idl.UnlinkedExecutable { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (bodyExpr != null) _result["bodyExpr"] = bodyExpr.toJson(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (constantInitializers.isNotEmpty) _result["constantInitializers"] = constantInitializers.map((_value) => _value.toJson()).toList(); if (constCycleSlot != 0) _result["constCycleSlot"] = constCycleSlot; if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (inferredReturnTypeSlot != 0) _result["inferredReturnTypeSlot"] = inferredReturnTypeSlot; if (isAbstract != false) _result["isAbstract"] = isAbstract; if (isAsynchronous != false) _result["isAsynchronous"] = isAsynchronous; if (isConst != false) _result["isConst"] = isConst; if (isExternal != false) _result["isExternal"] = isExternal; if (isFactory != false) _result["isFactory"] = isFactory; if (isGenerator != false) _result["isGenerator"] = isGenerator; if (isRedirectedConstructor != false) _result["isRedirectedConstructor"] = isRedirectedConstructor; if (isStatic != false) _result["isStatic"] = isStatic; if (kind != idl.UnlinkedExecutableKind.functionOrMethod) _result["kind"] = kind.toString().split('.')[1]; if (localFunctions.isNotEmpty) _result["localFunctions"] = localFunctions.map((_value) => _value.toJson()).toList(); if (name != '') _result["name"] = name; if (nameEnd != 0) _result["nameEnd"] = nameEnd; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (parameters.isNotEmpty) _result["parameters"] = parameters.map((_value) => _value.toJson()).toList(); if (periodOffset != 0) _result["periodOffset"] = periodOffset; if (redirectedConstructor != null) _result["redirectedConstructor"] = redirectedConstructor.toJson(); if (redirectedConstructorName != '') _result["redirectedConstructorName"] = redirectedConstructorName; if (returnType != null) _result["returnType"] = returnType.toJson(); if (typeParameters.isNotEmpty) _result["typeParameters"] = typeParameters.map((_value) => _value.toJson()).toList(); if (visibleLength != 0) _result["visibleLength"] = visibleLength; if (visibleOffset != 0) _result["visibleOffset"] = visibleOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "bodyExpr": bodyExpr, "codeRange": codeRange, "constantInitializers": constantInitializers, "constCycleSlot": constCycleSlot, "documentationComment": documentationComment, "inferredReturnTypeSlot": inferredReturnTypeSlot, "isAbstract": isAbstract, "isAsynchronous": isAsynchronous, "isConst": isConst, "isExternal": isExternal, "isFactory": isFactory, "isGenerator": isGenerator, "isRedirectedConstructor": isRedirectedConstructor, "isStatic": isStatic, "kind": kind, "localFunctions": localFunctions, "name": name, "nameEnd": nameEnd, "nameOffset": nameOffset, "parameters": parameters, "periodOffset": periodOffset, "redirectedConstructor": redirectedConstructor, "redirectedConstructorName": redirectedConstructorName, "returnType": returnType, "typeParameters": typeParameters, "visibleLength": visibleLength, "visibleOffset": visibleOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedExportNonPublicBuilder extends Object with _UnlinkedExportNonPublicMixin implements idl.UnlinkedExportNonPublic { List<UnlinkedExprBuilder> _annotations; int _offset; int _uriEnd; int _uriOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this export directive. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override int get offset => _offset ??= 0; /// Offset of the "export" keyword. set offset(int value) { assert(value == null || value >= 0); this._offset = value; } @override int get uriEnd => _uriEnd ??= 0; /// End of the URI string (including quotes) relative to the beginning of the /// file. set uriEnd(int value) { assert(value == null || value >= 0); this._uriEnd = value; } @override int get uriOffset => _uriOffset ??= 0; /// Offset of the URI string (including quotes) relative to the beginning of /// the file. set uriOffset(int value) { assert(value == null || value >= 0); this._uriOffset = value; } UnlinkedExportNonPublicBuilder( {List<UnlinkedExprBuilder> annotations, int offset, int uriEnd, int uriOffset}) : _annotations = annotations, _offset = offset, _uriEnd = uriEnd, _uriOffset = uriOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _offset = null; _uriEnd = null; _uriOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(3, offset_annotations); } if (_offset != null && _offset != 0) { fbBuilder.addUint32(0, _offset); } if (_uriEnd != null && _uriEnd != 0) { fbBuilder.addUint32(1, _uriEnd); } if (_uriOffset != null && _uriOffset != 0) { fbBuilder.addUint32(2, _uriOffset); } return fbBuilder.endTable(); } } class _UnlinkedExportNonPublicReader extends fb.TableReader<_UnlinkedExportNonPublicImpl> { const _UnlinkedExportNonPublicReader(); @override _UnlinkedExportNonPublicImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedExportNonPublicImpl(bc, offset); } class _UnlinkedExportNonPublicImpl extends Object with _UnlinkedExportNonPublicMixin implements idl.UnlinkedExportNonPublic { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedExportNonPublicImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; int _offset; int _uriEnd; int _uriOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.UnlinkedExpr>[]); return _annotations; } @override int get offset { _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _offset; } @override int get uriEnd { _uriEnd ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _uriEnd; } @override int get uriOffset { _uriOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _uriOffset; } } abstract class _UnlinkedExportNonPublicMixin implements idl.UnlinkedExportNonPublic { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (offset != 0) _result["offset"] = offset; if (uriEnd != 0) _result["uriEnd"] = uriEnd; if (uriOffset != 0) _result["uriOffset"] = uriOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "offset": offset, "uriEnd": uriEnd, "uriOffset": uriOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedExportPublicBuilder extends Object with _UnlinkedExportPublicMixin implements idl.UnlinkedExportPublic { List<UnlinkedCombinatorBuilder> _combinators; List<UnlinkedConfigurationBuilder> _configurations; String _uri; @override List<UnlinkedCombinatorBuilder> get combinators => _combinators ??= <UnlinkedCombinatorBuilder>[]; /// Combinators contained in this export declaration. set combinators(List<UnlinkedCombinatorBuilder> value) { this._combinators = value; } @override List<UnlinkedConfigurationBuilder> get configurations => _configurations ??= <UnlinkedConfigurationBuilder>[]; /// Configurations used to control which library will actually be loaded at /// run-time. set configurations(List<UnlinkedConfigurationBuilder> value) { this._configurations = value; } @override String get uri => _uri ??= ''; /// URI used in the source code to reference the exported library. set uri(String value) { this._uri = value; } UnlinkedExportPublicBuilder( {List<UnlinkedCombinatorBuilder> combinators, List<UnlinkedConfigurationBuilder> configurations, String uri}) : _combinators = combinators, _configurations = configurations, _uri = uri; /// Flush [informative] data recursively. void flushInformative() { _combinators?.forEach((b) => b.flushInformative()); _configurations?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._uri ?? ''); if (this._combinators == null) { signature.addInt(0); } else { signature.addInt(this._combinators.length); for (var x in this._combinators) { x?.collectApiSignature(signature); } } if (this._configurations == null) { signature.addInt(0); } else { signature.addInt(this._configurations.length); for (var x in this._configurations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_combinators; fb.Offset offset_configurations; fb.Offset offset_uri; if (!(_combinators == null || _combinators.isEmpty)) { offset_combinators = fbBuilder .writeList(_combinators.map((b) => b.finish(fbBuilder)).toList()); } if (!(_configurations == null || _configurations.isEmpty)) { offset_configurations = fbBuilder .writeList(_configurations.map((b) => b.finish(fbBuilder)).toList()); } if (_uri != null) { offset_uri = fbBuilder.writeString(_uri); } fbBuilder.startTable(); if (offset_combinators != null) { fbBuilder.addOffset(1, offset_combinators); } if (offset_configurations != null) { fbBuilder.addOffset(2, offset_configurations); } if (offset_uri != null) { fbBuilder.addOffset(0, offset_uri); } return fbBuilder.endTable(); } } class _UnlinkedExportPublicReader extends fb.TableReader<_UnlinkedExportPublicImpl> { const _UnlinkedExportPublicReader(); @override _UnlinkedExportPublicImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedExportPublicImpl(bc, offset); } class _UnlinkedExportPublicImpl extends Object with _UnlinkedExportPublicMixin implements idl.UnlinkedExportPublic { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedExportPublicImpl(this._bc, this._bcOffset); List<idl.UnlinkedCombinator> _combinators; List<idl.UnlinkedConfiguration> _configurations; String _uri; @override List<idl.UnlinkedCombinator> get combinators { _combinators ??= const fb.ListReader<idl.UnlinkedCombinator>( const _UnlinkedCombinatorReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.UnlinkedCombinator>[]); return _combinators; } @override List<idl.UnlinkedConfiguration> get configurations { _configurations ??= const fb.ListReader<idl.UnlinkedConfiguration>( const _UnlinkedConfigurationReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedConfiguration>[]); return _configurations; } @override String get uri { _uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _uri; } } abstract class _UnlinkedExportPublicMixin implements idl.UnlinkedExportPublic { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (combinators.isNotEmpty) _result["combinators"] = combinators.map((_value) => _value.toJson()).toList(); if (configurations.isNotEmpty) _result["configurations"] = configurations.map((_value) => _value.toJson()).toList(); if (uri != '') _result["uri"] = uri; return _result; } @override Map<String, Object> toMap() => { "combinators": combinators, "configurations": configurations, "uri": uri, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedExprBuilder extends Object with _UnlinkedExprMixin implements idl.UnlinkedExpr { List<idl.UnlinkedExprAssignOperator> _assignmentOperators; List<double> _doubles; List<int> _ints; bool _isValidConst; List<idl.UnlinkedExprOperation> _operations; List<EntityRefBuilder> _references; String _sourceRepresentation; List<String> _strings; @override List<idl.UnlinkedExprAssignOperator> get assignmentOperators => _assignmentOperators ??= <idl.UnlinkedExprAssignOperator>[]; /// Sequence of operators used by assignment operations. set assignmentOperators(List<idl.UnlinkedExprAssignOperator> value) { this._assignmentOperators = value; } @override List<double> get doubles => _doubles ??= <double>[]; /// Sequence of 64-bit doubles consumed by the operation `pushDouble`. set doubles(List<double> value) { this._doubles = value; } @override List<int> get ints => _ints ??= <int>[]; /// Sequence of unsigned 32-bit integers consumed by the operations /// `pushArgument`, `pushInt`, `shiftOr`, `concatenate`, `invokeConstructor`, /// `makeList`, and `makeMap`. set ints(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._ints = value; } @override bool get isValidConst => _isValidConst ??= false; /// Indicates whether the expression is a valid potentially constant /// expression. set isValidConst(bool value) { this._isValidConst = value; } @override List<idl.UnlinkedExprOperation> get operations => _operations ??= <idl.UnlinkedExprOperation>[]; /// Sequence of operations to execute (starting with an empty stack) to form /// the constant value. set operations(List<idl.UnlinkedExprOperation> value) { this._operations = value; } @override List<EntityRefBuilder> get references => _references ??= <EntityRefBuilder>[]; /// Sequence of language constructs consumed by the operations /// `pushReference`, `invokeConstructor`, `makeList`, and `makeMap`. Note /// that in the case of `pushReference` (and sometimes `invokeConstructor` the /// actual entity being referred to may be something other than a type. set references(List<EntityRefBuilder> value) { this._references = value; } @override String get sourceRepresentation => _sourceRepresentation ??= ''; /// String representation of the expression in a form suitable to be tokenized /// and parsed. set sourceRepresentation(String value) { this._sourceRepresentation = value; } @override List<String> get strings => _strings ??= <String>[]; /// Sequence of strings consumed by the operations `pushString` and /// `invokeConstructor`. set strings(List<String> value) { this._strings = value; } UnlinkedExprBuilder( {List<idl.UnlinkedExprAssignOperator> assignmentOperators, List<double> doubles, List<int> ints, bool isValidConst, List<idl.UnlinkedExprOperation> operations, List<EntityRefBuilder> references, String sourceRepresentation, List<String> strings}) : _assignmentOperators = assignmentOperators, _doubles = doubles, _ints = ints, _isValidConst = isValidConst, _operations = operations, _references = references, _sourceRepresentation = sourceRepresentation, _strings = strings; /// Flush [informative] data recursively. void flushInformative() { _references?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._operations == null) { signature.addInt(0); } else { signature.addInt(this._operations.length); for (var x in this._operations) { signature.addInt(x.index); } } if (this._ints == null) { signature.addInt(0); } else { signature.addInt(this._ints.length); for (var x in this._ints) { signature.addInt(x); } } if (this._references == null) { signature.addInt(0); } else { signature.addInt(this._references.length); for (var x in this._references) { x?.collectApiSignature(signature); } } if (this._strings == null) { signature.addInt(0); } else { signature.addInt(this._strings.length); for (var x in this._strings) { signature.addString(x); } } if (this._doubles == null) { signature.addInt(0); } else { signature.addInt(this._doubles.length); for (var x in this._doubles) { signature.addDouble(x); } } signature.addBool(this._isValidConst == true); if (this._assignmentOperators == null) { signature.addInt(0); } else { signature.addInt(this._assignmentOperators.length); for (var x in this._assignmentOperators) { signature.addInt(x.index); } } signature.addString(this._sourceRepresentation ?? ''); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_assignmentOperators; fb.Offset offset_doubles; fb.Offset offset_ints; fb.Offset offset_operations; fb.Offset offset_references; fb.Offset offset_sourceRepresentation; fb.Offset offset_strings; if (!(_assignmentOperators == null || _assignmentOperators.isEmpty)) { offset_assignmentOperators = fbBuilder .writeListUint8(_assignmentOperators.map((b) => b.index).toList()); } if (!(_doubles == null || _doubles.isEmpty)) { offset_doubles = fbBuilder.writeListFloat64(_doubles); } if (!(_ints == null || _ints.isEmpty)) { offset_ints = fbBuilder.writeListUint32(_ints); } if (!(_operations == null || _operations.isEmpty)) { offset_operations = fbBuilder.writeListUint8(_operations.map((b) => b.index).toList()); } if (!(_references == null || _references.isEmpty)) { offset_references = fbBuilder .writeList(_references.map((b) => b.finish(fbBuilder)).toList()); } if (_sourceRepresentation != null) { offset_sourceRepresentation = fbBuilder.writeString(_sourceRepresentation); } if (!(_strings == null || _strings.isEmpty)) { offset_strings = fbBuilder .writeList(_strings.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_assignmentOperators != null) { fbBuilder.addOffset(6, offset_assignmentOperators); } if (offset_doubles != null) { fbBuilder.addOffset(4, offset_doubles); } if (offset_ints != null) { fbBuilder.addOffset(1, offset_ints); } if (_isValidConst == true) { fbBuilder.addBool(5, true); } if (offset_operations != null) { fbBuilder.addOffset(0, offset_operations); } if (offset_references != null) { fbBuilder.addOffset(2, offset_references); } if (offset_sourceRepresentation != null) { fbBuilder.addOffset(7, offset_sourceRepresentation); } if (offset_strings != null) { fbBuilder.addOffset(3, offset_strings); } return fbBuilder.endTable(); } } class _UnlinkedExprReader extends fb.TableReader<_UnlinkedExprImpl> { const _UnlinkedExprReader(); @override _UnlinkedExprImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedExprImpl(bc, offset); } class _UnlinkedExprImpl extends Object with _UnlinkedExprMixin implements idl.UnlinkedExpr { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedExprImpl(this._bc, this._bcOffset); List<idl.UnlinkedExprAssignOperator> _assignmentOperators; List<double> _doubles; List<int> _ints; bool _isValidConst; List<idl.UnlinkedExprOperation> _operations; List<idl.EntityRef> _references; String _sourceRepresentation; List<String> _strings; @override List<idl.UnlinkedExprAssignOperator> get assignmentOperators { _assignmentOperators ??= const fb.ListReader<idl.UnlinkedExprAssignOperator>( const _UnlinkedExprAssignOperatorReader()) .vTableGet( _bc, _bcOffset, 6, const <idl.UnlinkedExprAssignOperator>[]); return _assignmentOperators; } @override List<double> get doubles { _doubles ??= const fb.Float64ListReader() .vTableGet(_bc, _bcOffset, 4, const <double>[]); return _doubles; } @override List<int> get ints { _ints ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 1, const <int>[]); return _ints; } @override bool get isValidConst { _isValidConst ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 5, false); return _isValidConst; } @override List<idl.UnlinkedExprOperation> get operations { _operations ??= const fb.ListReader<idl.UnlinkedExprOperation>( const _UnlinkedExprOperationReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.UnlinkedExprOperation>[]); return _operations; } @override List<idl.EntityRef> get references { _references ??= const fb.ListReader<idl.EntityRef>(const _EntityRefReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.EntityRef>[]); return _references; } @override String get sourceRepresentation { _sourceRepresentation ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 7, ''); return _sourceRepresentation; } @override List<String> get strings { _strings ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 3, const <String>[]); return _strings; } } abstract class _UnlinkedExprMixin implements idl.UnlinkedExpr { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (assignmentOperators.isNotEmpty) _result["assignmentOperators"] = assignmentOperators .map((_value) => _value.toString().split('.')[1]) .toList(); if (doubles.isNotEmpty) _result["doubles"] = doubles .map((_value) => _value.isFinite ? _value : _value.toString()) .toList(); if (ints.isNotEmpty) _result["ints"] = ints; if (isValidConst != false) _result["isValidConst"] = isValidConst; if (operations.isNotEmpty) _result["operations"] = operations.map((_value) => _value.toString().split('.')[1]).toList(); if (references.isNotEmpty) _result["references"] = references.map((_value) => _value.toJson()).toList(); if (sourceRepresentation != '') _result["sourceRepresentation"] = sourceRepresentation; if (strings.isNotEmpty) _result["strings"] = strings; return _result; } @override Map<String, Object> toMap() => { "assignmentOperators": assignmentOperators, "doubles": doubles, "ints": ints, "isValidConst": isValidConst, "operations": operations, "references": references, "sourceRepresentation": sourceRepresentation, "strings": strings, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedExtensionBuilder extends Object with _UnlinkedExtensionMixin implements idl.UnlinkedExtension { List<UnlinkedExprBuilder> _annotations; CodeRangeBuilder _codeRange; UnlinkedDocumentationCommentBuilder _documentationComment; List<UnlinkedExecutableBuilder> _executables; EntityRefBuilder _extendedType; List<UnlinkedVariableBuilder> _fields; String _name; int _nameOffset; List<UnlinkedTypeParamBuilder> _typeParameters; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this extension. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the extension. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the extension, or `null` if there is no /// documentation comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override List<UnlinkedExecutableBuilder> get executables => _executables ??= <UnlinkedExecutableBuilder>[]; /// Executable objects (methods, getters, and setters) contained in the /// extension. set executables(List<UnlinkedExecutableBuilder> value) { this._executables = value; } @override EntityRefBuilder get extendedType => _extendedType; /// The type being extended. set extendedType(EntityRefBuilder value) { this._extendedType = value; } @override List<UnlinkedVariableBuilder> get fields => _fields ??= <UnlinkedVariableBuilder>[]; /// Field declarations contained in the extension. set fields(List<UnlinkedVariableBuilder> value) { this._fields = value; } @override String get name => _name ??= ''; /// Name of the extension, or an empty string if there is no name. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the extension name relative to the beginning of the file, or /// zero if there is no name. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override List<UnlinkedTypeParamBuilder> get typeParameters => _typeParameters ??= <UnlinkedTypeParamBuilder>[]; /// Type parameters of the extension, if any. set typeParameters(List<UnlinkedTypeParamBuilder> value) { this._typeParameters = value; } UnlinkedExtensionBuilder( {List<UnlinkedExprBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, List<UnlinkedExecutableBuilder> executables, EntityRefBuilder extendedType, List<UnlinkedVariableBuilder> fields, String name, int nameOffset, List<UnlinkedTypeParamBuilder> typeParameters}) : _annotations = annotations, _codeRange = codeRange, _documentationComment = documentationComment, _executables = executables, _extendedType = extendedType, _fields = fields, _name = name, _nameOffset = nameOffset, _typeParameters = typeParameters; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _codeRange = null; _documentationComment = null; _executables?.forEach((b) => b.flushInformative()); _extendedType?.flushInformative(); _fields?.forEach((b) => b.flushInformative()); _nameOffset = null; _typeParameters?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); if (this._executables == null) { signature.addInt(0); } else { signature.addInt(this._executables.length); for (var x in this._executables) { x?.collectApiSignature(signature); } } signature.addBool(this._extendedType != null); this._extendedType?.collectApiSignature(signature); if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } if (this._typeParameters == null) { signature.addInt(0); } else { signature.addInt(this._typeParameters.length); for (var x in this._typeParameters) { x?.collectApiSignature(signature); } } if (this._fields == null) { signature.addInt(0); } else { signature.addInt(this._fields.length); for (var x in this._fields) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_codeRange; fb.Offset offset_documentationComment; fb.Offset offset_executables; fb.Offset offset_extendedType; fb.Offset offset_fields; fb.Offset offset_name; fb.Offset offset_typeParameters; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (!(_executables == null || _executables.isEmpty)) { offset_executables = fbBuilder .writeList(_executables.map((b) => b.finish(fbBuilder)).toList()); } if (_extendedType != null) { offset_extendedType = _extendedType.finish(fbBuilder); } if (!(_fields == null || _fields.isEmpty)) { offset_fields = fbBuilder.writeList(_fields.map((b) => b.finish(fbBuilder)).toList()); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_typeParameters == null || _typeParameters.isEmpty)) { offset_typeParameters = fbBuilder .writeList(_typeParameters.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(4, offset_annotations); } if (offset_codeRange != null) { fbBuilder.addOffset(7, offset_codeRange); } if (offset_documentationComment != null) { fbBuilder.addOffset(5, offset_documentationComment); } if (offset_executables != null) { fbBuilder.addOffset(2, offset_executables); } if (offset_extendedType != null) { fbBuilder.addOffset(3, offset_extendedType); } if (offset_fields != null) { fbBuilder.addOffset(8, offset_fields); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } if (offset_typeParameters != null) { fbBuilder.addOffset(6, offset_typeParameters); } return fbBuilder.endTable(); } } class _UnlinkedExtensionReader extends fb.TableReader<_UnlinkedExtensionImpl> { const _UnlinkedExtensionReader(); @override _UnlinkedExtensionImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedExtensionImpl(bc, offset); } class _UnlinkedExtensionImpl extends Object with _UnlinkedExtensionMixin implements idl.UnlinkedExtension { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedExtensionImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.CodeRange _codeRange; idl.UnlinkedDocumentationComment _documentationComment; List<idl.UnlinkedExecutable> _executables; idl.EntityRef _extendedType; List<idl.UnlinkedVariable> _fields; String _name; int _nameOffset; List<idl.UnlinkedTypeParam> _typeParameters; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 7, null); return _codeRange; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 5, null); return _documentationComment; } @override List<idl.UnlinkedExecutable> get executables { _executables ??= const fb.ListReader<idl.UnlinkedExecutable>( const _UnlinkedExecutableReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedExecutable>[]); return _executables; } @override idl.EntityRef get extendedType { _extendedType ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 3, null); return _extendedType; } @override List<idl.UnlinkedVariable> get fields { _fields ??= const fb.ListReader<idl.UnlinkedVariable>( const _UnlinkedVariableReader()) .vTableGet(_bc, _bcOffset, 8, const <idl.UnlinkedVariable>[]); return _fields; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } @override List<idl.UnlinkedTypeParam> get typeParameters { _typeParameters ??= const fb.ListReader<idl.UnlinkedTypeParam>( const _UnlinkedTypeParamReader()) .vTableGet(_bc, _bcOffset, 6, const <idl.UnlinkedTypeParam>[]); return _typeParameters; } } abstract class _UnlinkedExtensionMixin implements idl.UnlinkedExtension { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (executables.isNotEmpty) _result["executables"] = executables.map((_value) => _value.toJson()).toList(); if (extendedType != null) _result["extendedType"] = extendedType.toJson(); if (fields.isNotEmpty) _result["fields"] = fields.map((_value) => _value.toJson()).toList(); if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (typeParameters.isNotEmpty) _result["typeParameters"] = typeParameters.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "codeRange": codeRange, "documentationComment": documentationComment, "executables": executables, "extendedType": extendedType, "fields": fields, "name": name, "nameOffset": nameOffset, "typeParameters": typeParameters, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedImportBuilder extends Object with _UnlinkedImportMixin implements idl.UnlinkedImport { List<UnlinkedExprBuilder> _annotations; List<UnlinkedCombinatorBuilder> _combinators; List<UnlinkedConfigurationBuilder> _configurations; bool _isDeferred; bool _isImplicit; int _offset; int _prefixOffset; int _prefixReference; String _uri; int _uriEnd; int _uriOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this import declaration. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override List<UnlinkedCombinatorBuilder> get combinators => _combinators ??= <UnlinkedCombinatorBuilder>[]; /// Combinators contained in this import declaration. set combinators(List<UnlinkedCombinatorBuilder> value) { this._combinators = value; } @override List<UnlinkedConfigurationBuilder> get configurations => _configurations ??= <UnlinkedConfigurationBuilder>[]; /// Configurations used to control which library will actually be loaded at /// run-time. set configurations(List<UnlinkedConfigurationBuilder> value) { this._configurations = value; } @override bool get isDeferred => _isDeferred ??= false; /// Indicates whether the import declaration uses the `deferred` keyword. set isDeferred(bool value) { this._isDeferred = value; } @override bool get isImplicit => _isImplicit ??= false; /// Indicates whether the import declaration is implicit. set isImplicit(bool value) { this._isImplicit = value; } @override int get offset => _offset ??= 0; /// If [isImplicit] is false, offset of the "import" keyword. If [isImplicit] /// is true, zero. set offset(int value) { assert(value == null || value >= 0); this._offset = value; } @override int get prefixOffset => _prefixOffset ??= 0; /// Offset of the prefix name relative to the beginning of the file, or zero /// if there is no prefix. set prefixOffset(int value) { assert(value == null || value >= 0); this._prefixOffset = value; } @override int get prefixReference => _prefixReference ??= 0; /// Index into [UnlinkedUnit.references] of the prefix declared by this /// import declaration, or zero if this import declaration declares no prefix. /// /// Note that multiple imports can declare the same prefix. set prefixReference(int value) { assert(value == null || value >= 0); this._prefixReference = value; } @override String get uri => _uri ??= ''; /// URI used in the source code to reference the imported library. set uri(String value) { this._uri = value; } @override int get uriEnd => _uriEnd ??= 0; /// End of the URI string (including quotes) relative to the beginning of the /// file. If [isImplicit] is true, zero. set uriEnd(int value) { assert(value == null || value >= 0); this._uriEnd = value; } @override int get uriOffset => _uriOffset ??= 0; /// Offset of the URI string (including quotes) relative to the beginning of /// the file. If [isImplicit] is true, zero. set uriOffset(int value) { assert(value == null || value >= 0); this._uriOffset = value; } UnlinkedImportBuilder( {List<UnlinkedExprBuilder> annotations, List<UnlinkedCombinatorBuilder> combinators, List<UnlinkedConfigurationBuilder> configurations, bool isDeferred, bool isImplicit, int offset, int prefixOffset, int prefixReference, String uri, int uriEnd, int uriOffset}) : _annotations = annotations, _combinators = combinators, _configurations = configurations, _isDeferred = isDeferred, _isImplicit = isImplicit, _offset = offset, _prefixOffset = prefixOffset, _prefixReference = prefixReference, _uri = uri, _uriEnd = uriEnd, _uriOffset = uriOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _combinators?.forEach((b) => b.flushInformative()); _configurations?.forEach((b) => b.flushInformative()); _offset = null; _prefixOffset = null; _uriEnd = null; _uriOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._uri ?? ''); if (this._combinators == null) { signature.addInt(0); } else { signature.addInt(this._combinators.length); for (var x in this._combinators) { x?.collectApiSignature(signature); } } signature.addBool(this._isImplicit == true); signature.addInt(this._prefixReference ?? 0); if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } signature.addBool(this._isDeferred == true); if (this._configurations == null) { signature.addInt(0); } else { signature.addInt(this._configurations.length); for (var x in this._configurations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_combinators; fb.Offset offset_configurations; fb.Offset offset_uri; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (!(_combinators == null || _combinators.isEmpty)) { offset_combinators = fbBuilder .writeList(_combinators.map((b) => b.finish(fbBuilder)).toList()); } if (!(_configurations == null || _configurations.isEmpty)) { offset_configurations = fbBuilder .writeList(_configurations.map((b) => b.finish(fbBuilder)).toList()); } if (_uri != null) { offset_uri = fbBuilder.writeString(_uri); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(8, offset_annotations); } if (offset_combinators != null) { fbBuilder.addOffset(4, offset_combinators); } if (offset_configurations != null) { fbBuilder.addOffset(10, offset_configurations); } if (_isDeferred == true) { fbBuilder.addBool(9, true); } if (_isImplicit == true) { fbBuilder.addBool(5, true); } if (_offset != null && _offset != 0) { fbBuilder.addUint32(0, _offset); } if (_prefixOffset != null && _prefixOffset != 0) { fbBuilder.addUint32(6, _prefixOffset); } if (_prefixReference != null && _prefixReference != 0) { fbBuilder.addUint32(7, _prefixReference); } if (offset_uri != null) { fbBuilder.addOffset(1, offset_uri); } if (_uriEnd != null && _uriEnd != 0) { fbBuilder.addUint32(2, _uriEnd); } if (_uriOffset != null && _uriOffset != 0) { fbBuilder.addUint32(3, _uriOffset); } return fbBuilder.endTable(); } } class _UnlinkedImportReader extends fb.TableReader<_UnlinkedImportImpl> { const _UnlinkedImportReader(); @override _UnlinkedImportImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedImportImpl(bc, offset); } class _UnlinkedImportImpl extends Object with _UnlinkedImportMixin implements idl.UnlinkedImport { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedImportImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; List<idl.UnlinkedCombinator> _combinators; List<idl.UnlinkedConfiguration> _configurations; bool _isDeferred; bool _isImplicit; int _offset; int _prefixOffset; int _prefixReference; String _uri; int _uriEnd; int _uriOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 8, const <idl.UnlinkedExpr>[]); return _annotations; } @override List<idl.UnlinkedCombinator> get combinators { _combinators ??= const fb.ListReader<idl.UnlinkedCombinator>( const _UnlinkedCombinatorReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnlinkedCombinator>[]); return _combinators; } @override List<idl.UnlinkedConfiguration> get configurations { _configurations ??= const fb.ListReader<idl.UnlinkedConfiguration>( const _UnlinkedConfigurationReader()) .vTableGet(_bc, _bcOffset, 10, const <idl.UnlinkedConfiguration>[]); return _configurations; } @override bool get isDeferred { _isDeferred ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 9, false); return _isDeferred; } @override bool get isImplicit { _isImplicit ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 5, false); return _isImplicit; } @override int get offset { _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _offset; } @override int get prefixOffset { _prefixOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 6, 0); return _prefixOffset; } @override int get prefixReference { _prefixReference ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 7, 0); return _prefixReference; } @override String get uri { _uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, ''); return _uri; } @override int get uriEnd { _uriEnd ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _uriEnd; } @override int get uriOffset { _uriOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _uriOffset; } } abstract class _UnlinkedImportMixin implements idl.UnlinkedImport { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (combinators.isNotEmpty) _result["combinators"] = combinators.map((_value) => _value.toJson()).toList(); if (configurations.isNotEmpty) _result["configurations"] = configurations.map((_value) => _value.toJson()).toList(); if (isDeferred != false) _result["isDeferred"] = isDeferred; if (isImplicit != false) _result["isImplicit"] = isImplicit; if (offset != 0) _result["offset"] = offset; if (prefixOffset != 0) _result["prefixOffset"] = prefixOffset; if (prefixReference != 0) _result["prefixReference"] = prefixReference; if (uri != '') _result["uri"] = uri; if (uriEnd != 0) _result["uriEnd"] = uriEnd; if (uriOffset != 0) _result["uriOffset"] = uriOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "combinators": combinators, "configurations": configurations, "isDeferred": isDeferred, "isImplicit": isImplicit, "offset": offset, "prefixOffset": prefixOffset, "prefixReference": prefixReference, "uri": uri, "uriEnd": uriEnd, "uriOffset": uriOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedInformativeDataBuilder extends Object with _UnlinkedInformativeDataMixin implements idl.UnlinkedInformativeData { int _variantField_2; int _variantField_3; int _variantField_9; int _variantField_8; List<int> _variantField_7; int _variantField_6; int _variantField_5; String _variantField_10; int _variantField_1; List<String> _variantField_4; idl.LinkedNodeKind _kind; @override int get codeLength { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_2 ??= 0; } set codeLength(int value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); assert(value == null || value >= 0); _variantField_2 = value; } @override int get codeOffset { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_3 ??= 0; } set codeOffset(int value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); assert(value == null || value >= 0); _variantField_3 = value; } @override int get combinatorEnd { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator); return _variantField_9 ??= 0; } set combinatorEnd(int value) { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator); assert(value == null || value >= 0); _variantField_9 = value; } @override int get combinatorKeywordOffset { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator); return _variantField_8 ??= 0; } @override int get importDirective_prefixOffset { assert(kind == idl.LinkedNodeKind.importDirective); return _variantField_8 ??= 0; } set combinatorKeywordOffset(int value) { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator); assert(value == null || value >= 0); _variantField_8 = value; } set importDirective_prefixOffset(int value) { assert(kind == idl.LinkedNodeKind.importDirective); assert(value == null || value >= 0); _variantField_8 = value; } @override List<int> get compilationUnit_lineStarts { assert(kind == idl.LinkedNodeKind.compilationUnit); return _variantField_7 ??= <int>[]; } /// Offsets of the first character of each line in the source code. set compilationUnit_lineStarts(List<int> value) { assert(kind == idl.LinkedNodeKind.compilationUnit); assert(value == null || value.every((e) => e >= 0)); _variantField_7 = value; } @override int get constructorDeclaration_periodOffset { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_6 ??= 0; } set constructorDeclaration_periodOffset(int value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); assert(value == null || value >= 0); _variantField_6 = value; } @override int get constructorDeclaration_returnTypeOffset { assert(kind == idl.LinkedNodeKind.constructorDeclaration); return _variantField_5 ??= 0; } set constructorDeclaration_returnTypeOffset(int value) { assert(kind == idl.LinkedNodeKind.constructorDeclaration); assert(value == null || value >= 0); _variantField_5 = value; } @override String get defaultFormalParameter_defaultValueCode { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); return _variantField_10 ??= ''; } /// If the parameter has a default value, the source text of the constant /// expression in the default value. Otherwise the empty string. set defaultFormalParameter_defaultValueCode(String value) { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_10 = value; } @override int get directiveKeywordOffset { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective); return _variantField_1 ??= 0; } @override int get nameOffset { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); return _variantField_1 ??= 0; } set directiveKeywordOffset(int value) { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective); assert(value == null || value >= 0); _variantField_1 = value; } set nameOffset(int value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); assert(value == null || value >= 0); _variantField_1 = value; } @override List<String> get documentationComment_tokens { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.topLevelVariableDeclaration); return _variantField_4 ??= <String>[]; } set documentationComment_tokens(List<String> value) { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.topLevelVariableDeclaration); _variantField_4 = value; } @override idl.LinkedNodeKind get kind => _kind ??= idl.LinkedNodeKind.adjacentStrings; /// The kind of the node. set kind(idl.LinkedNodeKind value) { this._kind = value; } UnlinkedInformativeDataBuilder.classDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.classDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.classTypeAlias({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.classTypeAlias, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.compilationUnit({ int codeLength, int codeOffset, List<int> compilationUnit_lineStarts, }) : _kind = idl.LinkedNodeKind.compilationUnit, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_7 = compilationUnit_lineStarts; UnlinkedInformativeDataBuilder.constructorDeclaration({ int codeLength, int codeOffset, int constructorDeclaration_periodOffset, int constructorDeclaration_returnTypeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.constructorDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_6 = constructorDeclaration_periodOffset, _variantField_5 = constructorDeclaration_returnTypeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.defaultFormalParameter({ int codeLength, int codeOffset, String defaultFormalParameter_defaultValueCode, }) : _kind = idl.LinkedNodeKind.defaultFormalParameter, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_10 = defaultFormalParameter_defaultValueCode; UnlinkedInformativeDataBuilder.enumConstantDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.enumConstantDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.enumDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.enumDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.exportDirective({ int directiveKeywordOffset, }) : _kind = idl.LinkedNodeKind.exportDirective, _variantField_1 = directiveKeywordOffset; UnlinkedInformativeDataBuilder.extensionDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.extensionDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.fieldDeclaration({ List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.fieldDeclaration, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.fieldFormalParameter({ int codeLength, int codeOffset, int nameOffset, }) : _kind = idl.LinkedNodeKind.fieldFormalParameter, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset; UnlinkedInformativeDataBuilder.functionDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.functionDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.functionTypeAlias({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.functionTypeAlias, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.functionTypedFormalParameter({ int codeLength, int codeOffset, int nameOffset, }) : _kind = idl.LinkedNodeKind.functionTypedFormalParameter, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset; UnlinkedInformativeDataBuilder.genericTypeAlias({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.genericTypeAlias, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.hideCombinator({ int combinatorEnd, int combinatorKeywordOffset, }) : _kind = idl.LinkedNodeKind.hideCombinator, _variantField_9 = combinatorEnd, _variantField_8 = combinatorKeywordOffset; UnlinkedInformativeDataBuilder.importDirective({ int importDirective_prefixOffset, int directiveKeywordOffset, }) : _kind = idl.LinkedNodeKind.importDirective, _variantField_8 = importDirective_prefixOffset, _variantField_1 = directiveKeywordOffset; UnlinkedInformativeDataBuilder.libraryDirective({ int directiveKeywordOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.libraryDirective, _variantField_1 = directiveKeywordOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.methodDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.methodDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.mixinDeclaration({ int codeLength, int codeOffset, int nameOffset, List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.mixinDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.partDirective({ int directiveKeywordOffset, }) : _kind = idl.LinkedNodeKind.partDirective, _variantField_1 = directiveKeywordOffset; UnlinkedInformativeDataBuilder.partOfDirective({ int directiveKeywordOffset, }) : _kind = idl.LinkedNodeKind.partOfDirective, _variantField_1 = directiveKeywordOffset; UnlinkedInformativeDataBuilder.showCombinator({ int combinatorEnd, int combinatorKeywordOffset, }) : _kind = idl.LinkedNodeKind.showCombinator, _variantField_9 = combinatorEnd, _variantField_8 = combinatorKeywordOffset; UnlinkedInformativeDataBuilder.simpleFormalParameter({ int codeLength, int codeOffset, int nameOffset, }) : _kind = idl.LinkedNodeKind.simpleFormalParameter, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset; UnlinkedInformativeDataBuilder.topLevelVariableDeclaration({ List<String> documentationComment_tokens, }) : _kind = idl.LinkedNodeKind.topLevelVariableDeclaration, _variantField_4 = documentationComment_tokens; UnlinkedInformativeDataBuilder.typeParameter({ int codeLength, int codeOffset, int nameOffset, }) : _kind = idl.LinkedNodeKind.typeParameter, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset; UnlinkedInformativeDataBuilder.variableDeclaration({ int codeLength, int codeOffset, int nameOffset, }) : _kind = idl.LinkedNodeKind.variableDeclaration, _variantField_2 = codeLength, _variantField_3 = codeOffset, _variantField_1 = nameOffset; /// Flush [informative] data recursively. void flushInformative() { if (kind == idl.LinkedNodeKind.classDeclaration) { } else if (kind == idl.LinkedNodeKind.classTypeAlias) { } else if (kind == idl.LinkedNodeKind.compilationUnit) { } else if (kind == idl.LinkedNodeKind.constructorDeclaration) { } else if (kind == idl.LinkedNodeKind.defaultFormalParameter) { } else if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { } else if (kind == idl.LinkedNodeKind.enumDeclaration) { } else if (kind == idl.LinkedNodeKind.exportDirective) { } else if (kind == idl.LinkedNodeKind.extensionDeclaration) { } else if (kind == idl.LinkedNodeKind.fieldDeclaration) { } else if (kind == idl.LinkedNodeKind.fieldFormalParameter) { } else if (kind == idl.LinkedNodeKind.functionDeclaration) { } else if (kind == idl.LinkedNodeKind.functionTypeAlias) { } else if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { } else if (kind == idl.LinkedNodeKind.genericTypeAlias) { } else if (kind == idl.LinkedNodeKind.hideCombinator) { } else if (kind == idl.LinkedNodeKind.importDirective) { } else if (kind == idl.LinkedNodeKind.libraryDirective) { } else if (kind == idl.LinkedNodeKind.methodDeclaration) { } else if (kind == idl.LinkedNodeKind.mixinDeclaration) { } else if (kind == idl.LinkedNodeKind.partDirective) { } else if (kind == idl.LinkedNodeKind.partOfDirective) { } else if (kind == idl.LinkedNodeKind.showCombinator) { } else if (kind == idl.LinkedNodeKind.simpleFormalParameter) { } else if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { } else if (kind == idl.LinkedNodeKind.typeParameter) { } else if (kind == idl.LinkedNodeKind.variableDeclaration) {} } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (kind == idl.LinkedNodeKind.classDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.classTypeAlias) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.compilationUnit) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.compilationUnit_lineStarts == null) { signature.addInt(0); } else { signature.addInt(this.compilationUnit_lineStarts.length); for (var x in this.compilationUnit_lineStarts) { signature.addInt(x); } } } else if (kind == idl.LinkedNodeKind.constructorDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } signature.addInt(this.constructorDeclaration_returnTypeOffset ?? 0); signature.addInt(this.constructorDeclaration_periodOffset ?? 0); } else if (kind == idl.LinkedNodeKind.defaultFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); signature.addString(this.defaultFormalParameter_defaultValueCode ?? ''); } else if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.enumDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.exportDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.directiveKeywordOffset ?? 0); } else if (kind == idl.LinkedNodeKind.extensionDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.fieldDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.fieldFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); } else if (kind == idl.LinkedNodeKind.functionDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.functionTypeAlias) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); } else if (kind == idl.LinkedNodeKind.genericTypeAlias) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.hideCombinator) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.combinatorKeywordOffset ?? 0); signature.addInt(this.combinatorEnd ?? 0); } else if (kind == idl.LinkedNodeKind.importDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.directiveKeywordOffset ?? 0); signature.addInt(this.importDirective_prefixOffset ?? 0); } else if (kind == idl.LinkedNodeKind.libraryDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.directiveKeywordOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.methodDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.mixinDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.partDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.directiveKeywordOffset ?? 0); } else if (kind == idl.LinkedNodeKind.partOfDirective) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.directiveKeywordOffset ?? 0); } else if (kind == idl.LinkedNodeKind.showCombinator) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.combinatorKeywordOffset ?? 0); signature.addInt(this.combinatorEnd ?? 0); } else if (kind == idl.LinkedNodeKind.simpleFormalParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); } else if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); if (this.documentationComment_tokens == null) { signature.addInt(0); } else { signature.addInt(this.documentationComment_tokens.length); for (var x in this.documentationComment_tokens) { signature.addString(x); } } } else if (kind == idl.LinkedNodeKind.typeParameter) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); } else if (kind == idl.LinkedNodeKind.variableDeclaration) { signature.addInt(this.kind == null ? 0 : this.kind.index); signature.addInt(this.nameOffset ?? 0); signature.addInt(this.codeLength ?? 0); signature.addInt(this.codeOffset ?? 0); } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_variantField_7; fb.Offset offset_variantField_10; fb.Offset offset_variantField_4; if (!(_variantField_7 == null || _variantField_7.isEmpty)) { offset_variantField_7 = fbBuilder.writeListUint32(_variantField_7); } if (_variantField_10 != null) { offset_variantField_10 = fbBuilder.writeString(_variantField_10); } if (!(_variantField_4 == null || _variantField_4.isEmpty)) { offset_variantField_4 = fbBuilder.writeList( _variantField_4.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (_variantField_2 != null && _variantField_2 != 0) { fbBuilder.addUint32(2, _variantField_2); } if (_variantField_3 != null && _variantField_3 != 0) { fbBuilder.addUint32(3, _variantField_3); } if (_variantField_9 != null && _variantField_9 != 0) { fbBuilder.addUint32(9, _variantField_9); } if (_variantField_8 != null && _variantField_8 != 0) { fbBuilder.addUint32(8, _variantField_8); } if (offset_variantField_7 != null) { fbBuilder.addOffset(7, offset_variantField_7); } if (_variantField_6 != null && _variantField_6 != 0) { fbBuilder.addUint32(6, _variantField_6); } if (_variantField_5 != null && _variantField_5 != 0) { fbBuilder.addUint32(5, _variantField_5); } if (offset_variantField_10 != null) { fbBuilder.addOffset(10, offset_variantField_10); } if (_variantField_1 != null && _variantField_1 != 0) { fbBuilder.addUint32(1, _variantField_1); } if (offset_variantField_4 != null) { fbBuilder.addOffset(4, offset_variantField_4); } if (_kind != null && _kind != idl.LinkedNodeKind.adjacentStrings) { fbBuilder.addUint8(0, _kind.index); } return fbBuilder.endTable(); } } class _UnlinkedInformativeDataReader extends fb.TableReader<_UnlinkedInformativeDataImpl> { const _UnlinkedInformativeDataReader(); @override _UnlinkedInformativeDataImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedInformativeDataImpl(bc, offset); } class _UnlinkedInformativeDataImpl extends Object with _UnlinkedInformativeDataMixin implements idl.UnlinkedInformativeData { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedInformativeDataImpl(this._bc, this._bcOffset); int _variantField_2; int _variantField_3; int _variantField_9; int _variantField_8; List<int> _variantField_7; int _variantField_6; int _variantField_5; String _variantField_10; int _variantField_1; List<String> _variantField_4; idl.LinkedNodeKind _kind; @override int get codeLength { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_2 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _variantField_2; } @override int get codeOffset { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.compilationUnit || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.defaultFormalParameter || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_3 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _variantField_3; } @override int get combinatorEnd { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator); _variantField_9 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 9, 0); return _variantField_9; } @override int get combinatorKeywordOffset { assert(kind == idl.LinkedNodeKind.hideCombinator || kind == idl.LinkedNodeKind.showCombinator); _variantField_8 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 8, 0); return _variantField_8; } @override int get importDirective_prefixOffset { assert(kind == idl.LinkedNodeKind.importDirective); _variantField_8 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 8, 0); return _variantField_8; } @override List<int> get compilationUnit_lineStarts { assert(kind == idl.LinkedNodeKind.compilationUnit); _variantField_7 ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 7, const <int>[]); return _variantField_7; } @override int get constructorDeclaration_periodOffset { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_6 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 6, 0); return _variantField_6; } @override int get constructorDeclaration_returnTypeOffset { assert(kind == idl.LinkedNodeKind.constructorDeclaration); _variantField_5 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 5, 0); return _variantField_5; } @override String get defaultFormalParameter_defaultValueCode { assert(kind == idl.LinkedNodeKind.defaultFormalParameter); _variantField_10 ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 10, ''); return _variantField_10; } @override int get directiveKeywordOffset { assert(kind == idl.LinkedNodeKind.exportDirective || kind == idl.LinkedNodeKind.importDirective || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.partDirective || kind == idl.LinkedNodeKind.partOfDirective); _variantField_1 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _variantField_1; } @override int get nameOffset { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldFormalParameter || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypedFormalParameter || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.simpleFormalParameter || kind == idl.LinkedNodeKind.typeParameter || kind == idl.LinkedNodeKind.variableDeclaration); _variantField_1 ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _variantField_1; } @override List<String> get documentationComment_tokens { assert(kind == idl.LinkedNodeKind.classDeclaration || kind == idl.LinkedNodeKind.classTypeAlias || kind == idl.LinkedNodeKind.constructorDeclaration || kind == idl.LinkedNodeKind.enumDeclaration || kind == idl.LinkedNodeKind.enumConstantDeclaration || kind == idl.LinkedNodeKind.extensionDeclaration || kind == idl.LinkedNodeKind.fieldDeclaration || kind == idl.LinkedNodeKind.functionDeclaration || kind == idl.LinkedNodeKind.functionTypeAlias || kind == idl.LinkedNodeKind.genericTypeAlias || kind == idl.LinkedNodeKind.libraryDirective || kind == idl.LinkedNodeKind.methodDeclaration || kind == idl.LinkedNodeKind.mixinDeclaration || kind == idl.LinkedNodeKind.topLevelVariableDeclaration); _variantField_4 ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 4, const <String>[]); return _variantField_4; } @override idl.LinkedNodeKind get kind { _kind ??= const _LinkedNodeKindReader() .vTableGet(_bc, _bcOffset, 0, idl.LinkedNodeKind.adjacentStrings); return _kind; } } abstract class _UnlinkedInformativeDataMixin implements idl.UnlinkedInformativeData { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (kind != idl.LinkedNodeKind.adjacentStrings) _result["kind"] = kind.toString().split('.')[1]; if (kind == idl.LinkedNodeKind.classDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.classTypeAlias) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.compilationUnit) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (compilationUnit_lineStarts.isNotEmpty) _result["compilationUnit_lineStarts"] = compilationUnit_lineStarts; } if (kind == idl.LinkedNodeKind.constructorDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (constructorDeclaration_periodOffset != 0) _result["constructorDeclaration_periodOffset"] = constructorDeclaration_periodOffset; if (constructorDeclaration_returnTypeOffset != 0) _result["constructorDeclaration_returnTypeOffset"] = constructorDeclaration_returnTypeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.defaultFormalParameter) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (defaultFormalParameter_defaultValueCode != '') _result["defaultFormalParameter_defaultValueCode"] = defaultFormalParameter_defaultValueCode; } if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.enumDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.exportDirective) { if (directiveKeywordOffset != 0) _result["directiveKeywordOffset"] = directiveKeywordOffset; } if (kind == idl.LinkedNodeKind.extensionDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.fieldDeclaration) { if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.fieldFormalParameter) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; } if (kind == idl.LinkedNodeKind.functionDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.functionTypeAlias) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; } if (kind == idl.LinkedNodeKind.genericTypeAlias) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.hideCombinator) { if (combinatorEnd != 0) _result["combinatorEnd"] = combinatorEnd; if (combinatorKeywordOffset != 0) _result["combinatorKeywordOffset"] = combinatorKeywordOffset; } if (kind == idl.LinkedNodeKind.importDirective) { if (importDirective_prefixOffset != 0) _result["importDirective_prefixOffset"] = importDirective_prefixOffset; if (directiveKeywordOffset != 0) _result["directiveKeywordOffset"] = directiveKeywordOffset; } if (kind == idl.LinkedNodeKind.libraryDirective) { if (directiveKeywordOffset != 0) _result["directiveKeywordOffset"] = directiveKeywordOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.methodDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.mixinDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.partDirective) { if (directiveKeywordOffset != 0) _result["directiveKeywordOffset"] = directiveKeywordOffset; } if (kind == idl.LinkedNodeKind.partOfDirective) { if (directiveKeywordOffset != 0) _result["directiveKeywordOffset"] = directiveKeywordOffset; } if (kind == idl.LinkedNodeKind.showCombinator) { if (combinatorEnd != 0) _result["combinatorEnd"] = combinatorEnd; if (combinatorKeywordOffset != 0) _result["combinatorKeywordOffset"] = combinatorKeywordOffset; } if (kind == idl.LinkedNodeKind.simpleFormalParameter) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; } if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { if (documentationComment_tokens.isNotEmpty) _result["documentationComment_tokens"] = documentationComment_tokens; } if (kind == idl.LinkedNodeKind.typeParameter) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; } if (kind == idl.LinkedNodeKind.variableDeclaration) { if (codeLength != 0) _result["codeLength"] = codeLength; if (codeOffset != 0) _result["codeOffset"] = codeOffset; if (nameOffset != 0) _result["nameOffset"] = nameOffset; } return _result; } @override Map<String, Object> toMap() { if (kind == idl.LinkedNodeKind.classDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.classTypeAlias) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.compilationUnit) { return { "codeLength": codeLength, "codeOffset": codeOffset, "compilationUnit_lineStarts": compilationUnit_lineStarts, "kind": kind, }; } if (kind == idl.LinkedNodeKind.constructorDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "constructorDeclaration_periodOffset": constructorDeclaration_periodOffset, "constructorDeclaration_returnTypeOffset": constructorDeclaration_returnTypeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.defaultFormalParameter) { return { "codeLength": codeLength, "codeOffset": codeOffset, "defaultFormalParameter_defaultValueCode": defaultFormalParameter_defaultValueCode, "kind": kind, }; } if (kind == idl.LinkedNodeKind.enumConstantDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.enumDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.exportDirective) { return { "directiveKeywordOffset": directiveKeywordOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.extensionDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.fieldDeclaration) { return { "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.fieldFormalParameter) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.functionDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.functionTypeAlias) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.functionTypedFormalParameter) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.genericTypeAlias) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.hideCombinator) { return { "combinatorEnd": combinatorEnd, "combinatorKeywordOffset": combinatorKeywordOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.importDirective) { return { "importDirective_prefixOffset": importDirective_prefixOffset, "directiveKeywordOffset": directiveKeywordOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.libraryDirective) { return { "directiveKeywordOffset": directiveKeywordOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.methodDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.mixinDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.partDirective) { return { "directiveKeywordOffset": directiveKeywordOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.partOfDirective) { return { "directiveKeywordOffset": directiveKeywordOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.showCombinator) { return { "combinatorEnd": combinatorEnd, "combinatorKeywordOffset": combinatorKeywordOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.simpleFormalParameter) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.topLevelVariableDeclaration) { return { "documentationComment_tokens": documentationComment_tokens, "kind": kind, }; } if (kind == idl.LinkedNodeKind.typeParameter) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "kind": kind, }; } if (kind == idl.LinkedNodeKind.variableDeclaration) { return { "codeLength": codeLength, "codeOffset": codeOffset, "nameOffset": nameOffset, "kind": kind, }; } throw StateError("Unexpected $kind"); } @override String toString() => convert.json.encode(toJson()); } class UnlinkedParamBuilder extends Object with _UnlinkedParamMixin implements idl.UnlinkedParam { List<UnlinkedExprBuilder> _annotations; CodeRangeBuilder _codeRange; String _defaultValueCode; int _inferredTypeSlot; int _inheritsCovariantSlot; UnlinkedExecutableBuilder _initializer; bool _isExplicitlyCovariant; bool _isFinal; bool _isFunctionTyped; bool _isInitializingFormal; idl.UnlinkedParamKind _kind; String _name; int _nameOffset; List<UnlinkedParamBuilder> _parameters; EntityRefBuilder _type; int _visibleLength; int _visibleOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this parameter. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the parameter. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override String get defaultValueCode => _defaultValueCode ??= ''; /// If the parameter has a default value, the source text of the constant /// expression in the default value. Otherwise the empty string. set defaultValueCode(String value) { this._defaultValueCode = value; } @override int get inferredTypeSlot => _inferredTypeSlot ??= 0; /// If this parameter's type is inferable, nonzero slot id identifying which /// entry in [LinkedLibrary.types] contains the inferred type. If there is no /// matching entry in [LinkedLibrary.types], then no type was inferred for /// this variable, so its static type is `dynamic`. /// /// Note that although strong mode considers initializing formals to be /// inferable, they are not marked as such in the summary; if their type is /// not specified, they always inherit the static type of the corresponding /// field. set inferredTypeSlot(int value) { assert(value == null || value >= 0); this._inferredTypeSlot = value; } @override int get inheritsCovariantSlot => _inheritsCovariantSlot ??= 0; /// If this is a parameter of an instance method, a nonzero slot id which is /// unique within this compilation unit. If this id is found in /// [LinkedUnit.parametersInheritingCovariant], then this parameter inherits /// `@covariant` behavior from a base class. /// /// Otherwise, zero. set inheritsCovariantSlot(int value) { assert(value == null || value >= 0); this._inheritsCovariantSlot = value; } @override UnlinkedExecutableBuilder get initializer => _initializer; /// The synthetic initializer function of the parameter. Absent if the /// variable does not have an initializer. set initializer(UnlinkedExecutableBuilder value) { this._initializer = value; } @override bool get isExplicitlyCovariant => _isExplicitlyCovariant ??= false; /// Indicates whether this parameter is explicitly marked as being covariant. set isExplicitlyCovariant(bool value) { this._isExplicitlyCovariant = value; } @override bool get isFinal => _isFinal ??= false; /// Indicates whether the parameter is declared using the `final` keyword. set isFinal(bool value) { this._isFinal = value; } @override bool get isFunctionTyped => _isFunctionTyped ??= false; /// Indicates whether this is a function-typed parameter. A parameter is /// function-typed if the declaration of the parameter has explicit formal /// parameters /// ``` /// int functionTyped(int p) /// ``` /// but is not function-typed if it does not, even if the type of the /// parameter is a function type. set isFunctionTyped(bool value) { this._isFunctionTyped = value; } @override bool get isInitializingFormal => _isInitializingFormal ??= false; /// Indicates whether this is an initializing formal parameter (i.e. it is /// declared using `this.` syntax). set isInitializingFormal(bool value) { this._isInitializingFormal = value; } @override idl.UnlinkedParamKind get kind => _kind ??= idl.UnlinkedParamKind.requiredPositional; /// Kind of the parameter. set kind(idl.UnlinkedParamKind value) { this._kind = value; } @override String get name => _name ??= ''; /// Name of the parameter. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the parameter name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override List<UnlinkedParamBuilder> get parameters => _parameters ??= <UnlinkedParamBuilder>[]; /// If [isFunctionTyped] is `true`, the parameters of the function type. set parameters(List<UnlinkedParamBuilder> value) { this._parameters = value; } @override EntityRefBuilder get type => _type; /// If [isFunctionTyped] is `true`, the declared return type. If /// [isFunctionTyped] is `false`, the declared type. Absent if the type is /// implicit. set type(EntityRefBuilder value) { this._type = value; } @override int get visibleLength => _visibleLength ??= 0; /// The length of the visible range. set visibleLength(int value) { assert(value == null || value >= 0); this._visibleLength = value; } @override int get visibleOffset => _visibleOffset ??= 0; /// The beginning of the visible range. set visibleOffset(int value) { assert(value == null || value >= 0); this._visibleOffset = value; } UnlinkedParamBuilder( {List<UnlinkedExprBuilder> annotations, CodeRangeBuilder codeRange, String defaultValueCode, int inferredTypeSlot, int inheritsCovariantSlot, UnlinkedExecutableBuilder initializer, bool isExplicitlyCovariant, bool isFinal, bool isFunctionTyped, bool isInitializingFormal, idl.UnlinkedParamKind kind, String name, int nameOffset, List<UnlinkedParamBuilder> parameters, EntityRefBuilder type, int visibleLength, int visibleOffset}) : _annotations = annotations, _codeRange = codeRange, _defaultValueCode = defaultValueCode, _inferredTypeSlot = inferredTypeSlot, _inheritsCovariantSlot = inheritsCovariantSlot, _initializer = initializer, _isExplicitlyCovariant = isExplicitlyCovariant, _isFinal = isFinal, _isFunctionTyped = isFunctionTyped, _isInitializingFormal = isInitializingFormal, _kind = kind, _name = name, _nameOffset = nameOffset, _parameters = parameters, _type = type, _visibleLength = visibleLength, _visibleOffset = visibleOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _codeRange = null; _defaultValueCode = null; _initializer?.flushInformative(); _nameOffset = null; _parameters?.forEach((b) => b.flushInformative()); _type?.flushInformative(); _visibleLength = null; _visibleOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addInt(this._inferredTypeSlot ?? 0); signature.addBool(this._type != null); this._type?.collectApiSignature(signature); signature.addInt(this._kind == null ? 0 : this._kind.index); signature.addBool(this._isFunctionTyped == true); signature.addBool(this._isInitializingFormal == true); if (this._parameters == null) { signature.addInt(0); } else { signature.addInt(this._parameters.length); for (var x in this._parameters) { x?.collectApiSignature(signature); } } if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } signature.addBool(this._initializer != null); this._initializer?.collectApiSignature(signature); signature.addInt(this._inheritsCovariantSlot ?? 0); signature.addBool(this._isExplicitlyCovariant == true); signature.addBool(this._isFinal == true); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_codeRange; fb.Offset offset_defaultValueCode; fb.Offset offset_initializer; fb.Offset offset_name; fb.Offset offset_parameters; fb.Offset offset_type; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_defaultValueCode != null) { offset_defaultValueCode = fbBuilder.writeString(_defaultValueCode); } if (_initializer != null) { offset_initializer = _initializer.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_parameters == null || _parameters.isEmpty)) { offset_parameters = fbBuilder .writeList(_parameters.map((b) => b.finish(fbBuilder)).toList()); } if (_type != null) { offset_type = _type.finish(fbBuilder); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(9, offset_annotations); } if (offset_codeRange != null) { fbBuilder.addOffset(7, offset_codeRange); } if (offset_defaultValueCode != null) { fbBuilder.addOffset(13, offset_defaultValueCode); } if (_inferredTypeSlot != null && _inferredTypeSlot != 0) { fbBuilder.addUint32(2, _inferredTypeSlot); } if (_inheritsCovariantSlot != null && _inheritsCovariantSlot != 0) { fbBuilder.addUint32(14, _inheritsCovariantSlot); } if (offset_initializer != null) { fbBuilder.addOffset(12, offset_initializer); } if (_isExplicitlyCovariant == true) { fbBuilder.addBool(15, true); } if (_isFinal == true) { fbBuilder.addBool(16, true); } if (_isFunctionTyped == true) { fbBuilder.addBool(5, true); } if (_isInitializingFormal == true) { fbBuilder.addBool(6, true); } if (_kind != null && _kind != idl.UnlinkedParamKind.requiredPositional) { fbBuilder.addUint8(4, _kind.index); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } if (offset_parameters != null) { fbBuilder.addOffset(8, offset_parameters); } if (offset_type != null) { fbBuilder.addOffset(3, offset_type); } if (_visibleLength != null && _visibleLength != 0) { fbBuilder.addUint32(10, _visibleLength); } if (_visibleOffset != null && _visibleOffset != 0) { fbBuilder.addUint32(11, _visibleOffset); } return fbBuilder.endTable(); } } class _UnlinkedParamReader extends fb.TableReader<_UnlinkedParamImpl> { const _UnlinkedParamReader(); @override _UnlinkedParamImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedParamImpl(bc, offset); } class _UnlinkedParamImpl extends Object with _UnlinkedParamMixin implements idl.UnlinkedParam { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedParamImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.CodeRange _codeRange; String _defaultValueCode; int _inferredTypeSlot; int _inheritsCovariantSlot; idl.UnlinkedExecutable _initializer; bool _isExplicitlyCovariant; bool _isFinal; bool _isFunctionTyped; bool _isInitializingFormal; idl.UnlinkedParamKind _kind; String _name; int _nameOffset; List<idl.UnlinkedParam> _parameters; idl.EntityRef _type; int _visibleLength; int _visibleOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 9, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 7, null); return _codeRange; } @override String get defaultValueCode { _defaultValueCode ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 13, ''); return _defaultValueCode; } @override int get inferredTypeSlot { _inferredTypeSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _inferredTypeSlot; } @override int get inheritsCovariantSlot { _inheritsCovariantSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 14, 0); return _inheritsCovariantSlot; } @override idl.UnlinkedExecutable get initializer { _initializer ??= const _UnlinkedExecutableReader().vTableGet(_bc, _bcOffset, 12, null); return _initializer; } @override bool get isExplicitlyCovariant { _isExplicitlyCovariant ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 15, false); return _isExplicitlyCovariant; } @override bool get isFinal { _isFinal ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 16, false); return _isFinal; } @override bool get isFunctionTyped { _isFunctionTyped ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 5, false); return _isFunctionTyped; } @override bool get isInitializingFormal { _isInitializingFormal ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 6, false); return _isInitializingFormal; } @override idl.UnlinkedParamKind get kind { _kind ??= const _UnlinkedParamKindReader() .vTableGet(_bc, _bcOffset, 4, idl.UnlinkedParamKind.requiredPositional); return _kind; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } @override List<idl.UnlinkedParam> get parameters { _parameters ??= const fb.ListReader<idl.UnlinkedParam>(const _UnlinkedParamReader()) .vTableGet(_bc, _bcOffset, 8, const <idl.UnlinkedParam>[]); return _parameters; } @override idl.EntityRef get type { _type ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 3, null); return _type; } @override int get visibleLength { _visibleLength ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 10, 0); return _visibleLength; } @override int get visibleOffset { _visibleOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 11, 0); return _visibleOffset; } } abstract class _UnlinkedParamMixin implements idl.UnlinkedParam { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (defaultValueCode != '') _result["defaultValueCode"] = defaultValueCode; if (inferredTypeSlot != 0) _result["inferredTypeSlot"] = inferredTypeSlot; if (inheritsCovariantSlot != 0) _result["inheritsCovariantSlot"] = inheritsCovariantSlot; if (initializer != null) _result["initializer"] = initializer.toJson(); if (isExplicitlyCovariant != false) _result["isExplicitlyCovariant"] = isExplicitlyCovariant; if (isFinal != false) _result["isFinal"] = isFinal; if (isFunctionTyped != false) _result["isFunctionTyped"] = isFunctionTyped; if (isInitializingFormal != false) _result["isInitializingFormal"] = isInitializingFormal; if (kind != idl.UnlinkedParamKind.requiredPositional) _result["kind"] = kind.toString().split('.')[1]; if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (parameters.isNotEmpty) _result["parameters"] = parameters.map((_value) => _value.toJson()).toList(); if (type != null) _result["type"] = type.toJson(); if (visibleLength != 0) _result["visibleLength"] = visibleLength; if (visibleOffset != 0) _result["visibleOffset"] = visibleOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "codeRange": codeRange, "defaultValueCode": defaultValueCode, "inferredTypeSlot": inferredTypeSlot, "inheritsCovariantSlot": inheritsCovariantSlot, "initializer": initializer, "isExplicitlyCovariant": isExplicitlyCovariant, "isFinal": isFinal, "isFunctionTyped": isFunctionTyped, "isInitializingFormal": isInitializingFormal, "kind": kind, "name": name, "nameOffset": nameOffset, "parameters": parameters, "type": type, "visibleLength": visibleLength, "visibleOffset": visibleOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedPartBuilder extends Object with _UnlinkedPartMixin implements idl.UnlinkedPart { List<UnlinkedExprBuilder> _annotations; int _uriEnd; int _uriOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this part declaration. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override int get uriEnd => _uriEnd ??= 0; /// End of the URI string (including quotes) relative to the beginning of the /// file. set uriEnd(int value) { assert(value == null || value >= 0); this._uriEnd = value; } @override int get uriOffset => _uriOffset ??= 0; /// Offset of the URI string (including quotes) relative to the beginning of /// the file. set uriOffset(int value) { assert(value == null || value >= 0); this._uriOffset = value; } UnlinkedPartBuilder( {List<UnlinkedExprBuilder> annotations, int uriEnd, int uriOffset}) : _annotations = annotations, _uriEnd = uriEnd, _uriOffset = uriOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _uriEnd = null; _uriOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(2, offset_annotations); } if (_uriEnd != null && _uriEnd != 0) { fbBuilder.addUint32(0, _uriEnd); } if (_uriOffset != null && _uriOffset != 0) { fbBuilder.addUint32(1, _uriOffset); } return fbBuilder.endTable(); } } class _UnlinkedPartReader extends fb.TableReader<_UnlinkedPartImpl> { const _UnlinkedPartReader(); @override _UnlinkedPartImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedPartImpl(bc, offset); } class _UnlinkedPartImpl extends Object with _UnlinkedPartMixin implements idl.UnlinkedPart { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedPartImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; int _uriEnd; int _uriOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedExpr>[]); return _annotations; } @override int get uriEnd { _uriEnd ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 0, 0); return _uriEnd; } @override int get uriOffset { _uriOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _uriOffset; } } abstract class _UnlinkedPartMixin implements idl.UnlinkedPart { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (uriEnd != 0) _result["uriEnd"] = uriEnd; if (uriOffset != 0) _result["uriOffset"] = uriOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "uriEnd": uriEnd, "uriOffset": uriOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedPublicNameBuilder extends Object with _UnlinkedPublicNameMixin implements idl.UnlinkedPublicName { idl.ReferenceKind _kind; List<UnlinkedPublicNameBuilder> _members; String _name; int _numTypeParameters; @override idl.ReferenceKind get kind => _kind ??= idl.ReferenceKind.classOrEnum; /// The kind of object referred to by the name. set kind(idl.ReferenceKind value) { this._kind = value; } @override List<UnlinkedPublicNameBuilder> get members => _members ??= <UnlinkedPublicNameBuilder>[]; /// If this [UnlinkedPublicName] is a class, the list of members which can be /// referenced statically - static fields, static methods, and constructors. /// Otherwise empty. /// /// Unnamed constructors are not included since they do not constitute a /// separate name added to any namespace. set members(List<UnlinkedPublicNameBuilder> value) { this._members = value; } @override String get name => _name ??= ''; /// The name itself. set name(String value) { this._name = value; } @override int get numTypeParameters => _numTypeParameters ??= 0; /// If the entity being referred to is generic, the number of type parameters /// it accepts. Otherwise zero. set numTypeParameters(int value) { assert(value == null || value >= 0); this._numTypeParameters = value; } UnlinkedPublicNameBuilder( {idl.ReferenceKind kind, List<UnlinkedPublicNameBuilder> members, String name, int numTypeParameters}) : _kind = kind, _members = members, _name = name, _numTypeParameters = numTypeParameters; /// Flush [informative] data recursively. void flushInformative() { _members?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addInt(this._kind == null ? 0 : this._kind.index); if (this._members == null) { signature.addInt(0); } else { signature.addInt(this._members.length); for (var x in this._members) { x?.collectApiSignature(signature); } } signature.addInt(this._numTypeParameters ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_members; fb.Offset offset_name; if (!(_members == null || _members.isEmpty)) { offset_members = fbBuilder .writeList(_members.map((b) => b.finish(fbBuilder)).toList()); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (_kind != null && _kind != idl.ReferenceKind.classOrEnum) { fbBuilder.addUint8(1, _kind.index); } if (offset_members != null) { fbBuilder.addOffset(2, offset_members); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_numTypeParameters != null && _numTypeParameters != 0) { fbBuilder.addUint32(3, _numTypeParameters); } return fbBuilder.endTable(); } } class _UnlinkedPublicNameReader extends fb.TableReader<_UnlinkedPublicNameImpl> { const _UnlinkedPublicNameReader(); @override _UnlinkedPublicNameImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedPublicNameImpl(bc, offset); } class _UnlinkedPublicNameImpl extends Object with _UnlinkedPublicNameMixin implements idl.UnlinkedPublicName { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedPublicNameImpl(this._bc, this._bcOffset); idl.ReferenceKind _kind; List<idl.UnlinkedPublicName> _members; String _name; int _numTypeParameters; @override idl.ReferenceKind get kind { _kind ??= const _ReferenceKindReader() .vTableGet(_bc, _bcOffset, 1, idl.ReferenceKind.classOrEnum); return _kind; } @override List<idl.UnlinkedPublicName> get members { _members ??= const fb.ListReader<idl.UnlinkedPublicName>( const _UnlinkedPublicNameReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedPublicName>[]); return _members; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get numTypeParameters { _numTypeParameters ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 3, 0); return _numTypeParameters; } } abstract class _UnlinkedPublicNameMixin implements idl.UnlinkedPublicName { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (kind != idl.ReferenceKind.classOrEnum) _result["kind"] = kind.toString().split('.')[1]; if (members.isNotEmpty) _result["members"] = members.map((_value) => _value.toJson()).toList(); if (name != '') _result["name"] = name; if (numTypeParameters != 0) _result["numTypeParameters"] = numTypeParameters; return _result; } @override Map<String, Object> toMap() => { "kind": kind, "members": members, "name": name, "numTypeParameters": numTypeParameters, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedPublicNamespaceBuilder extends Object with _UnlinkedPublicNamespaceMixin implements idl.UnlinkedPublicNamespace { List<UnlinkedExportPublicBuilder> _exports; List<UnlinkedPublicNameBuilder> _names; List<String> _parts; @override List<UnlinkedExportPublicBuilder> get exports => _exports ??= <UnlinkedExportPublicBuilder>[]; /// Export declarations in the compilation unit. set exports(List<UnlinkedExportPublicBuilder> value) { this._exports = value; } @override List<UnlinkedPublicNameBuilder> get names => _names ??= <UnlinkedPublicNameBuilder>[]; /// Public names defined in the compilation unit. /// /// TODO(paulberry): consider sorting these names to reduce unnecessary /// relinking. set names(List<UnlinkedPublicNameBuilder> value) { this._names = value; } @override List<String> get parts => _parts ??= <String>[]; /// URIs referenced by part declarations in the compilation unit. set parts(List<String> value) { this._parts = value; } UnlinkedPublicNamespaceBuilder( {List<UnlinkedExportPublicBuilder> exports, List<UnlinkedPublicNameBuilder> names, List<String> parts}) : _exports = exports, _names = names, _parts = parts; /// Flush [informative] data recursively. void flushInformative() { _exports?.forEach((b) => b.flushInformative()); _names?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._names == null) { signature.addInt(0); } else { signature.addInt(this._names.length); for (var x in this._names) { x?.collectApiSignature(signature); } } if (this._parts == null) { signature.addInt(0); } else { signature.addInt(this._parts.length); for (var x in this._parts) { signature.addString(x); } } if (this._exports == null) { signature.addInt(0); } else { signature.addInt(this._exports.length); for (var x in this._exports) { x?.collectApiSignature(signature); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "UPNS"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_exports; fb.Offset offset_names; fb.Offset offset_parts; if (!(_exports == null || _exports.isEmpty)) { offset_exports = fbBuilder .writeList(_exports.map((b) => b.finish(fbBuilder)).toList()); } if (!(_names == null || _names.isEmpty)) { offset_names = fbBuilder.writeList(_names.map((b) => b.finish(fbBuilder)).toList()); } if (!(_parts == null || _parts.isEmpty)) { offset_parts = fbBuilder .writeList(_parts.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_exports != null) { fbBuilder.addOffset(2, offset_exports); } if (offset_names != null) { fbBuilder.addOffset(0, offset_names); } if (offset_parts != null) { fbBuilder.addOffset(1, offset_parts); } return fbBuilder.endTable(); } } idl.UnlinkedPublicNamespace readUnlinkedPublicNamespace(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _UnlinkedPublicNamespaceReader().read(rootRef, 0); } class _UnlinkedPublicNamespaceReader extends fb.TableReader<_UnlinkedPublicNamespaceImpl> { const _UnlinkedPublicNamespaceReader(); @override _UnlinkedPublicNamespaceImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedPublicNamespaceImpl(bc, offset); } class _UnlinkedPublicNamespaceImpl extends Object with _UnlinkedPublicNamespaceMixin implements idl.UnlinkedPublicNamespace { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedPublicNamespaceImpl(this._bc, this._bcOffset); List<idl.UnlinkedExportPublic> _exports; List<idl.UnlinkedPublicName> _names; List<String> _parts; @override List<idl.UnlinkedExportPublic> get exports { _exports ??= const fb.ListReader<idl.UnlinkedExportPublic>( const _UnlinkedExportPublicReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedExportPublic>[]); return _exports; } @override List<idl.UnlinkedPublicName> get names { _names ??= const fb.ListReader<idl.UnlinkedPublicName>( const _UnlinkedPublicNameReader()) .vTableGet(_bc, _bcOffset, 0, const <idl.UnlinkedPublicName>[]); return _names; } @override List<String> get parts { _parts ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _parts; } } abstract class _UnlinkedPublicNamespaceMixin implements idl.UnlinkedPublicNamespace { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (exports.isNotEmpty) _result["exports"] = exports.map((_value) => _value.toJson()).toList(); if (names.isNotEmpty) _result["names"] = names.map((_value) => _value.toJson()).toList(); if (parts.isNotEmpty) _result["parts"] = parts; return _result; } @override Map<String, Object> toMap() => { "exports": exports, "names": names, "parts": parts, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedReferenceBuilder extends Object with _UnlinkedReferenceMixin implements idl.UnlinkedReference { String _name; int _prefixReference; @override String get name => _name ??= ''; /// Name of the entity being referred to. For the pseudo-type `dynamic`, the /// string is "dynamic". For the pseudo-type `void`, the string is "void". /// For the pseudo-type `bottom`, the string is "*bottom*". set name(String value) { this._name = value; } @override int get prefixReference => _prefixReference ??= 0; /// Prefix used to refer to the entity, or zero if no prefix is used. This is /// an index into [UnlinkedUnit.references]. /// /// Prefix references must always point backward; that is, for all i, if /// UnlinkedUnit.references[i].prefixReference != 0, then /// UnlinkedUnit.references[i].prefixReference < i. set prefixReference(int value) { assert(value == null || value >= 0); this._prefixReference = value; } UnlinkedReferenceBuilder({String name, int prefixReference}) : _name = name, _prefixReference = prefixReference; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addInt(this._prefixReference ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_name; if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_prefixReference != null && _prefixReference != 0) { fbBuilder.addUint32(1, _prefixReference); } return fbBuilder.endTable(); } } class _UnlinkedReferenceReader extends fb.TableReader<_UnlinkedReferenceImpl> { const _UnlinkedReferenceReader(); @override _UnlinkedReferenceImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedReferenceImpl(bc, offset); } class _UnlinkedReferenceImpl extends Object with _UnlinkedReferenceMixin implements idl.UnlinkedReference { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedReferenceImpl(this._bc, this._bcOffset); String _name; int _prefixReference; @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get prefixReference { _prefixReference ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _prefixReference; } } abstract class _UnlinkedReferenceMixin implements idl.UnlinkedReference { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (name != '') _result["name"] = name; if (prefixReference != 0) _result["prefixReference"] = prefixReference; return _result; } @override Map<String, Object> toMap() => { "name": name, "prefixReference": prefixReference, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedTokensBuilder extends Object with _UnlinkedTokensMixin implements idl.UnlinkedTokens { List<int> _endGroup; List<bool> _isSynthetic; List<idl.UnlinkedTokenKind> _kind; List<int> _length; List<String> _lexeme; List<int> _next; List<int> _offset; List<int> _precedingComment; List<idl.UnlinkedTokenType> _type; @override List<int> get endGroup => _endGroup ??= <int>[]; /// The token that corresponds to this token, or `0` if this token is not /// the first of a pair of matching tokens (such as parentheses). set endGroup(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._endGroup = value; } @override List<bool> get isSynthetic => _isSynthetic ??= <bool>[]; /// Return `true` if this token is a synthetic token. A synthetic token is a /// token that was introduced by the parser in order to recover from an error /// in the code. set isSynthetic(List<bool> value) { this._isSynthetic = value; } @override List<idl.UnlinkedTokenKind> get kind => _kind ??= <idl.UnlinkedTokenKind>[]; set kind(List<idl.UnlinkedTokenKind> value) { this._kind = value; } @override List<int> get length => _length ??= <int>[]; set length(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._length = value; } @override List<String> get lexeme => _lexeme ??= <String>[]; set lexeme(List<String> value) { this._lexeme = value; } @override List<int> get next => _next ??= <int>[]; /// The next token in the token stream, `0` for [UnlinkedTokenType.EOF] or /// the last comment token. set next(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._next = value; } @override List<int> get offset => _offset ??= <int>[]; set offset(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._offset = value; } @override List<int> get precedingComment => _precedingComment ??= <int>[]; /// The first comment token in the list of comments that precede this token, /// or `0` if there are no comments preceding this token. Additional comments /// can be reached by following the token stream using [next] until `0` is /// reached. set precedingComment(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._precedingComment = value; } @override List<idl.UnlinkedTokenType> get type => _type ??= <idl.UnlinkedTokenType>[]; set type(List<idl.UnlinkedTokenType> value) { this._type = value; } UnlinkedTokensBuilder( {List<int> endGroup, List<bool> isSynthetic, List<idl.UnlinkedTokenKind> kind, List<int> length, List<String> lexeme, List<int> next, List<int> offset, List<int> precedingComment, List<idl.UnlinkedTokenType> type}) : _endGroup = endGroup, _isSynthetic = isSynthetic, _kind = kind, _length = length, _lexeme = lexeme, _next = next, _offset = offset, _precedingComment = precedingComment, _type = type; /// Flush [informative] data recursively. void flushInformative() {} /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._endGroup == null) { signature.addInt(0); } else { signature.addInt(this._endGroup.length); for (var x in this._endGroup) { signature.addInt(x); } } if (this._isSynthetic == null) { signature.addInt(0); } else { signature.addInt(this._isSynthetic.length); for (var x in this._isSynthetic) { signature.addBool(x); } } if (this._kind == null) { signature.addInt(0); } else { signature.addInt(this._kind.length); for (var x in this._kind) { signature.addInt(x.index); } } if (this._length == null) { signature.addInt(0); } else { signature.addInt(this._length.length); for (var x in this._length) { signature.addInt(x); } } if (this._lexeme == null) { signature.addInt(0); } else { signature.addInt(this._lexeme.length); for (var x in this._lexeme) { signature.addString(x); } } if (this._next == null) { signature.addInt(0); } else { signature.addInt(this._next.length); for (var x in this._next) { signature.addInt(x); } } if (this._offset == null) { signature.addInt(0); } else { signature.addInt(this._offset.length); for (var x in this._offset) { signature.addInt(x); } } if (this._precedingComment == null) { signature.addInt(0); } else { signature.addInt(this._precedingComment.length); for (var x in this._precedingComment) { signature.addInt(x); } } if (this._type == null) { signature.addInt(0); } else { signature.addInt(this._type.length); for (var x in this._type) { signature.addInt(x.index); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_endGroup; fb.Offset offset_isSynthetic; fb.Offset offset_kind; fb.Offset offset_length; fb.Offset offset_lexeme; fb.Offset offset_next; fb.Offset offset_offset; fb.Offset offset_precedingComment; fb.Offset offset_type; if (!(_endGroup == null || _endGroup.isEmpty)) { offset_endGroup = fbBuilder.writeListUint32(_endGroup); } if (!(_isSynthetic == null || _isSynthetic.isEmpty)) { offset_isSynthetic = fbBuilder.writeListBool(_isSynthetic); } if (!(_kind == null || _kind.isEmpty)) { offset_kind = fbBuilder.writeListUint8(_kind.map((b) => b.index).toList()); } if (!(_length == null || _length.isEmpty)) { offset_length = fbBuilder.writeListUint32(_length); } if (!(_lexeme == null || _lexeme.isEmpty)) { offset_lexeme = fbBuilder .writeList(_lexeme.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_next == null || _next.isEmpty)) { offset_next = fbBuilder.writeListUint32(_next); } if (!(_offset == null || _offset.isEmpty)) { offset_offset = fbBuilder.writeListUint32(_offset); } if (!(_precedingComment == null || _precedingComment.isEmpty)) { offset_precedingComment = fbBuilder.writeListUint32(_precedingComment); } if (!(_type == null || _type.isEmpty)) { offset_type = fbBuilder.writeListUint8(_type.map((b) => b.index).toList()); } fbBuilder.startTable(); if (offset_endGroup != null) { fbBuilder.addOffset(0, offset_endGroup); } if (offset_isSynthetic != null) { fbBuilder.addOffset(1, offset_isSynthetic); } if (offset_kind != null) { fbBuilder.addOffset(2, offset_kind); } if (offset_length != null) { fbBuilder.addOffset(3, offset_length); } if (offset_lexeme != null) { fbBuilder.addOffset(4, offset_lexeme); } if (offset_next != null) { fbBuilder.addOffset(5, offset_next); } if (offset_offset != null) { fbBuilder.addOffset(6, offset_offset); } if (offset_precedingComment != null) { fbBuilder.addOffset(7, offset_precedingComment); } if (offset_type != null) { fbBuilder.addOffset(8, offset_type); } return fbBuilder.endTable(); } } class _UnlinkedTokensReader extends fb.TableReader<_UnlinkedTokensImpl> { const _UnlinkedTokensReader(); @override _UnlinkedTokensImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedTokensImpl(bc, offset); } class _UnlinkedTokensImpl extends Object with _UnlinkedTokensMixin implements idl.UnlinkedTokens { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedTokensImpl(this._bc, this._bcOffset); List<int> _endGroup; List<bool> _isSynthetic; List<idl.UnlinkedTokenKind> _kind; List<int> _length; List<String> _lexeme; List<int> _next; List<int> _offset; List<int> _precedingComment; List<idl.UnlinkedTokenType> _type; @override List<int> get endGroup { _endGroup ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 0, const <int>[]); return _endGroup; } @override List<bool> get isSynthetic { _isSynthetic ??= const fb.BoolListReader().vTableGet(_bc, _bcOffset, 1, const <bool>[]); return _isSynthetic; } @override List<idl.UnlinkedTokenKind> get kind { _kind ??= const fb.ListReader<idl.UnlinkedTokenKind>( const _UnlinkedTokenKindReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedTokenKind>[]); return _kind; } @override List<int> get length { _length ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 3, const <int>[]); return _length; } @override List<String> get lexeme { _lexeme ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 4, const <String>[]); return _lexeme; } @override List<int> get next { _next ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 5, const <int>[]); return _next; } @override List<int> get offset { _offset ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 6, const <int>[]); return _offset; } @override List<int> get precedingComment { _precedingComment ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 7, const <int>[]); return _precedingComment; } @override List<idl.UnlinkedTokenType> get type { _type ??= const fb.ListReader<idl.UnlinkedTokenType>( const _UnlinkedTokenTypeReader()) .vTableGet(_bc, _bcOffset, 8, const <idl.UnlinkedTokenType>[]); return _type; } } abstract class _UnlinkedTokensMixin implements idl.UnlinkedTokens { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (endGroup.isNotEmpty) _result["endGroup"] = endGroup; if (isSynthetic.isNotEmpty) _result["isSynthetic"] = isSynthetic; if (kind.isNotEmpty) _result["kind"] = kind.map((_value) => _value.toString().split('.')[1]).toList(); if (length.isNotEmpty) _result["length"] = length; if (lexeme.isNotEmpty) _result["lexeme"] = lexeme; if (next.isNotEmpty) _result["next"] = next; if (offset.isNotEmpty) _result["offset"] = offset; if (precedingComment.isNotEmpty) _result["precedingComment"] = precedingComment; if (type.isNotEmpty) _result["type"] = type.map((_value) => _value.toString().split('.')[1]).toList(); return _result; } @override Map<String, Object> toMap() => { "endGroup": endGroup, "isSynthetic": isSynthetic, "kind": kind, "length": length, "lexeme": lexeme, "next": next, "offset": offset, "precedingComment": precedingComment, "type": type, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedTypedefBuilder extends Object with _UnlinkedTypedefMixin implements idl.UnlinkedTypedef { List<UnlinkedExprBuilder> _annotations; CodeRangeBuilder _codeRange; UnlinkedDocumentationCommentBuilder _documentationComment; String _name; int _nameOffset; int _notSimplyBoundedSlot; List<UnlinkedParamBuilder> _parameters; EntityRefBuilder _returnType; idl.TypedefStyle _style; List<UnlinkedTypeParamBuilder> _typeParameters; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this typedef. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the typedef. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the typedef, or `null` if there is no /// documentation comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override String get name => _name ??= ''; /// Name of the typedef. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the typedef name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override int get notSimplyBoundedSlot => _notSimplyBoundedSlot ??= 0; /// If the typedef might not be simply bounded, a nonzero slot id which is /// unique within this compilation unit. If this id is found in /// [LinkedUnit.notSimplyBounded], then at least one of this typedef's type /// parameters is not simply bounded, hence this typedef can't be used as a /// raw type when specifying the bound of a type parameter. /// /// Otherwise, zero. set notSimplyBoundedSlot(int value) { assert(value == null || value >= 0); this._notSimplyBoundedSlot = value; } @override List<UnlinkedParamBuilder> get parameters => _parameters ??= <UnlinkedParamBuilder>[]; /// Parameters of the executable, if any. set parameters(List<UnlinkedParamBuilder> value) { this._parameters = value; } @override EntityRefBuilder get returnType => _returnType; /// If [style] is [TypedefStyle.functionType], the return type of the typedef. /// If [style] is [TypedefStyle.genericFunctionType], the function type being /// defined. set returnType(EntityRefBuilder value) { this._returnType = value; } @override idl.TypedefStyle get style => _style ??= idl.TypedefStyle.functionType; /// The style of the typedef. set style(idl.TypedefStyle value) { this._style = value; } @override List<UnlinkedTypeParamBuilder> get typeParameters => _typeParameters ??= <UnlinkedTypeParamBuilder>[]; /// Type parameters of the typedef, if any. set typeParameters(List<UnlinkedTypeParamBuilder> value) { this._typeParameters = value; } UnlinkedTypedefBuilder( {List<UnlinkedExprBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, String name, int nameOffset, int notSimplyBoundedSlot, List<UnlinkedParamBuilder> parameters, EntityRefBuilder returnType, idl.TypedefStyle style, List<UnlinkedTypeParamBuilder> typeParameters}) : _annotations = annotations, _codeRange = codeRange, _documentationComment = documentationComment, _name = name, _nameOffset = nameOffset, _notSimplyBoundedSlot = notSimplyBoundedSlot, _parameters = parameters, _returnType = returnType, _style = style, _typeParameters = typeParameters; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _codeRange = null; _documentationComment = null; _nameOffset = null; _parameters?.forEach((b) => b.flushInformative()); _returnType?.flushInformative(); _typeParameters?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addBool(this._returnType != null); this._returnType?.collectApiSignature(signature); if (this._parameters == null) { signature.addInt(0); } else { signature.addInt(this._parameters.length); for (var x in this._parameters) { x?.collectApiSignature(signature); } } if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } if (this._typeParameters == null) { signature.addInt(0); } else { signature.addInt(this._typeParameters.length); for (var x in this._typeParameters) { x?.collectApiSignature(signature); } } signature.addInt(this._style == null ? 0 : this._style.index); signature.addInt(this._notSimplyBoundedSlot ?? 0); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_codeRange; fb.Offset offset_documentationComment; fb.Offset offset_name; fb.Offset offset_parameters; fb.Offset offset_returnType; fb.Offset offset_typeParameters; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (!(_parameters == null || _parameters.isEmpty)) { offset_parameters = fbBuilder .writeList(_parameters.map((b) => b.finish(fbBuilder)).toList()); } if (_returnType != null) { offset_returnType = _returnType.finish(fbBuilder); } if (!(_typeParameters == null || _typeParameters.isEmpty)) { offset_typeParameters = fbBuilder .writeList(_typeParameters.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(4, offset_annotations); } if (offset_codeRange != null) { fbBuilder.addOffset(7, offset_codeRange); } if (offset_documentationComment != null) { fbBuilder.addOffset(6, offset_documentationComment); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } if (_notSimplyBoundedSlot != null && _notSimplyBoundedSlot != 0) { fbBuilder.addUint32(9, _notSimplyBoundedSlot); } if (offset_parameters != null) { fbBuilder.addOffset(3, offset_parameters); } if (offset_returnType != null) { fbBuilder.addOffset(2, offset_returnType); } if (_style != null && _style != idl.TypedefStyle.functionType) { fbBuilder.addUint8(8, _style.index); } if (offset_typeParameters != null) { fbBuilder.addOffset(5, offset_typeParameters); } return fbBuilder.endTable(); } } class _UnlinkedTypedefReader extends fb.TableReader<_UnlinkedTypedefImpl> { const _UnlinkedTypedefReader(); @override _UnlinkedTypedefImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedTypedefImpl(bc, offset); } class _UnlinkedTypedefImpl extends Object with _UnlinkedTypedefMixin implements idl.UnlinkedTypedef { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedTypedefImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.CodeRange _codeRange; idl.UnlinkedDocumentationComment _documentationComment; String _name; int _nameOffset; int _notSimplyBoundedSlot; List<idl.UnlinkedParam> _parameters; idl.EntityRef _returnType; idl.TypedefStyle _style; List<idl.UnlinkedTypeParam> _typeParameters; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 7, null); return _codeRange; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 6, null); return _documentationComment; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } @override int get notSimplyBoundedSlot { _notSimplyBoundedSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 9, 0); return _notSimplyBoundedSlot; } @override List<idl.UnlinkedParam> get parameters { _parameters ??= const fb.ListReader<idl.UnlinkedParam>(const _UnlinkedParamReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.UnlinkedParam>[]); return _parameters; } @override idl.EntityRef get returnType { _returnType ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 2, null); return _returnType; } @override idl.TypedefStyle get style { _style ??= const _TypedefStyleReader() .vTableGet(_bc, _bcOffset, 8, idl.TypedefStyle.functionType); return _style; } @override List<idl.UnlinkedTypeParam> get typeParameters { _typeParameters ??= const fb.ListReader<idl.UnlinkedTypeParam>( const _UnlinkedTypeParamReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.UnlinkedTypeParam>[]); return _typeParameters; } } abstract class _UnlinkedTypedefMixin implements idl.UnlinkedTypedef { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (notSimplyBoundedSlot != 0) _result["notSimplyBoundedSlot"] = notSimplyBoundedSlot; if (parameters.isNotEmpty) _result["parameters"] = parameters.map((_value) => _value.toJson()).toList(); if (returnType != null) _result["returnType"] = returnType.toJson(); if (style != idl.TypedefStyle.functionType) _result["style"] = style.toString().split('.')[1]; if (typeParameters.isNotEmpty) _result["typeParameters"] = typeParameters.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "codeRange": codeRange, "documentationComment": documentationComment, "name": name, "nameOffset": nameOffset, "notSimplyBoundedSlot": notSimplyBoundedSlot, "parameters": parameters, "returnType": returnType, "style": style, "typeParameters": typeParameters, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedTypeParamBuilder extends Object with _UnlinkedTypeParamMixin implements idl.UnlinkedTypeParam { List<UnlinkedExprBuilder> _annotations; EntityRefBuilder _bound; CodeRangeBuilder _codeRange; String _name; int _nameOffset; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this type parameter. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override EntityRefBuilder get bound => _bound; /// Bound of the type parameter, if a bound is explicitly declared. Otherwise /// null. set bound(EntityRefBuilder value) { this._bound = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the type parameter. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override String get name => _name ??= ''; /// Name of the type parameter. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the type parameter name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } UnlinkedTypeParamBuilder( {List<UnlinkedExprBuilder> annotations, EntityRefBuilder bound, CodeRangeBuilder codeRange, String name, int nameOffset}) : _annotations = annotations, _bound = bound, _codeRange = codeRange, _name = name, _nameOffset = nameOffset; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _bound?.flushInformative(); _codeRange = null; _nameOffset = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addBool(this._bound != null); this._bound?.collectApiSignature(signature); if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_bound; fb.Offset offset_codeRange; fb.Offset offset_name; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_bound != null) { offset_bound = _bound.finish(fbBuilder); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(3, offset_annotations); } if (offset_bound != null) { fbBuilder.addOffset(2, offset_bound); } if (offset_codeRange != null) { fbBuilder.addOffset(4, offset_codeRange); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } return fbBuilder.endTable(); } } class _UnlinkedTypeParamReader extends fb.TableReader<_UnlinkedTypeParamImpl> { const _UnlinkedTypeParamReader(); @override _UnlinkedTypeParamImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedTypeParamImpl(bc, offset); } class _UnlinkedTypeParamImpl extends Object with _UnlinkedTypeParamMixin implements idl.UnlinkedTypeParam { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedTypeParamImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.EntityRef _bound; idl.CodeRange _codeRange; String _name; int _nameOffset; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.EntityRef get bound { _bound ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 2, null); return _bound; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 4, null); return _codeRange; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } } abstract class _UnlinkedTypeParamMixin implements idl.UnlinkedTypeParam { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (bound != null) _result["bound"] = bound.toJson(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "bound": bound, "codeRange": codeRange, "name": name, "nameOffset": nameOffset, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedUnitBuilder extends Object with _UnlinkedUnitMixin implements idl.UnlinkedUnit { List<int> _apiSignature; List<UnlinkedClassBuilder> _classes; CodeRangeBuilder _codeRange; List<UnlinkedEnumBuilder> _enums; List<UnlinkedExecutableBuilder> _executables; List<UnlinkedExportNonPublicBuilder> _exports; List<UnlinkedExtensionBuilder> _extensions; List<UnlinkedImportBuilder> _imports; bool _isNNBD; bool _isPartOf; List<UnlinkedExprBuilder> _libraryAnnotations; UnlinkedDocumentationCommentBuilder _libraryDocumentationComment; String _libraryName; int _libraryNameLength; int _libraryNameOffset; List<int> _lineStarts; List<UnlinkedClassBuilder> _mixins; List<UnlinkedPartBuilder> _parts; UnlinkedPublicNamespaceBuilder _publicNamespace; List<UnlinkedReferenceBuilder> _references; List<UnlinkedTypedefBuilder> _typedefs; List<UnlinkedVariableBuilder> _variables; @override List<int> get apiSignature => _apiSignature ??= <int>[]; /// MD5 hash of the non-informative fields of the [UnlinkedUnit] (not /// including this one) as 16 unsigned 8-bit integer values. This can be used /// to identify when the API of a unit may have changed. set apiSignature(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._apiSignature = value; } @override List<UnlinkedClassBuilder> get classes => _classes ??= <UnlinkedClassBuilder>[]; /// Classes declared in the compilation unit. set classes(List<UnlinkedClassBuilder> value) { this._classes = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the unit. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override List<UnlinkedEnumBuilder> get enums => _enums ??= <UnlinkedEnumBuilder>[]; /// Enums declared in the compilation unit. set enums(List<UnlinkedEnumBuilder> value) { this._enums = value; } @override List<UnlinkedExecutableBuilder> get executables => _executables ??= <UnlinkedExecutableBuilder>[]; /// Top level executable objects (functions, getters, and setters) declared in /// the compilation unit. set executables(List<UnlinkedExecutableBuilder> value) { this._executables = value; } @override List<UnlinkedExportNonPublicBuilder> get exports => _exports ??= <UnlinkedExportNonPublicBuilder>[]; /// Export declarations in the compilation unit. set exports(List<UnlinkedExportNonPublicBuilder> value) { this._exports = value; } @override List<UnlinkedExtensionBuilder> get extensions => _extensions ??= <UnlinkedExtensionBuilder>[]; /// Extensions declared in the compilation unit. set extensions(List<UnlinkedExtensionBuilder> value) { this._extensions = value; } @override Null get fallbackModePath => throw new UnimplementedError('attempt to access deprecated field'); @override List<UnlinkedImportBuilder> get imports => _imports ??= <UnlinkedImportBuilder>[]; /// Import declarations in the compilation unit. set imports(List<UnlinkedImportBuilder> value) { this._imports = value; } @override bool get isNNBD => _isNNBD ??= false; /// Indicates whether this compilation unit is opted into NNBD. set isNNBD(bool value) { this._isNNBD = value; } @override bool get isPartOf => _isPartOf ??= false; /// Indicates whether the unit contains a "part of" declaration. set isPartOf(bool value) { this._isPartOf = value; } @override List<UnlinkedExprBuilder> get libraryAnnotations => _libraryAnnotations ??= <UnlinkedExprBuilder>[]; /// Annotations for the library declaration, or the empty list if there is no /// library declaration. set libraryAnnotations(List<UnlinkedExprBuilder> value) { this._libraryAnnotations = value; } @override UnlinkedDocumentationCommentBuilder get libraryDocumentationComment => _libraryDocumentationComment; /// Documentation comment for the library, or `null` if there is no /// documentation comment. set libraryDocumentationComment(UnlinkedDocumentationCommentBuilder value) { this._libraryDocumentationComment = value; } @override String get libraryName => _libraryName ??= ''; /// Name of the library (from a "library" declaration, if present). set libraryName(String value) { this._libraryName = value; } @override int get libraryNameLength => _libraryNameLength ??= 0; /// Length of the library name as it appears in the source code (or 0 if the /// library has no name). set libraryNameLength(int value) { assert(value == null || value >= 0); this._libraryNameLength = value; } @override int get libraryNameOffset => _libraryNameOffset ??= 0; /// Offset of the library name relative to the beginning of the file (or 0 if /// the library has no name). set libraryNameOffset(int value) { assert(value == null || value >= 0); this._libraryNameOffset = value; } @override List<int> get lineStarts => _lineStarts ??= <int>[]; /// Offsets of the first character of each line in the source code. set lineStarts(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._lineStarts = value; } @override List<UnlinkedClassBuilder> get mixins => _mixins ??= <UnlinkedClassBuilder>[]; /// Mixins declared in the compilation unit. set mixins(List<UnlinkedClassBuilder> value) { this._mixins = value; } @override List<UnlinkedPartBuilder> get parts => _parts ??= <UnlinkedPartBuilder>[]; /// Part declarations in the compilation unit. set parts(List<UnlinkedPartBuilder> value) { this._parts = value; } @override UnlinkedPublicNamespaceBuilder get publicNamespace => _publicNamespace; /// Unlinked public namespace of this compilation unit. set publicNamespace(UnlinkedPublicNamespaceBuilder value) { this._publicNamespace = value; } @override List<UnlinkedReferenceBuilder> get references => _references ??= <UnlinkedReferenceBuilder>[]; /// Top level and prefixed names referred to by this compilation unit. The /// zeroth element of this array is always populated and is used to represent /// the absence of a reference in places where a reference is optional (for /// example [UnlinkedReference.prefixReference or /// UnlinkedImport.prefixReference]). set references(List<UnlinkedReferenceBuilder> value) { this._references = value; } @override List<UnlinkedTypedefBuilder> get typedefs => _typedefs ??= <UnlinkedTypedefBuilder>[]; /// Typedefs declared in the compilation unit. set typedefs(List<UnlinkedTypedefBuilder> value) { this._typedefs = value; } @override List<UnlinkedVariableBuilder> get variables => _variables ??= <UnlinkedVariableBuilder>[]; /// Top level variables declared in the compilation unit. set variables(List<UnlinkedVariableBuilder> value) { this._variables = value; } UnlinkedUnitBuilder( {List<int> apiSignature, List<UnlinkedClassBuilder> classes, CodeRangeBuilder codeRange, List<UnlinkedEnumBuilder> enums, List<UnlinkedExecutableBuilder> executables, List<UnlinkedExportNonPublicBuilder> exports, List<UnlinkedExtensionBuilder> extensions, List<UnlinkedImportBuilder> imports, bool isNNBD, bool isPartOf, List<UnlinkedExprBuilder> libraryAnnotations, UnlinkedDocumentationCommentBuilder libraryDocumentationComment, String libraryName, int libraryNameLength, int libraryNameOffset, List<int> lineStarts, List<UnlinkedClassBuilder> mixins, List<UnlinkedPartBuilder> parts, UnlinkedPublicNamespaceBuilder publicNamespace, List<UnlinkedReferenceBuilder> references, List<UnlinkedTypedefBuilder> typedefs, List<UnlinkedVariableBuilder> variables}) : _apiSignature = apiSignature, _classes = classes, _codeRange = codeRange, _enums = enums, _executables = executables, _exports = exports, _extensions = extensions, _imports = imports, _isNNBD = isNNBD, _isPartOf = isPartOf, _libraryAnnotations = libraryAnnotations, _libraryDocumentationComment = libraryDocumentationComment, _libraryName = libraryName, _libraryNameLength = libraryNameLength, _libraryNameOffset = libraryNameOffset, _lineStarts = lineStarts, _mixins = mixins, _parts = parts, _publicNamespace = publicNamespace, _references = references, _typedefs = typedefs, _variables = variables; /// Flush [informative] data recursively. void flushInformative() { _classes?.forEach((b) => b.flushInformative()); _codeRange = null; _enums?.forEach((b) => b.flushInformative()); _executables?.forEach((b) => b.flushInformative()); _exports?.forEach((b) => b.flushInformative()); _extensions?.forEach((b) => b.flushInformative()); _imports?.forEach((b) => b.flushInformative()); _libraryAnnotations?.forEach((b) => b.flushInformative()); _libraryDocumentationComment = null; _libraryNameLength = null; _libraryNameOffset = null; _lineStarts = null; _mixins?.forEach((b) => b.flushInformative()); _parts?.forEach((b) => b.flushInformative()); _publicNamespace?.flushInformative(); _references?.forEach((b) => b.flushInformative()); _typedefs?.forEach((b) => b.flushInformative()); _variables?.forEach((b) => b.flushInformative()); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addBool(this._publicNamespace != null); this._publicNamespace?.collectApiSignature(signature); if (this._references == null) { signature.addInt(0); } else { signature.addInt(this._references.length); for (var x in this._references) { x?.collectApiSignature(signature); } } if (this._classes == null) { signature.addInt(0); } else { signature.addInt(this._classes.length); for (var x in this._classes) { x?.collectApiSignature(signature); } } if (this._variables == null) { signature.addInt(0); } else { signature.addInt(this._variables.length); for (var x in this._variables) { x?.collectApiSignature(signature); } } if (this._executables == null) { signature.addInt(0); } else { signature.addInt(this._executables.length); for (var x in this._executables) { x?.collectApiSignature(signature); } } if (this._imports == null) { signature.addInt(0); } else { signature.addInt(this._imports.length); for (var x in this._imports) { x?.collectApiSignature(signature); } } signature.addString(this._libraryName ?? ''); if (this._typedefs == null) { signature.addInt(0); } else { signature.addInt(this._typedefs.length); for (var x in this._typedefs) { x?.collectApiSignature(signature); } } if (this._parts == null) { signature.addInt(0); } else { signature.addInt(this._parts.length); for (var x in this._parts) { x?.collectApiSignature(signature); } } if (this._enums == null) { signature.addInt(0); } else { signature.addInt(this._enums.length); for (var x in this._enums) { x?.collectApiSignature(signature); } } if (this._exports == null) { signature.addInt(0); } else { signature.addInt(this._exports.length); for (var x in this._exports) { x?.collectApiSignature(signature); } } if (this._libraryAnnotations == null) { signature.addInt(0); } else { signature.addInt(this._libraryAnnotations.length); for (var x in this._libraryAnnotations) { x?.collectApiSignature(signature); } } signature.addBool(this._isPartOf == true); if (this._apiSignature == null) { signature.addInt(0); } else { signature.addInt(this._apiSignature.length); for (var x in this._apiSignature) { signature.addInt(x); } } if (this._mixins == null) { signature.addInt(0); } else { signature.addInt(this._mixins.length); for (var x in this._mixins) { x?.collectApiSignature(signature); } } signature.addBool(this._isNNBD == true); if (this._extensions == null) { signature.addInt(0); } else { signature.addInt(this._extensions.length); for (var x in this._extensions) { x?.collectApiSignature(signature); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "UUnt"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_apiSignature; fb.Offset offset_classes; fb.Offset offset_codeRange; fb.Offset offset_enums; fb.Offset offset_executables; fb.Offset offset_exports; fb.Offset offset_extensions; fb.Offset offset_imports; fb.Offset offset_libraryAnnotations; fb.Offset offset_libraryDocumentationComment; fb.Offset offset_libraryName; fb.Offset offset_lineStarts; fb.Offset offset_mixins; fb.Offset offset_parts; fb.Offset offset_publicNamespace; fb.Offset offset_references; fb.Offset offset_typedefs; fb.Offset offset_variables; if (!(_apiSignature == null || _apiSignature.isEmpty)) { offset_apiSignature = fbBuilder.writeListUint32(_apiSignature); } if (!(_classes == null || _classes.isEmpty)) { offset_classes = fbBuilder .writeList(_classes.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (!(_enums == null || _enums.isEmpty)) { offset_enums = fbBuilder.writeList(_enums.map((b) => b.finish(fbBuilder)).toList()); } if (!(_executables == null || _executables.isEmpty)) { offset_executables = fbBuilder .writeList(_executables.map((b) => b.finish(fbBuilder)).toList()); } if (!(_exports == null || _exports.isEmpty)) { offset_exports = fbBuilder .writeList(_exports.map((b) => b.finish(fbBuilder)).toList()); } if (!(_extensions == null || _extensions.isEmpty)) { offset_extensions = fbBuilder .writeList(_extensions.map((b) => b.finish(fbBuilder)).toList()); } if (!(_imports == null || _imports.isEmpty)) { offset_imports = fbBuilder .writeList(_imports.map((b) => b.finish(fbBuilder)).toList()); } if (!(_libraryAnnotations == null || _libraryAnnotations.isEmpty)) { offset_libraryAnnotations = fbBuilder.writeList( _libraryAnnotations.map((b) => b.finish(fbBuilder)).toList()); } if (_libraryDocumentationComment != null) { offset_libraryDocumentationComment = _libraryDocumentationComment.finish(fbBuilder); } if (_libraryName != null) { offset_libraryName = fbBuilder.writeString(_libraryName); } if (!(_lineStarts == null || _lineStarts.isEmpty)) { offset_lineStarts = fbBuilder.writeListUint32(_lineStarts); } if (!(_mixins == null || _mixins.isEmpty)) { offset_mixins = fbBuilder.writeList(_mixins.map((b) => b.finish(fbBuilder)).toList()); } if (!(_parts == null || _parts.isEmpty)) { offset_parts = fbBuilder.writeList(_parts.map((b) => b.finish(fbBuilder)).toList()); } if (_publicNamespace != null) { offset_publicNamespace = _publicNamespace.finish(fbBuilder); } if (!(_references == null || _references.isEmpty)) { offset_references = fbBuilder .writeList(_references.map((b) => b.finish(fbBuilder)).toList()); } if (!(_typedefs == null || _typedefs.isEmpty)) { offset_typedefs = fbBuilder .writeList(_typedefs.map((b) => b.finish(fbBuilder)).toList()); } if (!(_variables == null || _variables.isEmpty)) { offset_variables = fbBuilder .writeList(_variables.map((b) => b.finish(fbBuilder)).toList()); } fbBuilder.startTable(); if (offset_apiSignature != null) { fbBuilder.addOffset(19, offset_apiSignature); } if (offset_classes != null) { fbBuilder.addOffset(2, offset_classes); } if (offset_codeRange != null) { fbBuilder.addOffset(15, offset_codeRange); } if (offset_enums != null) { fbBuilder.addOffset(12, offset_enums); } if (offset_executables != null) { fbBuilder.addOffset(4, offset_executables); } if (offset_exports != null) { fbBuilder.addOffset(13, offset_exports); } if (offset_extensions != null) { fbBuilder.addOffset(22, offset_extensions); } if (offset_imports != null) { fbBuilder.addOffset(5, offset_imports); } if (_isNNBD == true) { fbBuilder.addBool(21, true); } if (_isPartOf == true) { fbBuilder.addBool(18, true); } if (offset_libraryAnnotations != null) { fbBuilder.addOffset(14, offset_libraryAnnotations); } if (offset_libraryDocumentationComment != null) { fbBuilder.addOffset(9, offset_libraryDocumentationComment); } if (offset_libraryName != null) { fbBuilder.addOffset(6, offset_libraryName); } if (_libraryNameLength != null && _libraryNameLength != 0) { fbBuilder.addUint32(7, _libraryNameLength); } if (_libraryNameOffset != null && _libraryNameOffset != 0) { fbBuilder.addUint32(8, _libraryNameOffset); } if (offset_lineStarts != null) { fbBuilder.addOffset(17, offset_lineStarts); } if (offset_mixins != null) { fbBuilder.addOffset(20, offset_mixins); } if (offset_parts != null) { fbBuilder.addOffset(11, offset_parts); } if (offset_publicNamespace != null) { fbBuilder.addOffset(0, offset_publicNamespace); } if (offset_references != null) { fbBuilder.addOffset(1, offset_references); } if (offset_typedefs != null) { fbBuilder.addOffset(10, offset_typedefs); } if (offset_variables != null) { fbBuilder.addOffset(3, offset_variables); } return fbBuilder.endTable(); } } idl.UnlinkedUnit readUnlinkedUnit(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _UnlinkedUnitReader().read(rootRef, 0); } class _UnlinkedUnitReader extends fb.TableReader<_UnlinkedUnitImpl> { const _UnlinkedUnitReader(); @override _UnlinkedUnitImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedUnitImpl(bc, offset); } class _UnlinkedUnitImpl extends Object with _UnlinkedUnitMixin implements idl.UnlinkedUnit { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedUnitImpl(this._bc, this._bcOffset); List<int> _apiSignature; List<idl.UnlinkedClass> _classes; idl.CodeRange _codeRange; List<idl.UnlinkedEnum> _enums; List<idl.UnlinkedExecutable> _executables; List<idl.UnlinkedExportNonPublic> _exports; List<idl.UnlinkedExtension> _extensions; List<idl.UnlinkedImport> _imports; bool _isNNBD; bool _isPartOf; List<idl.UnlinkedExpr> _libraryAnnotations; idl.UnlinkedDocumentationComment _libraryDocumentationComment; String _libraryName; int _libraryNameLength; int _libraryNameOffset; List<int> _lineStarts; List<idl.UnlinkedClass> _mixins; List<idl.UnlinkedPart> _parts; idl.UnlinkedPublicNamespace _publicNamespace; List<idl.UnlinkedReference> _references; List<idl.UnlinkedTypedef> _typedefs; List<idl.UnlinkedVariable> _variables; @override List<int> get apiSignature { _apiSignature ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 19, const <int>[]); return _apiSignature; } @override List<idl.UnlinkedClass> get classes { _classes ??= const fb.ListReader<idl.UnlinkedClass>(const _UnlinkedClassReader()) .vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedClass>[]); return _classes; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 15, null); return _codeRange; } @override List<idl.UnlinkedEnum> get enums { _enums ??= const fb.ListReader<idl.UnlinkedEnum>(const _UnlinkedEnumReader()) .vTableGet(_bc, _bcOffset, 12, const <idl.UnlinkedEnum>[]); return _enums; } @override List<idl.UnlinkedExecutable> get executables { _executables ??= const fb.ListReader<idl.UnlinkedExecutable>( const _UnlinkedExecutableReader()) .vTableGet(_bc, _bcOffset, 4, const <idl.UnlinkedExecutable>[]); return _executables; } @override List<idl.UnlinkedExportNonPublic> get exports { _exports ??= const fb.ListReader<idl.UnlinkedExportNonPublic>( const _UnlinkedExportNonPublicReader()) .vTableGet(_bc, _bcOffset, 13, const <idl.UnlinkedExportNonPublic>[]); return _exports; } @override List<idl.UnlinkedExtension> get extensions { _extensions ??= const fb.ListReader<idl.UnlinkedExtension>( const _UnlinkedExtensionReader()) .vTableGet(_bc, _bcOffset, 22, const <idl.UnlinkedExtension>[]); return _extensions; } @override Null get fallbackModePath => throw new UnimplementedError('attempt to access deprecated field'); @override List<idl.UnlinkedImport> get imports { _imports ??= const fb.ListReader<idl.UnlinkedImport>(const _UnlinkedImportReader()) .vTableGet(_bc, _bcOffset, 5, const <idl.UnlinkedImport>[]); return _imports; } @override bool get isNNBD { _isNNBD ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 21, false); return _isNNBD; } @override bool get isPartOf { _isPartOf ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 18, false); return _isPartOf; } @override List<idl.UnlinkedExpr> get libraryAnnotations { _libraryAnnotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 14, const <idl.UnlinkedExpr>[]); return _libraryAnnotations; } @override idl.UnlinkedDocumentationComment get libraryDocumentationComment { _libraryDocumentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 9, null); return _libraryDocumentationComment; } @override String get libraryName { _libraryName ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 6, ''); return _libraryName; } @override int get libraryNameLength { _libraryNameLength ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 7, 0); return _libraryNameLength; } @override int get libraryNameOffset { _libraryNameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 8, 0); return _libraryNameOffset; } @override List<int> get lineStarts { _lineStarts ??= const fb.Uint32ListReader() .vTableGet(_bc, _bcOffset, 17, const <int>[]); return _lineStarts; } @override List<idl.UnlinkedClass> get mixins { _mixins ??= const fb.ListReader<idl.UnlinkedClass>(const _UnlinkedClassReader()) .vTableGet(_bc, _bcOffset, 20, const <idl.UnlinkedClass>[]); return _mixins; } @override List<idl.UnlinkedPart> get parts { _parts ??= const fb.ListReader<idl.UnlinkedPart>(const _UnlinkedPartReader()) .vTableGet(_bc, _bcOffset, 11, const <idl.UnlinkedPart>[]); return _parts; } @override idl.UnlinkedPublicNamespace get publicNamespace { _publicNamespace ??= const _UnlinkedPublicNamespaceReader() .vTableGet(_bc, _bcOffset, 0, null); return _publicNamespace; } @override List<idl.UnlinkedReference> get references { _references ??= const fb.ListReader<idl.UnlinkedReference>( const _UnlinkedReferenceReader()) .vTableGet(_bc, _bcOffset, 1, const <idl.UnlinkedReference>[]); return _references; } @override List<idl.UnlinkedTypedef> get typedefs { _typedefs ??= const fb.ListReader<idl.UnlinkedTypedef>(const _UnlinkedTypedefReader()) .vTableGet(_bc, _bcOffset, 10, const <idl.UnlinkedTypedef>[]); return _typedefs; } @override List<idl.UnlinkedVariable> get variables { _variables ??= const fb.ListReader<idl.UnlinkedVariable>( const _UnlinkedVariableReader()) .vTableGet(_bc, _bcOffset, 3, const <idl.UnlinkedVariable>[]); return _variables; } } abstract class _UnlinkedUnitMixin implements idl.UnlinkedUnit { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (apiSignature.isNotEmpty) _result["apiSignature"] = apiSignature; if (classes.isNotEmpty) _result["classes"] = classes.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (enums.isNotEmpty) _result["enums"] = enums.map((_value) => _value.toJson()).toList(); if (executables.isNotEmpty) _result["executables"] = executables.map((_value) => _value.toJson()).toList(); if (exports.isNotEmpty) _result["exports"] = exports.map((_value) => _value.toJson()).toList(); if (extensions.isNotEmpty) _result["extensions"] = extensions.map((_value) => _value.toJson()).toList(); if (imports.isNotEmpty) _result["imports"] = imports.map((_value) => _value.toJson()).toList(); if (isNNBD != false) _result["isNNBD"] = isNNBD; if (isPartOf != false) _result["isPartOf"] = isPartOf; if (libraryAnnotations.isNotEmpty) _result["libraryAnnotations"] = libraryAnnotations.map((_value) => _value.toJson()).toList(); if (libraryDocumentationComment != null) _result["libraryDocumentationComment"] = libraryDocumentationComment.toJson(); if (libraryName != '') _result["libraryName"] = libraryName; if (libraryNameLength != 0) _result["libraryNameLength"] = libraryNameLength; if (libraryNameOffset != 0) _result["libraryNameOffset"] = libraryNameOffset; if (lineStarts.isNotEmpty) _result["lineStarts"] = lineStarts; if (mixins.isNotEmpty) _result["mixins"] = mixins.map((_value) => _value.toJson()).toList(); if (parts.isNotEmpty) _result["parts"] = parts.map((_value) => _value.toJson()).toList(); if (publicNamespace != null) _result["publicNamespace"] = publicNamespace.toJson(); if (references.isNotEmpty) _result["references"] = references.map((_value) => _value.toJson()).toList(); if (typedefs.isNotEmpty) _result["typedefs"] = typedefs.map((_value) => _value.toJson()).toList(); if (variables.isNotEmpty) _result["variables"] = variables.map((_value) => _value.toJson()).toList(); return _result; } @override Map<String, Object> toMap() => { "apiSignature": apiSignature, "classes": classes, "codeRange": codeRange, "enums": enums, "executables": executables, "exports": exports, "extensions": extensions, "imports": imports, "isNNBD": isNNBD, "isPartOf": isPartOf, "libraryAnnotations": libraryAnnotations, "libraryDocumentationComment": libraryDocumentationComment, "libraryName": libraryName, "libraryNameLength": libraryNameLength, "libraryNameOffset": libraryNameOffset, "lineStarts": lineStarts, "mixins": mixins, "parts": parts, "publicNamespace": publicNamespace, "references": references, "typedefs": typedefs, "variables": variables, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedUnit2Builder extends Object with _UnlinkedUnit2Mixin implements idl.UnlinkedUnit2 { List<int> _apiSignature; List<String> _exports; bool _hasLibraryDirective; bool _hasPartOfDirective; List<String> _imports; List<UnlinkedInformativeDataBuilder> _informativeData; List<int> _lineStarts; List<String> _parts; @override List<int> get apiSignature => _apiSignature ??= <int>[]; /// The MD5 hash signature of the API portion of this unit. It depends on all /// tokens that might affect APIs of declarations in the unit. set apiSignature(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._apiSignature = value; } @override List<String> get exports => _exports ??= <String>[]; /// URIs of `export` directives. set exports(List<String> value) { this._exports = value; } @override bool get hasLibraryDirective => _hasLibraryDirective ??= false; /// Is `true` if the unit contains a `library` directive. set hasLibraryDirective(bool value) { this._hasLibraryDirective = value; } @override bool get hasPartOfDirective => _hasPartOfDirective ??= false; /// Is `true` if the unit contains a `part of` directive. set hasPartOfDirective(bool value) { this._hasPartOfDirective = value; } @override List<String> get imports => _imports ??= <String>[]; /// URIs of `import` directives. set imports(List<String> value) { this._imports = value; } @override List<UnlinkedInformativeDataBuilder> get informativeData => _informativeData ??= <UnlinkedInformativeDataBuilder>[]; set informativeData(List<UnlinkedInformativeDataBuilder> value) { this._informativeData = value; } @override List<int> get lineStarts => _lineStarts ??= <int>[]; /// Offsets of the first character of each line in the source code. set lineStarts(List<int> value) { assert(value == null || value.every((e) => e >= 0)); this._lineStarts = value; } @override List<String> get parts => _parts ??= <String>[]; /// URIs of `part` directives. set parts(List<String> value) { this._parts = value; } UnlinkedUnit2Builder( {List<int> apiSignature, List<String> exports, bool hasLibraryDirective, bool hasPartOfDirective, List<String> imports, List<UnlinkedInformativeDataBuilder> informativeData, List<int> lineStarts, List<String> parts}) : _apiSignature = apiSignature, _exports = exports, _hasLibraryDirective = hasLibraryDirective, _hasPartOfDirective = hasPartOfDirective, _imports = imports, _informativeData = informativeData, _lineStarts = lineStarts, _parts = parts; /// Flush [informative] data recursively. void flushInformative() { _informativeData?.forEach((b) => b.flushInformative()); _lineStarts = null; } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { if (this._apiSignature == null) { signature.addInt(0); } else { signature.addInt(this._apiSignature.length); for (var x in this._apiSignature) { signature.addInt(x); } } if (this._exports == null) { signature.addInt(0); } else { signature.addInt(this._exports.length); for (var x in this._exports) { signature.addString(x); } } if (this._imports == null) { signature.addInt(0); } else { signature.addInt(this._imports.length); for (var x in this._imports) { signature.addString(x); } } signature.addBool(this._hasPartOfDirective == true); if (this._parts == null) { signature.addInt(0); } else { signature.addInt(this._parts.length); for (var x in this._parts) { signature.addString(x); } } signature.addBool(this._hasLibraryDirective == true); if (this._informativeData == null) { signature.addInt(0); } else { signature.addInt(this._informativeData.length); for (var x in this._informativeData) { x?.collectApiSignature(signature); } } } List<int> toBuffer() { fb.Builder fbBuilder = new fb.Builder(); return fbBuilder.finish(finish(fbBuilder), "UUN2"); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_apiSignature; fb.Offset offset_exports; fb.Offset offset_imports; fb.Offset offset_informativeData; fb.Offset offset_lineStarts; fb.Offset offset_parts; if (!(_apiSignature == null || _apiSignature.isEmpty)) { offset_apiSignature = fbBuilder.writeListUint32(_apiSignature); } if (!(_exports == null || _exports.isEmpty)) { offset_exports = fbBuilder .writeList(_exports.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_imports == null || _imports.isEmpty)) { offset_imports = fbBuilder .writeList(_imports.map((b) => fbBuilder.writeString(b)).toList()); } if (!(_informativeData == null || _informativeData.isEmpty)) { offset_informativeData = fbBuilder .writeList(_informativeData.map((b) => b.finish(fbBuilder)).toList()); } if (!(_lineStarts == null || _lineStarts.isEmpty)) { offset_lineStarts = fbBuilder.writeListUint32(_lineStarts); } if (!(_parts == null || _parts.isEmpty)) { offset_parts = fbBuilder .writeList(_parts.map((b) => fbBuilder.writeString(b)).toList()); } fbBuilder.startTable(); if (offset_apiSignature != null) { fbBuilder.addOffset(0, offset_apiSignature); } if (offset_exports != null) { fbBuilder.addOffset(1, offset_exports); } if (_hasLibraryDirective == true) { fbBuilder.addBool(6, true); } if (_hasPartOfDirective == true) { fbBuilder.addBool(3, true); } if (offset_imports != null) { fbBuilder.addOffset(2, offset_imports); } if (offset_informativeData != null) { fbBuilder.addOffset(7, offset_informativeData); } if (offset_lineStarts != null) { fbBuilder.addOffset(5, offset_lineStarts); } if (offset_parts != null) { fbBuilder.addOffset(4, offset_parts); } return fbBuilder.endTable(); } } idl.UnlinkedUnit2 readUnlinkedUnit2(List<int> buffer) { fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer); return const _UnlinkedUnit2Reader().read(rootRef, 0); } class _UnlinkedUnit2Reader extends fb.TableReader<_UnlinkedUnit2Impl> { const _UnlinkedUnit2Reader(); @override _UnlinkedUnit2Impl createObject(fb.BufferContext bc, int offset) => new _UnlinkedUnit2Impl(bc, offset); } class _UnlinkedUnit2Impl extends Object with _UnlinkedUnit2Mixin implements idl.UnlinkedUnit2 { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedUnit2Impl(this._bc, this._bcOffset); List<int> _apiSignature; List<String> _exports; bool _hasLibraryDirective; bool _hasPartOfDirective; List<String> _imports; List<idl.UnlinkedInformativeData> _informativeData; List<int> _lineStarts; List<String> _parts; @override List<int> get apiSignature { _apiSignature ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 0, const <int>[]); return _apiSignature; } @override List<String> get exports { _exports ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 1, const <String>[]); return _exports; } @override bool get hasLibraryDirective { _hasLibraryDirective ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 6, false); return _hasLibraryDirective; } @override bool get hasPartOfDirective { _hasPartOfDirective ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 3, false); return _hasPartOfDirective; } @override List<String> get imports { _imports ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 2, const <String>[]); return _imports; } @override List<idl.UnlinkedInformativeData> get informativeData { _informativeData ??= const fb.ListReader<idl.UnlinkedInformativeData>( const _UnlinkedInformativeDataReader()) .vTableGet(_bc, _bcOffset, 7, const <idl.UnlinkedInformativeData>[]); return _informativeData; } @override List<int> get lineStarts { _lineStarts ??= const fb.Uint32ListReader().vTableGet(_bc, _bcOffset, 5, const <int>[]); return _lineStarts; } @override List<String> get parts { _parts ??= const fb.ListReader<String>(const fb.StringReader()) .vTableGet(_bc, _bcOffset, 4, const <String>[]); return _parts; } } abstract class _UnlinkedUnit2Mixin implements idl.UnlinkedUnit2 { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (apiSignature.isNotEmpty) _result["apiSignature"] = apiSignature; if (exports.isNotEmpty) _result["exports"] = exports; if (hasLibraryDirective != false) _result["hasLibraryDirective"] = hasLibraryDirective; if (hasPartOfDirective != false) _result["hasPartOfDirective"] = hasPartOfDirective; if (imports.isNotEmpty) _result["imports"] = imports; if (informativeData.isNotEmpty) _result["informativeData"] = informativeData.map((_value) => _value.toJson()).toList(); if (lineStarts.isNotEmpty) _result["lineStarts"] = lineStarts; if (parts.isNotEmpty) _result["parts"] = parts; return _result; } @override Map<String, Object> toMap() => { "apiSignature": apiSignature, "exports": exports, "hasLibraryDirective": hasLibraryDirective, "hasPartOfDirective": hasPartOfDirective, "imports": imports, "informativeData": informativeData, "lineStarts": lineStarts, "parts": parts, }; @override String toString() => convert.json.encode(toJson()); } class UnlinkedVariableBuilder extends Object with _UnlinkedVariableMixin implements idl.UnlinkedVariable { List<UnlinkedExprBuilder> _annotations; CodeRangeBuilder _codeRange; UnlinkedDocumentationCommentBuilder _documentationComment; int _inferredTypeSlot; int _inheritsCovariantSlot; UnlinkedExecutableBuilder _initializer; bool _isConst; bool _isCovariant; bool _isFinal; bool _isLate; bool _isStatic; String _name; int _nameOffset; int _propagatedTypeSlot; EntityRefBuilder _type; @override List<UnlinkedExprBuilder> get annotations => _annotations ??= <UnlinkedExprBuilder>[]; /// Annotations for this variable. set annotations(List<UnlinkedExprBuilder> value) { this._annotations = value; } @override CodeRangeBuilder get codeRange => _codeRange; /// Code range of the variable. set codeRange(CodeRangeBuilder value) { this._codeRange = value; } @override UnlinkedDocumentationCommentBuilder get documentationComment => _documentationComment; /// Documentation comment for the variable, or `null` if there is no /// documentation comment. set documentationComment(UnlinkedDocumentationCommentBuilder value) { this._documentationComment = value; } @override int get inferredTypeSlot => _inferredTypeSlot ??= 0; /// If this variable is inferable, nonzero slot id identifying which entry in /// [LinkedLibrary.types] contains the inferred type for this variable. If /// there is no matching entry in [LinkedLibrary.types], then no type was /// inferred for this variable, so its static type is `dynamic`. set inferredTypeSlot(int value) { assert(value == null || value >= 0); this._inferredTypeSlot = value; } @override int get inheritsCovariantSlot => _inheritsCovariantSlot ??= 0; /// If this is an instance non-final field, a nonzero slot id which is unique /// within this compilation unit. If this id is found in /// [LinkedUnit.parametersInheritingCovariant], then the parameter of the /// synthetic setter inherits `@covariant` behavior from a base class. /// /// Otherwise, zero. set inheritsCovariantSlot(int value) { assert(value == null || value >= 0); this._inheritsCovariantSlot = value; } @override UnlinkedExecutableBuilder get initializer => _initializer; /// The synthetic initializer function of the variable. Absent if the /// variable does not have an initializer. set initializer(UnlinkedExecutableBuilder value) { this._initializer = value; } @override bool get isConst => _isConst ??= false; /// Indicates whether the variable is declared using the `const` keyword. set isConst(bool value) { this._isConst = value; } @override bool get isCovariant => _isCovariant ??= false; /// Indicates whether this variable is declared using the `covariant` keyword. /// This should be false for everything except instance fields. set isCovariant(bool value) { this._isCovariant = value; } @override bool get isFinal => _isFinal ??= false; /// Indicates whether the variable is declared using the `final` keyword. set isFinal(bool value) { this._isFinal = value; } @override bool get isLate => _isLate ??= false; /// Indicates whether the variable is declared using the `late` keyword. set isLate(bool value) { this._isLate = value; } @override bool get isStatic => _isStatic ??= false; /// Indicates whether the variable is declared using the `static` keyword. /// /// Note that for top level variables, this flag is false, since they are not /// declared using the `static` keyword (even though they are considered /// static for semantic purposes). set isStatic(bool value) { this._isStatic = value; } @override String get name => _name ??= ''; /// Name of the variable. set name(String value) { this._name = value; } @override int get nameOffset => _nameOffset ??= 0; /// Offset of the variable name relative to the beginning of the file. set nameOffset(int value) { assert(value == null || value >= 0); this._nameOffset = value; } @override int get propagatedTypeSlot => _propagatedTypeSlot ??= 0; /// If this variable is propagable, nonzero slot id identifying which entry in /// [LinkedLibrary.types] contains the propagated type for this variable. If /// there is no matching entry in [LinkedLibrary.types], then this variable's /// propagated type is the same as its declared type. /// /// Non-propagable variables have a [propagatedTypeSlot] of zero. set propagatedTypeSlot(int value) { assert(value == null || value >= 0); this._propagatedTypeSlot = value; } @override EntityRefBuilder get type => _type; /// Declared type of the variable. Absent if the type is implicit. set type(EntityRefBuilder value) { this._type = value; } @override Null get visibleLength => throw new UnimplementedError('attempt to access deprecated field'); @override Null get visibleOffset => throw new UnimplementedError('attempt to access deprecated field'); UnlinkedVariableBuilder( {List<UnlinkedExprBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, int inferredTypeSlot, int inheritsCovariantSlot, UnlinkedExecutableBuilder initializer, bool isConst, bool isCovariant, bool isFinal, bool isLate, bool isStatic, String name, int nameOffset, int propagatedTypeSlot, EntityRefBuilder type}) : _annotations = annotations, _codeRange = codeRange, _documentationComment = documentationComment, _inferredTypeSlot = inferredTypeSlot, _inheritsCovariantSlot = inheritsCovariantSlot, _initializer = initializer, _isConst = isConst, _isCovariant = isCovariant, _isFinal = isFinal, _isLate = isLate, _isStatic = isStatic, _name = name, _nameOffset = nameOffset, _propagatedTypeSlot = propagatedTypeSlot, _type = type; /// Flush [informative] data recursively. void flushInformative() { _annotations?.forEach((b) => b.flushInformative()); _codeRange = null; _documentationComment = null; _initializer?.flushInformative(); _nameOffset = null; _type?.flushInformative(); } /// Accumulate non-[informative] data into [signature]. void collectApiSignature(api_sig.ApiSignature signature) { signature.addString(this._name ?? ''); signature.addInt(this._propagatedTypeSlot ?? 0); signature.addBool(this._type != null); this._type?.collectApiSignature(signature); signature.addBool(this._isStatic == true); signature.addBool(this._isConst == true); signature.addBool(this._isFinal == true); if (this._annotations == null) { signature.addInt(0); } else { signature.addInt(this._annotations.length); for (var x in this._annotations) { x?.collectApiSignature(signature); } } signature.addInt(this._inferredTypeSlot ?? 0); signature.addBool(this._initializer != null); this._initializer?.collectApiSignature(signature); signature.addBool(this._isCovariant == true); signature.addInt(this._inheritsCovariantSlot ?? 0); signature.addBool(this._isLate == true); } fb.Offset finish(fb.Builder fbBuilder) { fb.Offset offset_annotations; fb.Offset offset_codeRange; fb.Offset offset_documentationComment; fb.Offset offset_initializer; fb.Offset offset_name; fb.Offset offset_type; if (!(_annotations == null || _annotations.isEmpty)) { offset_annotations = fbBuilder .writeList(_annotations.map((b) => b.finish(fbBuilder)).toList()); } if (_codeRange != null) { offset_codeRange = _codeRange.finish(fbBuilder); } if (_documentationComment != null) { offset_documentationComment = _documentationComment.finish(fbBuilder); } if (_initializer != null) { offset_initializer = _initializer.finish(fbBuilder); } if (_name != null) { offset_name = fbBuilder.writeString(_name); } if (_type != null) { offset_type = _type.finish(fbBuilder); } fbBuilder.startTable(); if (offset_annotations != null) { fbBuilder.addOffset(8, offset_annotations); } if (offset_codeRange != null) { fbBuilder.addOffset(5, offset_codeRange); } if (offset_documentationComment != null) { fbBuilder.addOffset(10, offset_documentationComment); } if (_inferredTypeSlot != null && _inferredTypeSlot != 0) { fbBuilder.addUint32(9, _inferredTypeSlot); } if (_inheritsCovariantSlot != null && _inheritsCovariantSlot != 0) { fbBuilder.addUint32(15, _inheritsCovariantSlot); } if (offset_initializer != null) { fbBuilder.addOffset(13, offset_initializer); } if (_isConst == true) { fbBuilder.addBool(6, true); } if (_isCovariant == true) { fbBuilder.addBool(14, true); } if (_isFinal == true) { fbBuilder.addBool(7, true); } if (_isLate == true) { fbBuilder.addBool(16, true); } if (_isStatic == true) { fbBuilder.addBool(4, true); } if (offset_name != null) { fbBuilder.addOffset(0, offset_name); } if (_nameOffset != null && _nameOffset != 0) { fbBuilder.addUint32(1, _nameOffset); } if (_propagatedTypeSlot != null && _propagatedTypeSlot != 0) { fbBuilder.addUint32(2, _propagatedTypeSlot); } if (offset_type != null) { fbBuilder.addOffset(3, offset_type); } return fbBuilder.endTable(); } } class _UnlinkedVariableReader extends fb.TableReader<_UnlinkedVariableImpl> { const _UnlinkedVariableReader(); @override _UnlinkedVariableImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedVariableImpl(bc, offset); } class _UnlinkedVariableImpl extends Object with _UnlinkedVariableMixin implements idl.UnlinkedVariable { final fb.BufferContext _bc; final int _bcOffset; _UnlinkedVariableImpl(this._bc, this._bcOffset); List<idl.UnlinkedExpr> _annotations; idl.CodeRange _codeRange; idl.UnlinkedDocumentationComment _documentationComment; int _inferredTypeSlot; int _inheritsCovariantSlot; idl.UnlinkedExecutable _initializer; bool _isConst; bool _isCovariant; bool _isFinal; bool _isLate; bool _isStatic; String _name; int _nameOffset; int _propagatedTypeSlot; idl.EntityRef _type; @override List<idl.UnlinkedExpr> get annotations { _annotations ??= const fb.ListReader<idl.UnlinkedExpr>(const _UnlinkedExprReader()) .vTableGet(_bc, _bcOffset, 8, const <idl.UnlinkedExpr>[]); return _annotations; } @override idl.CodeRange get codeRange { _codeRange ??= const _CodeRangeReader().vTableGet(_bc, _bcOffset, 5, null); return _codeRange; } @override idl.UnlinkedDocumentationComment get documentationComment { _documentationComment ??= const _UnlinkedDocumentationCommentReader() .vTableGet(_bc, _bcOffset, 10, null); return _documentationComment; } @override int get inferredTypeSlot { _inferredTypeSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 9, 0); return _inferredTypeSlot; } @override int get inheritsCovariantSlot { _inheritsCovariantSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 15, 0); return _inheritsCovariantSlot; } @override idl.UnlinkedExecutable get initializer { _initializer ??= const _UnlinkedExecutableReader().vTableGet(_bc, _bcOffset, 13, null); return _initializer; } @override bool get isConst { _isConst ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 6, false); return _isConst; } @override bool get isCovariant { _isCovariant ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 14, false); return _isCovariant; } @override bool get isFinal { _isFinal ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 7, false); return _isFinal; } @override bool get isLate { _isLate ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 16, false); return _isLate; } @override bool get isStatic { _isStatic ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 4, false); return _isStatic; } @override String get name { _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, ''); return _name; } @override int get nameOffset { _nameOffset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0); return _nameOffset; } @override int get propagatedTypeSlot { _propagatedTypeSlot ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0); return _propagatedTypeSlot; } @override idl.EntityRef get type { _type ??= const _EntityRefReader().vTableGet(_bc, _bcOffset, 3, null); return _type; } @override Null get visibleLength => throw new UnimplementedError('attempt to access deprecated field'); @override Null get visibleOffset => throw new UnimplementedError('attempt to access deprecated field'); } abstract class _UnlinkedVariableMixin implements idl.UnlinkedVariable { @override Map<String, Object> toJson() { Map<String, Object> _result = <String, Object>{}; if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList(); if (codeRange != null) _result["codeRange"] = codeRange.toJson(); if (documentationComment != null) _result["documentationComment"] = documentationComment.toJson(); if (inferredTypeSlot != 0) _result["inferredTypeSlot"] = inferredTypeSlot; if (inheritsCovariantSlot != 0) _result["inheritsCovariantSlot"] = inheritsCovariantSlot; if (initializer != null) _result["initializer"] = initializer.toJson(); if (isConst != false) _result["isConst"] = isConst; if (isCovariant != false) _result["isCovariant"] = isCovariant; if (isFinal != false) _result["isFinal"] = isFinal; if (isLate != false) _result["isLate"] = isLate; if (isStatic != false) _result["isStatic"] = isStatic; if (name != '') _result["name"] = name; if (nameOffset != 0) _result["nameOffset"] = nameOffset; if (propagatedTypeSlot != 0) _result["propagatedTypeSlot"] = propagatedTypeSlot; if (type != null) _result["type"] = type.toJson(); return _result; } @override Map<String, Object> toMap() => { "annotations": annotations, "codeRange": codeRange, "documentationComment": documentationComment, "inferredTypeSlot": inferredTypeSlot, "inheritsCovariantSlot": inheritsCovariantSlot, "initializer": initializer, "isConst": isConst, "isCovariant": isCovariant, "isFinal": isFinal, "isLate": isLate, "isStatic": isStatic, "name": name, "nameOffset": nameOffset, "propagatedTypeSlot": propagatedTypeSlot, "type": type, }; @override String toString() => convert.json.encode(toJson()); }
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/summary/name_filter.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 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/src/summary/idl.dart'; /** * A [NameFilter] represents the set of filtering rules implied by zero or more * combinators in an `export` or `import` statement. */ class NameFilter { /** * A [NameFilter] representing no filtering at all (i.e. no combinators). */ static final NameFilter identity = new NameFilter._(hiddenNames: new Set<String>()); /** * If this [NameFilter] accepts a finite number of names and hides all * others, the (possibly empty) set of names it accepts. Otherwise `null`. */ final Set<String> shownNames; /** * If [shownNames] is `null`, the (possibly empty) set of names not accepted * by this filter (all other names are accepted). If [shownNames] is not * `null`, then [hiddenNames] will be `null`. */ final Set<String> hiddenNames; /** * Create a [NameFilter] based on the given [combinator]. */ factory NameFilter.forNamespaceCombinator(NamespaceCombinator combinator) { if (combinator is ShowElementCombinator) { return new NameFilter._(shownNames: combinator.shownNames.toSet()); } else if (combinator is HideElementCombinator) { return new NameFilter._(hiddenNames: combinator.hiddenNames.toSet()); } else { throw new StateError( 'Unexpected combinator type ${combinator.runtimeType}'); } } /** * Create a [NameFilter] based on the given (possibly empty) sequence of * [combinators]. */ factory NameFilter.forNamespaceCombinators( List<NamespaceCombinator> combinators) { NameFilter result = identity; for (NamespaceCombinator combinator in combinators) { result = result.merge(new NameFilter.forNamespaceCombinator(combinator)); } return result; } /** * Create a [NameFilter] based on the given [combinator]. */ factory NameFilter.forUnlinkedCombinator(UnlinkedCombinator combinator) { if (combinator.shows.isNotEmpty) { return new NameFilter._(shownNames: combinator.shows.toSet()); } else { return new NameFilter._(hiddenNames: combinator.hides.toSet()); } } /** * Create a [NameFilter] based on the given (possibly empty) sequence of * [combinators]. */ factory NameFilter.forUnlinkedCombinators( List<UnlinkedCombinator> combinators) { NameFilter result = identity; for (UnlinkedCombinator combinator in combinators) { result = result.merge(new NameFilter.forUnlinkedCombinator(combinator)); } return result; } const NameFilter._({this.shownNames, this.hiddenNames}); /** * Determine if the given [name] is accepted by this [NameFilter]. */ bool accepts(String name) { if (name.endsWith('=')) { name = name.substring(0, name.length - 1); } if (shownNames != null) { return shownNames.contains(name); } else { return !hiddenNames.contains(name); } } /** * Produce a new [NameFilter] by combining this [NameFilter] with another * one. The new [NameFilter] will only accept names that would be accepted * by both input filters. */ NameFilter merge(NameFilter other) { if (shownNames != null) { if (other.shownNames != null) { return new NameFilter._( shownNames: shownNames.intersection(other.shownNames)); } else { return new NameFilter._( shownNames: shownNames.difference(other.hiddenNames)); } } else { if (other.shownNames != null) { return new NameFilter._( shownNames: other.shownNames.difference(hiddenNames)); } else { return new NameFilter._( hiddenNames: hiddenNames.union(other.hiddenNames)); } } } }
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/summary/summarize_elements.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'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; /** * Object that gathers information uses it to assemble a new * [PackageBundleBuilder]. */ class PackageBundleAssembler { /** * Value that will be stored in [PackageBundle.majorVersion] for any summaries * created by this code. When making a breaking change to the summary format, * this value should be incremented by 1 and [currentMinorVersion] should be * reset to zero. */ static const int currentMajorVersion = 1; /** * Value that will be stored in [PackageBundle.minorVersion] for any summaries * created by this code. When making a non-breaking change to the summary * format that clients might need to be aware of (such as adding a kind of * data that was previously not summarized), this value should be incremented * by 1. */ static const int currentMinorVersion = 1; final List<String> _linkedLibraryUris = <String>[]; final List<LinkedLibraryBuilder> _linkedLibraries = <LinkedLibraryBuilder>[]; final List<String> _unlinkedUnitUris = <String>[]; final List<UnlinkedUnitBuilder> _unlinkedUnits = <UnlinkedUnitBuilder>[]; final Map<String, UnlinkedUnitBuilder> _unlinkedUnitMap = <String, UnlinkedUnitBuilder>{}; LinkedNodeBundleBuilder _bundle2; void addLinkedLibrary(String uri, LinkedLibraryBuilder library) { _linkedLibraries.add(library); _linkedLibraryUris.add(uri); } void addUnlinkedUnit(Source source, UnlinkedUnitBuilder unit) { addUnlinkedUnitViaUri(source.uri.toString(), unit); } void addUnlinkedUnitViaUri(String uri, UnlinkedUnitBuilder unit) { _unlinkedUnitUris.add(uri); _unlinkedUnits.add(unit); _unlinkedUnitMap[uri] = unit; } /** * Assemble a new [PackageBundleBuilder] using the gathered information. */ PackageBundleBuilder assemble() { return new PackageBundleBuilder( linkedLibraryUris: _linkedLibraryUris, linkedLibraries: _linkedLibraries, unlinkedUnitUris: _unlinkedUnitUris, unlinkedUnits: _unlinkedUnits, majorVersion: currentMajorVersion, minorVersion: currentMinorVersion, bundle2: _bundle2); } void setBundle2(LinkedNodeBundleBuilder bundle2) { if (this._bundle2 != null) { throw StateError('Bundle2 may be set only once.'); } _bundle2 = bundle2; } }
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/summary/summary_file_builder.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/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/file_system/physical_file_system.dart'; import 'package:analyzer/src/dart/scanner/reader.dart'; import 'package:analyzer/src/dart/scanner/scanner.dart'; import 'package:analyzer/src/dart/sdk/sdk.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/parser.dart'; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/summary/summarize_elements.dart'; import 'package:analyzer/src/summary2/link.dart' as summary2; import 'package:analyzer/src/summary2/linked_element_factory.dart' as summary2; import 'package:analyzer/src/summary2/reference.dart' as summary2; class SummaryBuilder { final Iterable<Source> librarySources; final AnalysisContext context; /** * Create a summary builder for these [librarySources] and [context]. */ SummaryBuilder(this.librarySources, this.context); /** * Create an SDK summary builder for the dart SDK at the given [sdkPath]. */ factory SummaryBuilder.forSdk(String sdkPath) { // // Prepare SDK. // ResourceProvider resourceProvider = PhysicalResourceProvider.INSTANCE; FolderBasedDartSdk sdk = new FolderBasedDartSdk( resourceProvider, resourceProvider.getFolder(sdkPath), true); sdk.useSummary = false; sdk.analysisOptions = new AnalysisOptionsImpl(); // // Prepare 'dart:' URIs to serialize. // Set<String> uriSet = sdk.sdkLibraries.map((SdkLibrary library) => library.shortName).toSet(); uriSet.add('dart:html_common/html_common_dart2js.dart'); Set<Source> librarySources = new HashSet<Source>(); for (String uri in uriSet) { librarySources.add(sdk.mapDartUri(uri)); } return new SummaryBuilder(librarySources, sdk.context); } /** * Build the linked bundle and return its bytes. */ List<int> build() => new _Builder(context, librarySources).build(); } class _Builder { final AnalysisContext context; final Iterable<Source> librarySources; final Set<String> libraryUris = new Set<String>(); final List<summary2.LinkInputLibrary> inputLibraries = []; final PackageBundleAssembler bundleAssembler = new PackageBundleAssembler(); _Builder(this.context, this.librarySources); /** * Build the linked bundle and return its bytes. */ List<int> build() { librarySources.forEach(_addLibrary); var elementFactory = summary2.LinkedElementFactory( context, null, summary2.Reference.root(), ); var linkResult = summary2.link(elementFactory, inputLibraries); bundleAssembler.setBundle2(linkResult.bundle); return bundleAssembler.assemble().toBuffer(); } void _addLibrary(Source source) { String uriStr = source.uri.toString(); if (!libraryUris.add(uriStr)) { return; } var inputUnits = <summary2.LinkInputUnit>[]; CompilationUnit definingUnit = _parse(source); inputUnits.add( summary2.LinkInputUnit(null, source, false, definingUnit), ); for (Directive directive in definingUnit.directives) { if (directive is NamespaceDirective) { String libUri = directive.uri.stringValue; Source libSource = context.sourceFactory.resolveUri(source, libUri); _addLibrary(libSource); } else if (directive is PartDirective) { String partUri = directive.uri.stringValue; Source partSource = context.sourceFactory.resolveUri(source, partUri); CompilationUnit partUnit = _parse(partSource); inputUnits.add( summary2.LinkInputUnit(partUri, partSource, false, partUnit), ); } } inputLibraries.add( summary2.LinkInputLibrary(source, inputUnits), ); } CompilationUnit _parse(Source source) { AnalysisErrorListener errorListener = AnalysisErrorListener.NULL_LISTENER; String code = source.contents.data; CharSequenceReader reader = new CharSequenceReader(code); // TODO(paulberry): figure out the appropriate featureSet to use here var featureSet = FeatureSet.fromEnableFlags([]); Scanner scanner = new Scanner(source, reader, errorListener) ..configureFeatures(featureSet); Token token = scanner.tokenize(); LineInfo lineInfo = new LineInfo(scanner.lineStarts); Parser parser = new Parser(source, errorListener, featureSet: featureSet, useFasta: context.analysisOptions.useFastaParser); parser.enableOptionalNewAndConst = true; CompilationUnit unit = parser.parseCompilationUnit(token); unit.lineInfo = lineInfo; return unit; } }
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/source/path_filter.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/glob.dart'; import 'package:path/path.dart' as path; /// Filter paths against a set of [_ignorePatterns] relative to a [root] /// directory. Paths outside of [root] are also ignored. class PathFilter { /// The path context to use when manipulating paths. final path.Context pathContext; /// Path that all ignore patterns are relative to. final String root; /// List of ignore patterns that paths are tested against. final List<Glob> _ignorePatterns = new List<Glob>(); /// Construct a new path filter rooted at [root] with [ignorePatterns]. /// If [pathContext] is not specified, then the system path context is used. PathFilter(this.root, List<String> ignorePatterns, [path.Context pathContext]) : this.pathContext = pathContext ?? path.context { setIgnorePatterns(ignorePatterns); } /// Returns true if [path] should be ignored. A path is ignored if it is not /// contained in [root] or matches one of the ignore patterns. /// [path] is absolute or relative to [root]. bool ignored(String path) { path = _canonicalize(path); return !_contained(path) || _match(path); } /// Set the ignore patterns. void setIgnorePatterns(List<String> ignorePatterns) { _ignorePatterns.clear(); if (ignorePatterns != null) { for (var ignorePattern in ignorePatterns) { _ignorePatterns.add(new Glob(pathContext.separator, ignorePattern)); } } } @override String toString() { StringBuffer sb = new StringBuffer(); for (Glob pattern in _ignorePatterns) { sb.write('$pattern '); } sb.writeln(''); return sb.toString(); } /// Returns the absolute path of [path], relative to [root]. String _canonicalize(String path) => pathContext.normalize(pathContext.join(root, path)); /// Returns true when [path] is contained inside [root]. bool _contained(String path) => path.startsWith(root); /// Returns true if [path] matches any ignore patterns. bool _match(String path) { path = _relative(path); for (Glob glob in _ignorePatterns) { if (glob.matches(path)) { return true; } } return false; } /// Returns the relative portion of [path] from [root]. String _relative(String path) => pathContext.relative(path, from: root); }
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/source/source_resource.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/file_system/file_system.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/source.dart'; /** * A function that can translate the contents of files on disk as they are read. * This is now obsolete, but supported the ability of server to deal with * clients that convert all text to an internal format. */ typedef String FileReadMode(String s); /** * A source that represents a file. */ class FileSource extends Source { /** * A function that changes the way that files are read off of disk. */ static FileReadMode fileReadMode = (String s) => s; /** * Map from encoded URI/filepath pair to a unique integer identifier. This * identifier is used for equality tests and hash codes. * * The URI and filepath are joined into a pair by separating them with an '@' * character. */ static final Map<String, int> _idTable = new HashMap<String, int>(); /** * The URI from which this source was originally derived. */ @override final Uri uri; /** * The unique ID associated with this source. */ final int id; /** * The file represented by this source. */ final File file; /** * The cached absolute path of this source. */ String _absolutePath; /** * The cached encoding for this source. */ String _encoding; /** * Initialize a newly created source object to represent the given [file]. If * a [uri] is given, then it will be used as the URI from which the source was * derived, otherwise a `file:` URI will be created based on the [file]. */ FileSource(File file, [Uri uri]) : this.uri = uri ?? file.toUri(), this.file = file, id = _idTable.putIfAbsent( '${uri ?? file.toUri()}@${file.path}', () => _idTable.length); @override TimestampedData<String> get contents { return PerformanceStatistics.io.makeCurrentWhile(() { return contentsFromFile; }); } /** * Get and return the contents and timestamp of the underlying file. * * 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. * * Throws an exception if the contents of this source could not be accessed. * See [contents]. */ TimestampedData<String> get contentsFromFile { return new TimestampedData<String>( modificationStamp, fileReadMode(file.readAsStringSync())); } @override String get encoding => _encoding ??= uri.toString(); @override String get fullName => _absolutePath ??= file.path; @override int get hashCode => uri.hashCode; @override bool get isInSystemLibrary => uri.scheme == DartUriResolver.DART_SCHEME; @override int get modificationStamp { try { return file.modificationStamp; } on FileSystemException { return -1; } } @override String get shortName => file.shortName; @override UriKind get uriKind => UriKind.fromScheme(uri.scheme); @override bool operator ==(Object object) { if (object is FileSource) { return id == object.id; } else if (object is Source) { return uri == object.uri; } return false; } @override bool exists() => file.exists; @override String toString() { if (file == null) { return "<unknown source>"; } return file.path; } }
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/source/sdk_ext.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:convert'; import 'dart:core'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/generated/java_io.dart' show JavaFile; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/source_io.dart' show FileBasedSource; import 'package:analyzer/src/source/package_map_provider.dart' show PackageMapProvider; import 'package:path/path.dart' as pathos; /// Given a packageMap (see [PackageMapProvider]), check in each package's lib /// directory for the existence of a `_sdkext` file. This file must contain a /// JSON encoded map. Each key in the map is a `dart:` library name. Each value /// is a path (relative to the directory containing `_sdkext`) to a dart script /// for the given library. For example: /// { /// "dart:sky": "../sdk_ext/dart_sky.dart" /// } /// /// If a key doesn't begin with `dart:` it is ignored. class SdkExtUriResolver extends UriResolver { static const String SDK_EXT_NAME = '_sdkext'; static const String DART_COLON_PREFIX = 'dart:'; final Map<String, String> _urlMappings = <String, String>{}; /** * The absolute paths of the extension files that contributed to the * [_urlMappings]. */ final List<String> extensionFilePaths = <String>[]; /// Construct a [SdkExtUriResolver] from a package map /// (see [PackageMapProvider]). SdkExtUriResolver(Map<String, List<Folder>> packageMap) { if (packageMap == null) { return; } packageMap.forEach(_processPackage); } /// Number of sdk extensions. int get length => _urlMappings.length; /** * Return a table mapping the names of extensions to the paths where those * extensions can be found. */ Map<String, String> get urlMappings => new Map<String, String>.from(_urlMappings); /// Return the path mapping for [libName] or null if there is none. String operator [](String libName) => _urlMappings[libName]; /// Programmatically add a new SDK extension given a JSON description /// ([sdkExtJSON]) and a lib directory ([libDir]). void addSdkExt(String sdkExtJSON, Folder libDir) { _processSdkExt(sdkExtJSON, libDir); } @override Source resolveAbsolute(Uri importUri, [Uri actualUri]) { String libraryName = _libraryName(importUri); String partPath = _partPath(importUri); // Lookup library name in mappings. String mapping = _urlMappings[libraryName]; if (mapping == null) { // Not found. return null; } // This mapping points to the main entry file of the sdk extension. Uri libraryEntry = new Uri.file(mapping); if (!libraryEntry.isAbsolute) { // We expect an absolute path. return null; } if (partPath != null) { return _resolvePart(libraryEntry, partPath, importUri); } else { return _resolveEntry(libraryEntry, importUri); } } @override Uri restoreAbsolute(Source source) { String extensionName = _findExtensionNameFor(source.fullName); if (extensionName != null) { return Uri.parse(extensionName); } // TODO(johnmccutchan): Handle restoring parts. return null; } /// Return the extension name for [fullName] or `null`. String _findExtensionNameFor(String fullName) { var result; _urlMappings.forEach((extensionName, pathMapping) { if (pathMapping == fullName) { result = extensionName; } }); return result; } /// Return the library name of [importUri]. String _libraryName(Uri importUri) { var uri = importUri.toString(); int index = uri.indexOf('/'); if (index >= 0) { return uri.substring(0, index); } return uri; } /// Return the part path of [importUri]. String _partPath(Uri importUri) { var uri = importUri.toString(); int index = uri.indexOf('/'); if (index >= 0) { return uri.substring(index + 1); } return null; } /// Given a package [name] and a list of folders ([libDirs]), /// add any found sdk extensions. void _processPackage(String name, List<Folder> libDirs) { for (var libDir in libDirs) { var sdkExt = _readDotSdkExt(libDir); if (sdkExt != null) { _processSdkExt(sdkExt, libDir); } } } /// Given the JSON for an SDK extension ([sdkExtJSON]) and a folder /// ([libDir]), setup the uri mapping. void _processSdkExt(String sdkExtJSON, Folder libDir) { var sdkExt; try { sdkExt = json.decode(sdkExtJSON); } catch (e) { return; } if ((sdkExt == null) || (sdkExt is! Map)) { return; } bool contributed = false; sdkExt.forEach((k, v) { if (_processSdkExtension(k, v, libDir)) { contributed = true; } }); if (contributed) { extensionFilePaths.add(libDir.getChild(SDK_EXT_NAME).path); } } /// Install the mapping from [name] to [libDir]/[file]. bool _processSdkExtension(String name, String file, Folder libDir) { if (!name.startsWith(DART_COLON_PREFIX)) { // SDK extensions must begin with 'dart:'. return false; } var key = name; var value = libDir.canonicalizePath(file); _urlMappings[key] = value; return true; } /// Read the contents of [libDir]/[SDK_EXT_NAME] as a string. /// Returns null if the file doesn't exist. String _readDotSdkExt(Folder libDir) { File file = libDir.getChild(SDK_EXT_NAME); try { return file.readAsStringSync(); } on FileSystemException { // File can't be read. return null; } } /// Resolve an import of an sdk extension. Source _resolveEntry(Uri libraryEntry, Uri importUri) { // Library entry. JavaFile javaFile = new JavaFile.fromUri(libraryEntry); return new FileBasedSource(javaFile, importUri); } /// Resolve a 'part' statement inside an sdk extension. Source _resolvePart(Uri libraryEntry, String partPath, Uri importUri) { // Library part. var directory = pathos.dirname(libraryEntry.path); var partUri = new Uri.file(pathos.join(directory, partPath)); assert(partUri.isAbsolute); JavaFile javaFile = new JavaFile.fromUri(partUri); return new FileBasedSource(javaFile, importUri); } }
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/source/custom_resolver.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 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/util/uri.dart'; class CustomUriResolver extends UriResolver { final ResourceProvider resourceProvider; final Map<String, String> _urlMappings; CustomUriResolver(this.resourceProvider, 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; } var pathContext = resourceProvider.pathContext; var path = fileUriToNormalizedPath(pathContext, fileUri); return resourceProvider.getFile(path).createSource(actualUri ?? uri); } }
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/source/package_map_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 'dart:core'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/util/asserts.dart' as asserts; import 'package:path/path.dart' as pathos; /** * A [UriResolver] implementation for the `package:` scheme that uses a map of * package names to their directories. */ class PackageMapUriResolver extends UriResolver { /** * The name of the `package` scheme. */ static const String PACKAGE_SCHEME = "package"; /** * A table mapping package names to the path of the directories containing * the package. */ final Map<String, List<Folder>> packageMap; /** * The [ResourceProvider] for this resolver. */ final ResourceProvider resourceProvider; /** * Create a new [PackageMapUriResolver]. * * [packageMap] is a table mapping package names to the paths of the * directories containing the package */ PackageMapUriResolver(this.resourceProvider, this.packageMap) { asserts.notNull(resourceProvider); asserts.notNull(packageMap); packageMap.forEach((name, folders) { if (folders.length != 1) { throw new ArgumentError( 'Exactly one folder must be specified for a package.' 'Found $name = $folders'); } }); } @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!isPackageUri(uri)) { return null; } // Prepare path. String path = uri.path; // Prepare path components. int index = path.indexOf('/'); if (index == -1 || index == 0) { return null; } // <pkgName>/<relPath> String pkgName = path.substring(0, index); String relPath = path.substring(index + 1); // If the package is known, return the corresponding file. List<Folder> packageDirs = packageMap[pkgName]; if (packageDirs != null) { Folder packageDir = packageDirs.single; File file = packageDir.getChildAssumingFile(relPath); return file.createSource(uri); } return null; } @override Uri restoreAbsolute(Source source) { String sourcePath = source.fullName; pathos.Context pathContext = resourceProvider.pathContext; for (String pkgName in packageMap.keys) { Folder pkgFolder = packageMap[pkgName][0]; String pkgFolderPath = pkgFolder.path; if (sourcePath.startsWith(pkgFolderPath + pathContext.separator)) { String relPath = sourcePath.substring(pkgFolderPath.length + 1); List<String> relPathComponents = pathContext.split(relPath); String relUriPath = pathos.posix.joinAll(relPathComponents); return Uri.parse('$PACKAGE_SCHEME:$pkgName/$relUriPath'); } } return null; } /** * Returns `true` if [uri] is a `package` URI. */ static bool isPackageUri(Uri uri) { return uri.scheme == PACKAGE_SCHEME; } }
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/source/package_map_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/file_system/file_system.dart'; /** * Data structure output by PackageMapProvider. This contains both the package * map and dependency information. */ class PackageMapInfo { /** * The package map itself. This is a map from package name to a list of * the folders containing source code for the package. * * `null` if an error occurred. */ Map<String, List<Folder>> packageMap; /** * Dependency information. This is a set of the paths which were consulted * in order to generate the package map. If any of these files is * modified, the package map will need to be regenerated. */ Set<String> dependencies; PackageMapInfo(this.packageMap, this.dependencies); } /** * A PackageMapProvider is an entity capable of determining the mapping from * package name to source directory for a given folder. */ abstract class PackageMapProvider { /** * Compute a package map for the given folder, if possible. * * If a package map can't be computed (e.g. because an error occurred), a * [PackageMapInfo] will still be returned, but its packageMap will be null. */ PackageMapInfo computePackageMap(Folder folder); }
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/workspace/bazel.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 'dart:core'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/file_system/file_system.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/summary/package_bundle_reader.dart'; import 'package:analyzer/src/util/uri.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:path/path.dart' as path; /** * Instances of the class `BazelFileUriResolver` resolve `file` URI's by first * resolving file uri's in the expected way, and then by looking in the * corresponding generated directories. */ class BazelFileUriResolver extends ResourceUriResolver { final BazelWorkspace workspace; BazelFileUriResolver(BazelWorkspace workspace) : workspace = workspace, super(workspace.provider); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!ResourceUriResolver.isFileUri(uri)) { return null; } String filePath = fileUriToNormalizedPath(provider.pathContext, uri); File file = workspace.findFile(filePath); if (file != null) { return file.createSource(actualUri ?? uri); } return null; } } /** * The [UriResolver] that can resolve `package` URIs in [BazelWorkspace]. */ class BazelPackageUriResolver extends UriResolver { final BazelWorkspace _workspace; final path.Context _context; /** * The cache of absolute [Uri]s to [Source]s mappings. */ final Map<Uri, Source> _sourceCache = new HashMap<Uri, Source>(); BazelPackageUriResolver(BazelWorkspace workspace) : _workspace = workspace, _context = workspace.provider.pathContext; @override void clearCache() { _sourceCache.clear(); } @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { return _sourceCache.putIfAbsent(uri, () { if (uri.scheme != 'package') { return null; } String uriPath = uri.path; int slash = uriPath.indexOf('/'); // If the path either starts with a slash or has no slash, it is invalid. if (slash < 1) { return null; } String packageName = uriPath.substring(0, slash); String fileUriPart = uriPath.substring(slash + 1); String filePath = fileUriPart.replaceAll('/', _context.separator); if (!packageName.contains('.')) { String fullFilePath = _context.join(_workspace.root, 'third_party', 'dart', packageName, 'lib', filePath); File file = _workspace.findFile(fullFilePath); return file?.createSource(uri); } else { String packagePath = packageName.replaceAll('.', _context.separator); String fullFilePath = _context.join(_workspace.root, packagePath, 'lib', filePath); File file = _workspace.findFile(fullFilePath); return file?.createSource(uri); } }); } @override Uri restoreAbsolute(Source source) { String filePath = source.fullName; // Search in each root. for (String root in [ _workspace.bin, _workspace.genfiles, _workspace.readonly, _workspace.root ]) { List<String> uriParts = _restoreUriParts(root, filePath); if (uriParts != null) { return Uri.parse('package:${uriParts[0]}/${uriParts[1]}'); } } return null; } /// Restore [filePath] to its 'package:' URI parts. /// /// Returns `null` if [root] is null or if [filePath] is not within [root]. List<String> _restoreUriParts(String root, String filePath) { path.Context context = _workspace.provider.pathContext; if (root != null && context.isWithin(root, filePath)) { String relative = context.relative(filePath, from: root); List<String> components = context.split(relative); if (components.length > 4 && components[0] == 'third_party' && components[1] == 'dart' && components[3] == 'lib') { String packageName = components[2]; String pathInLib = components.skip(4).join('/'); return [packageName, pathInLib]; } else { for (int i = 2; i < components.length - 1; i++) { String component = components[i]; if (component == 'lib') { String packageName = components.getRange(0, i).join('.'); String pathInLib = components.skip(i + 1).join('/'); return [packageName, pathInLib]; } } } } return null; } } /** * Information about a Bazel workspace. */ class BazelWorkspace extends Workspace { static const String _WORKSPACE = 'WORKSPACE'; static const String _READONLY = 'READONLY'; /** * The name of the file that identifies a set of Bazel Targets. * * For Dart package purposes, a BUILD file identifies a package. */ static const String _buildFileName = 'BUILD'; /** * Default prefix for "-genfiles" and "-bin" that will be assumed if no build * output symlinks are found. */ static const defaultSymlinkPrefix = 'bazel'; final ResourceProvider provider; /** * The absolute workspace root path. * * It contains the `WORKSPACE` file or its parent contains the `READONLY` * folder. */ final String root; /** * The absolute path to the optional read only workspace root, in the * `READONLY` folder if a git-based workspace, or `null`. */ final String readonly; /** * The absolute path to the `bazel-bin` folder. */ final String bin; /** * The absolute path to the `bazel-genfiles` folder. */ final String genfiles; BazelWorkspace._( this.provider, this.root, this.readonly, this.bin, this.genfiles); @override Map<String, List<Folder>> get packageMap => null; @override UriResolver get packageUriResolver => new BazelPackageUriResolver(this); @override SourceFactory createSourceFactory(DartSdk sdk, SummaryDataStore summaryData) { List<UriResolver> resolvers = <UriResolver>[]; if (sdk != null) { resolvers.add(new DartUriResolver(sdk)); } resolvers.add(packageUriResolver); resolvers.add(new BazelFileUriResolver(this)); if (summaryData != null) { resolvers.add(InSummaryUriResolver(provider, summaryData)); } return new SourceFactory(resolvers, null, provider); } /** * Return the file with the given [absolutePath], looking first into * directories for generated files: `bazel-bin` and `bazel-genfiles`, and * then into the workspace root. The file in the workspace root is returned * even if it does not exist. Return `null` if the given [absolutePath] is * not in the workspace [root]. */ File findFile(String absolutePath) { path.Context context = provider.pathContext; try { String relative = context.relative(absolutePath, from: root); if (relative == '.') { return null; } // genfiles if (genfiles != null) { File file = provider.getFile(context.join(genfiles, relative)); if (file.exists) { return file; } } // bin if (bin != null) { File file = provider.getFile(context.join(bin, relative)); if (file.exists) { return file; } } // Writable File writableFile = provider.getFile(absolutePath); if (writableFile.exists) { return writableFile; } // READONLY if (readonly != null) { File file = provider.getFile(context.join(readonly, relative)); if (file.exists) { return file; } } // Not generated, return the default one. return writableFile; } catch (_) { return null; } } @override WorkspacePackage findPackageFor(String filePath) { path.Context context = provider.pathContext; Folder folder = provider.getFolder(context.dirname(filePath)); while (true) { Folder parent = folder.parent; if (parent == null) { return null; } if (parent.path.length < root.length) { // We've walked up outside of [root], so [path] is definitely not // defined in any package in this workspace. return null; } if (folder.getChildAssumingFile(_buildFileName).exists) { // Found the BUILD file, denoting a Dart package. List<String> uriParts = (packageUriResolver as BazelPackageUriResolver) ._restoreUriParts(root, '${folder.path}/lib/__fake__.dart'); if (uriParts == null || uriParts.isEmpty) { return BazelWorkspacePackage(null, folder.path, this); } else { return BazelWorkspacePackage(uriParts[0], folder.path, this); } } // Go up a folder. folder = parent; } } /** * Find the Bazel workspace that contains the given [filePath]. * * Return `null` if a workspace marker, such as the `WORKSPACE` file, or * the sibling `READONLY` folder cannot be found. * * Return `null` if the workspace does not have `bazel-genfiles` or * `blaze-genfiles` folders, since we don't know where to search generated * files. * * Return `null` if there is a folder 'foo' with the sibling `READONLY` * folder, but there is corresponding folder 'foo' in `READONLY`, i.e. the * corresponding readonly workspace root. */ static BazelWorkspace find(ResourceProvider provider, String filePath) { Resource resource = provider.getResource(filePath); if (resource is File && resource.parent != null) { filePath = resource.parent.path; } path.Context context = provider.pathContext; Folder folder = provider.getFolder(filePath); while (true) { Folder parent = folder.parent; if (parent == null) { return null; } // Found the READONLY folder, might be a git-based workspace. Folder readonlyFolder = parent.getChildAssumingFolder(_READONLY); if (readonlyFolder.exists) { String root = folder.path; String readonlyRoot = context.join(readonlyFolder.path, folder.shortName); if (provider.getFolder(readonlyRoot).exists) { String symlinkPrefix = _findSymlinkPrefix(provider, root); if (symlinkPrefix != null) { return new BazelWorkspace._( provider, root, readonlyRoot, context.join(root, '$symlinkPrefix-bin'), context.join(root, '$symlinkPrefix-genfiles')); } } } // Found the WORKSPACE file, must be a non-git workspace. if (folder.getChildAssumingFile(_WORKSPACE).exists) { String root = folder.path; String symlinkPrefix = _findSymlinkPrefix(provider, root); if (symlinkPrefix == null) { return null; } return new BazelWorkspace._( provider, root, null, context.join(root, '$symlinkPrefix-bin'), context.join(root, '$symlinkPrefix-genfiles')); } // Go up the folder. folder = parent; } } /** * Return the symlink prefix for folders `X-bin` or `X-genfiles` by probing * the internal `blaze-genfiles` and `bazel-genfiles`. Make a default * assumption according to defaultSymlinkPrefix if neither of the folders * exists. */ static String _findSymlinkPrefix(ResourceProvider provider, String root) { path.Context context = provider.pathContext; if (provider.getFolder(context.join(root, 'blaze-genfiles')).exists) { return 'blaze'; } if (provider.getFolder(context.join(root, 'bazel-genfiles')).exists) { return 'bazel'; } // Couldn't find it. Make a default assumption. return defaultSymlinkPrefix; } } /** * Information about a package defined in a BazelWorkspace. * * Separate from [Packages] or package maps, this class is designed to simply * understand whether arbitrary file paths represent libraries declared within * a given package in a BazelWorkspace. */ class BazelWorkspacePackage extends WorkspacePackage { /// A prefix for any URI of a path in this package. final String _uriPrefix; final String root; final BazelWorkspace workspace; BazelWorkspacePackage(String packageName, this.root, this.workspace) : this._uriPrefix = 'package:$packageName/'; @override bool contains(Source source) { if (source.uri.isScheme('package')) { return source.uri.toString().startsWith(_uriPrefix); } String filePath = source.fullName; if (filePath == null) return false; if (workspace.findFile(filePath) == null) { return false; } if (!workspace.provider.pathContext.isWithin(root, filePath)) { return false; } // Just because [filePath] is within [root] does not mean it is in this // package; it could be in a "subpackage." Must go through the work of // learning exactly which package [filePath] is contained in. return workspace.findPackageFor(filePath).root == root; } }
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/workspace/workspace.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/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/summary/package_bundle_reader.dart'; /** * Abstract superclass of classes that provide information about the workspace * in which analysis is being performed. */ abstract class Workspace { /** * Return `true` if this workspace defines a single "project" and that * "project" depends upon flutter. */ bool get hasFlutterDependency => packageMap?.containsKey('flutter') ?? false; /** * Return a (possibly null) map of package sources. */ Map<String, List<Folder>> get packageMap; /** * The [UriResolver] that can resolve `package` URIs. */ UriResolver get packageUriResolver; /** * The absolute workspace root path. */ String get root; /** * Create the source factory that should be used to resolve Uris to [Source]s. * The [sdk] may be `null`. The [summaryData] can also be `null`. */ SourceFactory createSourceFactory(DartSdk sdk, SummaryDataStore summaryData); /** * Find the [WorkspacePackage] where the library at [path] is defined. * * Separate from [Packages] or [packageMap], this method is designed to find * the package, by its root, in which a library at an arbitrary path is * defined. */ WorkspacePackage findPackageFor(String path); } /** * Abstract superclass of classes that provide information about a package * defined in a Workspace. * * Separate from [Packages] or package maps, this class is designed to simply * understand whether arbitrary file paths represent libraries declared within * a given package in a Workspace. */ abstract class WorkspacePackage { String get root; Workspace get workspace; bool contains(Source source); /// Return a file path for the location of [source]. /// /// If [source]'s URI scheme is package, it's fullName might be unusable (for /// example, the case of a [InSummarySource]). In this case, use /// [workspace]'s package URI resolver to fetch the file path. String filePathFromSource(Source source) { if (source.uri.scheme == 'package') { return workspace.packageUriResolver.resolveAbsolute(source.uri)?.fullName; } else { return source.fullName; } } }
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/workspace/basic.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/src/context/builder.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/workspace/simple.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:package_config/packages.dart'; /** * Information about a default Dart workspace. * * A BasicWorkspace should only be used when no other workspace type is valid. */ class BasicWorkspace extends SimpleWorkspace { /** * The singular package in this workspace. * * Each basic workspace is itself one package. */ BasicWorkspacePackage _theOnlyPackage; BasicWorkspace._( ResourceProvider provider, String root, ContextBuilder builder) : super(provider, root, builder); @override WorkspacePackage findPackageFor(String filePath) { final Folder folder = provider.getFolder(filePath); if (provider.pathContext.isWithin(root, folder.path)) { _theOnlyPackage ??= new BasicWorkspacePackage(root, this); return _theOnlyPackage; } else { return null; } } /** * Find the basic workspace that contains the given [path]. * * As a [BasicWorkspace] is not defined by any marker files or build * artifacts, this simply creates a BasicWorkspace with [path] as the [root] * (or [path]'s parent if [path] points to a file). */ static BasicWorkspace find( ResourceProvider provider, String path, ContextBuilder builder) { Resource resource = provider.getResource(path); if (resource is File) { path = resource.parent.path; } return new BasicWorkspace._(provider, path, builder); } } /** * Information about a package defined in a [BasicWorkspace]. * * Separate from [Packages] or package maps, this class is designed to simply * understand whether arbitrary file paths represent libraries declared within * a given package in a [BasicWorkspace]. */ class BasicWorkspacePackage extends WorkspacePackage { final String root; final BasicWorkspace workspace; BasicWorkspacePackage(this.root, this.workspace); @override bool contains(Source source) { // When dealing with a BasicWorkspace, [source] will always have a valid // fullName. String filePath = source.fullName; // There is a 1-1 relationship between [BasicWorkspace]s and // [BasicWorkspacePackage]s. If a file is in a package's workspace, then it // is in the package as well. return workspace.provider.pathContext.isWithin(root, filePath); } }
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/workspace/package_build.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:collection'; import 'dart:core'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/context/builder.dart'; import 'package:analyzer/src/file_system/file_system.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/source/package_map_resolver.dart'; import 'package:analyzer/src/summary/package_bundle_reader.dart'; import 'package:analyzer/src/util/uri.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:package_config/packages.dart'; import 'package:path/path.dart' as path; import 'package:yaml/yaml.dart'; /** * Instances of the class `PackageBuildFileUriResolver` resolve `file` URI's by * first resolving file uri's in the expected way, and then by looking in the * corresponding generated directories. */ class PackageBuildFileUriResolver extends ResourceUriResolver { final PackageBuildWorkspace workspace; PackageBuildFileUriResolver(PackageBuildWorkspace workspace) : workspace = workspace, super(workspace.provider); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!ResourceUriResolver.isFileUri(uri)) { return null; } String filePath = fileUriToNormalizedPath(provider.pathContext, uri); Resource resource = provider.getResource(filePath); if (resource is! File) { return null; } File file = workspace.findFile(filePath); if (file != null) { return file.createSource(actualUri ?? uri); } return null; } } /** * The [UriResolver] that can resolve `package` URIs in [PackageBuildWorkspace]. */ class PackageBuildPackageUriResolver extends UriResolver { final PackageBuildWorkspace _workspace; final UriResolver _normalUriResolver; final path.Context _context; /** * The cache of absolute [Uri]s to [Source]s mappings. */ final Map<Uri, Source> _sourceCache = new HashMap<Uri, Source>(); PackageBuildPackageUriResolver( PackageBuildWorkspace workspace, this._normalUriResolver) : _workspace = workspace, _context = workspace.provider.pathContext; @override Source resolveAbsolute(Uri _ignore, [Uri uri]) { uri ??= _ignore; return _sourceCache.putIfAbsent(uri, () { if (uri.scheme != 'package') { return null; } Source basicResolverSource = _normalUriResolver.resolveAbsolute(uri); if (basicResolverSource != null && basicResolverSource.exists()) { return basicResolverSource; } String uriPath = uri.path; int slash = uriPath.indexOf('/'); // If the path either starts with a slash or has no slash, it is invalid. if (slash < 1) { return null; } String packageName = uriPath.substring(0, slash); String fileUriPart = uriPath.substring(slash + 1); String filePath = fileUriPart.replaceAll('/', _context.separator); File file = _workspace.builtFile( _workspace.builtPackageSourcePath(filePath), packageName); if (file != null && file.exists) { return file.createSource(uri); } return basicResolverSource; }); } @override Uri restoreAbsolute(Source source) { String filePath = source.fullName; if (_context.isWithin(_workspace.root, filePath)) { List<String> uriParts = _restoreUriParts(filePath); if (uriParts != null) { return Uri.parse('package:${uriParts[0]}/${uriParts[1]}'); } } return source.uri; } List<String> _restoreUriParts(String filePath) { String relative = _context.relative(filePath, from: _workspace.root); List<String> components = _context.split(relative); if (components.length > 4 && components[0] == 'build' && components[1] == 'generated' && components[3] == 'lib') { String packageName = components[2]; String pathInLib = components.skip(4).join('/'); return [packageName, pathInLib]; } return null; } } /** * Information about a package:build workspace. */ class PackageBuildWorkspace extends Workspace { /** * The name of the directory that identifies the root of the workspace. Note, * the presence of this file does not show package:build is used. For that, * the subdirectory [_dartToolBuildName] must exist. A `pub` subdirectory * will usually exist in non-package:build projects too. */ static const String _dartToolRootName = '.dart_tool'; /** * The name of the subdirectory in [_dartToolName] that distinguishes projects * built with package:build. */ static const String _dartToolBuildName = 'build'; /** * We use pubspec.yaml to get the package name to be consistent with how * package:build does it. */ static const String _pubspecName = 'pubspec.yaml'; /** * The resource provider used to access the file system. */ final ResourceProvider provider; /** * The absolute workspace root path (the directory containing the `.dart_tool` * directory). */ final String root; /** * The name of the package under development as defined in pubspec.yaml. This * matches the behavior of package:build. */ final String projectPackageName; final ContextBuilder _builder; /** * The map of package locations indexed by package name. * * This is a cached field. */ Map<String, List<Folder>> _packageMap; /** * The package location strategy. * * This is a cached field. */ Packages _packages; /** * The singular package in this workspace. * * Each "package:build" workspace is itself one package. */ PackageBuildWorkspacePackage _theOnlyPackage; PackageBuildWorkspace._( this.provider, this.root, this.projectPackageName, this._builder); @override Map<String, List<Folder>> get packageMap { _packageMap ??= _builder.convertPackagesToMap(packages); return _packageMap; } Packages get packages { _packages ??= _builder.createPackageMap(root); return _packages; } @override UriResolver get packageUriResolver => new PackageBuildPackageUriResolver( this, new PackageMapUriResolver(provider, packageMap)); /** * For some package file, which may or may not be a package source (it could * be in `bin/`, `web/`, etc), find where its built counterpart will exist if * its a generated source. * * To get a [builtPath] for a package source file to use in this method, * use [builtPackageSourcePath]. For `bin/`, `web/`, etc, it must be relative * to the project root. */ File builtFile(String builtPath, String packageName) { if (!packageMap.containsKey(packageName)) { return null; } path.Context context = provider.pathContext; String fullBuiltPath = context.normalize(context.join( root, _dartToolRootName, 'build', 'generated', packageName, builtPath)); return provider.getFile(fullBuiltPath); } /** * Unlike the way that sources are resolved against `.packages` (if foo points * to folder bar, then `foo:baz.dart` is found at `bar/baz.dart`), the built * sources for a package require the `lib/` prefix first. This is because * `bin/`, `web/`, and `test/` etc can all be built as well. This method * exists to give a name to that prefix processing step. */ String builtPackageSourcePath(String filePath) { path.Context context = provider.pathContext; assert(context.isRelative(filePath), 'Not a relative path: $filePath'); return context.join('lib', filePath); } @override SourceFactory createSourceFactory(DartSdk sdk, SummaryDataStore summaryData) { if (summaryData != null) { throw new UnsupportedError( 'Summary files are not supported in a package:build workspace.'); } List<UriResolver> resolvers = <UriResolver>[]; if (sdk != null) { resolvers.add(new DartUriResolver(sdk)); } resolvers.add(packageUriResolver); resolvers.add(new PackageBuildFileUriResolver(this)); return new SourceFactory(resolvers, packages, provider); } /** * Return the file with the given [filePath], looking first in the generated * directory `.dart_tool/build/generated/$projectPackageName/`, then in * source directories. * * The file in the workspace [root] is returned even if it does not exist. * Return `null` if the given [filePath] is not in the workspace root. */ File findFile(String filePath) { path.Context context = provider.pathContext; assert(context.isAbsolute(filePath), 'Not an absolute path: $filePath'); try { final String relativePath = context.relative(filePath, from: root); final File file = builtFile(relativePath, projectPackageName); if (file.exists) { return file; } return provider.getFile(filePath); } catch (_) { return null; } } @override WorkspacePackage findPackageFor(String filePath) { path.Context context = provider.pathContext; final folder = provider.getFolder(context.dirname(filePath)); if (context.isWithin(root, folder.path)) { _theOnlyPackage ??= new PackageBuildWorkspacePackage(root, this); return _theOnlyPackage; } else { return null; } } /** * Find the package:build workspace that contains the given [filePath]. * * Return `null` if the filePath is not in a package:build workspace. */ static PackageBuildWorkspace find( ResourceProvider provider, String filePath, ContextBuilder builder) { Folder folder = provider.getFolder(filePath); while (true) { Folder parent = folder.parent; if (parent == null) { return null; } final File pubspec = folder.getChildAssumingFile(_pubspecName); final Folder dartToolDir = folder.getChildAssumingFolder(_dartToolRootName); final Folder dartToolBuildDir = dartToolDir.getChildAssumingFolder(_dartToolBuildName); // Found the .dart_tool file, that's our project root. We also require a // pubspec, to know the package name that package:build will assume. if (dartToolBuildDir.exists && pubspec.exists) { try { final yaml = loadYaml(pubspec.readAsStringSync()); return new PackageBuildWorkspace._( provider, folder.path, yaml['name'], builder); } on Exception {} } // Go up the folder. folder = parent; } } } /** * Information about a package defined in a PackageBuildWorkspace. * * Separate from [Packages] or package maps, this class is designed to simply * understand whether arbitrary file paths represent libraries declared within * a given package in a PackageBuildWorkspace. */ class PackageBuildWorkspacePackage extends WorkspacePackage { final String root; final PackageBuildWorkspace workspace; PackageBuildWorkspacePackage(this.root, this.workspace); @override bool contains(Source source) { String filePath = filePathFromSource(source); if (filePath == null) return false; // There is a 1-1 relationship between PackageBuildWorkspaces and // PackageBuildWorkspacePackages. If a file is in a package's workspace, // then it is in the package as well. return workspace.provider.pathContext.isWithin(workspace.root, filePath) && workspace.findFile(filePath) != 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/workspace/pub.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/context/builder.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/workspace/simple.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:package_config/packages.dart'; /// Information about a Pub workspace. class PubWorkspace extends SimpleWorkspace { /// The name of the file that identifies the root of the workspace. static const String _pubspecName = 'pubspec.yaml'; /// The singular package in this workspace. /// /// Each Pub workspace is itself one package. PubWorkspacePackage _theOnlyPackage; PubWorkspace._(ResourceProvider provider, String root, ContextBuilder builder) : super(provider, root, builder); @override WorkspacePackage findPackageFor(String filePath) { final Folder folder = provider.getFolder(filePath); if (provider.pathContext.isWithin(root, folder.path)) { _theOnlyPackage ??= new PubWorkspacePackage(root, this); return _theOnlyPackage; } else { return null; } } /// Find the pub workspace that contains the given [path]. static PubWorkspace find( ResourceProvider provider, String filePath, ContextBuilder builder) { Resource resource = provider.getResource(filePath); if (resource is File) { filePath = resource.parent.path; } Folder folder = provider.getFolder(filePath); while (true) { Folder parent = folder.parent; if (parent == null) { return null; } if (folder.getChildAssumingFile(_pubspecName).exists) { // Found the pubspec.yaml file; this is our root. String root = folder.path; return new PubWorkspace._(provider, root, builder); } // Go up a folder. folder = parent; } } } /// Information about a package defined in a [PubWorkspace]. /// /// Separate from [Packages] or package maps, this class is designed to simply /// understand whether arbitrary file paths represent libraries declared within /// a given package in a [PubWorkspace]. class PubWorkspacePackage extends WorkspacePackage { final String root; final PubWorkspace workspace; PubWorkspacePackage(this.root, this.workspace); @override bool contains(Source source) { String filePath = filePathFromSource(source); if (filePath == null) return false; // There is a 1-1 relationship between [PubWorkspace]s and // [PubWorkspacePackage]s. If a file is in a package's workspace, then it // is in the package as well. return workspace.provider.pathContext.isWithin(root, filePath); } }
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/workspace/gn.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 'dart:collection'; import 'dart:core'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/file_system/file_system.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/source/package_map_resolver.dart'; import 'package:analyzer/src/summary/package_bundle_reader.dart'; import 'package:analyzer/src/util/uri.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:package_config/packages.dart'; import 'package:package_config/packages_file.dart'; import 'package:package_config/src/packages_impl.dart'; import 'package:path/path.dart' as path; /** * Information about a Gn workspace. */ class GnWorkspace extends Workspace { /** * The name of the directory that identifies the root of the workspace. */ static const String _jiriRootName = '.jiri_root'; /** * The name of the file that identifies a set of GN Targets. * * For Dart package purposes, a BUILD.gn file identifies a package. */ static const String _buildFileName = 'BUILD.gn'; /** * The resource provider used to access the file system. */ final ResourceProvider provider; /** * The absolute workspace root path (the directory containing the `.jiri_root` * directory). */ final String root; /** * The paths to the .packages files. */ final List<String> _packagesFilePaths; /** * The map of package locations indexed by package name. * * This is a cached field. */ Map<String, List<Folder>> _packageMap; /** * The package location strategy. * * This is a cached field. */ Packages _packages; GnWorkspace._(this.provider, this.root, this._packagesFilePaths); @override Map<String, List<Folder>> get packageMap => _packageMap ??= _convertPackagesToMap(packages); Packages get packages => _packages ??= _createPackages(); @override UriResolver get packageUriResolver => new PackageMapUriResolver(provider, packageMap); @override SourceFactory createSourceFactory(DartSdk sdk, SummaryDataStore summaryData) { if (summaryData != null) { throw new UnsupportedError( 'Summary files are not supported in a GN workspace.'); } List<UriResolver> resolvers = <UriResolver>[]; if (sdk != null) { resolvers.add(new DartUriResolver(sdk)); } resolvers.add(packageUriResolver); resolvers.add(new ResourceUriResolver(provider)); return new SourceFactory(resolvers, packages, provider); } /** * Return the file with the given [absolutePath]. * * Return `null` if the given [absolutePath] is not in the workspace [root]. */ File findFile(String absolutePath) { try { File writableFile = provider.getFile(absolutePath); if (writableFile.exists) { return writableFile; } } catch (_) {} return null; } @override WorkspacePackage findPackageFor(String path) { Folder folder = provider.getFolder(provider.pathContext.dirname(path)); while (true) { Folder parent = folder.parent; if (parent == null) { return null; } if (parent.path.length < root.length) { // We've walked up outside of [root], so [path] is definitely not // defined in any package in this workspace. return null; } if (folder.getChildAssumingFile(_buildFileName).exists) { return GnWorkspacePackage(folder.path, this); } // Go up a folder. folder = parent; } } /** * Creates an alternate representation for available packages. */ Map<String, List<Folder>> _convertPackagesToMap(Packages packages) { Map<String, List<Folder>> folderMap = new HashMap<String, List<Folder>>(); if (packages != null && packages != Packages.noPackages) { var pathContext = provider.pathContext; packages.asMap().forEach((String packageName, Uri uri) { String filePath = fileUriToNormalizedPath(pathContext, uri); folderMap[packageName] = [provider.getFolder(filePath)]; }); } return folderMap; } /** * Loads the packages from the .packages file. */ Packages _createPackages() { Map<String, Uri> map = _packagesFilePaths.map((String filePath) { File configFile = provider.getFile(filePath); List<int> bytes = configFile.readAsBytesSync(); return parse(bytes, configFile.toUri()); }).reduce((mapOne, mapTwo) { mapOne.addAll(mapTwo); return mapOne; }); _resolveSymbolicLinks(map); return new MapPackages(map); } /** * Resolve any symbolic links encoded in the path to the given [folder]. */ String _resolveSymbolicLink(Folder folder) { try { return folder.resolveSymbolicLinksSync().path; } on FileSystemException { return folder.path; } } /** * Resolve any symbolic links encoded in the URI's in the given [map] by * replacing the values in the map. */ void _resolveSymbolicLinks(Map<String, Uri> map) { path.Context pathContext = provider.pathContext; for (String packageName in map.keys) { String filePath = fileUriToNormalizedPath(pathContext, map[packageName]); Folder folder = provider.getFolder(filePath); String folderPath = _resolveSymbolicLink(folder); // Add a '.' so that the URI is suitable for resolving relative URI's // against it. String uriPath = pathContext.join(folderPath, '.'); map[packageName] = pathContext.toUri(uriPath); } } /** * Find the GN workspace that contains the given [filePath]. * * Return `null` if a workspace could not be found. For a workspace to be * found, both a `.jiri_root` file must be found, and at least one "packages" * file must be found in [filePath]'s output directory. */ static GnWorkspace find(ResourceProvider provider, String filePath) { Resource resource = provider.getResource(filePath); if (resource is File) { filePath = resource.parent.path; } Folder folder = provider.getFolder(filePath); while (true) { Folder parent = folder.parent; if (parent == null) { return null; } if (folder.getChildAssumingFolder(_jiriRootName).exists) { // Found the .jiri_root file, must be a non-git workspace. String root = folder.path; List<String> packagesFiles = _findPackagesFile(provider, root, filePath); if (packagesFiles.isEmpty) { return null; } return new GnWorkspace._(provider, root, packagesFiles); } // Go up a folder. folder = parent; } } /** * For a source at `$root/foo/bar`, the packages files are generated in * `$root/out/<debug|release>-XYZ/dartlang/gen/foo/bar`. * * Note that in some cases multiple .packages files can be found at that * location, for example if the package contains both a library and a binary * target. For a complete view of the package, all of these files need to be * taken into account. */ static List<String> _findPackagesFile( ResourceProvider provider, String root, String filePath, ) { path.Context pathContext = provider.pathContext; String sourceDirectory = pathContext.relative(filePath, from: root); Folder outDirectory = _getOutDirectory(root, provider); if (outDirectory == null) { return const <String>[]; } Folder genDir = outDirectory.getChildAssumingFolder( pathContext.join('dartlang', 'gen', sourceDirectory)); if (!genDir.exists) { return const <String>[]; } return genDir .getChildren() .where((resource) => resource is File) .map((resource) => resource as File) .where((File file) => pathContext.extension(file.path) == '.packages') .map((File file) => file.path) .toList(); } /** * Returns the output directory of the build, or `null` if it could not be * found. * * First attempts to read a config file at the root of the source tree. If * that file cannot be found, looks for standard output directory locations. */ static Folder _getOutDirectory(String root, ResourceProvider provider) { const String fuchsiaDirConfigFile = '.fx-build-dir'; path.Context pathContext = provider.pathContext; File configFile = provider.getFile(pathContext.join(root, fuchsiaDirConfigFile)); if (configFile.exists) { String buildDirPath = configFile.readAsStringSync().trim(); if (buildDirPath.isNotEmpty) { if (pathContext.isRelative(buildDirPath)) { buildDirPath = pathContext.join(root, buildDirPath); } return provider.getFolder(buildDirPath); } } Folder outDirectory = provider.getFolder(pathContext.join(root, 'out')); if (!outDirectory.exists) { return null; } return outDirectory .getChildren() .where((resource) => resource is Folder) .map((resource) => resource as Folder) .firstWhere((Folder folder) { String baseName = pathContext.basename(folder.path); // Taking a best guess to identify a build dir. This is clearly a fallback // to the config-based method. return baseName.startsWith('debug') || baseName.startsWith('release'); }, orElse: () => null); } } /** * Information about a package defined in a GnWorkspace. * * Separate from [Packages] or package maps, this class is designed to simply * understand whether arbitrary file paths represent libraries declared within * a given package in a GnWorkspace. */ class GnWorkspacePackage extends WorkspacePackage { final String root; final GnWorkspace workspace; GnWorkspacePackage(this.root, this.workspace); @override bool contains(Source source) { String filePath = filePathFromSource(source); if (filePath == null) return false; if (workspace.findFile(filePath) == null) { return false; } if (!workspace.provider.pathContext.isWithin(root, filePath)) { return false; } // Just because [filePath] is within [root] does not mean it is in this // package; it could be in a "subpackage." Must go through the work of // learning exactly which package [filePath] is contained in. return workspace.findPackageFor(filePath).root == root; } }
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/workspace/simple.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/context/builder.dart'; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/source/package_map_resolver.dart'; import 'package:analyzer/src/summary/package_bundle_reader.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:package_config/packages.dart'; /// An abstract class for simple workspaces which do not feature any build /// artifacts or generated files. /// /// The [packageMap] and [packageUrlResolver] are simple derivations from the /// [ContextBuilder] and [ResourceProvider] required for the class. abstract class SimpleWorkspace extends Workspace { /// The [ResourceProvider] by which paths are converted into [Resource]s. final ResourceProvider provider; /// The absolute workspace root path. final String root; final ContextBuilder _builder; Map<String, List<Folder>> _packageMap; Packages _packages; SimpleWorkspace(this.provider, this.root, this._builder); @override Map<String, List<Folder>> get packageMap { _packageMap ??= _builder.convertPackagesToMap(packages); return _packageMap; } Packages get packages { _packages ??= _builder.createPackageMap(root); return _packages; } @override UriResolver get packageUriResolver => new PackageMapUriResolver(provider, packageMap); @override SourceFactory createSourceFactory(DartSdk sdk, SummaryDataStore summaryData) { if (summaryData != null) { throw new UnsupportedError( 'Summary files are not supported in a Pub workspace.'); } List<UriResolver> resolvers = <UriResolver>[]; if (sdk != null) { resolvers.add(new DartUriResolver(sdk)); } resolvers.add(packageUriResolver); resolvers.add(new ResourceUriResolver(provider)); return new SourceFactory(resolvers, packages, provider); } }
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/file_system/file_system.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/src/generated/source.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/util/uri.dart'; /** * A [UriResolver] for [Resource]s. */ class ResourceUriResolver extends UriResolver { /** * The name of the `file` scheme. */ static final String FILE_SCHEME = "file"; final ResourceProvider _provider; ResourceUriResolver(this._provider); ResourceProvider get provider => _provider; @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!isFileUri(uri)) { return null; } String path = fileUriToNormalizedPath(_provider.pathContext, uri); File file = _provider.getFile(path); return file.createSource(actualUri ?? uri); } @override Uri restoreAbsolute(Source source) => _provider.pathContext.toUri(source.fullName); /** * Return `true` if the given [uri] is a `file` URI. */ static bool isFileUri(Uri uri) => uri.scheme == FILE_SCHEME; }
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/summary2/linking_bundle_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/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/member.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/reference.dart'; class LinkingBundleContext { /// The `dynamic` class is declared in `dart:core`, but is not a class. /// Also, it is static, so we cannot set `reference` for it. /// So, we have to push it in a separate way. final Reference dynamicReference; /// References used in all libraries being linked. /// Element references in nodes are indexes in this list. final List<Reference> references = [null]; /// Data about [references]. final LinkedNodeReferencesBuilder referencesBuilder = LinkedNodeReferencesBuilder( parent: [0], name: [''], ); final Map<TypeParameterElement, int> _typeParameters = Map.identity(); int _nextSyntheticTypeParameterId = 0x10000; LinkingBundleContext(this.dynamicReference); /// We need indexes for references during linking, but once we are done, /// we must clear indexes to make references ready for linking a next bundle. void clearIndexes() { for (var reference in references) { if (reference != null) { reference.index = null; } } } int idOfTypeParameter(TypeParameterElement element) { return _typeParameters[element]; } int indexOfElement(Element element) { if (element == null) return 0; if (element is MultiplyDefinedElement) return 0; assert(element is! Member); if (identical(element, DynamicElementImpl.instance)) { return indexOfReference(dynamicReference); } var reference = (element as ElementImpl).reference; return indexOfReference(reference); } int indexOfReference(Reference reference) { if (reference == null) return 0; if (reference.parent == null) return 0; if (reference.index != null) return reference.index; var parentIndex = indexOfReference(reference.parent); referencesBuilder.parent.add(parentIndex); referencesBuilder.name.add(reference.name); reference.index = references.length; references.add(reference); return reference.index; } LinkedNodeTypeBuilder writeType(DartType type) { if (type == null) return null; if (type.isBottom) { return LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.bottom, nullabilitySuffix: _nullabilitySuffix(type), ); } else if (type.isDynamic) { return LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.dynamic_, ); } else if (type is FunctionType) { return _writeFunctionType(type); } else if (type is InterfaceType) { return LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.interface, interfaceClass: indexOfElement(type.element), interfaceTypeArguments: type.typeArguments.map(writeType).toList(), nullabilitySuffix: _nullabilitySuffix(type), ); } else if (type is TypeParameterType) { TypeParameterElementImpl element = type.element; var id = _typeParameters[element]; if (id != null) { return LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.typeParameter, nullabilitySuffix: _nullabilitySuffix(type), typeParameterId: id, ); } else { var index = indexOfElement(element); return LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.typeParameter, nullabilitySuffix: _nullabilitySuffix(type), typeParameterElement: index, ); } } else if (type is VoidType) { return LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.void_, ); } else { throw UnimplementedError('(${type.runtimeType}) $type'); } } LinkedNodeFormalParameterKind _formalParameterKind(ParameterElement p) { if (p.isRequiredPositional) { return LinkedNodeFormalParameterKind.requiredPositional; } else if (p.isRequiredNamed) { return LinkedNodeFormalParameterKind.requiredNamed; } else if (p.isOptionalPositional) { return LinkedNodeFormalParameterKind.optionalPositional; } else if (p.isOptionalNamed) { return LinkedNodeFormalParameterKind.optionalNamed; } else { throw StateError('Unexpected parameter kind: $p'); } } FunctionType _toSyntheticFunctionType(FunctionType type) { var typeParameters = type.typeFormals; if (typeParameters.isEmpty) return type; var onlySyntheticTypeParameters = typeParameters.every((e) { return e is TypeParameterElementImpl && e.linkedNode == null; }); if (onlySyntheticTypeParameters) return type; var parameters = getFreshTypeParameters(typeParameters); return parameters.applyToFunctionType(type); } LinkedNodeTypeBuilder _writeFunctionType(FunctionType type) { type = _toSyntheticFunctionType(type); var typeParameterBuilders = <LinkedNodeTypeTypeParameterBuilder>[]; var typeParameters = type.typeFormals; for (var i = 0; i < typeParameters.length; ++i) { var typeParameter = typeParameters[i]; _typeParameters[typeParameter] = _nextSyntheticTypeParameterId++; typeParameterBuilders.add( LinkedNodeTypeTypeParameterBuilder(name: typeParameter.name), ); } for (var i = 0; i < typeParameters.length; ++i) { var typeParameter = typeParameters[i]; typeParameterBuilders[i].bound = writeType(typeParameter.bound); } Element typedefElement; List<DartType> typedefTypeArguments = const <DartType>[]; if (type.element is GenericTypeAliasElement) { typedefElement = type.element; typedefTypeArguments = type.typeArguments; } // TODO(scheglov) Cleanup to always use GenericTypeAliasElement. if (type.element is GenericFunctionTypeElement && type.element.enclosingElement is GenericTypeAliasElement) { typedefElement = type.element.enclosingElement; typedefTypeArguments = type.typeArguments; } var result = LinkedNodeTypeBuilder( kind: LinkedNodeTypeKind.function, functionFormalParameters: type.parameters .map((p) => LinkedNodeTypeFormalParameterBuilder( kind: _formalParameterKind(p), name: p.name, type: writeType(p.type), )) .toList(), functionReturnType: writeType(type.returnType), functionTypeParameters: typeParameterBuilders, functionTypedef: indexOfElement(typedefElement), functionTypedefTypeArguments: typedefTypeArguments.map(writeType).toList(), nullabilitySuffix: _nullabilitySuffix(type), ); for (var typeParameter in typeParameters) { _typeParameters.remove(typeParameter); --_nextSyntheticTypeParameterId; } return result; } static EntityRefNullabilitySuffix _nullabilitySuffix(DartType type) { var nullabilitySuffix = (type as TypeImpl).nullabilitySuffix; switch (nullabilitySuffix) { case NullabilitySuffix.question: return EntityRefNullabilitySuffix.question; case NullabilitySuffix.star: return EntityRefNullabilitySuffix.starOrIrrelevant; case NullabilitySuffix.none: return EntityRefNullabilitySuffix.none; default: throw StateError('$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/summary2/linked_unit_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/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/standard_ast_factory.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/source/line_info.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/testing/token_factory.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/ast_binary_reader.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/linked_bundle_context.dart'; import 'package:analyzer/src/summary2/reference.dart'; import 'package:analyzer/src/summary2/type_builder.dart'; /// The context of a unit - the context of the bundle, and the unit tokens. class LinkedUnitContext { final LinkedBundleContext bundleContext; final LinkedLibraryContext libraryContext; final int indexInLibrary; final String partUriStr; final String uriStr; final Reference reference; final bool isSynthetic; final LinkedNodeUnit data; /// Optional informative data for the unit. List<UnlinkedInformativeData> informativeData; AstBinaryReader _astReader; CompilationUnit _unit; bool _hasDirectivesRead = false; /// Mapping from identifiers to synthetic type parameters. /// /// Synthetic type parameters are added when [readType] begins reading a /// [FunctionType], and removed when reading is done. final Map<int, TypeParameterElementImpl> _typeParameters = {}; int _nextSyntheticTypeParameterId = 0x10000; LinkedUnitContext( this.bundleContext, this.libraryContext, this.indexInLibrary, this.partUriStr, this.uriStr, this.reference, this.isSynthetic, this.data, {CompilationUnit unit}) { _astReader = AstBinaryReader(this); _astReader.isLazy = unit == null; _unit = unit; _hasDirectivesRead = _unit != null; } bool get hasPartOfDirective { for (var directive in unit_withDirectives.directives) { if (directive is PartOfDirective) { return true; } } return false; } /// Return `true` if this unit is a part of a bundle that is being linked. bool get isLinking => bundleContext.isLinking; bool get isNNBD { if (data != null) return data.isNNBD; return _unit.featureSet.isEnabled(Feature.non_nullable); } TypeProvider get typeProvider => bundleContext.elementFactory.analysisContext.typeProvider; CompilationUnit get unit => _unit; CompilationUnit get unit_withDeclarations { _ensureUnitWithDeclarations(); return _unit; } CompilationUnit get unit_withDirectives { _ensureUnitWithDeclarations(); if (!_hasDirectivesRead) { var directiveDataList = data.node.compilationUnit_directives; for (var i = 0; i < directiveDataList.length; ++i) { var directiveData = directiveDataList[i]; _unit.directives[i] = _astReader.readNode(directiveData); } _hasDirectivesRead = true; } return _unit; } Comment createComment(LinkedNode data) { var informativeData = getInformativeData(data); var tokenStringList = informativeData?.documentationComment_tokens; if (tokenStringList == null || tokenStringList.isEmpty) { return null; } var tokens = tokenStringList .map((lexeme) => TokenFactory.tokenFromString(lexeme)) .toList(); return astFactory.documentationComment(tokens); } void createGenericFunctionTypeElement(int id, GenericFunctionTypeImpl node) { var containerRef = this.reference.getChild('@genericFunctionType'); var reference = containerRef.getChild('$id'); var element = GenericFunctionTypeElementImpl.forLinkedNode( this.reference.element, reference, node, ); node.declaredElement = element; } /// Return the [LibraryElement] referenced in the [node]. LibraryElement directiveLibrary(UriBasedDirective node) { var uriStr = LazyDirective.getSelectedUri(node); if (uriStr == null || uriStr.isEmpty) return null; return bundleContext.elementFactory.libraryOfUri(uriStr); } int getCodeLength(AstNode node) { if (node is ClassDeclaration) { return LazyClassDeclaration.getCodeLength(this, node); } else if (node is ClassTypeAlias) { return LazyClassTypeAlias.getCodeLength(this, node); } else if (node is CompilationUnit) { if (data != null) { return getInformativeData(data.node)?.codeLength ?? 0; } else { return node.length; } } else if (node is ConstructorDeclaration) { return LazyConstructorDeclaration.getCodeLength(this, node); } else if (node is EnumConstantDeclaration) { return LazyEnumConstantDeclaration.getCodeLength(this, node); } else if (node is EnumDeclaration) { return LazyEnumDeclaration.getCodeLength(this, node); } else if (node is ExtensionDeclaration) { return LazyExtensionDeclaration.getCodeLength(this, node); } else if (node is FormalParameter) { return LazyFormalParameter.getCodeLength(this, node); } else if (node is FunctionDeclaration) { return LazyFunctionDeclaration.getCodeLength(this, node); } else if (node is FunctionTypeAliasImpl) { return LazyFunctionTypeAlias.getCodeLength(this, node); } else if (node is GenericTypeAlias) { return LazyGenericTypeAlias.getCodeLength(this, node); } else if (node is MethodDeclaration) { return LazyMethodDeclaration.getCodeLength(this, node); } else if (node is MixinDeclaration) { return LazyMixinDeclaration.getCodeLength(this, node); } else if (node is TypeParameter) { return LazyTypeParameter.getCodeLength(this, node); } else if (node is VariableDeclaration) { return LazyVariableDeclaration.getCodeLength(this, node); } throw UnimplementedError('${node.runtimeType}'); } int getCodeOffset(AstNode node) { if (node is ClassDeclaration) { return LazyClassDeclaration.getCodeOffset(this, node); } else if (node is ClassTypeAlias) { return LazyClassTypeAlias.getCodeOffset(this, node); } else if (node is CompilationUnit) { return 0; } else if (node is ConstructorDeclaration) { return LazyConstructorDeclaration.getCodeOffset(this, node); } else if (node is EnumConstantDeclaration) { return LazyEnumConstantDeclaration.getCodeOffset(this, node); } else if (node is EnumDeclaration) { return LazyEnumDeclaration.getCodeOffset(this, node); } else if (node is ExtensionDeclaration) { return LazyExtensionDeclaration.getCodeOffset(this, node); } else if (node is FormalParameter) { return LazyFormalParameter.getCodeOffset(this, node); } else if (node is FunctionDeclaration) { return LazyFunctionDeclaration.getCodeOffset(this, node); } else if (node is FunctionTypeAliasImpl) { return LazyFunctionTypeAlias.getCodeOffset(this, node); } else if (node is GenericTypeAlias) { return LazyGenericTypeAlias.getCodeOffset(this, node); } else if (node is MethodDeclaration) { return LazyMethodDeclaration.getCodeOffset(this, node); } else if (node is MixinDeclaration) { return LazyMixinDeclaration.getCodeOffset(this, node); } else if (node is TypeParameter) { return LazyTypeParameter.getCodeOffset(this, node); } else if (node is VariableDeclaration) { return LazyVariableDeclaration.getCodeOffset(this, node); } throw UnimplementedError('${node.runtimeType}'); } int getCombinatorEnd(ShowCombinator node) { return LazyCombinator.getEnd(this, node); } List<ConstructorInitializer> getConstructorInitializers( ConstructorDeclaration node, ) { LazyConstructorDeclaration.readInitializers(_astReader, node); return node.initializers; } ConstructorName getConstructorRedirected(ConstructorDeclaration node) { LazyConstructorDeclaration.readRedirectedConstructor(_astReader, node); return node.redirectedConstructor; } Iterable<ConstructorDeclaration> getConstructors(AstNode node) sync* { if (node is ClassOrMixinDeclaration) { var members = _getClassOrExtensionOrMixinMembers(node); for (var member in members) { if (member is ConstructorDeclaration) { yield member; } } } } DartType getDefaultType(TypeParameter node) { var type = LazyTypeParameter.getDefaultType(_astReader, node); if (type is TypeBuilder) { type = (type as TypeBuilder).build(); LazyAst.setDefaultType(node, type); } return type; } String getDefaultValueCode(AstNode node) { if (node is DefaultFormalParameter) { return LazyFormalParameter.getDefaultValueCode(this, node); } return null; } String getDefaultValueCodeData(LinkedNode data) { var informativeData = getInformativeData(data); return informativeData?.defaultFormalParameter_defaultValueCode; } int getDirectiveOffset(Directive node) { return node.keyword.offset; } Comment getDocumentationComment(AstNode node) { if (node is ClassDeclaration) { LazyClassDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is ClassTypeAlias) { LazyClassTypeAlias.readDocumentationComment(this, node); return node.documentationComment; } else if (node is ConstructorDeclaration) { LazyConstructorDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is EnumConstantDeclaration) { LazyEnumConstantDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is EnumDeclaration) { LazyEnumDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is ExtensionDeclaration) { LazyExtensionDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is FunctionTypeAlias) { LazyFunctionTypeAlias.readDocumentationComment(this, node); return node.documentationComment; } else if (node is GenericTypeAlias) { LazyGenericTypeAlias.readDocumentationComment(this, node); return node.documentationComment; } else if (node is MethodDeclaration) { LazyMethodDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is MixinDeclaration) { LazyMixinDeclaration.readDocumentationComment(this, node); return node.documentationComment; } else if (node is VariableDeclaration) { var parent2 = node.parent.parent; if (parent2 is FieldDeclaration) { LazyFieldDeclaration.readDocumentationComment(this, parent2); return parent2.documentationComment; } else if (parent2 is TopLevelVariableDeclaration) { LazyTopLevelVariableDeclaration.readDocumentationComment( this, parent2, ); return parent2.documentationComment; } else { throw UnimplementedError('${parent2.runtimeType}'); } } else { throw UnimplementedError('${node.runtimeType}'); } } List<EnumConstantDeclaration> getEnumConstants(EnumDeclaration node) { LazyEnumDeclaration.readConstants(_astReader, node); return node.constants; } TypeAnnotation getExtendedType(ExtensionDeclaration node) { LazyExtensionDeclaration.readExtendedType(_astReader, node); return node.extendedType; } String getExtensionRefName(ExtensionDeclaration node) { return LazyExtensionDeclaration.get(node).refName; } String getFieldFormalParameterName(AstNode node) { if (node is DefaultFormalParameter) { return getFieldFormalParameterName(node.parameter); } else if (node is FieldFormalParameter) { return node.identifier.name; } else { throw StateError('${node.runtimeType}'); } } Iterable<VariableDeclaration> getFields(CompilationUnitMember node) sync* { var members = _getClassOrExtensionOrMixinMembers(node); for (var member in members) { if (member is FieldDeclaration) { for (var field in member.fields.variables) { yield field; } } } } List<FormalParameter> getFormalParameters(AstNode node) { if (node is ConstructorDeclaration) { LazyConstructorDeclaration.readFormalParameters(_astReader, node); return node.parameters.parameters; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readFunctionExpression(_astReader, node); return getFormalParameters(node.functionExpression); } else if (node is FunctionExpression) { LazyFunctionExpression.readFormalParameters(_astReader, node); return node.parameters?.parameters; } else if (node is FormalParameter) { if (node is DefaultFormalParameter) { return getFormalParameters(node.parameter); } else if (node is FieldFormalParameter) { LazyFormalParameter.readFormalParameters(_astReader, node); return node.parameters?.parameters; } else if (node is FunctionTypedFormalParameter) { LazyFormalParameter.readFormalParameters(_astReader, node); return node.parameters.parameters; } else { return null; } } else if (node is FunctionTypeAlias) { LazyFunctionTypeAlias.readFormalParameters(_astReader, node); return node.parameters.parameters; } else if (node is GenericFunctionType) { return node.parameters.parameters; } else if (node is MethodDeclaration) { LazyMethodDeclaration.readFormalParameters(_astReader, node); return node.parameters?.parameters; } else { throw UnimplementedError('${node.runtimeType}'); } } Reference getGenericFunctionTypeReference(GenericFunctionType node) { var containerRef = reference.getChild('@genericFunctionType'); var id = LazyAst.getGenericFunctionTypeId(node); return containerRef.getChild('$id'); } GenericFunctionType getGeneticTypeAliasFunction(GenericTypeAlias node) { LazyGenericTypeAlias.readFunctionType(_astReader, node); return node.functionType; } bool getHasTypedefSelfReference(AstNode node) { if (node is FunctionTypeAlias) { return LazyFunctionTypeAlias.getHasSelfReference(node); } else if (node is GenericTypeAlias) { return LazyGenericTypeAlias.getHasSelfReference(node); } return false; } ImplementsClause getImplementsClause(AstNode node) { if (node is ClassDeclaration) { LazyClassDeclaration.readImplementsClause(_astReader, node); return node.implementsClause; } else if (node is ClassTypeAlias) { LazyClassTypeAlias.readImplementsClause(_astReader, node); return node.implementsClause; } else if (node is MixinDeclaration) { LazyMixinDeclaration.readImplementsClause(_astReader, node); return node.implementsClause; } else { throw UnimplementedError('${node.runtimeType}'); } } UnlinkedInformativeData getInformativeData(LinkedNode data) { if (informativeData == null) return null; var id = data.informativeId; if (id == 0) return null; return informativeData[id - 1]; } bool getInheritsCovariant(AstNode node) { if (node is DefaultFormalParameter) { return getInheritsCovariant(node.parameter); } else if (node is FormalParameter) { return LazyAst.getInheritsCovariant(node); } else if (node is VariableDeclaration) { return LazyAst.getInheritsCovariant(node); } else { throw StateError('${node.runtimeType}'); } } Comment getLibraryDocumentationComment(CompilationUnit unit) { for (var directive in unit.directives) { if (directive is LibraryDirective) { return directive.documentationComment; } } return null; } List<Annotation> getLibraryMetadata(CompilationUnit unit) { for (var directive in unit.directives) { if (directive is LibraryDirective) { return getMetadata(directive); } } return const <Annotation>[]; } List<Annotation> getMetadata(AstNode node) { if (node is ClassDeclaration) { LazyClassDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is ClassTypeAlias) { LazyClassTypeAlias.readMetadata(_astReader, node); return node.metadata; } else if (node is CompilationUnit) { assert(node == _unit); if (indexInLibrary != 0) { return _getPartDirectiveAnnotation(); } else { return const <Annotation>[]; } } else if (node is ConstructorDeclaration) { LazyConstructorDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is DefaultFormalParameter) { return getMetadata(node.parameter); } else if (node is Directive) { LazyDirective.readMetadata(_astReader, node); return node.metadata; } else if (node is EnumConstantDeclaration) { LazyEnumConstantDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is EnumDeclaration) { LazyEnumDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is ExtensionDeclaration) { LazyExtensionDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is FormalParameter) { LazyFormalParameter.readMetadata(_astReader, node); return node.metadata; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is FunctionTypeAlias) { LazyFunctionTypeAlias.readMetadata(_astReader, node); return node.metadata; } else if (node is GenericTypeAlias) { LazyGenericTypeAlias.readMetadata(_astReader, node); return node.metadata; } else if (node is MethodDeclaration) { LazyMethodDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is MixinDeclaration) { LazyMixinDeclaration.readMetadata(_astReader, node); return node.metadata; } else if (node is TypeParameter) { LazyTypeParameter.readMetadata(_astReader, node); return node.metadata; } else if (node is VariableDeclaration) { var parent2 = node.parent.parent; if (parent2 is FieldDeclaration) { LazyFieldDeclaration.readMetadata(_astReader, parent2); return parent2.metadata; } else if (parent2 is TopLevelVariableDeclaration) { LazyTopLevelVariableDeclaration.readMetadata(_astReader, parent2); return parent2.metadata; } } return const <Annotation>[]; } Iterable<MethodDeclaration> getMethods(CompilationUnitMember node) sync* { var members = _getClassOrExtensionOrMixinMembers(node); for (var member in members) { if (member is MethodDeclaration) { yield member; } } } List<String> getMixinSuperInvokedNames(MixinDeclaration node) { return LazyMixinDeclaration.get(node).getSuperInvokedNames(); } int getNameOffset(AstNode node) { if (node is ConstructorDeclaration) { if (node.name != null) { return node.name.offset; } else { return node.returnType.offset; } } else if (node is EnumConstantDeclaration) { return node.name.offset; } else if (node is ExtensionDeclaration) { return node.name?.offset ?? -1; } else if (node is FormalParameter) { return node.identifier?.offset ?? -1; } else if (node is MethodDeclaration) { return node.name.offset; } else if (node is NamedCompilationUnitMember) { return node.name.offset; } else if (node is TypeParameter) { return node.name.offset; } else if (node is VariableDeclaration) { return node.name.offset; } throw UnimplementedError('${node.runtimeType}'); } OnClause getOnClause(MixinDeclaration node) { LazyMixinDeclaration.readOnClause(_astReader, node); return node.onClause; } /// Return the actual return type for the [node] - explicit or inferred. DartType getReturnType(AstNode node) { if (node is FunctionDeclaration) { return LazyFunctionDeclaration.getReturnType(_astReader, node); } else if (node is FunctionTypeAlias) { return LazyFunctionTypeAlias.getReturnType(_astReader, node); } else if (node is GenericFunctionType) { return node.returnType?.type ?? DynamicTypeImpl.instance; } else if (node is MethodDeclaration) { return LazyMethodDeclaration.getReturnType(_astReader, node); } else { throw UnimplementedError('${node.runtimeType}'); } } TypeAnnotation getReturnTypeNode(AstNode node) { if (node is FunctionTypeAlias) { LazyFunctionTypeAlias.readReturnTypeNode(_astReader, node); return node.returnType; } else if (node is GenericFunctionType) { return node.returnType; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readReturnTypeNode(_astReader, node); return node.returnType; } else if (node is MethodDeclaration) { LazyMethodDeclaration.readReturnTypeNode(_astReader, node); return node.returnType; } else { throw UnimplementedError('${node.runtimeType}'); } } String getSelectedUri(UriBasedDirective node) { return LazyDirective.getSelectedUri(node); } TypeName getSuperclass(AstNode node) { if (node is ClassDeclaration) { LazyClassDeclaration.readExtendsClause(_astReader, node); return node.extendsClause?.superclass; } else if (node is ClassTypeAlias) { LazyClassTypeAlias.readSuperclass(_astReader, node); return node.superclass; } else { throw StateError('${node.runtimeType}'); } } /// Return the actual type for the [node] - explicit or inferred. DartType getType(AstNode node) { if (node is DefaultFormalParameter) { return getType(node.parameter); } else if (node is FormalParameter) { return LazyFormalParameter.getType(_astReader, node); } else if (node is VariableDeclaration) { return LazyVariableDeclaration.getType(_astReader, node); } else { throw UnimplementedError('${node.runtimeType}'); } } TopLevelInferenceError getTypeInferenceError(AstNode node) { if (node is DefaultFormalParameter) { return getTypeInferenceError(node.parameter); } else if (node is SimpleFormalParameter) { return LazyFormalParameter.getTypeInferenceError(node); } else if (node is VariableDeclaration) { return LazyVariableDeclaration.getTypeInferenceError(node); } else { return null; } } TypeAnnotation getTypeParameterBound(TypeParameter node) { LazyTypeParameter.readBound(_astReader, node); return node.bound; } TypeParameterList getTypeParameters2(AstNode node) { if (node is ClassDeclaration) { return node.typeParameters; } else if (node is ClassTypeAlias) { return node.typeParameters; } else if (node is ConstructorDeclaration) { return null; } else if (node is DefaultFormalParameter) { return getTypeParameters2(node.parameter); } else if (node is ExtensionDeclaration) { return node.typeParameters; } else if (node is FieldFormalParameter) { return node.typeParameters; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readFunctionExpression(_astReader, node); return getTypeParameters2(node.functionExpression); } else if (node is FunctionExpression) { return node.typeParameters; } else if (node is FunctionTypedFormalParameter) { return node.typeParameters; } else if (node is FunctionTypeAlias) { return node.typeParameters; } else if (node is GenericFunctionType) { return node.typeParameters; } else if (node is GenericTypeAlias) { return node.typeParameters; } else if (node is MethodDeclaration) { return node.typeParameters; } else if (node is MixinDeclaration) { return node.typeParameters; } else if (node is SimpleFormalParameter) { return null; } else { throw UnimplementedError('${node.runtimeType}'); } } WithClause getWithClause(AstNode node) { if (node is ClassDeclaration) { LazyClassDeclaration.readWithClause(_astReader, node); return node.withClause; } else if (node is ClassTypeAlias) { LazyClassTypeAlias.readWithClause(_astReader, node); return node.withClause; } else { throw UnimplementedError('${node.runtimeType}'); } } bool hasDefaultValue(FormalParameter node) { if (node is DefaultFormalParameter) { return LazyFormalParameter.hasDefaultValue(node); } return false; } bool hasImplicitReturnType(AstNode node) { if (node is FunctionDeclaration) { LazyFunctionDeclaration.readReturnTypeNode(_astReader, node); return node.returnType == null; } if (node is MethodDeclaration) { LazyMethodDeclaration.readReturnTypeNode(_astReader, node); return node.returnType == null; } return false; } bool hasImplicitType(AstNode node) { if (node is DefaultFormalParameter) { return hasImplicitType(node.parameter); } else if (node is SimpleFormalParameter) { return node.type == null; } else if (node is VariableDeclaration) { VariableDeclarationList parent = node.parent; LazyVariableDeclarationList.readTypeNode(_astReader, parent); return parent.type == null; } return false; } bool hasInitializer(VariableDeclaration node) { return LazyVariableDeclaration.hasInitializer(node); } bool hasOverrideInferenceDone(AstNode node) { // Only nodes in the libraries being linked might be not inferred yet. if (_astReader.isLazy) return true; return LazyAst.hasOverrideInferenceDone(node); } bool isAbstract(AstNode node) { if (node is ClassDeclaration) { return node.abstractKeyword != null; } else if (node is ClassTypeAlias) { return node.abstractKeyword != null; } else if (node is FunctionDeclaration) { return false; } else if (node is MethodDeclaration) { return LazyMethodDeclaration.isAbstract(node); } throw UnimplementedError('${node.runtimeType}'); } bool isAsynchronous(AstNode node) { if (node is ConstructorDeclaration) { return false; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readFunctionExpression(_astReader, node); return isAsynchronous(node.functionExpression); } else if (node is FunctionExpression) { return LazyFunctionExpression.isAsynchronous(node); } else if (node is MethodDeclaration) { return LazyMethodDeclaration.isAsynchronous(node); } else { throw UnimplementedError('${node.runtimeType}'); } } bool isConst(AstNode node) { if (node is FormalParameter) { return node.isConst; } if (node is VariableDeclaration) { VariableDeclarationList parent = node.parent; return parent.isConst; } throw UnimplementedError('${node.runtimeType}'); } bool isExplicitlyCovariant(AstNode node) { if (node is DefaultFormalParameter) { return isExplicitlyCovariant(node.parameter); } else if (node is EnumConstantDeclaration) { return false; } else if (node is FormalParameter) { return node.covariantKeyword != null; } else if (node is VariableDeclaration) { var parent2 = node.parent.parent; return parent2 is FieldDeclaration && parent2.covariantKeyword != null; } else { throw StateError('${node.runtimeType}'); } } bool isExternal(AstNode node) { if (node is ConstructorDeclaration) { return node.externalKeyword != null; } else if (node is FunctionDeclaration) { return node.externalKeyword != null; } else if (node is MethodDeclaration) { return node.externalKeyword != null || node.body is NativeFunctionBody; } else { throw UnimplementedError('${node.runtimeType}'); } } bool isFinal(AstNode node) { if (node is EnumConstantDeclaration) { return false; } if (node is VariableDeclaration) { VariableDeclarationList parent = node.parent; return parent.isFinal; } throw UnimplementedError('${node.runtimeType}'); } bool isGenerator(AstNode node) { if (node is ConstructorDeclaration) { return false; } else if (node is FunctionDeclaration) { LazyFunctionDeclaration.readFunctionExpression(_astReader, node); return isGenerator(node.functionExpression); } else if (node is FunctionExpression) { return LazyFunctionExpression.isGenerator(node); } else if (node is MethodDeclaration) { return LazyMethodDeclaration.isGenerator(node); } else { throw UnimplementedError('${node.runtimeType}'); } } bool isGetter(AstNode node) { if (node is FunctionDeclaration) { return node.isGetter; } else if (node is MethodDeclaration) { return node.isGetter; } else { throw StateError('${node.runtimeType}'); } } bool isLate(AstNode node) { if (node is VariableDeclaration) { return node.isLate; } if (node is EnumConstantDeclaration) { return false; } throw UnimplementedError('${node.runtimeType}'); } bool isNative(AstNode node) { if (node is MethodDeclaration) { return node.body is NativeFunctionBody; } else { throw UnimplementedError('${node.runtimeType}'); } } bool isSetter(AstNode node) { if (node is FunctionDeclaration) { return node.isSetter; } else if (node is MethodDeclaration) { return node.isSetter; } else { throw StateError('${node.runtimeType}'); } } bool isSimplyBounded(AstNode node) { return LazyAst.isSimplyBounded(node); } bool isStatic(AstNode node) { if (node is FunctionDeclaration) { return true; } else if (node is MethodDeclaration) { return node.modifierKeyword != null; } else if (node is VariableDeclaration) { var parent2 = node.parent.parent; return parent2 is FieldDeclaration && parent2.isStatic; } throw UnimplementedError('${node.runtimeType}'); } Expression readInitializer(AstNode node) { if (node is DefaultFormalParameter) { LazyFormalParameter.readDefaultValue(_astReader, node); return node.defaultValue; } else if (node is VariableDeclaration) { LazyVariableDeclaration.readInitializer(_astReader, node); return node.initializer; } else { throw StateError('${node.runtimeType}'); } } DartType readType(LinkedNodeType linkedType) { if (linkedType == null) return null; var kind = linkedType.kind; if (kind == LinkedNodeTypeKind.bottom) { var nullabilitySuffix = _nullabilitySuffix(linkedType.nullabilitySuffix); return BottomTypeImpl.instance.withNullability(nullabilitySuffix); } else if (kind == LinkedNodeTypeKind.dynamic_) { return DynamicTypeImpl.instance; } else if (kind == LinkedNodeTypeKind.function) { var typeParameterDataList = linkedType.functionTypeParameters; var typeParametersLength = typeParameterDataList.length; var typeParameters = List<TypeParameterElement>(typeParametersLength); for (var i = 0; i < typeParametersLength; ++i) { var typeParameterData = typeParameterDataList[i]; var element = TypeParameterElementImpl(typeParameterData.name, -1); typeParameters[i] = element; _typeParameters[_nextSyntheticTypeParameterId++] = element; } // Type parameters might use each other in bounds, including forward // references. So, we read bounds after reading all type parameters. for (var i = 0; i < typeParametersLength; ++i) { var typeParameterData = typeParameterDataList[i]; TypeParameterElementImpl element = typeParameters[i]; element.bound = readType(typeParameterData.bound); } var returnType = readType(linkedType.functionReturnType); var formalParameters = linkedType.functionFormalParameters.map((p) { var type = readType(p.type); var kind = _formalParameterKind(p.kind); return ParameterElementImpl.synthetic(p.name, type, kind); }).toList(); for (var i = 0; i < typeParametersLength; ++i) { _typeParameters.remove(--_nextSyntheticTypeParameterId); } var nullabilitySuffix = _nullabilitySuffix(linkedType.nullabilitySuffix); GenericTypeAliasElement typedefElement; List<DartType> typedefTypeArguments = const <DartType>[]; if (linkedType.functionTypedef != 0) { typedefElement = bundleContext.elementOfIndex(linkedType.functionTypedef); typedefTypeArguments = linkedType.functionTypedefTypeArguments.map(readType).toList(); } return FunctionTypeImpl.synthetic( returnType, typeParameters, formalParameters, element: typedefElement, typeArguments: typedefTypeArguments) .withNullability(nullabilitySuffix); } else if (kind == LinkedNodeTypeKind.interface) { var element = bundleContext.elementOfIndex(linkedType.interfaceClass); var nullabilitySuffix = _nullabilitySuffix(linkedType.nullabilitySuffix); return InterfaceTypeImpl.explicit( element, linkedType.interfaceTypeArguments.map(readType).toList(), nullabilitySuffix: nullabilitySuffix, ); } else if (kind == LinkedNodeTypeKind.typeParameter) { TypeParameterElement element; var id = linkedType.typeParameterId; if (id != 0) { element = _typeParameters[id]; assert(element != null); } else { var index = linkedType.typeParameterElement; element = bundleContext.elementOfIndex(index); } var nullabilitySuffix = _nullabilitySuffix(linkedType.nullabilitySuffix); return TypeParameterTypeImpl(element).withNullability(nullabilitySuffix); } else if (kind == LinkedNodeTypeKind.void_) { return VoidTypeImpl.instance; } else { throw UnimplementedError('$kind'); } } void setInheritsCovariant(AstNode node, bool value) { if (node is DefaultFormalParameter) { setInheritsCovariant(node.parameter, value); } else if (node is FormalParameter) { LazyAst.setInheritsCovariant(node, value); } else if (node is VariableDeclaration) { LazyAst.setInheritsCovariant(node, value); } else { throw StateError('${node.runtimeType}'); } } void setOverrideInferenceDone(AstNode node) { // TODO(scheglov) This assert fails, check how to avoid this. // assert(!_astReader.isLazy); LazyAst.setOverrideInferenceDone(node); } void setReturnType(AstNode node, DartType type) { LazyAst.setReturnType(node, type); } void setVariableType(AstNode node, DartType type) { if (node is DefaultFormalParameter) { setVariableType(node.parameter, type); } else { LazyAst.setType(node, type); } } bool shouldBeConstFieldElement(AstNode node) { if (node is VariableDeclaration) { VariableDeclarationList variableList = node.parent; if (variableList.isConst) return true; FieldDeclaration fieldDeclaration = variableList.parent; if (fieldDeclaration.staticKeyword != null) return false; if (variableList.isFinal) { var class_ = fieldDeclaration.parent; if (class_ is ClassOrMixinDeclaration) { for (var member in class_.members) { if (member is ConstructorDeclaration && member.constKeyword != null) { return true; } } } } } return false; } Iterable<VariableDeclaration> topLevelVariables(CompilationUnit unit) sync* { for (var declaration in unit.declarations) { if (declaration is TopLevelVariableDeclaration) { for (var variable in declaration.variables.variables) { yield variable; } } } } void _ensureUnitWithDeclarations() { if (_unit == null) { _unit = _astReader.readNode(data.node); var informativeData = getInformativeData(data.node); var lineStarts = informativeData?.compilationUnit_lineStarts ?? []; if (lineStarts.isEmpty) { lineStarts = [0]; } _unit.lineInfo = LineInfo(lineStarts); } } ParameterKind _formalParameterKind(LinkedNodeFormalParameterKind kind) { if (kind == LinkedNodeFormalParameterKind.optionalNamed) { return ParameterKind.NAMED; } else if (kind == LinkedNodeFormalParameterKind.optionalPositional) { return ParameterKind.POSITIONAL; } else if (kind == LinkedNodeFormalParameterKind.requiredNamed) { return ParameterKind.NAMED_REQUIRED; } return ParameterKind.REQUIRED; } List<ClassMember> _getClassOrExtensionOrMixinMembers( CompilationUnitMember node, ) { if (node is ClassDeclaration) { LazyClassDeclaration.readMembers(_astReader, node); return node.members; } else if (node is ClassTypeAlias) { return <ClassMember>[]; } else if (node is ExtensionDeclaration) { LazyExtensionDeclaration.readMembers(_astReader, node); return node.members; } else if (node is MixinDeclaration) { LazyMixinDeclaration.readMembers(_astReader, node); return node.members; } else { throw StateError('${node.runtimeType}'); } } NodeList<Annotation> _getPartDirectiveAnnotation() { var definingContext = libraryContext.definingUnit; var unit = definingContext.unit; var partDirectiveIndex = 0; for (var directive in unit.directives) { if (directive is PartDirective) { partDirectiveIndex++; if (partDirectiveIndex == indexInLibrary) { LazyDirective.readMetadata(definingContext._astReader, directive); return directive.metadata; } } } throw StateError('Expected to find $indexInLibrary part directive.'); } static NullabilitySuffix _nullabilitySuffix(EntityRefNullabilitySuffix data) { switch (data) { case EntityRefNullabilitySuffix.starOrIrrelevant: return NullabilitySuffix.star; case EntityRefNullabilitySuffix.question: return NullabilitySuffix.question; case EntityRefNullabilitySuffix.none: return NullabilitySuffix.none; default: throw StateError('$data'); } } }
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/summary2/ast_binary_flags.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'; class AstBinaryFlags { static final Map<Type, int> _typeBits = {}; static final _hasAwait = _checkBit( 0, ForElement, ForStatement, ); static final _hasEqual = _checkBit( 0, Configuration, ); static final _hasInitializer = _checkBit( 0, DefaultFormalParameter, VariableDeclaration, ); static final _hasName = _checkBit( 5, ConstructorDeclaration, ); static final _hasNot = _checkBit( 0, IsExpression, ); static final _hasPeriod = _checkBit( 0, IndexExpression, MethodInvocation, ); static final _hasPeriod2 = _checkBit( 1, MethodInvocation, ); static final _hasQuestion = _checkBit( 1, GenericFunctionType, TypeName, ); static final _hasSeparatorColon = _checkBit( 0, ConstructorDeclaration, ); static final _hasSeparatorEquals = _checkBit( 2, ConstructorDeclaration, ); static final _hasThis = _checkBit( 0, ConstructorFieldInitializer, RedirectingConstructorInvocation, ); static final _hasTypeArguments = _checkBit( 0, TypedLiteral, TypeName, ); static final _isAbstract = _checkBit( 1, ClassDeclaration, ClassTypeAlias, ConstructorDeclaration, MethodDeclaration, ); static final _isAsync = _checkBit( 2, BlockFunctionBody, EmptyFunctionBody, FunctionExpression, MethodDeclaration, ); static final _isConst = _checkBit( 3, ConstructorDeclaration, DeclaredIdentifier, InstanceCreationExpression, NormalFormalParameter, TypedLiteral, VariableDeclarationList, ); static final _isCovariant = _checkBit( 2, FieldDeclaration, NormalFormalParameter, ); static final _isDeclaration = _checkBit( 0, SimpleIdentifier, ); static final _isDeferred = _checkBit( 0, ImportDirective, ); static final _isDelimiterCurly = _checkBit( 0, FormalParameterList, ); static final _isDelimiterSquare = _checkBit( 1, FormalParameterList, ); static final _isExternal = _checkBit( 7, ConstructorDeclaration, FunctionDeclaration, MethodDeclaration, ); static final _isFactory = _checkBit( 4, ConstructorDeclaration, ); static final _isFinal = _checkBit( 4, DeclaredIdentifier, NormalFormalParameter, VariableDeclarationList, ); static final _isGenerator = _checkBit( 3, FunctionExpression, MethodDeclaration, ); static final _isGet = _checkBit( 4, FunctionDeclaration, MethodDeclaration, ); static final _isLate = _checkBit( 0, VariableDeclarationList, ); static final _isMap = _checkBit( 1, TypedLiteral, ); static final _isNative = _checkBit( 8, MethodDeclaration, ); static final _isNew = _checkBit( 0, InstanceCreationExpression, ); static final _isOperator = _checkBit( 0, MethodDeclaration, ); static final _isRequired = _checkBit( 0, NormalFormalParameter, ); static final _isSet = _checkBit( 5, FunctionDeclaration, MethodDeclaration, TypedLiteral, ); static final _isStar = _checkBit( 0, BlockFunctionBody, YieldStatement, ); static final _isStatic = _checkBit( 6, FieldDeclaration, MethodDeclaration, ); static final _isStringInterpolationIdentifier = _checkBit( 0, InterpolationExpression, ); static final _isSync = _checkBit( 3, BlockFunctionBody, ExpressionFunctionBody, ); static final _isVar = _checkBit( 1, DeclaredIdentifier, NormalFormalParameter, VariableDeclarationList, ); static int encode({ bool hasAwait: false, bool hasEqual: false, bool hasInitializer: false, bool hasName: false, bool hasNot: false, bool hasPeriod: false, bool hasPeriod2: false, bool hasQuestion: false, bool hasSeparatorColon: false, bool hasSeparatorEquals: false, bool hasThis: false, bool hasTypeArguments: false, bool isAbstract: false, bool isAsync: false, bool isConst: false, bool isCovariant: false, bool isDeclaration: false, bool isDeferred: false, bool isDelimiterCurly: false, bool isDelimiterSquare: false, bool isExternal: false, bool isFactory: false, bool isFinal: false, bool isGenerator: false, bool isGet: false, bool isLate: false, bool isMap: false, bool isNative: false, bool isNew: false, bool isOperator: false, bool isRequired: false, bool isSet: false, bool isStar: false, bool isStatic: false, bool isStringInterpolationIdentifier: false, bool isSync: false, bool isVar: false, }) { var result = 0; if (hasAwait) { result |= _hasAwait; } if (hasEqual) { result |= _hasEqual; } if (hasInitializer) { result |= _hasInitializer; } if (hasName) { result |= _hasName; } if (hasNot) { result |= _hasNot; } if (hasPeriod) { result |= _hasPeriod; } if (hasPeriod2) { result |= _hasPeriod2; } if (hasQuestion) { result |= _hasQuestion; } if (hasSeparatorColon) { result |= _hasSeparatorColon; } if (hasSeparatorEquals) { result |= _hasSeparatorEquals; } if (hasThis) { result |= _hasThis; } if (hasTypeArguments) { result |= _hasTypeArguments; } if (isAbstract) { result |= _isAbstract; } if (isAsync) { result |= _isAsync; } if (isCovariant) { result |= _isCovariant; } if (isDeclaration) { result |= _isDeclaration; } if (isDeferred) { result |= _isDeferred; } if (isDelimiterCurly) { result |= _isDelimiterCurly; } if (isDelimiterSquare) { result |= _isDelimiterSquare; } if (isConst) { result |= _isConst; } if (isExternal) { result |= _isExternal; } if (isFactory) { result |= _isFactory; } if (isFinal) { result |= _isFinal; } if (isGenerator) { result |= _isGenerator; } if (isGet) { result |= _isGet; } if (isLate) { result |= _isLate; } if (isMap) { result |= _isMap; } if (isNative) { result |= _isNative; } if (isNew) { result |= _isNew; } if (isOperator) { result |= _isOperator; } if (isRequired) { result |= _isRequired; } if (isSet) { result |= _isSet; } if (isStar) { result |= _isStar; } if (isStatic) { result |= _isStatic; } if (isStringInterpolationIdentifier) { result |= _isStringInterpolationIdentifier; } if (isSync) { result |= _isSync; } if (isVar) { result |= _isVar; } return result; } static bool hasAwait(int flags) { return (flags & _hasAwait) != 0; } static bool hasEqual(int flags) { return (flags & _hasEqual) != 0; } static bool hasInitializer(int flags) { return (flags & _hasInitializer) != 0; } static bool hasName(int flags) { return (flags & _hasName) != 0; } static bool hasNot(int flags) { return (flags & _hasNot) != 0; } static bool hasPeriod(int flags) { return (flags & _hasPeriod) != 0; } static bool hasPeriod2(int flags) { return (flags & _hasPeriod2) != 0; } static bool hasQuestion(int flags) { return (flags & _isStringInterpolationIdentifier) != 0; } static bool hasSeparatorColon(int flags) { return (flags & _hasSeparatorColon) != 0; } static bool hasSeparatorEquals(int flags) { return (flags & _hasSeparatorEquals) != 0; } static bool hasThis(int flags) { return (flags & _hasThis) != 0; } static bool hasTypeArguments(int flags) { return (flags & _hasTypeArguments) != 0; } static bool isAbstract(int flags) { return (flags & _isAbstract) != 0; } static bool isAsync(int flags) { return (flags & _isAsync) != 0; } static bool isConst(int flags) { return (flags & _isConst) != 0; } static bool isCovariant(int flags) { return (flags & _isCovariant) != 0; } static bool isDeclaration(int flags) { return (flags & _isDeclaration) != 0; } static bool isDeferred(int flags) { return (flags & _isDeferred) != 0; } static bool isDelimiterCurly(int flags) { return (flags & _isDelimiterCurly) != 0; } static bool isDelimiterSquare(int flags) { return (flags & _isDelimiterSquare) != 0; } static bool isExternal(int flags) { return (flags & _isExternal) != 0; } static bool isFactory(int flags) { return (flags & _isFactory) != 0; } static bool isFinal(int flags) { return (flags & _isFinal) != 0; } static bool isGenerator(int flags) { return (flags & _isGenerator) != 0; } static bool isGet(int flags) { return (flags & _isGet) != 0; } static bool isLate(int flags) { return (flags & _isLate) != 0; } static bool isMap(int flags) { return (flags & _isMap) != 0; } static bool isNative(int flags) { return (flags & _isNative) != 0; } static bool isNew(int flags) { return (flags & _isNew) != 0; } static bool isOperator(int flags) { return (flags & _isOperator) != 0; } static bool isRequired(int flags) { return (flags & _isRequired) != 0; } static bool isSet(int flags) { return (flags & _isSet) != 0; } static bool isStar(int flags) { return (flags & _isStar) != 0; } static bool isStatic(int flags) { return (flags & _isStatic) != 0; } static bool isStringInterpolationIdentifier(int flags) { return (flags & _isStringInterpolationIdentifier) != 0; } static bool isSync(int flags) { return (flags & _isSync) != 0; } static bool isVar(int flags) { return (flags & _isVar) != 0; } /// Check the bit for its uniqueness for the given types. static int _checkBit(int shift, Type type1, [Type type2, Type type3, Type type4, Type type5, Type type6]) { _checkBit0(shift, type1); _checkBit0(shift, type2); _checkBit0(shift, type3); _checkBit0(shift, type4); _checkBit0(shift, type5); _checkBit0(shift, type6); return 1 << shift; } /// Check the bit for its uniqueness for the [type]. static void _checkBit0(int shift, Type type) { if (type != null) { var currentBits = _typeBits[type] ?? 0; var bit = 1 << shift; if ((currentBits & bit) != 0) { throw StateError('1 << $shift is already used for $type'); } _typeBits[type] = currentBits | bit; } } }
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/summary2/ast_binary_reader.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/standard_ast_factory.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/generated/testing/ast_test_factory.dart'; import 'package:analyzer/src/generated/testing/token_factory.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/ast_binary_flags.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/linked_unit_context.dart'; import 'package:analyzer/src/summary2/tokens_context.dart'; var timerAstBinaryReader = Stopwatch(); var timerAstBinaryReaderClass = Stopwatch(); var timerAstBinaryReaderDirective = Stopwatch(); var timerAstBinaryReaderFunctionBody = Stopwatch(); var timerAstBinaryReaderFunctionDeclaration = Stopwatch(); var timerAstBinaryReaderMixin = Stopwatch(); var timerAstBinaryReaderTopLevelVar = Stopwatch(); /// Deserializer of fully resolved ASTs from flat buffers. class AstBinaryReader { final LinkedUnitContext _unitContext; /// Set to `true` when this reader is used to lazily read its unit. bool isLazy = false; /// Whether we are reading a directive. /// /// [StringLiteral]s in directives are not actual expressions, and don't need /// a type. Moreover, when we are reading `dart:core` imports, the type /// provider is not ready yet, so we cannot access type `String`. bool _isReadingDirective = false; AstBinaryReader(this._unitContext); InterfaceType get _boolType => _unitContext.typeProvider.boolType; InterfaceType get _doubleType => _unitContext.typeProvider.doubleType; InterfaceType get _intType => _unitContext.typeProvider.intType; DartType get _nullType => _unitContext.typeProvider.nullType; InterfaceType get _stringType => _unitContext.typeProvider.stringType; AstNode readNode(LinkedNode data) { timerAstBinaryReader.start(); try { return _readNode(data); } finally { timerAstBinaryReader.stop(); } } DartType readType(LinkedNodeType data) { return _readType(data); } Token _combinatorKeyword(LinkedNode data, Keyword keyword, Token def) { var informativeData = _unitContext.getInformativeData(data); if (informativeData != null) { return TokenFactory.tokenFromKeyword(keyword) ..offset = informativeData.combinatorKeywordOffset; } return def; } SimpleIdentifier _declaredIdentifier(LinkedNode data) { var informativeData = _unitContext.getInformativeData(data); var offset = informativeData?.nameOffset ?? 0; return astFactory.simpleIdentifier( TokenFactory.tokenFromString(data.name)..offset = offset, isDeclaration: true, ); } Token _directiveKeyword(LinkedNode data, Keyword keyword, Token def) { var informativeData = _unitContext.getInformativeData(data); if (informativeData != null) { return TokenFactory.tokenFromKeyword(keyword) ..offset = informativeData.directiveKeywordOffset; } return def; } Element _elementOfComponents( int rawElementIndex, LinkedNodeTypeSubstitution substitutionNode, ) { var element = _getElement(rawElementIndex); if (substitutionNode == null) return element; var typeParameters = substitutionNode.typeParameters .map<TypeParameterElement>(_getElement) .toList(); var typeArguments = substitutionNode.typeArguments.map(_readType).toList(); var substitution = Substitution.fromPairs(typeParameters, typeArguments); return ExecutableMember.from2(element, substitution); } T _getElement<T extends Element>(int index) { var bundleContext = _unitContext.bundleContext; return bundleContext.elementOfIndex(index); } AdjacentStrings _read_adjacentStrings(LinkedNode data) { var node = astFactory.adjacentStrings( _readNodeList(data.adjacentStrings_strings), ); if (!_isReadingDirective) { node.staticType = _stringType; } return node; } Annotation _read_annotation(LinkedNode data) { return astFactory.annotation( _Tokens.AT, _readNode(data.annotation_name), _Tokens.PERIOD, _readNode(data.annotation_constructorName), _readNode(data.annotation_arguments), )..element = _elementOfComponents( data.annotation_element, data.annotation_substitution, ); } ArgumentList _read_argumentList(LinkedNode data) { return astFactory.argumentList( _Tokens.OPEN_PAREN, _readNodeList(data.argumentList_arguments), _Tokens.CLOSE_PAREN, ); } AsExpression _read_asExpression(LinkedNode data) { return astFactory.asExpression( _readNode(data.asExpression_expression), _Tokens.AS, _readNode(data.asExpression_type), )..staticType = _readType(data.expression_type); } AssertInitializer _read_assertInitializer(LinkedNode data) { return astFactory.assertInitializer( _Tokens.ASSERT, _Tokens.OPEN_PAREN, _readNode(data.assertInitializer_condition), _Tokens.COMMA, _readNode(data.assertInitializer_message), _Tokens.CLOSE_PAREN, ); } AssertStatement _read_assertStatement(LinkedNode data) { return astFactory.assertStatement( _Tokens.AS, _Tokens.OPEN_PAREN, _readNode(data.assertStatement_condition), _Tokens.COMMA, _readNode(data.assertStatement_message), _Tokens.CLOSE_PAREN, _Tokens.SEMICOLON, ); } AssignmentExpression _read_assignmentExpression(LinkedNode data) { return astFactory.assignmentExpression( _readNode(data.assignmentExpression_leftHandSide), _Tokens.fromType(data.assignmentExpression_operator), _readNode(data.assignmentExpression_rightHandSide), ) ..staticElement = _elementOfComponents( data.assignmentExpression_element, data.assignmentExpression_substitution, ) ..staticType = _readType(data.expression_type); } AwaitExpression _read_awaitExpression(LinkedNode data) { return astFactory.awaitExpression( _Tokens.AWAIT, _readNode(data.awaitExpression_expression), )..staticType = _readType(data.expression_type); } BinaryExpression _read_binaryExpression(LinkedNode data) { return astFactory.binaryExpression( _readNode(data.binaryExpression_leftOperand), _Tokens.fromType(data.binaryExpression_operator), _readNode(data.binaryExpression_rightOperand), ) ..staticElement = _elementOfComponents( data.binaryExpression_element, data.binaryExpression_substitution, ) ..staticType = _readType(data.expression_type); } Block _read_block(LinkedNode data) { return astFactory.block( _Tokens.OPEN_CURLY_BRACKET, _readNodeList(data.block_statements), _Tokens.CLOSE_CURLY_BRACKET, ); } BlockFunctionBody _read_blockFunctionBody(LinkedNode data) { timerAstBinaryReaderFunctionBody.start(); try { return astFactory.blockFunctionBody( _Tokens.choose( AstBinaryFlags.isAsync(data.flags), _Tokens.ASYNC, AstBinaryFlags.isSync(data.flags), _Tokens.SYNC, ), AstBinaryFlags.isStar(data.flags) ? _Tokens.STAR : null, _readNode(data.blockFunctionBody_block), ); } finally { timerAstBinaryReaderFunctionBody.stop(); } } BooleanLiteral _read_booleanLiteral(LinkedNode data) { return AstTestFactory.booleanLiteral(data.booleanLiteral_value) ..staticType = _boolType; } BreakStatement _read_breakStatement(LinkedNode data) { return astFactory.breakStatement( _Tokens.BREAK, _readNode(data.breakStatement_label), _Tokens.SEMICOLON, ); } CascadeExpression _read_cascadeExpression(LinkedNode data) { return astFactory.cascadeExpression( _readNode(data.cascadeExpression_target), _readNodeList(data.cascadeExpression_sections), )..staticType = _readType(data.expression_type); } CatchClause _read_catchClause(LinkedNode data) { var exceptionType = _readNode(data.catchClause_exceptionType); var exceptionParameter = _readNode(data.catchClause_exceptionParameter); var stackTraceParameter = _readNode(data.catchClause_stackTraceParameter); return astFactory.catchClause( exceptionType != null ? _Tokens.ON : null, exceptionType, exceptionParameter != null ? _Tokens.CATCH : null, exceptionParameter != null ? _Tokens.OPEN_PAREN : null, exceptionParameter, stackTraceParameter != null ? _Tokens.COMMA : null, stackTraceParameter, exceptionParameter != null ? _Tokens.CLOSE_PAREN : null, _readNode(data.catchClause_body), ); } ClassDeclaration _read_classDeclaration(LinkedNode data) { timerAstBinaryReaderClass.start(); try { var node = astFactory.classDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), AstBinaryFlags.isAbstract(data.flags) ? _Tokens.ABSTRACT : null, _Tokens.CLASS, _declaredIdentifier(data), _readNode(data.classOrMixinDeclaration_typeParameters), _readNodeLazy(data.classDeclaration_extendsClause), _readNodeLazy(data.classDeclaration_withClause), _readNodeLazy(data.classOrMixinDeclaration_implementsClause), _Tokens.OPEN_CURLY_BRACKET, _readNodeListLazy(data.classOrMixinDeclaration_members), _Tokens.CLOSE_CURLY_BRACKET, ); node.nativeClause = _readNodeLazy(data.classDeclaration_nativeClause); LazyClassDeclaration.setData(node, data); return node; } finally { timerAstBinaryReaderClass.stop(); } } ClassTypeAlias _read_classTypeAlias(LinkedNode data) { timerAstBinaryReaderClass.start(); try { var node = astFactory.classTypeAlias( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.CLASS, _declaredIdentifier(data), _readNode(data.classTypeAlias_typeParameters), _Tokens.EQ, AstBinaryFlags.isAbstract(data.flags) ? _Tokens.ABSTRACT : null, _readNodeLazy(data.classTypeAlias_superclass), _readNodeLazy(data.classTypeAlias_withClause), _readNodeLazy(data.classTypeAlias_implementsClause), _Tokens.SEMICOLON, ); LazyClassTypeAlias.setData(node, data); return node; } finally { timerAstBinaryReaderClass.stop(); } } Comment _read_comment(LinkedNode data) { var tokens = data.comment_tokens .map((lexeme) => TokenFactory.tokenFromString(lexeme)) .toList(); switch (data.comment_type) { case LinkedNodeCommentType.block: return astFactory.endOfLineComment( tokens, ); case LinkedNodeCommentType.documentation: return astFactory.documentationComment( tokens, _readNodeList(data.comment_references), ); case LinkedNodeCommentType.endOfLine: return astFactory.endOfLineComment( tokens, ); default: throw StateError('${data.comment_type}'); } } CommentReference _read_commentReference(LinkedNode data) { return astFactory.commentReference( AstBinaryFlags.isNew(data.flags) ? _Tokens.NEW : null, _readNode(data.commentReference_identifier), ); } CompilationUnit _read_compilationUnit(LinkedNode data) { return astFactory.compilationUnit( beginToken: null, scriptTag: _readNode(data.compilationUnit_scriptTag), directives: _readNodeList(data.compilationUnit_directives), declarations: _readNodeList(data.compilationUnit_declarations), endToken: null, featureSet: null); } ConditionalExpression _read_conditionalExpression(LinkedNode data) { return astFactory.conditionalExpression( _readNode(data.conditionalExpression_condition), _Tokens.QUESTION, _readNode(data.conditionalExpression_thenExpression), _Tokens.COLON, _readNode(data.conditionalExpression_elseExpression), )..staticType = _readType(data.expression_type); } Configuration _read_configuration(LinkedNode data) { return astFactory.configuration( _Tokens.IF, _Tokens.OPEN_PAREN, _readNode(data.configuration_name), AstBinaryFlags.hasEqual(data.flags) ? _Tokens.EQ : null, _readNode(data.configuration_value), _Tokens.CLOSE_PAREN, _readNode(data.configuration_uri), ); } ConstructorDeclaration _read_constructorDeclaration(LinkedNode data) { SimpleIdentifier returnType = _readNode( data.constructorDeclaration_returnType, ); var informativeData = _unitContext.getInformativeData(data); returnType.token.offset = informativeData?.constructorDeclaration_returnTypeOffset ?? 0; Token periodToken; SimpleIdentifier nameIdentifier; if (AstBinaryFlags.hasName(data.flags)) { periodToken = Token( TokenType.PERIOD, informativeData?.constructorDeclaration_periodOffset ?? 0, ); nameIdentifier = _declaredIdentifier(data); } var node = astFactory.constructorDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), AstBinaryFlags.isExternal(data.flags) ? _Tokens.EXTERNAL : null, AstBinaryFlags.isConst(data.flags) ? _Tokens.CONST : null, AstBinaryFlags.isFactory(data.flags) ? _Tokens.FACTORY : null, returnType, periodToken, nameIdentifier, _readNodeLazy(data.constructorDeclaration_parameters), _Tokens.choose( AstBinaryFlags.hasSeparatorColon(data.flags), _Tokens.COLON, AstBinaryFlags.hasSeparatorEquals(data.flags), _Tokens.EQ, ), _readNodeListLazy(data.constructorDeclaration_initializers), _readNodeLazy(data.constructorDeclaration_redirectedConstructor), _readNodeLazy(data.constructorDeclaration_body), ); LazyConstructorDeclaration.setData(node, data); return node; } ConstructorFieldInitializer _read_constructorFieldInitializer( LinkedNode data) { var hasThis = AstBinaryFlags.hasThis(data.flags); return astFactory.constructorFieldInitializer( hasThis ? _Tokens.THIS : null, hasThis ? _Tokens.PERIOD : null, _readNode(data.constructorFieldInitializer_fieldName), _Tokens.EQ, _readNode(data.constructorFieldInitializer_expression), ); } ConstructorName _read_constructorName(LinkedNode data) { return astFactory.constructorName( _readNode(data.constructorName_type), data.constructorName_name != null ? _Tokens.PERIOD : null, _readNode(data.constructorName_name), )..staticElement = _elementOfComponents( data.constructorName_element, data.constructorName_substitution, ); } ContinueStatement _read_continueStatement(LinkedNode data) { return astFactory.continueStatement( _Tokens.CONTINUE, _readNode(data.continueStatement_label), _Tokens.SEMICOLON, ); } DeclaredIdentifier _read_declaredIdentifier(LinkedNode data) { return astFactory.declaredIdentifier( _readDocumentationComment(data), _readNodeList(data.annotatedNode_metadata), _Tokens.choose( AstBinaryFlags.isConst(data.flags), _Tokens.CONST, AstBinaryFlags.isFinal(data.flags), _Tokens.FINAL, AstBinaryFlags.isVar(data.flags), _Tokens.VAR, ), _readNode(data.declaredIdentifier_type), _readNode(data.declaredIdentifier_identifier), ); } DefaultFormalParameter _read_defaultFormalParameter(LinkedNode data) { var node = astFactory.defaultFormalParameter( _readNode(data.defaultFormalParameter_parameter), _toParameterKind(data.defaultFormalParameter_kind), data.defaultFormalParameter_defaultValue != null ? _Tokens.COLON : null, _readNodeLazy(data.defaultFormalParameter_defaultValue), ); LazyFormalParameter.setData(node, data); return node; } DoStatement _read_doStatement(LinkedNode data) { return astFactory.doStatement( _Tokens.DO, _readNode(data.doStatement_body), _Tokens.WHILE, _Tokens.OPEN_PAREN, _readNode(data.doStatement_condition), _Tokens.CLOSE_PAREN, _Tokens.SEMICOLON, ); } DottedName _read_dottedName(LinkedNode data) { return astFactory.dottedName( _readNodeList(data.dottedName_components), ); } DoubleLiteral _read_doubleLiteral(LinkedNode data) { return AstTestFactory.doubleLiteral(data.doubleLiteral_value) ..staticType = _doubleType; } EmptyFunctionBody _read_emptyFunctionBody(LinkedNode data) { return astFactory.emptyFunctionBody( _Tokens.SEMICOLON, ); } EmptyStatement _read_emptyStatement(LinkedNode data) { return astFactory.emptyStatement( _Tokens.SEMICOLON, ); } EnumConstantDeclaration _read_enumConstantDeclaration(LinkedNode data) { var node = astFactory.enumConstantDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _declaredIdentifier(data), ); LazyEnumConstantDeclaration.setData(node, data); return node; } EnumDeclaration _read_enumDeclaration(LinkedNode data) { var node = astFactory.enumDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.ENUM, _declaredIdentifier(data), _Tokens.OPEN_CURLY_BRACKET, _readNodeListLazy(data.enumDeclaration_constants), _Tokens.CLOSE_CURLY_BRACKET, ); LazyEnumDeclaration.setData(node, data); return node; } ExportDirective _read_exportDirective(LinkedNode data) { timerAstBinaryReaderDirective.start(); _isReadingDirective = true; try { var node = astFactory.exportDirective( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _directiveKeyword(data, Keyword.EXPORT, _Tokens.EXPORT), _readNode(data.uriBasedDirective_uri), _readNodeList(data.namespaceDirective_configurations), _readNodeList(data.namespaceDirective_combinators), _Tokens.SEMICOLON, ); LazyDirective.setData(node, data); return node; } finally { _isReadingDirective = false; timerAstBinaryReaderDirective.stop(); } } ExpressionFunctionBody _read_expressionFunctionBody(LinkedNode data) { timerAstBinaryReaderFunctionBody.start(); try { return astFactory.expressionFunctionBody( _Tokens.choose( AstBinaryFlags.isAsync(data.flags), _Tokens.ASYNC, AstBinaryFlags.isSync(data.flags), _Tokens.SYNC, ), _Tokens.ARROW, _readNode(data.expressionFunctionBody_expression), _Tokens.SEMICOLON, ); } finally { timerAstBinaryReaderFunctionBody.stop(); } } ExpressionStatement _read_expressionStatement(LinkedNode data) { return astFactory.expressionStatement( _readNode(data.expressionStatement_expression), _Tokens.SEMICOLON, ); } ExtendsClause _read_extendsClause(LinkedNode data) { return astFactory.extendsClause( _Tokens.EXTENDS, _readNode(data.extendsClause_superclass), ); } ExtensionDeclaration _read_extensionDeclaration(LinkedNode data) { timerAstBinaryReaderClass.start(); try { var node = astFactory.extensionDeclaration( comment: _readDocumentationComment(data), metadata: _readNodeListLazy(data.annotatedNode_metadata), extensionKeyword: _Tokens.EXTENSION, name: data.name.isNotEmpty ? _declaredIdentifier(data) : null, typeParameters: _readNode(data.extensionDeclaration_typeParameters), onKeyword: _Tokens.ON, extendedType: _readNodeLazy(data.extensionDeclaration_extendedType), leftBracket: _Tokens.OPEN_CURLY_BRACKET, members: _readNodeListLazy(data.extensionDeclaration_members), rightBracket: _Tokens.CLOSE_CURLY_BRACKET, ); LazyExtensionDeclaration(node, data); return node; } finally { timerAstBinaryReaderClass.stop(); } } ExtensionOverride _read_extensionOverride(LinkedNode data) { var node = astFactory.extensionOverride( extensionName: _readNode(data.extensionOverride_extensionName), argumentList: astFactory.argumentList( _Tokens.OPEN_PAREN, _readNodeList( data.extensionOverride_arguments, ), _Tokens.CLOSE_PAREN, ), typeArguments: _readNode(data.extensionOverride_typeArguments), ) as ExtensionOverrideImpl; node.extendedType = _readType(data.extensionOverride_extendedType); node.typeArgumentTypes = data.extensionOverride_typeArgumentTypes.map(_readType).toList(); return node; } FieldDeclaration _read_fieldDeclaration(LinkedNode data) { var node = astFactory.fieldDeclaration2( comment: _readDocumentationComment(data), covariantKeyword: AstBinaryFlags.isCovariant(data.flags) ? _Tokens.COVARIANT : null, fieldList: _readNode(data.fieldDeclaration_fields), metadata: _readNodeListLazy(data.annotatedNode_metadata), semicolon: _Tokens.SEMICOLON, staticKeyword: AstBinaryFlags.isStatic(data.flags) ? _Tokens.STATIC : null, ); LazyFieldDeclaration.setData(node, data); return node; } FieldFormalParameter _read_fieldFormalParameter(LinkedNode data) { var node = astFactory.fieldFormalParameter2( identifier: _declaredIdentifier(data), period: _Tokens.PERIOD, thisKeyword: _Tokens.THIS, covariantKeyword: AstBinaryFlags.isCovariant(data.flags) ? _Tokens.COVARIANT : null, typeParameters: _readNode(data.fieldFormalParameter_typeParameters), keyword: _Tokens.choose( AstBinaryFlags.isConst(data.flags), _Tokens.CONST, AstBinaryFlags.isFinal(data.flags), _Tokens.FINAL, AstBinaryFlags.isVar(data.flags), _Tokens.VAR, ), metadata: _readNodeList(data.normalFormalParameter_metadata), comment: _readDocumentationComment(data), type: _readNodeLazy(data.fieldFormalParameter_type), parameters: _readNodeLazy(data.fieldFormalParameter_formalParameters), requiredKeyword: AstBinaryFlags.isRequired(data.flags) ? _Tokens.REQUIRED : null, ); LazyFormalParameter.setData(node, data); return node; } ForEachPartsWithDeclaration _read_forEachPartsWithDeclaration( LinkedNode data) { return astFactory.forEachPartsWithDeclaration( inKeyword: _Tokens.IN, iterable: _readNode(data.forEachParts_iterable), loopVariable: _readNode(data.forEachPartsWithDeclaration_loopVariable), ); } ForEachPartsWithIdentifier _read_forEachPartsWithIdentifier(LinkedNode data) { return astFactory.forEachPartsWithIdentifier( inKeyword: _Tokens.IN, iterable: _readNode(data.forEachParts_iterable), identifier: _readNode(data.forEachPartsWithIdentifier_identifier), ); } ForElement _read_forElement(LinkedNode data) { return astFactory.forElement( awaitKeyword: AstBinaryFlags.hasAwait(data.flags) ? _Tokens.AWAIT : null, body: _readNode(data.forElement_body), forKeyword: _Tokens.FOR, forLoopParts: _readNode(data.forMixin_forLoopParts), leftParenthesis: _Tokens.OPEN_PAREN, rightParenthesis: _Tokens.CLOSE_PAREN, ); } FormalParameterList _read_formalParameterList(LinkedNode data) { return astFactory.formalParameterList( _Tokens.OPEN_PAREN, _readNodeList(data.formalParameterList_parameters), _Tokens.choose( AstBinaryFlags.isDelimiterCurly(data.flags), _Tokens.OPEN_CURLY_BRACKET, AstBinaryFlags.isDelimiterSquare(data.flags), _Tokens.OPEN_SQUARE_BRACKET, ), _Tokens.choose( AstBinaryFlags.isDelimiterCurly(data.flags), _Tokens.CLOSE_CURLY_BRACKET, AstBinaryFlags.isDelimiterSquare(data.flags), _Tokens.CLOSE_SQUARE_BRACKET, ), _Tokens.CLOSE_PAREN, ); } ForPartsWithDeclarations _read_forPartsWithDeclarations(LinkedNode data) { return astFactory.forPartsWithDeclarations( condition: _readNode(data.forParts_condition), leftSeparator: _Tokens.SEMICOLON, rightSeparator: _Tokens.SEMICOLON, updaters: _readNodeList(data.forParts_updaters), variables: _readNode(data.forPartsWithDeclarations_variables), ); } ForPartsWithExpression _read_forPartsWithExpression(LinkedNode data) { return astFactory.forPartsWithExpression( condition: _readNode(data.forParts_condition), initialization: _readNode(data.forPartsWithExpression_initialization), leftSeparator: _Tokens.SEMICOLON, rightSeparator: _Tokens.SEMICOLON, updaters: _readNodeList(data.forParts_updaters), ); } ForStatement _read_forStatement(LinkedNode data) { return astFactory.forStatement( awaitKeyword: AstBinaryFlags.hasAwait(data.flags) ? _Tokens.AWAIT : null, forKeyword: _Tokens.FOR, leftParenthesis: _Tokens.OPEN_PAREN, forLoopParts: _readNode(data.forMixin_forLoopParts), rightParenthesis: _Tokens.CLOSE_PAREN, body: _readNode(data.forStatement_body), ); } FunctionDeclaration _read_functionDeclaration(LinkedNode data) { timerAstBinaryReaderFunctionDeclaration.start(); try { var node = astFactory.functionDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), AstBinaryFlags.isExternal(data.flags) ? _Tokens.EXTERNAL : null, _readNodeLazy(data.functionDeclaration_returnType), _Tokens.choose( AstBinaryFlags.isGet(data.flags), _Tokens.GET, AstBinaryFlags.isSet(data.flags), _Tokens.SET, ), _declaredIdentifier(data), _readNodeLazy(data.functionDeclaration_functionExpression), ); LazyFunctionDeclaration.setData(node, data); return node; } finally { timerAstBinaryReaderFunctionDeclaration.stop(); } } FunctionDeclarationStatement _read_functionDeclarationStatement( LinkedNode data) { return astFactory.functionDeclarationStatement( _readNode(data.functionDeclarationStatement_functionDeclaration), ); } FunctionExpression _read_functionExpression(LinkedNode data) { var node = astFactory.functionExpression( _readNode(data.functionExpression_typeParameters), _readNodeLazy(data.functionExpression_formalParameters), _readNodeLazy(data.functionExpression_body), ); LazyFunctionExpression.setData(node, data); return node; } FunctionExpressionInvocation _read_functionExpressionInvocation( LinkedNode data) { return astFactory.functionExpressionInvocation( _readNode(data.functionExpressionInvocation_function), _readNode(data.invocationExpression_typeArguments), _readNode(data.invocationExpression_arguments), )..staticInvokeType = _readType(data.invocationExpression_invokeType); } FunctionTypeAlias _read_functionTypeAlias(LinkedNode data) { var node = astFactory.functionTypeAlias( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.TYPEDEF, _readNodeLazy(data.functionTypeAlias_returnType), _declaredIdentifier(data), _readNode(data.functionTypeAlias_typeParameters), _readNodeLazy(data.functionTypeAlias_formalParameters), _Tokens.SEMICOLON, ); LazyFunctionTypeAlias.setData(node, data); LazyFunctionTypeAlias.setHasSelfReference( node, data.typeAlias_hasSelfReference, ); return node; } FunctionTypedFormalParameter _read_functionTypedFormalParameter( LinkedNode data) { var node = astFactory.functionTypedFormalParameter2( comment: _readDocumentationComment(data), covariantKeyword: AstBinaryFlags.isCovariant(data.flags) ? _Tokens.COVARIANT : null, identifier: _declaredIdentifier(data), metadata: _readNodeListLazy(data.normalFormalParameter_metadata), parameters: _readNodeLazy( data.functionTypedFormalParameter_formalParameters, ), requiredKeyword: AstBinaryFlags.isRequired(data.flags) ? _Tokens.REQUIRED : null, returnType: _readNodeLazy(data.functionTypedFormalParameter_returnType), typeParameters: _readNode( data.functionTypedFormalParameter_typeParameters, ), ); LazyFormalParameter.setData(node, data); return node; } GenericFunctionType _read_genericFunctionType(LinkedNode data) { var id = data.genericFunctionType_id; // Read type parameters, without bounds, to avoid forward references. TypeParameterList typeParameterList; var typeParameterListData = data.genericFunctionType_typeParameters; if (typeParameterListData != null) { var dataList = typeParameterListData.typeParameterList_typeParameters; var typeParameters = List<TypeParameter>(dataList.length); for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; typeParameters[i] = astFactory.typeParameter( _readDocumentationComment(data), _readNodeList(data.annotatedNode_metadata), _declaredIdentifier(data), data.typeParameter_bound != null ? _Tokens.EXTENDS : null, null, ); } typeParameterList = astFactory.typeParameterList( _Tokens.LT, typeParameters, _Tokens.GT, ); } GenericFunctionTypeImpl node = astFactory.genericFunctionType( null, _Tokens.FUNCTION, typeParameterList, null, question: AstBinaryFlags.hasQuestion(data.flags) ? _Tokens.QUESTION : null, ); // Create the node element, so now type parameter elements are available. LazyAst.setGenericFunctionTypeId(node, id); _unitContext.createGenericFunctionTypeElement(id, node); // Finish reading. if (typeParameterListData != null) { var dataList = typeParameterListData.typeParameterList_typeParameters; var typeParameters = typeParameterList.typeParameters; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; var node = typeParameters[i]; node.bound = _readNode(data.typeParameter_bound); } } node.returnType = readNode(data.genericFunctionType_returnType); node.parameters = _readNode(data.genericFunctionType_formalParameters); node.type = _readType(data.genericFunctionType_type); return node; } GenericTypeAlias _read_genericTypeAlias(LinkedNode data) { var node = astFactory.genericTypeAlias( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.TYPEDEF, _declaredIdentifier(data), _readNode(data.genericTypeAlias_typeParameters), _Tokens.EQ, _readNodeLazy(data.genericTypeAlias_functionType), _Tokens.SEMICOLON, ); LazyGenericTypeAlias.setData(node, data); LazyGenericTypeAlias.setHasSelfReference( node, data.typeAlias_hasSelfReference, ); return node; } HideCombinator _read_hideCombinator(LinkedNode data) { var node = astFactory.hideCombinator( _combinatorKeyword(data, Keyword.HIDE, _Tokens.HIDE), data.names.map((name) => AstTestFactory.identifier3(name)).toList(), ); LazyCombinator(node, data); return node; } IfElement _read_ifElement(LinkedNode data) { var elseElement = _readNode(data.ifElement_elseElement); return astFactory.ifElement( condition: _readNode(data.ifMixin_condition), elseElement: elseElement, elseKeyword: elseElement != null ? _Tokens.ELSE : null, ifKeyword: _Tokens.IF, leftParenthesis: _Tokens.OPEN_PAREN, rightParenthesis: _Tokens.CLOSE_PAREN, thenElement: _readNode(data.ifElement_thenElement), ); } IfStatement _read_ifStatement(LinkedNode data) { var elseStatement = _readNode(data.ifStatement_elseStatement); return astFactory.ifStatement( _Tokens.IF, _Tokens.OPEN_PAREN, _readNode(data.ifMixin_condition), _Tokens.CLOSE_PAREN, _readNode(data.ifStatement_thenStatement), elseStatement != null ? _Tokens.ELSE : null, elseStatement, ); } ImplementsClause _read_implementsClause(LinkedNode data) { return astFactory.implementsClause( _Tokens.IMPLEMENTS, _readNodeList(data.implementsClause_interfaces), ); } ImportDirective _read_importDirective(LinkedNode data) { timerAstBinaryReaderDirective.start(); _isReadingDirective = true; try { SimpleIdentifier prefix; if (data.importDirective_prefix.isNotEmpty) { prefix = astFactory.simpleIdentifier( TokenFactory.tokenFromString(data.importDirective_prefix), ); var informativeData = _unitContext.getInformativeData(data); prefix.token.offset = informativeData?.importDirective_prefixOffset ?? 0; } var node = astFactory.importDirective( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _directiveKeyword(data, Keyword.IMPORT, _Tokens.IMPORT), _readNode(data.uriBasedDirective_uri), _readNodeList(data.namespaceDirective_configurations), AstBinaryFlags.isDeferred(data.flags) ? _Tokens.DEFERRED : null, _Tokens.AS, prefix, _readNodeList(data.namespaceDirective_combinators), _Tokens.SEMICOLON, ); LazyDirective.setData(node, data); return node; } finally { _isReadingDirective = false; timerAstBinaryReaderDirective.stop(); } } IndexExpression _read_indexExpression(LinkedNode data) { return astFactory.indexExpressionForTarget( _readNode(data.indexExpression_target), _Tokens.OPEN_SQUARE_BRACKET, _readNode(data.indexExpression_index), _Tokens.CLOSE_SQUARE_BRACKET, ) ..period = AstBinaryFlags.hasPeriod(data.flags) ? _Tokens.PERIOD_PERIOD : null ..staticElement = _elementOfComponents( data.indexExpression_element, data.indexExpression_substitution, ) ..staticType = _readType(data.expression_type); } InstanceCreationExpression _read_instanceCreationExpression(LinkedNode data) { var node = astFactory.instanceCreationExpression( _Tokens.choose( AstBinaryFlags.isConst(data.flags), _Tokens.CONST, AstBinaryFlags.isNew(data.flags), _Tokens.NEW, ), _readNode(data.instanceCreationExpression_constructorName), astFactory.argumentList( _Tokens.OPEN_PAREN, _readNodeList( data.instanceCreationExpression_arguments, ), _Tokens.CLOSE_PAREN, ), typeArguments: _readNode(data.instanceCreationExpression_typeArguments), ); node.staticElement = node.constructorName.staticElement; node.staticType = _readType(data.expression_type); return node; } IntegerLiteral _read_integerLiteral(LinkedNode data) { // TODO(scheglov) Remove `?? _intType` after internal SDK roll. return AstTestFactory.integer(data.integerLiteral_value) ..staticType = _readType(data.expression_type) ?? _intType; } InterpolationExpression _read_interpolationExpression(LinkedNode data) { var isIdentifier = AstBinaryFlags.isStringInterpolationIdentifier(data.flags); return astFactory.interpolationExpression( isIdentifier ? _Tokens.OPEN_CURLY_BRACKET : _Tokens.STRING_INTERPOLATION_EXPRESSION, _readNode(data.interpolationExpression_expression), isIdentifier ? null : _Tokens.CLOSE_CURLY_BRACKET, ); } InterpolationString _read_interpolationString(LinkedNode data) { return astFactory.interpolationString( TokenFactory.tokenFromString(data.interpolationString_value), data.interpolationString_value, ); } IsExpression _read_isExpression(LinkedNode data) { return astFactory.isExpression( _readNode(data.isExpression_expression), _Tokens.IS, AstBinaryFlags.hasNot(data.flags) ? _Tokens.BANG : null, _readNode(data.isExpression_type), )..staticType = _boolType; } Label _read_label(LinkedNode data) { return astFactory.label( _readNode(data.label_label), _Tokens.COLON, ); } LabeledStatement _read_labeledStatement(LinkedNode data) { return astFactory.labeledStatement( _readNodeList(data.labeledStatement_labels), _readNode(data.labeledStatement_statement), ); } LibraryDirective _read_libraryDirective(LinkedNode data) { timerAstBinaryReaderDirective.start(); _isReadingDirective = true; try { var node = astFactory.libraryDirective( _unitContext.createComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.LIBRARY, _readNode(data.libraryDirective_name), _Tokens.SEMICOLON, ); LazyDirective.setData(node, data); return node; } finally { _isReadingDirective = false; timerAstBinaryReaderDirective.stop(); } } LibraryIdentifier _read_libraryIdentifier(LinkedNode data) { return astFactory.libraryIdentifier( _readNodeList(data.libraryIdentifier_components), ); } ListLiteral _read_listLiteral(LinkedNode data) { return astFactory.listLiteral( AstBinaryFlags.isConst(data.flags) ? _Tokens.CONST : null, AstBinaryFlags.hasTypeArguments(data.flags) ? astFactory.typeArgumentList( _Tokens.LT, _readNodeList(data.typedLiteral_typeArguments), _Tokens.GT, ) : null, _Tokens.OPEN_SQUARE_BRACKET, _readNodeList(data.listLiteral_elements), _Tokens.CLOSE_SQUARE_BRACKET, )..staticType = _readType(data.expression_type); } MapLiteralEntry _read_mapLiteralEntry(LinkedNode data) { return astFactory.mapLiteralEntry( _readNode(data.mapLiteralEntry_key), _Tokens.COLON, _readNode(data.mapLiteralEntry_value), ); } MethodDeclaration _read_methodDeclaration(LinkedNode data) { FunctionBody body; if (AstBinaryFlags.isNative(data.flags)) { body = AstTestFactory.nativeFunctionBody(''); } else if (AstBinaryFlags.isAbstract(data.flags)) { body = AstTestFactory.emptyFunctionBody(); } else { body = AstTestFactory.blockFunctionBody(AstTestFactory.block()); } var node = astFactory.methodDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), AstBinaryFlags.isExternal(data.flags) ? _Tokens.EXTERNAL : null, AstBinaryFlags.isStatic(data.flags) ? _Tokens.STATIC : null, _readNodeLazy(data.methodDeclaration_returnType), _Tokens.choose( AstBinaryFlags.isGet(data.flags), _Tokens.GET, AstBinaryFlags.isSet(data.flags), _Tokens.SET, ), AstBinaryFlags.isOperator(data.flags) ? _Tokens.OPERATOR : null, _declaredIdentifier(data), _readNode(data.methodDeclaration_typeParameters), _readNodeLazy(data.methodDeclaration_formalParameters), body, ); LazyMethodDeclaration.setData(node, data); return node; } MethodInvocation _read_methodInvocation(LinkedNode data) { return astFactory.methodInvocation( _readNode(data.methodInvocation_target), _Tokens.choose( AstBinaryFlags.hasPeriod(data.flags), _Tokens.PERIOD, AstBinaryFlags.hasPeriod2(data.flags), _Tokens.PERIOD_PERIOD, ), _readNode(data.methodInvocation_methodName), _readNode(data.invocationExpression_typeArguments), _readNode(data.invocationExpression_arguments), )..staticInvokeType = _readType(data.invocationExpression_invokeType); } MixinDeclaration _read_mixinDeclaration(LinkedNode data) { timerAstBinaryReaderMixin.start(); try { var node = astFactory.mixinDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.MIXIN, _declaredIdentifier(data), _readNode(data.classOrMixinDeclaration_typeParameters), _readNodeLazy(data.mixinDeclaration_onClause), _readNodeLazy(data.classOrMixinDeclaration_implementsClause), _Tokens.OPEN_CURLY_BRACKET, _readNodeListLazy(data.classOrMixinDeclaration_members), _Tokens.CLOSE_CURLY_BRACKET, ); LazyMixinDeclaration(node, data); return node; } finally { timerAstBinaryReaderMixin.stop(); } } NamedExpression _read_namedExpression(LinkedNode data) { Expression expression = _readNode(data.namedExpression_expression); return astFactory.namedExpression( _readNode(data.namedExpression_name), expression, )..staticType = expression.staticType; } NativeClause _read_nativeClause(LinkedNode data) { return astFactory.nativeClause( _Tokens.NATIVE, _readNode(data.nativeClause_name), ); } NativeFunctionBody _read_nativeFunctionBody(LinkedNode data) { return astFactory.nativeFunctionBody( _Tokens.NATIVE, _readNode(data.nativeFunctionBody_stringLiteral), _Tokens.SEMICOLON, ); } NullLiteral _read_nullLiteral(LinkedNode data) { return astFactory.nullLiteral( _Tokens.NULL, )..staticType = _nullType; } OnClause _read_onClause(LinkedNode data) { return astFactory.onClause( _Tokens.ON, _readNodeList(data.onClause_superclassConstraints), ); } ParenthesizedExpression _read_parenthesizedExpression(LinkedNode data) { return astFactory.parenthesizedExpression( _Tokens.OPEN_PAREN, _readNode(data.parenthesizedExpression_expression), _Tokens.CLOSE_PAREN, )..staticType = _readType(data.expression_type); } PartDirective _read_partDirective(LinkedNode data) { timerAstBinaryReaderDirective.start(); _isReadingDirective = true; try { var node = astFactory.partDirective( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.PART, _readNode(data.uriBasedDirective_uri), _Tokens.SEMICOLON, ); LazyDirective.setData(node, data); return node; } finally { _isReadingDirective = false; timerAstBinaryReaderDirective.stop(); } } PartOfDirective _read_partOfDirective(LinkedNode data) { timerAstBinaryReaderDirective.start(); _isReadingDirective = true; try { var node = astFactory.partOfDirective( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _Tokens.PART, _Tokens.OF, _readNode(data.partOfDirective_uri), _readNode(data.partOfDirective_libraryName), _Tokens.SEMICOLON, ); LazyDirective.setData(node, data); return node; } finally { _isReadingDirective = false; timerAstBinaryReaderDirective.stop(); } } PostfixExpression _read_postfixExpression(LinkedNode data) { return astFactory.postfixExpression( _readNode(data.postfixExpression_operand), _Tokens.fromType(data.postfixExpression_operator), ) ..staticElement = _elementOfComponents( data.postfixExpression_element, data.postfixExpression_substitution, ) ..staticType = _readType(data.expression_type); } PrefixedIdentifier _read_prefixedIdentifier(LinkedNode data) { return astFactory.prefixedIdentifier( _readNode(data.prefixedIdentifier_prefix), _Tokens.PERIOD, _readNode(data.prefixedIdentifier_identifier), )..staticType = _readType(data.expression_type); } PrefixExpression _read_prefixExpression(LinkedNode data) { return astFactory.prefixExpression( _Tokens.fromType(data.prefixExpression_operator), _readNode(data.prefixExpression_operand), ) ..staticElement = _elementOfComponents( data.prefixExpression_element, data.prefixExpression_substitution, ) ..staticType = _readType(data.expression_type); } PropertyAccess _read_propertyAccess(LinkedNode data) { return astFactory.propertyAccess( _readNode(data.propertyAccess_target), _Tokens.fromType(data.propertyAccess_operator), _readNode(data.propertyAccess_propertyName), )..staticType = _readType(data.expression_type); } RedirectingConstructorInvocation _read_redirectingConstructorInvocation( LinkedNode data) { var hasThis = AstBinaryFlags.hasThis(data.flags); return astFactory.redirectingConstructorInvocation( hasThis ? _Tokens.THIS : null, hasThis ? _Tokens.PERIOD : null, _readNode(data.redirectingConstructorInvocation_constructorName), _readNode(data.redirectingConstructorInvocation_arguments), )..staticElement = _elementOfComponents( data.redirectingConstructorInvocation_element, data.redirectingConstructorInvocation_substitution, ); } RethrowExpression _read_rethrowExpression(LinkedNode data) { return astFactory.rethrowExpression( _Tokens.RETHROW, )..staticType = _readType(data.expression_type); } ReturnStatement _read_returnStatement(LinkedNode data) { return astFactory.returnStatement( _Tokens.RETURN, _readNode(data.returnStatement_expression), _Tokens.SEMICOLON, ); } SetOrMapLiteral _read_setOrMapLiteral(LinkedNode data) { SetOrMapLiteralImpl node = astFactory.setOrMapLiteral( constKeyword: AstBinaryFlags.isConst(data.flags) ? _Tokens.CONST : null, elements: _readNodeList(data.setOrMapLiteral_elements), leftBracket: _Tokens.OPEN_CURLY_BRACKET, typeArguments: AstBinaryFlags.hasTypeArguments(data.flags) ? astFactory.typeArgumentList( _Tokens.LT, _readNodeList(data.typedLiteral_typeArguments), _Tokens.GT, ) : null, rightBracket: _Tokens.CLOSE_CURLY_BRACKET, )..staticType = _readType(data.expression_type); if (AstBinaryFlags.isMap(data.flags)) { node.becomeMap(); } else if (AstBinaryFlags.isSet(data.flags)) { node.becomeSet(); } return node; } ShowCombinator _read_showCombinator(LinkedNode data) { var node = astFactory.showCombinator( _combinatorKeyword(data, Keyword.SHOW, _Tokens.SHOW), data.names.map((name) => AstTestFactory.identifier3(name)).toList(), ); LazyCombinator(node, data); return node; } SimpleFormalParameter _read_simpleFormalParameter(LinkedNode data) { SimpleFormalParameterImpl node = astFactory.simpleFormalParameter2( identifier: _declaredIdentifier(data), type: _readNode(data.simpleFormalParameter_type), covariantKeyword: AstBinaryFlags.isCovariant(data.flags) ? _Tokens.COVARIANT : null, comment: _readDocumentationComment(data), metadata: _readNodeList(data.normalFormalParameter_metadata), keyword: _Tokens.choose( AstBinaryFlags.isConst(data.flags), _Tokens.CONST, AstBinaryFlags.isFinal(data.flags), _Tokens.FINAL, AstBinaryFlags.isVar(data.flags), _Tokens.VAR, ), requiredKeyword: AstBinaryFlags.isRequired(data.flags) ? _Tokens.REQUIRED : null, ); LazyFormalParameter.setData(node, data); LazyAst.setInheritsCovariant(node, data.inheritsCovariant); return node; } SimpleIdentifier _read_simpleIdentifier(LinkedNode data) { return astFactory.simpleIdentifier( TokenFactory.tokenFromString(data.name), isDeclaration: AstBinaryFlags.isDeclaration(data.flags), ) ..staticElement = _elementOfComponents( data.simpleIdentifier_element, data.simpleIdentifier_substitution, ) ..staticType = _readType(data.expression_type); } SimpleStringLiteral _read_simpleStringLiteral(LinkedNode data) { var node = AstTestFactory.string2(data.simpleStringLiteral_value); if (!_isReadingDirective) { node.staticType = _stringType; } return node; } SpreadElement _read_spreadElement(LinkedNode data) { return astFactory.spreadElement( spreadOperator: _Tokens.fromType(data.spreadElement_spreadOperator), expression: _readNode(data.spreadElement_expression), ); } StringInterpolation _read_stringInterpolation(LinkedNode data) { return astFactory.stringInterpolation( _readNodeList(data.stringInterpolation_elements), )..staticType = _stringType; } SuperConstructorInvocation _read_superConstructorInvocation(LinkedNode data) { return astFactory.superConstructorInvocation( _Tokens.SUPER, _Tokens.PERIOD, _readNode(data.superConstructorInvocation_constructorName), _readNode(data.superConstructorInvocation_arguments), )..staticElement = _elementOfComponents( data.superConstructorInvocation_element, data.superConstructorInvocation_substitution, ); } SuperExpression _read_superExpression(LinkedNode data) { return astFactory.superExpression( _Tokens.SUPER, )..staticType = _readType(data.expression_type); } SwitchCase _read_switchCase(LinkedNode data) { return astFactory.switchCase( _readNodeList(data.switchMember_labels), _Tokens.CASE, _readNode(data.switchCase_expression), _Tokens.COLON, _readNodeList(data.switchMember_statements), ); } SwitchDefault _read_switchDefault(LinkedNode data) { return astFactory.switchDefault( _readNodeList(data.switchMember_labels), _Tokens.DEFAULT, _Tokens.COLON, _readNodeList(data.switchMember_statements), ); } SwitchStatement _read_switchStatement(LinkedNode data) { return astFactory.switchStatement( _Tokens.SWITCH, _Tokens.OPEN_PAREN, _readNode(data.switchStatement_expression), _Tokens.CLOSE_PAREN, _Tokens.OPEN_CURLY_BRACKET, _readNodeList(data.switchStatement_members), _Tokens.CLOSE_CURLY_BRACKET, ); } SymbolLiteral _read_symbolLiteral(LinkedNode data) { return astFactory.symbolLiteral( _Tokens.HASH, data.names.map((lexeme) => TokenFactory.tokenFromString(lexeme)).toList(), )..staticType = _readType(data.expression_type); } ThisExpression _read_thisExpression(LinkedNode data) { return astFactory.thisExpression( _Tokens.THIS, )..staticType = _readType(data.expression_type); } ThrowExpression _read_throwExpression(LinkedNode data) { return astFactory.throwExpression( _Tokens.THROW, _readNode(data.throwExpression_expression), )..staticType = _readType(data.expression_type); } TopLevelVariableDeclaration _read_topLevelVariableDeclaration( LinkedNode data) { timerAstBinaryReaderTopLevelVar.start(); try { var node = astFactory.topLevelVariableDeclaration( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _readNode(data.topLevelVariableDeclaration_variableList), _Tokens.SEMICOLON, ); LazyTopLevelVariableDeclaration.setData(node, data); return node; } finally { timerAstBinaryReaderTopLevelVar.stop(); } } TryStatement _read_tryStatement(LinkedNode data) { return astFactory.tryStatement( _Tokens.TRY, _readNode(data.tryStatement_body), _readNodeList(data.tryStatement_catchClauses), _Tokens.FINALLY, _readNode(data.tryStatement_finallyBlock), ); } TypeArgumentList _read_typeArgumentList(LinkedNode data) { return astFactory.typeArgumentList( _Tokens.LT, _readNodeList(data.typeArgumentList_arguments), _Tokens.GT, ); } TypeName _read_typeName(LinkedNode data) { return astFactory.typeName( _readNode(data.typeName_name), AstBinaryFlags.hasTypeArguments(data.flags) ? astFactory.typeArgumentList( _Tokens.LT, _readNodeList(data.typeName_typeArguments), _Tokens.GT, ) : null, question: AstBinaryFlags.hasQuestion(data.flags) ? _Tokens.QUESTION : null, )..type = _readType(data.typeName_type); } TypeParameter _read_typeParameter(LinkedNode data) { var node = astFactory.typeParameter( _readDocumentationComment(data), _readNodeListLazy(data.annotatedNode_metadata), _declaredIdentifier(data), _Tokens.EXTENDS, _readNodeLazy(data.typeParameter_bound), ); LazyTypeParameter.setData(node, data); return node; } TypeParameterList _read_typeParameterList(LinkedNode data) { return astFactory.typeParameterList( _Tokens.LT, _readNodeList(data.typeParameterList_typeParameters), _Tokens.GT, ); } VariableDeclaration _read_variableDeclaration(LinkedNode data) { var node = astFactory.variableDeclaration( _declaredIdentifier(data), _Tokens.EQ, _readNodeLazy(data.variableDeclaration_initializer), ); LazyVariableDeclaration.setData(node, data); LazyAst.setInheritsCovariant(node, data.inheritsCovariant); return node; } VariableDeclarationList _read_variableDeclarationList(LinkedNode data) { var node = astFactory.variableDeclarationList2( comment: _readDocumentationComment(data), keyword: _Tokens.choose( AstBinaryFlags.isConst(data.flags), _Tokens.CONST, AstBinaryFlags.isFinal(data.flags), _Tokens.FINAL, AstBinaryFlags.isVar(data.flags), _Tokens.VAR, ), lateKeyword: AstBinaryFlags.isLate(data.flags) ? _Tokens.LATE : null, metadata: _readNodeListLazy(data.annotatedNode_metadata), type: _readNodeLazy(data.variableDeclarationList_type), variables: _readNodeList(data.variableDeclarationList_variables), ); LazyVariableDeclarationList.setData(node, data); return node; } VariableDeclarationStatement _read_variableDeclarationStatement( LinkedNode data) { return astFactory.variableDeclarationStatement( _readNode(data.variableDeclarationStatement_variables), _Tokens.SEMICOLON, ); } WhileStatement _read_whileStatement(LinkedNode data) { return astFactory.whileStatement( _Tokens.WHILE, _Tokens.OPEN_PAREN, _readNode(data.whileStatement_condition), _Tokens.CLOSE_PAREN, _readNode(data.whileStatement_body), ); } WithClause _read_withClause(LinkedNode data) { return astFactory.withClause( _Tokens.WITH, _readNodeList(data.withClause_mixinTypes), ); } YieldStatement _read_yieldStatement(LinkedNode data) { return astFactory.yieldStatement( _Tokens.YIELD, AstBinaryFlags.isStar(data.flags) ? _Tokens.STAR : null, _readNode(data.yieldStatement_expression), _Tokens.SEMICOLON, ); } Comment _readDocumentationComment(LinkedNode data) { return null; } AstNode _readNode(LinkedNode data) { if (data == null) return null; switch (data.kind) { case LinkedNodeKind.adjacentStrings: return _read_adjacentStrings(data); case LinkedNodeKind.annotation: return _read_annotation(data); case LinkedNodeKind.argumentList: return _read_argumentList(data); case LinkedNodeKind.asExpression: return _read_asExpression(data); case LinkedNodeKind.assertInitializer: return _read_assertInitializer(data); case LinkedNodeKind.assertStatement: return _read_assertStatement(data); case LinkedNodeKind.assignmentExpression: return _read_assignmentExpression(data); case LinkedNodeKind.awaitExpression: return _read_awaitExpression(data); case LinkedNodeKind.binaryExpression: return _read_binaryExpression(data); case LinkedNodeKind.block: return _read_block(data); case LinkedNodeKind.blockFunctionBody: return _read_blockFunctionBody(data); case LinkedNodeKind.booleanLiteral: return _read_booleanLiteral(data); case LinkedNodeKind.breakStatement: return _read_breakStatement(data); case LinkedNodeKind.cascadeExpression: return _read_cascadeExpression(data); case LinkedNodeKind.catchClause: return _read_catchClause(data); case LinkedNodeKind.classDeclaration: return _read_classDeclaration(data); case LinkedNodeKind.classTypeAlias: return _read_classTypeAlias(data); case LinkedNodeKind.comment: return _read_comment(data); case LinkedNodeKind.commentReference: return _read_commentReference(data); case LinkedNodeKind.compilationUnit: return _read_compilationUnit(data); case LinkedNodeKind.conditionalExpression: return _read_conditionalExpression(data); case LinkedNodeKind.configuration: return _read_configuration(data); case LinkedNodeKind.constructorDeclaration: return _read_constructorDeclaration(data); case LinkedNodeKind.constructorFieldInitializer: return _read_constructorFieldInitializer(data); case LinkedNodeKind.constructorName: return _read_constructorName(data); case LinkedNodeKind.continueStatement: return _read_continueStatement(data); case LinkedNodeKind.declaredIdentifier: return _read_declaredIdentifier(data); case LinkedNodeKind.defaultFormalParameter: return _read_defaultFormalParameter(data); case LinkedNodeKind.doStatement: return _read_doStatement(data); case LinkedNodeKind.dottedName: return _read_dottedName(data); case LinkedNodeKind.doubleLiteral: return _read_doubleLiteral(data); case LinkedNodeKind.emptyFunctionBody: return _read_emptyFunctionBody(data); case LinkedNodeKind.emptyStatement: return _read_emptyStatement(data); case LinkedNodeKind.enumConstantDeclaration: return _read_enumConstantDeclaration(data); case LinkedNodeKind.enumDeclaration: return _read_enumDeclaration(data); case LinkedNodeKind.exportDirective: return _read_exportDirective(data); case LinkedNodeKind.expressionFunctionBody: return _read_expressionFunctionBody(data); case LinkedNodeKind.expressionStatement: return _read_expressionStatement(data); case LinkedNodeKind.extendsClause: return _read_extendsClause(data); case LinkedNodeKind.extensionDeclaration: return _read_extensionDeclaration(data); case LinkedNodeKind.extensionOverride: return _read_extensionOverride(data); case LinkedNodeKind.fieldDeclaration: return _read_fieldDeclaration(data); case LinkedNodeKind.fieldFormalParameter: return _read_fieldFormalParameter(data); case LinkedNodeKind.forEachPartsWithDeclaration: return _read_forEachPartsWithDeclaration(data); case LinkedNodeKind.forEachPartsWithIdentifier: return _read_forEachPartsWithIdentifier(data); case LinkedNodeKind.forElement: return _read_forElement(data); case LinkedNodeKind.forPartsWithExpression: return _read_forPartsWithExpression(data); case LinkedNodeKind.forPartsWithDeclarations: return _read_forPartsWithDeclarations(data); case LinkedNodeKind.forStatement: return _read_forStatement(data); case LinkedNodeKind.formalParameterList: return _read_formalParameterList(data); case LinkedNodeKind.functionDeclaration: return _read_functionDeclaration(data); case LinkedNodeKind.functionDeclarationStatement: return _read_functionDeclarationStatement(data); case LinkedNodeKind.functionExpression: return _read_functionExpression(data); case LinkedNodeKind.functionExpressionInvocation: return _read_functionExpressionInvocation(data); case LinkedNodeKind.functionTypeAlias: return _read_functionTypeAlias(data); case LinkedNodeKind.functionTypedFormalParameter: return _read_functionTypedFormalParameter(data); case LinkedNodeKind.genericFunctionType: return _read_genericFunctionType(data); case LinkedNodeKind.genericTypeAlias: return _read_genericTypeAlias(data); case LinkedNodeKind.hideCombinator: return _read_hideCombinator(data); case LinkedNodeKind.ifElement: return _read_ifElement(data); case LinkedNodeKind.ifStatement: return _read_ifStatement(data); case LinkedNodeKind.implementsClause: return _read_implementsClause(data); case LinkedNodeKind.importDirective: return _read_importDirective(data); case LinkedNodeKind.indexExpression: return _read_indexExpression(data); case LinkedNodeKind.instanceCreationExpression: return _read_instanceCreationExpression(data); case LinkedNodeKind.integerLiteral: return _read_integerLiteral(data); case LinkedNodeKind.interpolationString: return _read_interpolationString(data); case LinkedNodeKind.interpolationExpression: return _read_interpolationExpression(data); case LinkedNodeKind.isExpression: return _read_isExpression(data); case LinkedNodeKind.label: return _read_label(data); case LinkedNodeKind.labeledStatement: return _read_labeledStatement(data); case LinkedNodeKind.libraryDirective: return _read_libraryDirective(data); case LinkedNodeKind.libraryIdentifier: return _read_libraryIdentifier(data); case LinkedNodeKind.listLiteral: return _read_listLiteral(data); case LinkedNodeKind.mapLiteralEntry: return _read_mapLiteralEntry(data); case LinkedNodeKind.methodDeclaration: return _read_methodDeclaration(data); case LinkedNodeKind.methodInvocation: return _read_methodInvocation(data); case LinkedNodeKind.mixinDeclaration: return _read_mixinDeclaration(data); case LinkedNodeKind.namedExpression: return _read_namedExpression(data); case LinkedNodeKind.nativeClause: return _read_nativeClause(data); case LinkedNodeKind.nativeFunctionBody: return _read_nativeFunctionBody(data); case LinkedNodeKind.nullLiteral: return _read_nullLiteral(data); case LinkedNodeKind.onClause: return _read_onClause(data); case LinkedNodeKind.parenthesizedExpression: return _read_parenthesizedExpression(data); case LinkedNodeKind.partDirective: return _read_partDirective(data); case LinkedNodeKind.partOfDirective: return _read_partOfDirective(data); case LinkedNodeKind.postfixExpression: return _read_postfixExpression(data); case LinkedNodeKind.prefixExpression: return _read_prefixExpression(data); case LinkedNodeKind.propertyAccess: return _read_propertyAccess(data); case LinkedNodeKind.prefixedIdentifier: return _read_prefixedIdentifier(data); case LinkedNodeKind.redirectingConstructorInvocation: return _read_redirectingConstructorInvocation(data); case LinkedNodeKind.rethrowExpression: return _read_rethrowExpression(data); case LinkedNodeKind.returnStatement: return _read_returnStatement(data); case LinkedNodeKind.setOrMapLiteral: return _read_setOrMapLiteral(data); case LinkedNodeKind.showCombinator: return _read_showCombinator(data); case LinkedNodeKind.simpleFormalParameter: return _read_simpleFormalParameter(data); case LinkedNodeKind.simpleIdentifier: return _read_simpleIdentifier(data); case LinkedNodeKind.simpleStringLiteral: return _read_simpleStringLiteral(data); case LinkedNodeKind.spreadElement: return _read_spreadElement(data); case LinkedNodeKind.stringInterpolation: return _read_stringInterpolation(data); case LinkedNodeKind.superConstructorInvocation: return _read_superConstructorInvocation(data); case LinkedNodeKind.superExpression: return _read_superExpression(data); case LinkedNodeKind.switchCase: return _read_switchCase(data); case LinkedNodeKind.switchDefault: return _read_switchDefault(data); case LinkedNodeKind.switchStatement: return _read_switchStatement(data); case LinkedNodeKind.symbolLiteral: return _read_symbolLiteral(data); case LinkedNodeKind.thisExpression: return _read_thisExpression(data); case LinkedNodeKind.throwExpression: return _read_throwExpression(data); case LinkedNodeKind.topLevelVariableDeclaration: return _read_topLevelVariableDeclaration(data); case LinkedNodeKind.tryStatement: return _read_tryStatement(data); case LinkedNodeKind.typeArgumentList: return _read_typeArgumentList(data); case LinkedNodeKind.typeName: return _read_typeName(data); case LinkedNodeKind.typeParameter: return _read_typeParameter(data); case LinkedNodeKind.typeParameterList: return _read_typeParameterList(data); case LinkedNodeKind.variableDeclaration: return _read_variableDeclaration(data); case LinkedNodeKind.variableDeclarationList: return _read_variableDeclarationList(data); case LinkedNodeKind.variableDeclarationStatement: return _read_variableDeclarationStatement(data); case LinkedNodeKind.whileStatement: return _read_whileStatement(data); case LinkedNodeKind.withClause: return _read_withClause(data); case LinkedNodeKind.yieldStatement: return _read_yieldStatement(data); default: throw UnimplementedError('Expression kind: ${data.kind}'); } } AstNode _readNodeLazy(LinkedNode data) { if (isLazy) return null; return _readNode(data); } List<T> _readNodeList<T>(List<LinkedNode> nodeList) { var result = List<T>.filled(nodeList.length, null); for (var i = 0; i < nodeList.length; ++i) { var linkedNode = nodeList[i]; result[i] = _readNode(linkedNode) as T; } return result; } List<T> _readNodeListLazy<T>(List<LinkedNode> nodeList) { if (isLazy) { return List<T>.filled(nodeList.length, null); } return _readNodeList(nodeList); } DartType _readType(LinkedNodeType data) { return _unitContext.readType(data); } static ParameterKind _toParameterKind(LinkedNodeFormalParameterKind kind) { switch (kind) { case LinkedNodeFormalParameterKind.requiredPositional: return ParameterKind.REQUIRED; case LinkedNodeFormalParameterKind.requiredNamed: return ParameterKind.NAMED_REQUIRED; break; case LinkedNodeFormalParameterKind.optionalPositional: return ParameterKind.POSITIONAL; break; case LinkedNodeFormalParameterKind.optionalNamed: return ParameterKind.NAMED; default: throw StateError('Unexpected: $kind'); } } } class _Tokens { static final ABSTRACT = TokenFactory.tokenFromKeyword(Keyword.ABSTRACT); static final ARROW = TokenFactory.tokenFromType(TokenType.FUNCTION); static final AS = TokenFactory.tokenFromKeyword(Keyword.AS); static final ASSERT = TokenFactory.tokenFromKeyword(Keyword.ASSERT); static final AT = TokenFactory.tokenFromType(TokenType.AT); static final ASYNC = TokenFactory.tokenFromKeyword(Keyword.ASYNC); static final AWAIT = TokenFactory.tokenFromKeyword(Keyword.AWAIT); static final BANG = TokenFactory.tokenFromType(TokenType.BANG); static final BREAK = TokenFactory.tokenFromKeyword(Keyword.BREAK); static final CASE = TokenFactory.tokenFromKeyword(Keyword.CASE); static final CATCH = TokenFactory.tokenFromKeyword(Keyword.CATCH); static final CLASS = TokenFactory.tokenFromKeyword(Keyword.CLASS); static final CLOSE_CURLY_BRACKET = TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET); static final CLOSE_PAREN = TokenFactory.tokenFromType(TokenType.CLOSE_PAREN); static final CLOSE_SQUARE_BRACKET = TokenFactory.tokenFromType(TokenType.CLOSE_SQUARE_BRACKET); static final COLON = TokenFactory.tokenFromType(TokenType.COLON); static final COMMA = TokenFactory.tokenFromType(TokenType.COMMA); static final CONST = TokenFactory.tokenFromKeyword(Keyword.CONST); static final CONTINUE = TokenFactory.tokenFromKeyword(Keyword.CONTINUE); static final COVARIANT = TokenFactory.tokenFromKeyword(Keyword.COVARIANT); static final DEFERRED = TokenFactory.tokenFromKeyword(Keyword.DEFERRED); static final ELSE = TokenFactory.tokenFromKeyword(Keyword.ELSE); static final EXTERNAL = TokenFactory.tokenFromKeyword(Keyword.EXTERNAL); static final FACTORY = TokenFactory.tokenFromKeyword(Keyword.FACTORY); static final DEFAULT = TokenFactory.tokenFromKeyword(Keyword.DEFAULT); static final DO = TokenFactory.tokenFromKeyword(Keyword.DO); static final ENUM = TokenFactory.tokenFromKeyword(Keyword.ENUM); static final EQ = TokenFactory.tokenFromType(TokenType.EQ); static final EXPORT = TokenFactory.tokenFromKeyword(Keyword.EXPORT); static final EXTENDS = TokenFactory.tokenFromKeyword(Keyword.EXTENDS); static final EXTENSION = TokenFactory.tokenFromKeyword(Keyword.EXTENSION); static final FINAL = TokenFactory.tokenFromKeyword(Keyword.FINAL); static final FINALLY = TokenFactory.tokenFromKeyword(Keyword.FINALLY); static final FOR = TokenFactory.tokenFromKeyword(Keyword.FOR); static final FUNCTION = TokenFactory.tokenFromKeyword(Keyword.FUNCTION); static final GET = TokenFactory.tokenFromKeyword(Keyword.GET); static final GT = TokenFactory.tokenFromType(TokenType.GT); static final HASH = TokenFactory.tokenFromType(TokenType.HASH); static final HIDE = TokenFactory.tokenFromKeyword(Keyword.HIDE); static final IF = TokenFactory.tokenFromKeyword(Keyword.IF); static final IMPLEMENTS = TokenFactory.tokenFromKeyword(Keyword.IMPORT); static final IMPORT = TokenFactory.tokenFromKeyword(Keyword.IMPLEMENTS); static final IN = TokenFactory.tokenFromKeyword(Keyword.IN); static final IS = TokenFactory.tokenFromKeyword(Keyword.IS); static final LATE = TokenFactory.tokenFromKeyword(Keyword.LATE); static final LIBRARY = TokenFactory.tokenFromKeyword(Keyword.LIBRARY); static final LT = TokenFactory.tokenFromType(TokenType.LT); static final MIXIN = TokenFactory.tokenFromKeyword(Keyword.MIXIN); static final NATIVE = TokenFactory.tokenFromKeyword(Keyword.NATIVE); static final NEW = TokenFactory.tokenFromKeyword(Keyword.NEW); static final NULL = TokenFactory.tokenFromKeyword(Keyword.NULL); static final OF = TokenFactory.tokenFromKeyword(Keyword.OF); static final ON = TokenFactory.tokenFromKeyword(Keyword.ON); static final OPEN_CURLY_BRACKET = TokenFactory.tokenFromType(TokenType.OPEN_CURLY_BRACKET); static final OPEN_PAREN = TokenFactory.tokenFromType(TokenType.OPEN_PAREN); static final OPEN_SQUARE_BRACKET = TokenFactory.tokenFromType(TokenType.OPEN_SQUARE_BRACKET); static final OPERATOR = TokenFactory.tokenFromKeyword(Keyword.OPERATOR); static final PART = TokenFactory.tokenFromKeyword(Keyword.PART); static final PERIOD = TokenFactory.tokenFromType(TokenType.PERIOD); static final PERIOD_PERIOD = TokenFactory.tokenFromType(TokenType.PERIOD_PERIOD); static final QUESTION = TokenFactory.tokenFromType(TokenType.QUESTION); static final REQUIRED = TokenFactory.tokenFromKeyword(Keyword.REQUIRED); static final RETHROW = TokenFactory.tokenFromKeyword(Keyword.RETHROW); static final RETURN = TokenFactory.tokenFromKeyword(Keyword.RETURN); static final SEMICOLON = TokenFactory.tokenFromType(TokenType.SEMICOLON); static final SET = TokenFactory.tokenFromKeyword(Keyword.SET); static final SHOW = TokenFactory.tokenFromKeyword(Keyword.SHOW); static final STAR = TokenFactory.tokenFromType(TokenType.STAR); static final STATIC = TokenFactory.tokenFromKeyword(Keyword.STATIC); static final STRING_INTERPOLATION_EXPRESSION = TokenFactory.tokenFromType(TokenType.STRING_INTERPOLATION_EXPRESSION); static final SUPER = TokenFactory.tokenFromKeyword(Keyword.SUPER); static final SWITCH = TokenFactory.tokenFromKeyword(Keyword.SWITCH); static final SYNC = TokenFactory.tokenFromKeyword(Keyword.SYNC); static final THIS = TokenFactory.tokenFromKeyword(Keyword.THIS); static final THROW = TokenFactory.tokenFromKeyword(Keyword.THROW); static final TRY = TokenFactory.tokenFromKeyword(Keyword.TRY); static final TYPEDEF = TokenFactory.tokenFromKeyword(Keyword.TYPEDEF); static final VAR = TokenFactory.tokenFromKeyword(Keyword.VAR); static final WITH = TokenFactory.tokenFromKeyword(Keyword.WITH); static final WHILE = TokenFactory.tokenFromKeyword(Keyword.WHILE); static final YIELD = TokenFactory.tokenFromKeyword(Keyword.YIELD); static Token choose(bool if1, Token then1, bool if2, Token then2, [bool if3, Token then3]) { if (if1) return then1; if (if2) return then2; if (if2 == true) return then3; return null; } static Token fromType(UnlinkedTokenType type) { return TokenFactory.tokenFromType( TokensContext.binaryToAstTokenType(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/summary2/ast_text_printer.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/source/line_info.dart'; /// AST visitor that prints tokens into their original positions. class AstTextPrinter extends ThrowingAstVisitor<void> { final StringBuffer _buffer; final LineInfo _lineInfo; Token _last; int _lastEnd = 0; int _lastEndLine = 0; AstTextPrinter(this._buffer, this._lineInfo); @override void visitAdjacentStrings(AdjacentStrings node) { _nodeList(node.strings); } @override void visitAnnotation(Annotation node) { _token(node.atSign); node.name.accept(this); _token(node.period); node.constructorName?.accept(this); node.arguments?.accept(this); } @override void visitArgumentList(ArgumentList node) { _token(node.leftParenthesis); _nodeList(node.arguments, node.rightParenthesis); _token(node.rightParenthesis); } @override void visitAsExpression(AsExpression node) { node.expression.accept(this); _token(node.asOperator); node.type.accept(this); } @override void visitAssertInitializer(AssertInitializer node) { _token(node.assertKeyword); _token(node.leftParenthesis); node.condition.accept(this); _tokenIfNot(node.condition.endToken.next, node.rightParenthesis); node.message?.accept(this); _tokenIfNot(node.message?.endToken?.next, node.rightParenthesis); _token(node.rightParenthesis); } @override void visitAssertStatement(AssertStatement node) { _token(node.assertKeyword); _token(node.leftParenthesis); node.condition.accept(this); _tokenIfNot(node.condition.endToken.next, node.rightParenthesis); node.message?.accept(this); _tokenIfNot(node.message?.endToken?.next, node.rightParenthesis); _token(node.rightParenthesis); _token(node.semicolon); } @override void visitAssignmentExpression(AssignmentExpression node) { node.leftHandSide.accept(this); _token(node.operator); node.rightHandSide.accept(this); } @override void visitAwaitExpression(AwaitExpression node) { _token(node.awaitKeyword); node.expression.accept(this); } @override void visitBinaryExpression(BinaryExpression node) { node.leftOperand.accept(this); _token(node.operator); node.rightOperand.accept(this); } @override void visitBlock(Block node) { _token(node.leftBracket); _nodeList(node.statements); _token(node.rightBracket); } @override void visitBlockFunctionBody(BlockFunctionBody node) { _functionBody(node); node.block.accept(this); } @override void visitBooleanLiteral(BooleanLiteral node) { _token(node.literal); } @override void visitBreakStatement(BreakStatement node) { _token(node.breakKeyword); node.label?.accept(this); _token(node.semicolon); } @override void visitCascadeExpression(CascadeExpression node) { node.target.accept(this); _nodeList(node.cascadeSections); } @override void visitCatchClause(CatchClause node) { _token(node.onKeyword); node.exceptionType?.accept(this); _token(node.catchKeyword); _token(node.leftParenthesis); node.exceptionParameter?.accept(this); _token(node.comma); node.stackTraceParameter?.accept(this); _token(node.rightParenthesis); node.body.accept(this); } @override void visitClassDeclaration(ClassDeclaration node) { _compilationUnitMember(node); _token(node.abstractKeyword); _token(node.classKeyword); node.name.accept(this); node.typeParameters?.accept(this); node.extendsClause?.accept(this); node.withClause?.accept(this); node.implementsClause?.accept(this); node.nativeClause?.accept(this); _token(node.leftBracket); node.members.accept(this); _token(node.rightBracket); } @override void visitClassTypeAlias(ClassTypeAlias node) { _compilationUnitMember(node); _token(node.abstractKeyword); _token(node.typedefKeyword); node.name.accept(this); node.typeParameters?.accept(this); _token(node.equals); node.superclass?.accept(this); node.withClause.accept(this); node.implementsClause?.accept(this); _token(node.semicolon); } @override void visitComment(Comment node) {} @override void visitCompilationUnit(CompilationUnit node) { node.scriptTag?.accept(this); node.directives.accept(this); node.declarations.accept(this); _token(node.endToken); } @override void visitConditionalExpression(ConditionalExpression node) { node.condition.accept(this); _token(node.question); node.thenExpression.accept(this); _token(node.colon); node.elseExpression.accept(this); } @override void visitConfiguration(Configuration node) { _token(node.ifKeyword); _token(node.leftParenthesis); node.name.accept(this); _token(node.equalToken); node.value?.accept(this); _token(node.rightParenthesis); node.uri.accept(this); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { _classMember(node); _token(node.externalKeyword); _token(node.constKeyword); _token(node.factoryKeyword); node.returnType?.accept(this); _token(node.period); node.name?.accept(this); node.parameters.accept(this); _token(node.separator); _nodeList(node.initializers, node.body.beginToken); node.redirectedConstructor?.accept(this); node.body.accept(this); } @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { _token(node.thisKeyword); _token(node.period); node.fieldName.accept(this); _token(node.equals); node.expression.accept(this); } @override void visitConstructorName(ConstructorName node) { node.type.accept(this); _token(node.period); node.name?.accept(this); } @override void visitContinueStatement(ContinueStatement node) { _token(node.continueKeyword); node.label?.accept(this); _token(node.semicolon); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { _declaration(node); _token(node.keyword); node.type?.accept(this); node.identifier.accept(this); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { node.parameter.accept(this); _token(node.separator); node.defaultValue?.accept(this); } @override void visitDoStatement(DoStatement node) { _token(node.doKeyword); node.body.accept(this); _token(node.whileKeyword); _token(node.leftParenthesis); node.condition.accept(this); _token(node.rightParenthesis); _token(node.semicolon); } @override void visitDottedName(DottedName node) { _nodeList(node.components, node.endToken.next); } @override void visitDoubleLiteral(DoubleLiteral node) { _token(node.literal); } @override void visitEmptyFunctionBody(EmptyFunctionBody node) { _functionBody(node); _token(node.semicolon); } @override void visitEmptyStatement(EmptyStatement node) { _token(node.semicolon); } @override void visitEnumConstantDeclaration(EnumConstantDeclaration node) { _declaration(node); node.name.accept(this); } @override void visitEnumDeclaration(EnumDeclaration node) { _compilationUnitMember(node); _token(node.enumKeyword); node.name.accept(this); _token(node.leftBracket); _nodeList(node.constants, node.rightBracket); _token(node.rightBracket); } @override void visitExportDirective(ExportDirective node) { _directive(node); _token(node.keyword); node.uri.accept(this); node.configurations?.accept(this); _nodeList(node.combinators); _token(node.semicolon); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { _functionBody(node); _token(node.functionDefinition); node.expression.accept(this); _token(node.semicolon); } @override void visitExpressionStatement(ExpressionStatement node) { node.expression.accept(this); _token(node.semicolon); } @override void visitExtendsClause(ExtendsClause node) { _token(node.extendsKeyword); node.superclass.accept(this); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { _compilationUnitMember(node); _token(node.extensionKeyword); node.name?.accept(this); node.typeParameters?.accept(this); _token(node.onKeyword); node.extendedType.accept(this); _token(node.leftBracket); node.members.accept(this); _token(node.rightBracket); } @override void visitExtensionOverride(ExtensionOverride node) { node.extensionName.accept(this); node.typeArguments.accept(this); node.argumentList.accept(this); } @override void visitFieldDeclaration(FieldDeclaration node) { _classMember(node); _token(node.staticKeyword); _token(node.covariantKeyword); node.fields.accept(this); _token(node.semicolon); } @override void visitFieldFormalParameter(FieldFormalParameter node) { _normalFormalParameter(node); _token(node.keyword); node.type?.accept(this); _token(node.thisKeyword); _token(node.period); node.identifier.accept(this); node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) { node.loopVariable.accept(this); _token(node.inKeyword); node.iterable.accept(this); } @override void visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) { node.identifier.accept(this); _token(node.inKeyword); node.iterable.accept(this); } @override void visitForElement(ForElement node) { _token(node.forKeyword); _token(node.leftParenthesis); node.forLoopParts.accept(this); _token(node.rightParenthesis); node.body.accept(this); } @override void visitFormalParameterList(FormalParameterList node) { _token(node.leftParenthesis); var parameters = node.parameters; for (var i = 0; i < parameters.length; ++i) { var parameter = parameters[i]; if (node.leftDelimiter?.next == parameter.beginToken) { _token(node.leftDelimiter); } parameter.accept(this); var itemSeparator = parameter.endToken.next; if (itemSeparator != node.rightParenthesis) { _token(itemSeparator); itemSeparator = itemSeparator.next; } if (itemSeparator == node.rightDelimiter) { _token(node.rightDelimiter); } } _token(node.rightParenthesis); } @override void visitForPartsWithDeclarations(ForPartsWithDeclarations node) { node.variables.accept(this); _token(node.leftSeparator); node.condition?.accept(this); _token(node.rightSeparator); _nodeList(node.updaters, node.endToken.next); } @override void visitForPartsWithExpression(ForPartsWithExpression node) { node.initialization?.accept(this); _token(node.leftSeparator); node.condition?.accept(this); _token(node.rightSeparator); _nodeList(node.updaters, node.updaters.endToken?.next); } @override void visitForStatement(ForStatement node) { _token(node.awaitKeyword); _token(node.forKeyword); _token(node.leftParenthesis); node.forLoopParts.accept(this); _token(node.rightParenthesis); node.body.accept(this); } @override void visitFunctionDeclaration(FunctionDeclaration node) { _compilationUnitMember(node); _token(node.externalKeyword); node.returnType?.accept(this); _token(node.propertyKeyword); node.name.accept(this); node.functionExpression.accept(this); } @override void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) { node.functionDeclaration.accept(this); } @override void visitFunctionExpression(FunctionExpression node) { node.typeParameters?.accept(this); node.parameters?.accept(this); node.body.accept(this); } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { node.function.accept(this); node.typeArguments?.accept(this); node.argumentList.accept(this); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { _compilationUnitMember(node); _token(node.typedefKeyword); node.returnType?.accept(this); node.name.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); _token(node.semicolon); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { _normalFormalParameter(node); node.returnType?.accept(this); node.identifier.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); _token(node.question); } @override void visitGenericFunctionType(GenericFunctionType node) { node.returnType?.accept(this); _token(node.functionKeyword); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitGenericTypeAlias(GenericTypeAlias node) { _compilationUnitMember(node); _token(node.typedefKeyword); node.name.accept(this); node.typeParameters?.accept(this); _token(node.equals); node.functionType.accept(this); _token(node.semicolon); } @override void visitHideCombinator(HideCombinator node) { _token(node.keyword); _nodeList(node.hiddenNames, node.endToken.next); } @override void visitIfElement(IfElement node) { _token(node.ifKeyword); _token(node.leftParenthesis); node.condition.accept(this); _token(node.rightParenthesis); node.thenElement.accept(this); _token(node.elseKeyword); node.elseElement?.accept(this); } @override void visitIfStatement(IfStatement node) { _token(node.ifKeyword); _token(node.leftParenthesis); node.condition.accept(this); _token(node.rightParenthesis); node.thenStatement.accept(this); _token(node.elseKeyword); node.elseStatement?.accept(this); } @override void visitImplementsClause(ImplementsClause node) { _token(node.implementsKeyword); _nodeList(node.interfaces, node.endToken.next); } @override void visitImportDirective(ImportDirective node) { _directive(node); _token(node.keyword); node.uri.accept(this); node.configurations?.accept(this); _token(node.deferredKeyword); _token(node.asKeyword); node.prefix?.accept(this); _nodeList(node.combinators); _token(node.semicolon); } @override void visitIndexExpression(IndexExpression node) { node.target?.accept(this); _token(node.period); _token(node.leftBracket); node.index.accept(this); _token(node.rightBracket); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { _token(node.keyword); node.constructorName.accept(this); node.argumentList.accept(this); } @override void visitIntegerLiteral(IntegerLiteral node) { _token(node.literal); } @override void visitInterpolationExpression(InterpolationExpression node) { _token(node.leftBracket); node.expression.accept(this); _token(node.rightBracket); } @override void visitInterpolationString(InterpolationString node) { _token(node.contents); } @override void visitIsExpression(IsExpression node) { node.expression.accept(this); _token(node.isOperator); _token(node.notOperator); node.type.accept(this); } @override void visitLabel(Label node) { node.label.accept(this); _token(node.colon); } @override void visitLabeledStatement(LabeledStatement node) { _nodeList(node.labels); node.statement.accept(this); } @override void visitLibraryDirective(LibraryDirective node) { _directive(node); _token(node.libraryKeyword); node.name.accept(this); _token(node.semicolon); } @override void visitLibraryIdentifier(LibraryIdentifier node) { _nodeList(node.components, node.endToken.next); } @override void visitListLiteral(ListLiteral node) { _typedLiteral(node); _token(node.leftBracket); _nodeList(node.elements, node.rightBracket); _token(node.rightBracket); } @override void visitMapLiteralEntry(MapLiteralEntry node) { node.key.accept(this); _token(node.separator); node.value.accept(this); } @override void visitMethodDeclaration(MethodDeclaration node) { _classMember(node); _token(node.externalKeyword); _token(node.modifierKeyword); node.returnType?.accept(this); _token(node.propertyKeyword); _token(node.operatorKeyword); node.name.accept(this); node.typeParameters?.accept(this); node.parameters?.accept(this); node.body?.accept(this); } @override void visitMethodInvocation(MethodInvocation node) { node.target?.accept(this); _token(node.operator); node.methodName.accept(this); node.typeArguments?.accept(this); node.argumentList.accept(this); } @override void visitMixinDeclaration(MixinDeclaration node) { _compilationUnitMember(node); _token(node.mixinKeyword); node.name.accept(this); node.typeParameters?.accept(this); node.onClause?.accept(this); node.implementsClause?.accept(this); _token(node.leftBracket); node.members.accept(this); _token(node.rightBracket); } @override void visitNamedExpression(NamedExpression node) { node.name.accept(this); node.expression.accept(this); } @override void visitNativeClause(NativeClause node) { _token(node.nativeKeyword); node.name.accept(this); } @override void visitNativeFunctionBody(NativeFunctionBody node) { _token(node.nativeKeyword); node.stringLiteral?.accept(this); _token(node.semicolon); } @override void visitNullLiteral(NullLiteral node) { _token(node.literal); } @override void visitOnClause(OnClause node) { _token(node.onKeyword); _nodeList(node.superclassConstraints, node.endToken.next); } @override void visitParenthesizedExpression(ParenthesizedExpression node) { _token(node.leftParenthesis); node.expression.accept(this); _token(node.rightParenthesis); } @override void visitPartDirective(PartDirective node) { _directive(node); _token(node.partKeyword); node.uri.accept(this); _token(node.semicolon); } @override void visitPartOfDirective(PartOfDirective node) { _directive(node); _token(node.partKeyword); _token(node.ofKeyword); node.uri?.accept(this); node.libraryName?.accept(this); _token(node.semicolon); } @override void visitPostfixExpression(PostfixExpression node) { node.operand.accept(this); _token(node.operator); } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { node.prefix.accept(this); _token(node.period); node.identifier.accept(this); } @override void visitPrefixExpression(PrefixExpression node) { _token(node.operator); node.operand.accept(this); } @override void visitPropertyAccess(PropertyAccess node) { node.target?.accept(this); _token(node.operator); node.propertyName.accept(this); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { _token(node.thisKeyword); _token(node.period); node.constructorName?.accept(this); node.argumentList.accept(this); } @override void visitRethrowExpression(RethrowExpression node) { _token(node.rethrowKeyword); } @override void visitReturnStatement(ReturnStatement node) { _token(node.returnKeyword); node.expression?.accept(this); _token(node.semicolon); } @override void visitScriptTag(ScriptTag node) { _token(node.scriptTag); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { _typedLiteral(node); _token(node.leftBracket); _nodeList(node.elements, node.rightBracket); _token(node.rightBracket); } @override void visitShowCombinator(ShowCombinator node) { _token(node.keyword); _nodeList(node.shownNames, node.endToken.next); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { _normalFormalParameter(node); _token(node.keyword); node.type?.accept(this); node.identifier?.accept(this); } @override void visitSimpleIdentifier(SimpleIdentifier node) { _token(node.token); } @override void visitSimpleStringLiteral(SimpleStringLiteral node) { _token(node.literal); } @override void visitSpreadElement(SpreadElement node) { _token(node.spreadOperator); node.expression.accept(this); } @override void visitStringInterpolation(StringInterpolation node) { _nodeList(node.elements); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { _token(node.superKeyword); _token(node.period); node.constructorName?.accept(this); node.argumentList.accept(this); } @override void visitSuperExpression(SuperExpression node) { _token(node.superKeyword); } @override void visitSwitchCase(SwitchCase node) { _nodeList(node.labels); _token(node.keyword); node.expression.accept(this); _token(node.colon); _nodeList(node.statements); } @override void visitSwitchDefault(SwitchDefault node) { _nodeList(node.labels); _token(node.keyword); _token(node.colon); _nodeList(node.statements); } @override void visitSwitchStatement(SwitchStatement node) { _token(node.switchKeyword); _token(node.leftParenthesis); node.expression.accept(this); _token(node.rightParenthesis); _token(node.leftBracket); _nodeList(node.members); _token(node.rightBracket); } @override void visitSymbolLiteral(SymbolLiteral node) { _token(node.poundSign); var components = node.components; for (var i = 0; i < components.length; ++i) { var component = components[i]; _token(component); if (i != components.length - 1) { _token(component.next); } } } @override void visitThisExpression(ThisExpression node) { _token(node.thisKeyword); } @override void visitThrowExpression(ThrowExpression node) { _token(node.throwKeyword); node.expression.accept(this); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { _compilationUnitMember(node); node.variables.accept(this); _token(node.semicolon); } @override void visitTryStatement(TryStatement node) { _token(node.tryKeyword); node.body.accept(this); _nodeList(node.catchClauses); _token(node.finallyKeyword); node.finallyBlock?.accept(this); } @override void visitTypeArgumentList(TypeArgumentList node) { _token(node.leftBracket); _nodeList(node.arguments, node.rightBracket); _token(node.rightBracket); } @override void visitTypeName(TypeName node) { node.name.accept(this); node.typeArguments?.accept(this); } @override void visitTypeParameter(TypeParameter node) { _declaration(node); node.name?.accept(this); _token(node.extendsKeyword); node.bound?.accept(this); } @override void visitTypeParameterList(TypeParameterList node) { _token(node.leftBracket); _nodeList(node.typeParameters, node.rightBracket); _token(node.rightBracket); } @override void visitVariableDeclaration(VariableDeclaration node) { _annotatedNode(node); node.name.accept(this); _token(node.equals); node.initializer?.accept(this); } @override void visitVariableDeclarationList(VariableDeclarationList node) { _annotatedNode(node); _token(node.keyword); node.type?.accept(this); _nodeList(node.variables, node.endToken.next); } @override void visitVariableDeclarationStatement(VariableDeclarationStatement node) { node.variables.accept(this); _token(node.semicolon); } @override void visitWhileStatement(WhileStatement node) { _token(node.whileKeyword); _token(node.leftParenthesis); node.condition.accept(this); _token(node.rightParenthesis); node.body.accept(this); } @override void visitWithClause(WithClause node) { _token(node.withKeyword); _nodeList(node.mixinTypes, node.endToken.next); } @override void visitYieldStatement(YieldStatement node) { _token(node.yieldKeyword); _token(node.star); node.expression.accept(this); _token(node.semicolon); } void _annotatedNode(AnnotatedNode node) { node.documentationComment?.accept(this); _nodeList(node.metadata); } void _classMember(ClassMember node) { _declaration(node); } void _compilationUnitMember(CompilationUnitMember node) { _declaration(node); } void _declaration(Declaration node) { _annotatedNode(node); } void _directive(Directive node) { _annotatedNode(node); } void _functionBody(FunctionBody node) { _token(node.keyword); _token(node.star); } /// Print nodes from the [nodeList]. /// /// If the [endToken] is not `null`, print one token after every node, /// unless it is the [endToken]. void _nodeList(List<AstNode> nodeList, [Token endToken]) { var length = nodeList.length; for (var i = 0; i < length; ++i) { var node = nodeList[i]; node.accept(this); if (endToken != null && node.endToken.next != endToken) { _token(node.endToken.next); } } } void _normalFormalParameter(NormalFormalParameter node) { node.documentationComment?.accept(this); _nodeList(node.metadata); _token(node.covariantKeyword); } void _token(Token token) { if (token == null) return; if (_last != null) { if (_last.next != token) { throw StateError( '|$_last| must be followed by |${_last.next}|, got |$token|', ); } } // Print preceding comments as a separate sequence of tokens. if (token.precedingComments != null) { var lastToken = _last; _last = null; for (var c = token.precedingComments; c != null; c = c.next) { _token(c); } _last = lastToken; } for (var offset = _lastEnd; offset < token.offset; offset++) { var offsetLocation = _lineInfo.getLocation(offset + 1); var offsetLine = offsetLocation.lineNumber - 1; if (offsetLine == _lastEndLine) { _buffer.write(' '); } else { _buffer.write('\n'); _lastEndLine++; } } _buffer.write(token.lexeme); _last = token; _lastEnd = token.end; var endLocation = _lineInfo.getLocation(token.end); _lastEndLine = endLocation.lineNumber - 1; } void _tokenIfNot(Token maybe, Token ifNot) { if (maybe == null) return; if (maybe == ifNot) return; _token(maybe); } _typedLiteral(TypedLiteral node) { _token(node.constKeyword); node.typeArguments?.accept(this); } }
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/summary2/tokens_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/token.dart'; import 'package:analyzer/src/summary/idl.dart'; /// The context for reading tokens. class TokensContext { static TokenType binaryToAstTokenType(UnlinkedTokenType type) { switch (type) { case UnlinkedTokenType.ABSTRACT: return Keyword.ABSTRACT; case UnlinkedTokenType.AMPERSAND: return TokenType.AMPERSAND; case UnlinkedTokenType.AMPERSAND_AMPERSAND: return TokenType.AMPERSAND_AMPERSAND; case UnlinkedTokenType.AMPERSAND_EQ: return TokenType.AMPERSAND_EQ; case UnlinkedTokenType.AS: return TokenType.AS; case UnlinkedTokenType.ASSERT: return Keyword.ASSERT; case UnlinkedTokenType.ASYNC: return Keyword.ASYNC; case UnlinkedTokenType.AT: return TokenType.AT; case UnlinkedTokenType.AWAIT: return Keyword.AWAIT; case UnlinkedTokenType.BACKPING: return TokenType.BACKPING; case UnlinkedTokenType.BACKSLASH: return TokenType.BACKSLASH; case UnlinkedTokenType.BANG: return TokenType.BANG; case UnlinkedTokenType.BANG_EQ: return TokenType.BANG_EQ; case UnlinkedTokenType.BANG_EQ_EQ: return TokenType.BANG_EQ_EQ; case UnlinkedTokenType.BAR: return TokenType.BAR; case UnlinkedTokenType.BAR_BAR: return TokenType.BAR_BAR; case UnlinkedTokenType.BAR_EQ: return TokenType.BAR_EQ; case UnlinkedTokenType.BREAK: return Keyword.BREAK; case UnlinkedTokenType.CARET: return TokenType.CARET; case UnlinkedTokenType.CARET_EQ: return TokenType.CARET_EQ; case UnlinkedTokenType.CASE: return Keyword.CASE; case UnlinkedTokenType.CATCH: return Keyword.CATCH; case UnlinkedTokenType.CLASS: return Keyword.CLASS; case UnlinkedTokenType.CLOSE_CURLY_BRACKET: return TokenType.CLOSE_CURLY_BRACKET; case UnlinkedTokenType.CLOSE_PAREN: return TokenType.CLOSE_PAREN; case UnlinkedTokenType.CLOSE_SQUARE_BRACKET: return TokenType.CLOSE_SQUARE_BRACKET; case UnlinkedTokenType.COLON: return TokenType.COLON; case UnlinkedTokenType.COMMA: return TokenType.COMMA; case UnlinkedTokenType.CONST: return Keyword.CONST; case UnlinkedTokenType.CONTINUE: return Keyword.CONTINUE; case UnlinkedTokenType.COVARIANT: return Keyword.COVARIANT; case UnlinkedTokenType.DEFAULT: return Keyword.DEFAULT; case UnlinkedTokenType.DEFERRED: return Keyword.DEFERRED; case UnlinkedTokenType.DO: return Keyword.DO; case UnlinkedTokenType.DOUBLE: return TokenType.DOUBLE; case UnlinkedTokenType.DYNAMIC: return Keyword.DYNAMIC; case UnlinkedTokenType.ELSE: return Keyword.ELSE; case UnlinkedTokenType.ENUM: return Keyword.ENUM; case UnlinkedTokenType.EOF: return TokenType.EOF; case UnlinkedTokenType.EQ: return TokenType.EQ; case UnlinkedTokenType.EQ_EQ: return TokenType.EQ_EQ; case UnlinkedTokenType.EQ_EQ_EQ: return TokenType.EQ_EQ_EQ; case UnlinkedTokenType.EXPORT: return Keyword.EXPORT; case UnlinkedTokenType.EXTENDS: return Keyword.EXTENDS; case UnlinkedTokenType.EXTERNAL: return Keyword.EXTERNAL; case UnlinkedTokenType.FACTORY: return Keyword.FACTORY; case UnlinkedTokenType.FALSE: return Keyword.FALSE; case UnlinkedTokenType.FINAL: return Keyword.FINAL; case UnlinkedTokenType.FINALLY: return Keyword.FINALLY; case UnlinkedTokenType.FOR: return Keyword.FOR; case UnlinkedTokenType.FUNCTION: return TokenType.FUNCTION; case UnlinkedTokenType.FUNCTION_KEYWORD: return Keyword.FUNCTION; case UnlinkedTokenType.GET: return Keyword.GET; case UnlinkedTokenType.GT: return TokenType.GT; case UnlinkedTokenType.GT_EQ: return TokenType.GT_EQ; case UnlinkedTokenType.GT_GT: return TokenType.GT_GT; case UnlinkedTokenType.GT_GT_EQ: return TokenType.GT_GT_EQ; case UnlinkedTokenType.GT_GT_GT: return TokenType.GT_GT_GT; case UnlinkedTokenType.GT_GT_GT_EQ: return TokenType.GT_GT_GT_EQ; case UnlinkedTokenType.HASH: return TokenType.HASH; case UnlinkedTokenType.HEXADECIMAL: return TokenType.HEXADECIMAL; case UnlinkedTokenType.HIDE: return Keyword.HIDE; case UnlinkedTokenType.IDENTIFIER: return TokenType.IDENTIFIER; case UnlinkedTokenType.IF: return Keyword.IF; case UnlinkedTokenType.IMPLEMENTS: return Keyword.IMPLEMENTS; case UnlinkedTokenType.IMPORT: return Keyword.IMPORT; case UnlinkedTokenType.IN: return Keyword.IN; case UnlinkedTokenType.INDEX: return TokenType.INDEX; case UnlinkedTokenType.INDEX_EQ: return TokenType.INDEX_EQ; case UnlinkedTokenType.INT: return TokenType.INT; case UnlinkedTokenType.INTERFACE: return Keyword.INTERFACE; case UnlinkedTokenType.IS: return TokenType.IS; case UnlinkedTokenType.LATE: return Keyword.LATE; case UnlinkedTokenType.LIBRARY: return Keyword.LIBRARY; case UnlinkedTokenType.LT: return TokenType.LT; case UnlinkedTokenType.LT_EQ: return TokenType.LT_EQ; case UnlinkedTokenType.LT_LT: return TokenType.LT_LT; case UnlinkedTokenType.LT_LT_EQ: return TokenType.LT_LT_EQ; case UnlinkedTokenType.MINUS: return TokenType.MINUS; case UnlinkedTokenType.MINUS_EQ: return TokenType.MINUS_EQ; case UnlinkedTokenType.MINUS_MINUS: return TokenType.MINUS_MINUS; case UnlinkedTokenType.MIXIN: return Keyword.MIXIN; case UnlinkedTokenType.MULTI_LINE_COMMENT: return TokenType.MULTI_LINE_COMMENT; case UnlinkedTokenType.NATIVE: return Keyword.NATIVE; case UnlinkedTokenType.NEW: return Keyword.NEW; case UnlinkedTokenType.NULL: return Keyword.NULL; case UnlinkedTokenType.OF: return Keyword.OF; case UnlinkedTokenType.ON: return Keyword.ON; case UnlinkedTokenType.OPEN_CURLY_BRACKET: return TokenType.OPEN_CURLY_BRACKET; case UnlinkedTokenType.OPEN_PAREN: return TokenType.OPEN_PAREN; case UnlinkedTokenType.OPEN_SQUARE_BRACKET: return TokenType.OPEN_SQUARE_BRACKET; case UnlinkedTokenType.OPERATOR: return Keyword.OPERATOR; case UnlinkedTokenType.PART: return Keyword.PART; case UnlinkedTokenType.PATCH: return Keyword.PATCH; case UnlinkedTokenType.PERCENT: return TokenType.PERCENT; case UnlinkedTokenType.PERCENT_EQ: return TokenType.PERCENT_EQ; case UnlinkedTokenType.PERIOD: return TokenType.PERIOD; case UnlinkedTokenType.PERIOD_PERIOD: return TokenType.PERIOD_PERIOD; case UnlinkedTokenType.PERIOD_PERIOD_PERIOD: return TokenType.PERIOD_PERIOD_PERIOD; case UnlinkedTokenType.PERIOD_PERIOD_PERIOD_QUESTION: return TokenType.PERIOD_PERIOD_PERIOD_QUESTION; case UnlinkedTokenType.PLUS: return TokenType.PLUS; case UnlinkedTokenType.PLUS_EQ: return TokenType.PLUS_EQ; case UnlinkedTokenType.PLUS_PLUS: return TokenType.PLUS_PLUS; case UnlinkedTokenType.QUESTION: return TokenType.QUESTION; case UnlinkedTokenType.QUESTION_PERIOD: return TokenType.QUESTION_PERIOD; case UnlinkedTokenType.QUESTION_QUESTION: return TokenType.QUESTION_QUESTION; case UnlinkedTokenType.QUESTION_QUESTION_EQ: return TokenType.QUESTION_QUESTION_EQ; case UnlinkedTokenType.REQUIRED: return Keyword.REQUIRED; case UnlinkedTokenType.RETHROW: return Keyword.RETHROW; case UnlinkedTokenType.RETURN: return Keyword.RETURN; case UnlinkedTokenType.SCRIPT_TAG: return TokenType.SCRIPT_TAG; case UnlinkedTokenType.SEMICOLON: return TokenType.SEMICOLON; case UnlinkedTokenType.SET: return Keyword.SET; case UnlinkedTokenType.SHOW: return Keyword.SHOW; case UnlinkedTokenType.SINGLE_LINE_COMMENT: return TokenType.SINGLE_LINE_COMMENT; case UnlinkedTokenType.SLASH: return TokenType.SLASH; case UnlinkedTokenType.SLASH_EQ: return TokenType.SLASH_EQ; case UnlinkedTokenType.SOURCE: return Keyword.SOURCE; case UnlinkedTokenType.STAR: return TokenType.STAR; case UnlinkedTokenType.STAR_EQ: return TokenType.STAR_EQ; case UnlinkedTokenType.STATIC: return Keyword.STATIC; case UnlinkedTokenType.STRING: return TokenType.STRING; case UnlinkedTokenType.STRING_INTERPOLATION_EXPRESSION: return TokenType.STRING_INTERPOLATION_EXPRESSION; case UnlinkedTokenType.STRING_INTERPOLATION_IDENTIFIER: return TokenType.STRING_INTERPOLATION_IDENTIFIER; case UnlinkedTokenType.SUPER: return Keyword.SUPER; case UnlinkedTokenType.SWITCH: return Keyword.SWITCH; case UnlinkedTokenType.SYNC: return Keyword.SYNC; case UnlinkedTokenType.THIS: return Keyword.THIS; case UnlinkedTokenType.THROW: return Keyword.THROW; case UnlinkedTokenType.TILDE: return TokenType.TILDE; case UnlinkedTokenType.TILDE_SLASH: return TokenType.TILDE_SLASH; case UnlinkedTokenType.TILDE_SLASH_EQ: return TokenType.TILDE_SLASH_EQ; case UnlinkedTokenType.TRUE: return Keyword.TRUE; case UnlinkedTokenType.TRY: return Keyword.TRY; case UnlinkedTokenType.TYPEDEF: return Keyword.TYPEDEF; case UnlinkedTokenType.VAR: return Keyword.VAR; case UnlinkedTokenType.VOID: return Keyword.VOID; case UnlinkedTokenType.WHILE: return Keyword.WHILE; case UnlinkedTokenType.WITH: return Keyword.WITH; case UnlinkedTokenType.YIELD: return Keyword.YIELD; default: throw StateError('Unexpected type: $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/summary2/top_level_inference.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/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/builder.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary/link.dart' as graph show DependencyWalker, Node; import 'package:analyzer/src/summary2/ast_resolver.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/link.dart'; import 'package:analyzer/src/summary2/linking_node_scope.dart'; import 'package:analyzer/src/task/strong_mode.dart'; DartType _dynamicIfNull(DartType type) { if (type == null || type.isBottom || type.isDartCoreNull) { return DynamicTypeImpl.instance; } return type; } AstNode _getLinkedNode(Element element) { return (element as ElementImpl).linkedNode; } /// Resolver for typed constant top-level variables and fields initializers. /// /// Initializers of untyped variables are resolved during [TopLevelInference]. class ConstantInitializersResolver { final Linker linker; LibraryElement _library; bool _enclosingClassHasConstConstructor = false; Scope _scope; ConstantInitializersResolver(this.linker); void perform() { for (var builder in linker.builders.values) { _library = builder.element; for (var unit in _library.units) { unit.extensions.forEach(_resolveExtensionFields); unit.mixins.forEach(_resolveClassFields); unit.types.forEach(_resolveClassFields); _scope = builder.scope; unit.topLevelVariables.forEach(_resolveVariable); } } } void _resolveClassFields(ClassElement class_) { _enclosingClassHasConstConstructor = class_.constructors.any((c) => c.isConst); var node = _getLinkedNode(class_); _scope = LinkingNodeContext.get(node).scope; for (var element in class_.fields) { _resolveVariable(element); } _enclosingClassHasConstConstructor = false; } void _resolveExtensionFields(ExtensionElement extension_) { var node = _getLinkedNode(extension_); _scope = LinkingNodeContext.get(node).scope; for (var element in extension_.fields) { _resolveVariable(element); } } void _resolveVariable(VariableElement element) { if (element.isSynthetic) return; VariableDeclaration variable = _getLinkedNode(element); if (variable.initializer == null) return; VariableDeclarationList declarationList = variable.parent; var typeNode = declarationList.type; if (typeNode != null) { if (declarationList.isConst || declarationList.isFinal && _enclosingClassHasConstConstructor) { var holder = ElementHolder(); variable.initializer.accept(LocalElementBuilder(holder, null)); (element as VariableElementImpl).encloseElements(holder.functions); var astResolver = AstResolver(linker, _library, _scope); astResolver.rewriteAst(variable.initializer); InferenceContext.setType(variable.initializer, typeNode.type); astResolver.resolve(variable.initializer); } } } } class TopLevelInference { final Linker linker; TopLevelInference(this.linker); void infer() { var initializerInference = _InitializerInference(linker); initializerInference.createNodes(); _performOverrideInference(); initializerInference.perform(); } void _performOverrideInference() { var inferrer = new InstanceMemberInferrer( linker.typeProvider, linker.inheritance, ); for (var builder in linker.builders.values) { for (var unit in builder.element.units) { inferrer.inferCompilationUnit(unit); } } } } class _ConstructorInferenceNode extends _InferenceNode { final _InferenceWalker _walker; final ConstructorElement _constructor; /// The parameters that have types from [_fields]. final List<FieldFormalParameter> _parameters = []; /// The parallel list of fields corresponding to [_parameters]. final List<FieldElement> _fields = []; @override bool isEvaluated = false; _ConstructorInferenceNode( this._walker, this._constructor, Map<String, FieldElement> fieldMap, ) { for (var parameterElement in _constructor.parameters) { if (parameterElement is FieldFormalParameterElement) { var parameterNode = _getLinkedNode(parameterElement); if (parameterNode is DefaultFormalParameter) { var defaultParameter = parameterNode as DefaultFormalParameter; parameterNode = defaultParameter.parameter; } if (parameterNode is FieldFormalParameter && parameterNode.type == null && parameterNode.parameters == null) { parameterNode.identifier.staticElement = parameterElement; var name = parameterNode.identifier.name; var fieldElement = fieldMap[name]; if (fieldElement != null) { _parameters.add(parameterNode); _fields.add(fieldElement); } else { LazyAst.setType(parameterNode, DynamicTypeImpl.instance); } } } } } @override String get displayName => '$_constructor'; @override List<_InferenceNode> computeDependencies() { return _fields.map(_walker.getNode).where((node) => node != null).toList(); } @override void evaluate() { for (var i = 0; i < _parameters.length; ++i) { var parameter = _parameters[i]; var type = _fields[i].type; LazyAst.setType(parameter, type); (parameter.declaredElement as ParameterElementImpl).type = type; } isEvaluated = true; } @override void markCircular(List<_InferenceNode> cycle) { for (var i = 0; i < _parameters.length; ++i) { var parameterNode = _parameters[i]; LazyAst.setType(parameterNode, DynamicTypeImpl.instance); } isEvaluated = true; } } class _FunctionElementForLink_Initializer implements FunctionElementImpl { final _VariableInferenceNode _node; @override Element enclosingElement; _FunctionElementForLink_Initializer(this._node); @override DartType get returnType { if (!_node.isEvaluated) { _node._walker.walk(_node); } return LazyAst.getType(_node._node); } noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class _InferenceDependenciesCollector extends RecursiveAstVisitor<void> { final Set<Element> _set = Set.identity(); @override void visitInstanceCreationExpression(InstanceCreationExpression node) { var element = node.staticElement; if (element == null) return; if (element is ConstructorMember) { element = (element as ConstructorMember).baseElement; } _set.add(element); if (element.enclosingElement.typeParameters.isNotEmpty) { node.argumentList.accept(this); } } @override void visitSimpleIdentifier(SimpleIdentifier node) { var element = node.staticElement; if (element is PropertyAccessorElement && element.isGetter) { _set.add(element.variable); } } } abstract class _InferenceNode extends graph.Node<_InferenceNode> { String get displayName; void evaluate(); void markCircular(List<_InferenceNode> cycle); } class _InferenceWalker extends graph.DependencyWalker<_InferenceNode> { final Linker _linker; final Map<Element, _InferenceNode> _nodes = Map.identity(); _InferenceWalker(this._linker); @override void evaluate(_InferenceNode v) { v.evaluate(); } @override void evaluateScc(List<_InferenceNode> scc) { for (var node in scc) { node.markCircular(scc); } } _InferenceNode getNode(Element element) { return _nodes[element]; } void walkNodes() { for (var node in _nodes.values) { if (!node.isEvaluated) { walk(node); } } } } class _InitializerInference { final Linker _linker; final _InferenceWalker _walker; LibraryElement _library; Scope _scope; _InitializerInference(this._linker) : _walker = _InferenceWalker(_linker); void createNodes() { for (var builder in _linker.builders.values) { _library = builder.element; for (var unit in _library.units) { unit.extensions.forEach(_addExtensionElementFields); unit.mixins.forEach(_addClassElementFields); unit.types.forEach(_addClassConstructorFieldFormals); unit.types.forEach(_addClassElementFields); _scope = builder.scope; for (var element in unit.topLevelVariables) { _addVariableNode(element); } } } } void perform() { _walker.walkNodes(); } void _addClassConstructorFieldFormals(ClassElement class_) { var fieldMap = <String, FieldElement>{}; for (var field in class_.fields) { if (field.isStatic) continue; if (field.isSynthetic) continue; fieldMap[field.name] ??= field; } for (var constructor in class_.constructors) { var inferenceNode = _ConstructorInferenceNode(_walker, constructor, fieldMap); _walker._nodes[constructor] = inferenceNode; } } void _addClassElementFields(ClassElement class_) { var node = _getLinkedNode(class_); _scope = LinkingNodeContext.get(node).scope; for (var element in class_.fields) { _addVariableNode(element); } } void _addExtensionElementFields(ExtensionElement extension_) { var node = _getLinkedNode(extension_); _scope = LinkingNodeContext.get(node).scope; for (var element in extension_.fields) { _addVariableNode(element); } } void _addVariableNode(PropertyInducingElement element) { if (element.isSynthetic) return; VariableDeclaration node = _getLinkedNode(element); if (LazyAst.getType(node) != null) return; if (node.initializer != null) { var inferenceNode = _VariableInferenceNode(_walker, _library, _scope, element, node); _walker._nodes[element] = inferenceNode; (element as PropertyInducingElementImpl).initializer = _FunctionElementForLink_Initializer(inferenceNode); } else { LazyAst.setType(node, DynamicTypeImpl.instance); } } } class _VariableInferenceNode extends _InferenceNode { final _InferenceWalker _walker; final LibraryElement _library; final Scope _scope; final PropertyInducingElementImpl _element; final VariableDeclaration _node; @override bool isEvaluated = false; _VariableInferenceNode( this._walker, this._library, this._scope, this._element, this._node, ); @override String get displayName { return _node.name.name; } bool get isImplicitlyTypedInstanceField { VariableDeclarationList variables = _node.parent; if (variables.type == null) { var parent = variables.parent; return parent is FieldDeclaration && !parent.isStatic; } return false; } @override List<_InferenceNode> computeDependencies() { _buildLocalElements(); _resolveInitializer(); var collector = _InferenceDependenciesCollector(); _node.initializer.accept(collector); if (collector._set.isEmpty) { return const <_InferenceNode>[]; } var dependencies = collector._set .map(_walker.getNode) .where((node) => node != null) .toList(); for (var node in dependencies) { if (node is _VariableInferenceNode && node.isImplicitlyTypedInstanceField) { LazyAst.setType(_node, DynamicTypeImpl.instance); isEvaluated = true; return const <_InferenceNode>[]; } } return dependencies; } @override void evaluate() { _resolveInitializer(); if (LazyAst.getType(_node) == null) { var initializerType = _node.initializer.staticType; initializerType = _dynamicIfNull(initializerType); LazyAst.setType(_node, initializerType); } isEvaluated = true; } @override void markCircular(List<_InferenceNode> cycle) { LazyAst.setType(_node, DynamicTypeImpl.instance); var cycleNames = Set<String>(); for (var inferenceNode in cycle) { cycleNames.add(inferenceNode.displayName); } LazyAst.setTypeInferenceError( _node, TopLevelInferenceErrorBuilder( kind: TopLevelInferenceErrorKind.dependencyCycle, arguments: cycleNames.toList(), ), ); isEvaluated = true; } void _buildLocalElements() { var holder = ElementHolder(); _node.initializer.accept(LocalElementBuilder(holder, null)); _element.encloseElements(holder.functions); } void _resolveInitializer() { var astResolver = AstResolver(_walker._linker, _library, _scope); astResolver.rewriteAst(_node.initializer); astResolver.resolve(_node.initializer); } }
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/summary2/metadata_resolver.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/element/element.dart'; import 'package:analyzer/src/dart/element/builder.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/summary2/ast_resolver.dart'; import 'package:analyzer/src/summary2/link.dart'; import 'package:analyzer/src/summary2/linking_node_scope.dart'; class MetadataResolver extends ThrowingAstVisitor<void> { final Linker _linker; final LibraryElement _libraryElement; final Scope _libraryScope; final CompilationUnitElement _unitElement; Scope _scope; MetadataResolver( this._linker, this._libraryElement, this._libraryScope, this._unitElement) : _scope = _libraryScope; @override void visitAnnotation(Annotation node) { node.elementAnnotation = ElementAnnotationImpl(_unitElement); var holder = ElementHolder(); node.accept(LocalElementBuilder(holder, null)); var astResolver = AstResolver(_linker, _libraryElement, _scope); astResolver.rewriteAst(node); astResolver.resolve(node); } @override void visitClassDeclaration(ClassDeclaration node) { node.metadata.accept(this); node.typeParameters?.accept(this); _scope = LinkingNodeContext.get(node).scope; try { node.members.accept(this); } finally { _scope = _libraryScope; } } @override void visitClassTypeAlias(ClassTypeAlias node) { node.metadata.accept(this); node.typeParameters?.accept(this); } @override void visitCompilationUnit(CompilationUnit node) { node.directives.accept(this); node.declarations.accept(this); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { node.metadata.accept(this); node.parameters.accept(this); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { node.parameter.accept(this); } @override void visitEnumConstantDeclaration(EnumConstantDeclaration node) { node.metadata.accept(this); } @override void visitEnumDeclaration(EnumDeclaration node) { node.metadata.accept(this); node.constants.accept(this); } @override void visitExportDirective(ExportDirective node) { node.metadata.accept(this); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { node.metadata.accept(this); node.typeParameters?.accept(this); _scope = LinkingNodeContext.get(node).scope; try { node.members.accept(this); } finally { _scope = _libraryScope; } } @override void visitFieldDeclaration(FieldDeclaration node) { node.metadata.accept(this); } @override void visitFieldFormalParameter(FieldFormalParameter node) { node.metadata.accept(this); node.parameters?.accept(this); } @override void visitFormalParameterList(FormalParameterList node) { node.parameters.accept(this); } @override void visitFunctionDeclaration(FunctionDeclaration node) { node.metadata.accept(this); node.functionExpression.accept(this); } @override void visitFunctionExpression(FunctionExpression node) { node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { node.metadata.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { node.metadata.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitGenericFunctionType(GenericFunctionType node) { node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitGenericTypeAlias(GenericTypeAlias node) { node.metadata.accept(this); node.typeParameters?.accept(this); node.functionType?.accept(this); } @override void visitImportDirective(ImportDirective node) { node.metadata.accept(this); } @override void visitLibraryDirective(LibraryDirective node) { node.metadata.accept(this); } @override void visitMethodDeclaration(MethodDeclaration node) { node.metadata.accept(this); node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitMixinDeclaration(MixinDeclaration node) { node.metadata.accept(this); node.typeParameters?.accept(this); _scope = LinkingNodeContext.get(node).scope; try { node.members.accept(this); } finally { _scope = _libraryScope; } } @override void visitPartDirective(PartDirective node) { node.metadata.accept(this); } @override void visitPartOfDirective(PartOfDirective node) { node.metadata.accept(this); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { node.metadata.accept(this); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { node.metadata.accept(this); } @override void visitTypeParameter(TypeParameter node) { node.metadata.accept(this); } @override void visitTypeParameterList(TypeParameterList node) { node.typeParameters.accept(this); } }
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/summary2/linking_node_scope.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/src/generated/resolver.dart'; /// This class provides access to [Scope]s corresponding to [AstNode]s. class LinkingNodeContext { static const _key = 'linkingNodeContext'; final Scope scope; LinkingNodeContext(AstNode node, this.scope) { node.setProperty(_key, this); } static LinkingNodeContext get(AstNode node) { LinkingNodeContext context = node.getProperty(_key); if (context == null) { throw StateError('No context for: $node'); } 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/summary2/reference.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/src/summary2/scope.dart'; /// Indirection between a name and the corresponding [Element]. /// /// References are organized in a prefix tree. /// Each reference knows its parent, children, and the [Element]. /// /// Library: /// URI of library /// /// Class: /// Reference of the enclosing library /// "@class" /// Name of the class /// /// Method: /// Reference of the enclosing class /// "@method" /// Name of the method /// /// There is only one reference object per [Element]. class Reference { /// The parent of this reference, or `null` if the root. final Reference parent; /// The simple name of the reference in its [parent]. final String name; /// The corresponding [AstNode], or `null` if a named container. AstNode node; /// The corresponding [Element], or `null` if a named container. Element element; /// Temporary index used during serialization and linking. int index; Map<String, Reference> _children; /// If this reference is an import prefix, the scope of this prefix. Scope prefixScope; Reference.root() : this._(null, ''); Reference._(this.parent, this.name); Iterable<Reference> get children { if (_children != null) { return _children.values; } return const []; } bool get isClass => parent != null && parent.name == '@class'; bool get isDynamic => name == 'dynamic' && parent?.name == 'dart:core'; bool get isEnum => parent != null && parent.name == '@enum'; bool get isPrefix => parent != null && parent.name == '@prefix'; bool get isSetter => parent != null && parent.name == '@setter'; bool get isTypeAlias => parent != null && parent.name == '@typeAlias'; /// Return the child with the given name, or `null` if does not exist. Reference operator [](String name) { return _children != null ? _children[name] : null; } /// Return the child with the given name, create if does not exist yet. Reference getChild(String name) { var map = _children ??= <String, Reference>{}; return map[name] ??= new Reference._(this, name); } /// If the reference has element, and it is for the [node], return `true`. /// /// The element might be not `null`, but the node is different in case of /// duplicate declarations. bool hasElementFor(AstNode node) { if (element != null && this.node == node) { return true; } else { if (node == null) { this.node = node; } return false; } } void removeChild(String name) { _children.remove(name); } String toString() => parent == null ? 'root' : '$parent::$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/summary2/link.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/declared_variables.dart'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart' show CompilationUnit; import 'package:analyzer/src/dart/element/inheritance_manager3.dart'; import 'package:analyzer/src/dart/element/type_provider.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/type_system.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary2/ast_binary_writer.dart'; import 'package:analyzer/src/summary2/library_builder.dart'; import 'package:analyzer/src/summary2/linked_bundle_context.dart'; import 'package:analyzer/src/summary2/linked_element_factory.dart'; import 'package:analyzer/src/summary2/linking_bundle_context.dart'; import 'package:analyzer/src/summary2/reference.dart'; import 'package:analyzer/src/summary2/simply_bounded.dart'; import 'package:analyzer/src/summary2/top_level_inference.dart'; import 'package:analyzer/src/summary2/type_alias.dart'; import 'package:analyzer/src/summary2/types_builder.dart'; var timerLinkingLinkingBundle = Stopwatch(); var timerLinkingRemoveBundle = Stopwatch(); LinkResult link( LinkedElementFactory elementFactory, List<LinkInputLibrary> inputLibraries, ) { var linker = Linker(elementFactory); linker.link(inputLibraries); return LinkResult(linker.linkingBundle); } class Linker { final LinkedElementFactory elementFactory; LinkedNodeBundleBuilder linkingBundle; LinkedBundleContext bundleContext; LinkingBundleContext linkingBundleContext; /// Libraries that are being linked. final Map<Uri, LibraryBuilder> builders = {}; InheritanceManager3 inheritance; // TODO(scheglov) cache it Linker(this.elementFactory) { linkingBundleContext = LinkingBundleContext( elementFactory.dynamicRef, ); bundleContext = LinkedBundleContext.forAst( elementFactory, linkingBundleContext.references, ); } InternalAnalysisContext get analysisContext { return elementFactory.analysisContext; } DeclaredVariables get declaredVariables { return analysisContext.declaredVariables; } Reference get rootReference => elementFactory.rootReference; TypeProvider get typeProvider => analysisContext.typeProvider; Dart2TypeSystem get typeSystem => analysisContext.typeSystem; void link(List<LinkInputLibrary> inputLibraries) { for (var inputLibrary in inputLibraries) { LibraryBuilder.build(this, inputLibrary); } // TODO(scheglov) do in build() ? elementFactory.addBundle(bundleContext); _buildOutlines(); timerLinkingLinkingBundle.start(); _createLinkingBundle(); timerLinkingLinkingBundle.stop(); timerLinkingRemoveBundle.start(); linkingBundleContext.clearIndexes(); elementFactory.removeBundle(bundleContext); timerLinkingRemoveBundle.stop(); } void _buildOutlines() { _resolveUriDirectives(); _computeLibraryScopes(); _createTypeSystem(); _resolveTypes(); TypeAliasSelfReferenceFinder().perform(this); _createLoadLibraryFunctions(); _performTopLevelInference(); _resolveConstructors(); _resolveConstantInitializers(); _resolveDefaultValues(); _resolveMetadata(); _collectMixinSuperInvokedNames(); } void _collectMixinSuperInvokedNames() { for (var library in builders.values) { library.collectMixinSuperInvokedNames(); } } void _computeLibraryScopes() { for (var library in builders.values) { library.addLocalDeclarations(); } for (var library in builders.values) { library.buildInitialExportScope(); } var exporters = new Set<LibraryBuilder>(); var exportees = new Set<LibraryBuilder>(); for (var library in builders.values) { library.addExporters(); } for (var library in builders.values) { if (library.exporters.isNotEmpty) { exportees.add(library); for (var exporter in library.exporters) { exporters.add(exporter.exporter); } } } var both = new Set<LibraryBuilder>(); for (var exported in exportees) { if (exporters.contains(exported)) { both.add(exported); } for (var export in exported.exporters) { exported.exportScope.forEach(export.addToExportScope); } } while (true) { var hasChanges = false; for (var exported in both) { for (var export in exported.exporters) { exported.exportScope.forEach((name, member) { if (export.addToExportScope(name, member)) { hasChanges = true; } }); } } if (!hasChanges) break; } for (var library in builders.values) { library.storeExportScope(); } for (var library in builders.values) { library.buildElement(); } } void _createLinkingBundle() { var linkingLibraries = <LinkedNodeLibraryBuilder>[]; for (var builder in builders.values) { linkingLibraries.add(builder.node); for (var unitContext in builder.context.units) { var unit = unitContext.unit; var writer = AstBinaryWriter(linkingBundleContext); var unitLinkedNode = writer.writeUnit(unit); builder.node.units.add( LinkedNodeUnitBuilder( isSynthetic: unitContext.isSynthetic, partUriStr: unitContext.partUriStr, uriStr: unitContext.uriStr, node: unitLinkedNode, isNNBD: unit.featureSet.isEnabled(Feature.non_nullable), ), ); } } linkingBundle = LinkedNodeBundleBuilder( references: linkingBundleContext.referencesBuilder, libraries: linkingLibraries, ); } void _createLoadLibraryFunctions() { for (var library in builders.values) { library.element.createLoadLibraryFunction(typeProvider); } } void _createTypeSystem() { if (typeProvider != null) { inheritance = InheritanceManager3(typeSystem); return; } var coreLib = elementFactory.libraryOfUri('dart:core'); var asyncLib = elementFactory.libraryOfUri('dart:async'); analysisContext.typeProvider = TypeProviderImpl(coreLib, asyncLib); inheritance = InheritanceManager3(typeSystem); } void _performTopLevelInference() { TopLevelInference(this).infer(); } void _resolveConstantInitializers() { ConstantInitializersResolver(this).perform(); } void _resolveConstructors() { for (var library in builders.values) { library.resolveConstructors(); } } void _resolveDefaultValues() { for (var library in builders.values) { library.resolveDefaultValues(); } } void _resolveMetadata() { for (var library in builders.values) { library.resolveMetadata(); } } void _resolveTypes() { var nodesToBuildType = NodesToBuildType(); for (var library in builders.values) { library.resolveTypes(nodesToBuildType); } computeSimplyBounded(bundleContext, builders.values); TypesBuilder(typeSystem).build(nodesToBuildType); } void _resolveUriDirectives() { for (var library in builders.values) { library.resolveUriDirectives(); } } } class LinkInputLibrary { final Source source; final List<LinkInputUnit> units; LinkInputLibrary(this.source, this.units); } class LinkInputUnit { final String partUriStr; final Source source; final bool isSynthetic; final CompilationUnit unit; LinkInputUnit( this.partUriStr, this.source, this.isSynthetic, this.unit, ); } class LinkResult { final LinkedNodeBundleBuilder bundle; LinkResult(this.bundle); }
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/summary2/ast_resolver.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/error/listener.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/resolver/ast_rewrite.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/summary2/link.dart'; /// Used to resolve some AST nodes - variable initializers, and annotations. class AstResolver { final Linker _linker; final LibraryElement _library; final Scope _nameScope; AstResolver(this._linker, this._library, this._nameScope); void resolve( AstNode node, { ClassElement enclosingClassElement, ExecutableElement enclosingExecutableElement, FunctionBody enclosingFunctionBody, }) { var featureSet = node.thisOrAncestorOfType<CompilationUnit>().featureSet; var source = _FakeSource(); var errorListener = AnalysisErrorListener.NULL_LISTENER; var typeResolverVisitor = new TypeResolverVisitor( _library, source, _linker.typeProvider, errorListener, featureSet: featureSet, nameScope: _nameScope); node.accept(typeResolverVisitor); var variableResolverVisitor = new VariableResolverVisitor( _library, source, _linker.typeProvider, errorListener, nameScope: _nameScope, localVariableInfo: LocalVariableInfo()); node.accept(variableResolverVisitor); // if (_linker.getAst != null) { // expression.accept(_partialResolverVisitor); // } var resolverVisitor = new ResolverVisitor(_linker.inheritance, _library, source, _linker.typeProvider, errorListener, featureSet: featureSet, nameScope: _nameScope, propagateTypes: false, reportConstEvaluationErrors: false); resolverVisitor.prepareEnclosingDeclarations( enclosingClassElement: enclosingClassElement, enclosingExecutableElement: enclosingExecutableElement, ); if (enclosingFunctionBody != null) { resolverVisitor.prepareCurrentFunctionBody(enclosingFunctionBody); } node.accept(resolverVisitor); } void rewriteAst(AstNode node) { var source = _FakeSource(); var errorListener = AnalysisErrorListener.NULL_LISTENER; var astRewriteVisitor = new AstRewriteVisitor(_linker.typeSystem, _library, source, _linker.typeProvider, errorListener, nameScope: _nameScope); node.accept(astRewriteVisitor); } } class _FakeSource implements Source { @override String get fullName => '/package/lib/test.dart'; @override noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); }
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/summary2/simply_bounded.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/src/dart/element/element.dart'; import 'package:analyzer/src/summary/link.dart' as graph show DependencyWalker, Node; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/library_builder.dart'; import 'package:analyzer/src/summary2/linked_bundle_context.dart'; /// Compute simple-boundedness for all classes and generic types aliases in /// the source [libraryBuilders]. There might be dependencies between them, /// so they all should be processed simultaneously. void computeSimplyBounded( LinkedBundleContext bundleContext, Iterable<LibraryBuilder> libraryBuilders, ) { var walker = SimplyBoundedDependencyWalker(bundleContext); var nodes = <SimplyBoundedNode>[]; for (var libraryBuilder in libraryBuilders) { for (var unit in libraryBuilder.element.units) { for (var element in unit.functionTypeAliases) { var node = walker.getNode(element); nodes.add(node); } for (var element in unit.mixins) { var node = walker.getNode(element); nodes.add(node); } for (var element in unit.types) { var node = walker.getNode(element); nodes.add(node); } } } for (var node in nodes) { if (!node.isEvaluated) { walker.walk(node); } LazyAst.setSimplyBounded(node._node, node.isSimplyBounded); } } /// The graph walker for evaluating whether types are simply bounded. class SimplyBoundedDependencyWalker extends graph.DependencyWalker<SimplyBoundedNode> { final LinkedBundleContext bundleContext; final Map<Element, SimplyBoundedNode> nodeMap = Map.identity(); SimplyBoundedDependencyWalker(this.bundleContext); @override void evaluate(SimplyBoundedNode v) { v._evaluate(); } @override void evaluateScc(List<SimplyBoundedNode> scc) { for (var node in scc) { node._markCircular(); } } SimplyBoundedNode getNode(Element element) { var graphNode = nodeMap[element]; if (graphNode == null) { var node = (element as ElementImpl).linkedNode; if (node is ClassDeclaration) { var parameters = node.typeParameters?.typeParameters; graphNode = SimplyBoundedNode( this, node, parameters ?? const <TypeParameter>[], const <TypeAnnotation>[], ); } else if (node is ClassTypeAlias) { var parameters = node.typeParameters?.typeParameters; graphNode = SimplyBoundedNode( this, node, parameters ?? const <TypeParameter>[], const <TypeAnnotation>[], ); } else if (node is FunctionTypeAlias) { var parameters = node.typeParameters?.typeParameters; graphNode = SimplyBoundedNode( this, node, parameters ?? const <TypeParameter>[], _collectTypedefRhsTypes(node), ); } else if (node is GenericTypeAlias) { var parameters = node.typeParameters?.typeParameters; graphNode = SimplyBoundedNode( this, node, parameters ?? const <TypeParameter>[], _collectTypedefRhsTypes(node), ); } else if (node is MixinDeclaration) { var parameters = node.typeParameters?.typeParameters; graphNode = SimplyBoundedNode( this, node, parameters ?? const <TypeParameter>[], const <TypeAnnotation>[], ); } else { throw UnimplementedError('(${node.runtimeType}) $node'); } nodeMap[element] = graphNode; } return graphNode; } /// Collects all the type references appearing on the "right hand side" of a /// typedef. /// /// The "right hand side" of a typedef is the type appearing after the "=" /// in a new style typedef declaration, or for an old style typedef /// declaration, the type that *would* appear after the "=" if it were /// converted to a new style typedef declaration. This means that type /// parameter declarations and their bounds are not included. static List<TypeAnnotation> _collectTypedefRhsTypes(AstNode node) { if (node is FunctionTypeAlias) { var collector = _TypeCollector(); collector.addType(node.returnType); collector.visitParameters(node.parameters); return collector.types; } else if (node is GenericTypeAlias) { var functionType = node.functionType; if (functionType != null) { var collector = _TypeCollector(); collector.addType(functionType.returnType); collector.visitParameters(functionType.parameters); return collector.types; } else { return const <TypeAnnotation>[]; } } else { throw StateError('(${node.runtimeType}) $node'); } } } /// The graph node used to construct the dependency graph for evaluating /// whether types are simply bounded. class SimplyBoundedNode extends graph.Node<SimplyBoundedNode> { final SimplyBoundedDependencyWalker _walker; final AstNode _node; /// The type parameters of the type whose simple-boundedness we check. final List<TypeParameter> _typeParameters; /// If the type whose simple-boundedness we check is a typedef, the types /// appearing in its "right hand side". final List<TypeAnnotation> _rhsTypes; @override bool isEvaluated = false; /// After execution of [_evaluate], indicates whether the type is /// simply bounded. /// /// Prior to execution of [computeDependencies], `true`. /// /// Between execution of [computeDependencies] and [_evaluate], `true` /// indicates that the type is simply bounded only if all of its dependencies /// are simply bounded; `false` indicates that the type is not simply bounded. bool isSimplyBounded = true; SimplyBoundedNode( this._walker, this._node, this._typeParameters, this._rhsTypes, ); @override List<SimplyBoundedNode> computeDependencies() { var dependencies = <SimplyBoundedNode>[]; for (var typeParameter in _typeParameters) { var bound = typeParameter.bound; if (bound != null) { if (!_visitType(dependencies, bound, false)) { // Note: we might consider setting isEvaluated=true here to prevent an // unnecessary call to SimplyBoundedDependencyWalker.evaluate. // However, we'd have to be careful to make sure this doesn't violate // an invariant of the DependencyWalker algorithm, since normally it // only expects isEvaluated to change during a call to .evaluate or // .evaluateScc. isSimplyBounded = false; return const []; } } } for (var type in _rhsTypes) { if (!_visitType(dependencies, type, true)) { // Note: we might consider setting isEvaluated=true here to prevent an // unnecessary call to SimplyBoundedDependencyWalker.evaluate. // However, we'd have to be careful to make sure this doesn't violate // an invariant of the DependencyWalker algorithm, since normally it // only expects isEvaluated to change during a call to .evaluate or // .evaluateScc. isSimplyBounded = false; return const []; } } return dependencies; } void _evaluate() { for (var dependency in graph.Node.getDependencies(this)) { if (!dependency.isSimplyBounded) { isSimplyBounded = false; break; } } isEvaluated = true; } void _markCircular() { isSimplyBounded = false; isEvaluated = true; } /// Visits the type specified by [type], storing the [SimplyBoundedNode] for /// any types it references in [dependencies]. /// /// Return `false` if a type that is known to be not simply bound is found. /// /// Return `false` if a reference to a type parameter is found, and /// [allowTypeParameters] is `false`. /// /// If `false` is returned, further visiting is short-circuited. /// /// Otherwise `true` is returned. bool _visitType(List<SimplyBoundedNode> dependencies, TypeAnnotation type, bool allowTypeParameters) { if (type == null) return true; if (type is TypeName) { var element = type.name.staticElement; if (element is TypeParameterElement) { return allowTypeParameters; } var arguments = type.typeArguments; if (arguments == null) { var graphNode = _walker.nodeMap[element]; // If not a node being linked, then the flag is already set. if (graphNode == null) { if (element is TypeParameterizedElement) { return element.isSimplyBounded; } return true; } dependencies.add(graphNode); } else { for (var argument in arguments.arguments) { if (!_visitType(dependencies, argument, allowTypeParameters)) { return false; } } } return true; } if (type is GenericFunctionType) { var collector = _TypeCollector(); collector.addType(type.returnType); collector.visitParameters(type.parameters); for (var type in collector.types) { if (!_visitType(dependencies, type, allowTypeParameters)) { return false; } } return true; } throw UnimplementedError('(${type.runtimeType}) $type'); } } /// Helper for collecting type annotations. class _TypeCollector { final List<TypeAnnotation> types = []; void addType(TypeAnnotation type) { if (type != null) { types.add(type); } } void visitParameter(FormalParameter node) { if (node is DefaultFormalParameter) { visitParameter(node.parameter); } else if (node is FieldFormalParameter) { // The spec does not allow them here, ignore. } else if (node is FunctionTypedFormalParameter) { addType(node.returnType); visitParameters(node.parameters); } else if (node is SimpleFormalParameter) { addType(node.type); } else { throw UnimplementedError('(${node.runtimeType}) $node'); } } void visitParameters(FormalParameterList parameterList) { for (var parameter in parameterList.parameters) { visitParameter(parameter); } } }
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/summary2/lazy_ast.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'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/ast_binary_flags.dart'; import 'package:analyzer/src/summary2/ast_binary_reader.dart'; import 'package:analyzer/src/summary2/linked_unit_context.dart'; /// Accessor for reading AST lazily, or read data that is stored in IDL, but /// cannot be stored in AST, like inferred types. class LazyAst { static const _defaultTypedKey = 'lazyAst_defaultType'; static const _genericFunctionTypeIdKey = 'lazyAst_genericFunctionTypeId'; static const _hasOverrideInferenceKey = 'lazyAst_hasOverrideInference'; static const _inheritsCovariantKey = 'lazyAst_isCovariant'; static const _isSimplyBoundedKey = 'lazyAst_simplyBounded'; static const _returnTypeKey = 'lazyAst_returnType'; static const _typeInferenceErrorKey = 'lazyAst_typeInferenceError'; static const _typeKey = 'lazyAst_type'; final LinkedNode data; LazyAst(this.data); static DartType getDefaultType(TypeParameter node) { return node.getProperty(_defaultTypedKey); } static int getGenericFunctionTypeId(GenericFunctionType node) { return node.getProperty(_genericFunctionTypeIdKey); } static bool getInheritsCovariant(AstNode node) { return node.getProperty(_inheritsCovariantKey) ?? false; } static DartType getReturnType(AstNode node) { return node.getProperty(_returnTypeKey); } static DartType getType(AstNode node) { return node.getProperty(_typeKey); } static TopLevelInferenceError getTypeInferenceError(AstNode node) { return node.getProperty(_typeInferenceErrorKey); } static bool hasOverrideInferenceDone(AstNode node) { return node.getProperty(_hasOverrideInferenceKey) ?? false; } static bool isSimplyBounded(AstNode node) { return node.getProperty(_isSimplyBoundedKey); } static void setDefaultType(TypeParameter node, DartType type) { node.setProperty(_defaultTypedKey, type); } static void setGenericFunctionTypeId(GenericFunctionType node, int id) { node.setProperty(_genericFunctionTypeIdKey, id); } static void setInheritsCovariant(AstNode node, bool value) { node.setProperty(_inheritsCovariantKey, value); } static void setOverrideInferenceDone(AstNode node) { node.setProperty(_hasOverrideInferenceKey, true); } static void setReturnType(AstNode node, DartType type) { node.setProperty(_returnTypeKey, type); } static void setSimplyBounded(AstNode node, bool simplyBounded) { node.setProperty(_isSimplyBoundedKey, simplyBounded); } static void setType(AstNode node, DartType type) { node.setProperty(_typeKey, type); } static void setTypeInferenceError( AstNode node, TopLevelInferenceError error) { node.setProperty(_typeInferenceErrorKey, error); } } class LazyClassDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasExtendsClause = false; bool _hasImplementsClause = false; bool _hasMembers = false; bool _hasMetadata = false; bool _hasWithClause = false; LazyClassDeclaration(this.data); static LazyClassDeclaration get(ClassDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readDocumentationComment( LinkedUnitContext context, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readExtendsClause( AstBinaryReader reader, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasExtendsClause) { node.extendsClause = reader.readNode( lazy.data.classDeclaration_extendsClause, ); lazy._hasExtendsClause = true; } } static void readImplementsClause( AstBinaryReader reader, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasImplementsClause) { node.implementsClause = reader.readNode( lazy.data.classOrMixinDeclaration_implementsClause, ); lazy._hasImplementsClause = true; } } static void readMembers( AstBinaryReader reader, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMembers) { var dataList = lazy.data.classOrMixinDeclaration_members; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.members[i] = reader.readNode(data); } lazy._hasMembers = true; } } static void readMetadata( AstBinaryReader reader, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readWithClause( AstBinaryReader reader, ClassDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasWithClause) { node.withClause = reader.readNode( lazy.data.classDeclaration_withClause, ); lazy._hasWithClause = true; } } static void setData(ClassDeclaration node, LinkedNode data) { node.setProperty(_key, LazyClassDeclaration(data)); LazyAst.setSimplyBounded(node, data.simplyBoundable_isSimplyBounded); } } class LazyClassTypeAlias { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasImplementsClause = false; bool _hasMetadata = false; bool _hasSuperclass = false; bool _hasWithClause = false; LazyClassTypeAlias(this.data); static LazyClassTypeAlias get(ClassTypeAlias node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readDocumentationComment( LinkedUnitContext context, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readImplementsClause( AstBinaryReader reader, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasImplementsClause) { node.implementsClause = reader.readNode( lazy.data.classTypeAlias_implementsClause, ); lazy._hasImplementsClause = true; } } static void readMetadata( AstBinaryReader reader, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readSuperclass( AstBinaryReader reader, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasSuperclass) { node.superclass = reader.readNode( lazy.data.classTypeAlias_superclass, ); lazy._hasSuperclass = true; } } static void readWithClause( AstBinaryReader reader, ClassTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasWithClause) { node.withClause = reader.readNode( lazy.data.classTypeAlias_withClause, ); lazy._hasWithClause = true; } } static void setData(ClassTypeAlias node, LinkedNode data) { node.setProperty(_key, LazyClassTypeAlias(data)); LazyAst.setSimplyBounded(node, data.simplyBoundable_isSimplyBounded); } } class LazyCombinator { static const _key = 'lazyAst'; final LinkedNode data; LazyCombinator(Combinator node, this.data) { node.setProperty(_key, this); } static LazyCombinator get(Combinator node) { return node.getProperty(_key); } static int getEnd( LinkedUnitContext context, Combinator node, ) { var lazy = get(node); if (lazy != null) { var informativeData = context.getInformativeData(lazy.data); return informativeData?.combinatorEnd ?? 0; } return node.end; } } class LazyCompilationUnit { static const _key = 'lazyAst'; final LinkedNode data; LazyCompilationUnit(this.data); static LazyCompilationUnit get(CompilationUnit node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, CompilationUnit node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, CompilationUnit node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void setData(CompilationUnit node, LinkedNode data) { node.setProperty(_key, LazyCompilationUnit(data)); } } class LazyConstructorDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasBody = false; bool _hasDocumentationComment = false; bool _hasFormalParameters = false; bool _hasInitializers = false; bool _hasMetadata = false; bool _hasRedirectedConstructor = false; LazyConstructorDeclaration(this.data); static LazyConstructorDeclaration get(ConstructorDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readBody( AstBinaryReader reader, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasBody) { node.body = reader.readNode( lazy.data.constructorDeclaration_body, ); lazy._hasBody = true; } } static void readDocumentationComment( LinkedUnitContext context, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readFormalParameters( AstBinaryReader reader, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasFormalParameters) { node.parameters = reader.readNode( lazy.data.constructorDeclaration_parameters, ); lazy._hasFormalParameters = true; } } static void readInitializers( AstBinaryReader reader, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasInitializers) { var dataList = lazy.data.constructorDeclaration_initializers; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.initializers[i] = reader.readNode(data); } lazy._hasInitializers = true; } } static void readMetadata( AstBinaryReader reader, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readRedirectedConstructor( AstBinaryReader reader, ConstructorDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasRedirectedConstructor) { node.redirectedConstructor = reader.readNode( lazy.data.constructorDeclaration_redirectedConstructor, ); lazy._hasRedirectedConstructor = true; } } static void setData(ConstructorDeclaration node, LinkedNode data) { node.setProperty(_key, LazyConstructorDeclaration(data)); } } class LazyDirective { static const _key = 'lazyAst'; static const _uriKey = 'lazyAst_selectedUri'; final LinkedNode data; bool _hasMetadata = false; LazyDirective(this.data); static LazyDirective get(Directive node) { return node.getProperty(_key); } static String getSelectedUri(UriBasedDirective node) { return node.getProperty(_uriKey); } static void readMetadata(AstBinaryReader reader, Directive node) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(Directive node, LinkedNode data) { node.setProperty(_key, LazyDirective(data)); if (node is NamespaceDirective) { node.setProperty(_uriKey, data.namespaceDirective_selectedUri); } } static void setSelectedUri(UriBasedDirective node, String uriStr) { node.setProperty(_uriKey, uriStr); } } class LazyEnumConstantDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasMetadata = false; LazyEnumConstantDeclaration(this.data); static LazyEnumConstantDeclaration get(EnumConstantDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, EnumConstantDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, EnumConstantDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readDocumentationComment( LinkedUnitContext context, EnumConstantDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readMetadata( AstBinaryReader reader, EnumConstantDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(EnumConstantDeclaration node, LinkedNode data) { node.setProperty(_key, LazyEnumConstantDeclaration(data)); } } class LazyEnumDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasConstants = false; bool _hasDocumentationComment = false; bool _hasMetadata = false; LazyEnumDeclaration(this.data); static LazyEnumDeclaration get(EnumDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, EnumDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, EnumDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readConstants( AstBinaryReader reader, EnumDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasConstants) { var dataList = lazy.data.enumDeclaration_constants; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.constants[i] = reader.readNode(data); } lazy._hasConstants = true; } } static void readDocumentationComment( LinkedUnitContext context, EnumDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readMetadata( AstBinaryReader reader, EnumDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(EnumDeclaration node, LinkedNode data) { node.setProperty(_key, LazyEnumDeclaration(data)); } } class LazyExtensionDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasExtendedType = false; bool _hasMembers = false; bool _hasMetadata = false; /// The name for use in `Reference`. If the extension is named, the name /// of the extension. If the extension is unnamed, a synthetic name. String _refName; LazyExtensionDeclaration(ExtensionDeclaration node, this.data) { node.setProperty(_key, this); if (data != null) { _refName = data.extensionDeclaration_refName; } } String get refName => _refName; void put(LinkedNodeBuilder builder) { assert(_refName != null); builder.extensionDeclaration_refName = _refName; } void setRefName(String referenceName) { _refName = referenceName; } static LazyExtensionDeclaration get(ExtensionDeclaration node) { LazyExtensionDeclaration lazy = node.getProperty(_key); if (lazy == null) { return LazyExtensionDeclaration(node, null); } return lazy; } static int getCodeLength( LinkedUnitContext context, ExtensionDeclaration node, ) { var lazy = get(node); if (lazy?.data != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, ExtensionDeclaration node, ) { var lazy = get(node); if (lazy?.data != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readDocumentationComment( LinkedUnitContext context, ExtensionDeclaration node, ) { var lazy = get(node); if (lazy?.data != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readExtendedType( AstBinaryReader reader, ExtensionDeclaration node, ) { var lazy = get(node); if (lazy?.data != null && !lazy._hasExtendedType) { (node as ExtensionDeclarationImpl).extendedType = reader.readNode( lazy.data.extensionDeclaration_extendedType, ); lazy._hasExtendedType = true; } } static void readMembers( AstBinaryReader reader, ExtensionDeclaration node, ) { var lazy = get(node); if (lazy?.data != null && !lazy._hasMembers) { var dataList = lazy.data.extensionDeclaration_members; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.members[i] = reader.readNode(data); } lazy._hasMembers = true; } } static void readMetadata( AstBinaryReader reader, ExtensionDeclaration node, ) { var lazy = get(node); if (lazy?.data != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } } class LazyFieldDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasMetadata = false; LazyFieldDeclaration(this.data); static LazyFieldDeclaration get(FieldDeclaration node) { return node.getProperty(_key); } static void readDocumentationComment( LinkedUnitContext context, FieldDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readMetadata( AstBinaryReader reader, FieldDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(FieldDeclaration node, LinkedNode data) { node.setProperty(_key, LazyFieldDeclaration(data)); } } class LazyFormalParameter { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDefaultValue = false; bool _hasFormalParameters = false; bool _hasMetadata = false; bool _hasType = false; bool _hasTypeInferenceError = false; bool _hasTypeNode = false; LazyFormalParameter(this.data); static LazyFormalParameter get(FormalParameter node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, FormalParameter node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, FormalParameter node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static String getDefaultValueCode( LinkedUnitContext context, DefaultFormalParameter node, ) { var lazy = get(node); if (lazy != null) { if (lazy.data.defaultFormalParameter_defaultValue == null) { return null; } return context.getDefaultValueCodeData(lazy.data); } else { return node.defaultValue?.toSource(); } } static DartType getType( AstBinaryReader reader, FormalParameter node, ) { var lazy = get(node); if (lazy != null && !lazy._hasType) { var type = reader.readType(lazy.data.actualType); LazyAst.setType(node, type); lazy._hasType = true; } return LazyAst.getType(node); } static TopLevelInferenceError getTypeInferenceError(FormalParameter node) { var lazy = get(node); if (lazy != null && !lazy._hasTypeInferenceError) { var error = lazy.data.topLevelTypeInferenceError; LazyAst.setTypeInferenceError(node, error); lazy._hasTypeInferenceError = true; } return LazyAst.getTypeInferenceError(node); } static bool hasDefaultValue(DefaultFormalParameter node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.hasInitializer(lazy.data.flags); } else { return node.defaultValue != null; } } static void readDefaultValue( AstBinaryReader reader, DefaultFormalParameter node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDefaultValue) { node.defaultValue = reader.readNode( lazy.data.defaultFormalParameter_defaultValue, ); lazy._hasDefaultValue = true; } } static void readFormalParameters( AstBinaryReader reader, FormalParameter node, ) { var lazy = get(node); if (lazy != null && !lazy._hasFormalParameters) { if (node is FunctionTypedFormalParameter) { node.parameters = reader.readNode( lazy.data.functionTypedFormalParameter_formalParameters, ); } else if (node is FieldFormalParameter) { node.parameters = reader.readNode( lazy.data.fieldFormalParameter_formalParameters, ); } lazy._hasFormalParameters = true; } } static void readMetadata( AstBinaryReader reader, FormalParameter node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.normalFormalParameter_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readTypeNode( AstBinaryReader reader, FormalParameter node, ) { var lazy = get(node); if (lazy != null && !lazy._hasTypeNode) { if (node is SimpleFormalParameter) { node.type = reader.readNode( lazy.data.simpleFormalParameter_type, ); } lazy._hasTypeNode = true; } } static void setData(FormalParameter node, LinkedNode data) { node.setProperty(_key, LazyFormalParameter(data)); } } class LazyFunctionDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasMetadata = false; bool _hasReturnType = false; bool _hasReturnTypeNode = false; LazyFunctionDeclaration(this.data); static LazyFunctionDeclaration get(FunctionDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, FunctionDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, FunctionDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static DartType getReturnType( AstBinaryReader reader, FunctionDeclaration node, ) { readFunctionExpression(reader, node); var lazy = get(node); if (lazy != null && !lazy._hasReturnType) { var type = reader.readType(lazy.data.actualReturnType); LazyAst.setReturnType(node, type); lazy._hasReturnType = true; } return LazyAst.getReturnType(node); } static void readDocumentationComment( LinkedUnitContext context, FunctionDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readFunctionExpression( AstBinaryReader reader, FunctionDeclaration node, ) { if (node.functionExpression == null) { var lazy = get(node); node.functionExpression = reader.readNode( lazy.data.functionDeclaration_functionExpression, ); } } static void readMetadata( AstBinaryReader reader, FunctionDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readReturnTypeNode( AstBinaryReader reader, FunctionDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasReturnTypeNode) { node.returnType = reader.readNode( lazy.data.functionDeclaration_returnType, ); lazy._hasReturnTypeNode = true; } } static void setData(FunctionDeclaration node, LinkedNode data) { node.setProperty(_key, LazyFunctionDeclaration(data)); } } class LazyFunctionExpression { static const _key = 'lazyAst'; final LinkedNode data; bool _hasBody = false; bool _hasFormalParameters = false; LazyFunctionExpression(this.data); static LazyFunctionExpression get(FunctionExpression node) { return node.getProperty(_key); } static bool isAsynchronous(FunctionExpression node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.isAsync(lazy.data.flags); } else { return node.body.isAsynchronous; } } static bool isGenerator(FunctionExpression node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.isGenerator(lazy.data.flags); } else { return node.body.isGenerator; } } static void readBody( AstBinaryReader reader, FunctionExpression node, ) { var lazy = get(node); if (lazy != null && !lazy._hasBody) { node.body = reader.readNode( lazy.data.functionExpression_body, ); lazy._hasBody = true; } } static void readFormalParameters( AstBinaryReader reader, FunctionExpression node, ) { var lazy = get(node); if (lazy != null && !lazy._hasFormalParameters) { node.parameters = reader.readNode( lazy.data.functionExpression_formalParameters, ); lazy._hasFormalParameters = true; } } static void setData(FunctionExpression node, LinkedNode data) { node.setProperty(_key, LazyFunctionExpression(data)); } } class LazyFunctionTypeAlias { static const _key = 'lazyAst'; static const _hasSelfReferenceKey = 'lazyAst_hasSelfReferenceKey'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasFormalParameters = false; bool _hasMetadata = false; bool _hasReturnType = false; bool _hasReturnTypeNode = false; LazyFunctionTypeAlias(this.data); static LazyFunctionTypeAlias get(FunctionTypeAlias node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static bool getHasSelfReference(FunctionTypeAlias node) { return node.getProperty(_hasSelfReferenceKey); } static DartType getReturnType( AstBinaryReader reader, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasReturnType) { var type = reader.readType(lazy.data.actualReturnType); LazyAst.setReturnType(node, type); lazy._hasReturnType = true; } return LazyAst.getReturnType(node); } static void readDocumentationComment( LinkedUnitContext context, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readFormalParameters( AstBinaryReader reader, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasFormalParameters) { node.parameters = reader.readNode( lazy.data.functionTypeAlias_formalParameters, ); lazy._hasFormalParameters = true; } } static void readMetadata( AstBinaryReader reader, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readReturnTypeNode( AstBinaryReader reader, FunctionTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasReturnTypeNode) { node.returnType = reader.readNode( lazy.data.functionTypeAlias_returnType, ); lazy._hasReturnTypeNode = true; } } static void setData(FunctionTypeAlias node, LinkedNode data) { node.setProperty(_key, LazyFunctionTypeAlias(data)); LazyAst.setSimplyBounded(node, data.simplyBoundable_isSimplyBounded); } static void setHasSelfReference(FunctionTypeAlias node, bool value) { node.setProperty(_hasSelfReferenceKey, value); } } class LazyGenericTypeAlias { static const _key = 'lazyAst'; static const _hasSelfReferenceKey = 'lazyAst_hasSelfReferenceKey'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasFunction = false; bool _hasMetadata = false; LazyGenericTypeAlias(this.data); static LazyGenericTypeAlias get(GenericTypeAlias node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, GenericTypeAlias node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, GenericTypeAlias node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static bool getHasSelfReference(GenericTypeAlias node) { return node.getProperty(_hasSelfReferenceKey); } static void readDocumentationComment( LinkedUnitContext context, GenericTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readFunctionType( AstBinaryReader reader, GenericTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasFunction) { node.functionType = reader.readNode( lazy.data.genericTypeAlias_functionType, ); lazy._hasFunction = true; } } static void readMetadata( AstBinaryReader reader, GenericTypeAlias node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(GenericTypeAlias node, LinkedNode data) { node.setProperty(_key, LazyGenericTypeAlias(data)); LazyAst.setSimplyBounded(node, data.simplyBoundable_isSimplyBounded); } static void setHasSelfReference(GenericTypeAlias node, bool value) { node.setProperty(_hasSelfReferenceKey, value); } } class LazyMethodDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasBody = false; bool _hasDocumentationComment = false; bool _hasFormalParameters = false; bool _hasMetadata = false; bool _hasReturnType = false; bool _hasReturnTypeNode = false; LazyMethodDeclaration(this.data); static LazyMethodDeclaration get(MethodDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static DartType getReturnType( AstBinaryReader reader, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasReturnType) { var type = reader.readType(lazy.data.actualReturnType); LazyAst.setReturnType(node, type); lazy._hasReturnType = true; } return LazyAst.getReturnType(node); } static bool isAbstract(MethodDeclaration node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.isAbstract(lazy.data.flags); } else { return node.isAbstract; } } static bool isAsynchronous(MethodDeclaration node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.isAsync(lazy.data.flags); } else { return node.body.isAsynchronous; } } static bool isGenerator(MethodDeclaration node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.isGenerator(lazy.data.flags); } else { return node.body.isGenerator; } } static void readBody( AstBinaryReader reader, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasBody) { node.body = reader.readNode( lazy.data.methodDeclaration_body, ); lazy._hasBody = true; } } static void readDocumentationComment( LinkedUnitContext context, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readFormalParameters( AstBinaryReader reader, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasFormalParameters) { node.parameters = reader.readNode( lazy.data.methodDeclaration_formalParameters, ); lazy._hasFormalParameters = true; } } static void readMetadata( AstBinaryReader reader, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readReturnTypeNode( AstBinaryReader reader, MethodDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasReturnTypeNode) { node.returnType = reader.readNode( lazy.data.methodDeclaration_returnType, ); lazy._hasReturnTypeNode = true; } } static void setData(MethodDeclaration node, LinkedNode data) { node.setProperty(_key, LazyMethodDeclaration(data)); } } class LazyMixinDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasOnClause = false; bool _hasImplementsClause = false; bool _hasMembers = false; bool _hasMetadata = false; List<String> _superInvokedNames; LazyMixinDeclaration(MixinDeclaration node, this.data) { node.setProperty(_key, this); if (data != null) { LazyAst.setSimplyBounded(node, data.simplyBoundable_isSimplyBounded); } } List<String> getSuperInvokedNames() { return _superInvokedNames ??= data.mixinDeclaration_superInvokedNames; } void put(LinkedNodeBuilder builder) { builder.mixinDeclaration_superInvokedNames = _superInvokedNames ?? []; } void setSuperInvokedNames(List<String> value) { _superInvokedNames = value; } static LazyMixinDeclaration get(MixinDeclaration node) { LazyMixinDeclaration lazy = node.getProperty(_key); if (lazy == null) { return LazyMixinDeclaration(node, null); } return lazy; } static int getCodeLength( LinkedUnitContext context, MixinDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, MixinDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static void readDocumentationComment( LinkedUnitContext context, MixinDeclaration node, ) { var lazy = get(node); if (lazy.data != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readImplementsClause( AstBinaryReader reader, MixinDeclarationImpl node, ) { var lazy = get(node); if (lazy.data != null && !lazy._hasImplementsClause) { node.implementsClause = reader.readNode( lazy.data.classOrMixinDeclaration_implementsClause, ); lazy._hasImplementsClause = true; } } static void readMembers( AstBinaryReader reader, MixinDeclaration node, ) { var lazy = get(node); if (lazy.data != null && !lazy._hasMembers) { var dataList = lazy.data.classOrMixinDeclaration_members; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.members[i] = reader.readNode(data); } lazy._hasMembers = true; } } static void readMetadata( AstBinaryReader reader, MixinDeclaration node, ) { var lazy = get(node); if (lazy.data != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void readOnClause( AstBinaryReader reader, MixinDeclarationImpl node, ) { var lazy = get(node); if (lazy.data != null && !lazy._hasOnClause) { node.onClause = reader.readNode( lazy.data.mixinDeclaration_onClause, ); lazy._hasOnClause = true; } } } class LazyTopLevelVariableDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasDocumentationComment = false; bool _hasMetadata = false; LazyTopLevelVariableDeclaration(this.data); static LazyTopLevelVariableDeclaration get(TopLevelVariableDeclaration node) { return node.getProperty(_key); } static void readDocumentationComment( LinkedUnitContext context, TopLevelVariableDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasDocumentationComment) { node.documentationComment = context.createComment(lazy.data); lazy._hasDocumentationComment = true; } } static void readMetadata( AstBinaryReader reader, TopLevelVariableDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(TopLevelVariableDeclaration node, LinkedNode data) { node.setProperty(_key, LazyTopLevelVariableDeclaration(data)); } } class LazyTypeParameter { static const _key = 'lazyAst'; final LinkedNode data; bool _hasBound = false; bool _hasDefaultType = false; bool _hasMetadata = false; LazyTypeParameter(this.data); static LazyTypeParameter get(TypeParameter node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, TypeParameter node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } return node.length; } static int getCodeOffset( LinkedUnitContext context, TypeParameter node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } return node.offset; } static DartType getDefaultType(AstBinaryReader reader, TypeParameter node) { var lazy = get(node); if (lazy != null && !lazy._hasDefaultType) { lazy._hasDefaultType = true; var type = reader.readType(lazy.data.typeParameter_defaultType); LazyAst.setDefaultType(node, type); return type; } return LazyAst.getDefaultType(node); } static void readBound(AstBinaryReader reader, TypeParameter node) { var lazy = get(node); if (lazy != null && !lazy._hasBound) { node.bound = reader.readNode(lazy.data.typeParameter_bound); lazy._hasBound = true; } } static void readMetadata( AstBinaryReader reader, TypeParameter node, ) { var lazy = get(node); if (lazy != null && !lazy._hasMetadata) { var dataList = lazy.data.annotatedNode_metadata; for (var i = 0; i < dataList.length; ++i) { var data = dataList[i]; node.metadata[i] = reader.readNode(data); } lazy._hasMetadata = true; } } static void setData(TypeParameter node, LinkedNode data) { node.setProperty(_key, LazyTypeParameter(data)); } } class LazyVariableDeclaration { static const _key = 'lazyAst'; final LinkedNode data; bool _hasInitializer = false; bool _hasType = false; bool _hasTypeInferenceError = false; LazyVariableDeclaration(this.data); static LazyVariableDeclaration get(VariableDeclaration node) { return node.getProperty(_key); } static int getCodeLength( LinkedUnitContext context, VariableDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeLength ?? 0; } VariableDeclarationList parent = node.parent; if (parent.variables[0] == node) { return node.end - parent.offset; } else { return node.end - node.offset; } } static int getCodeOffset( LinkedUnitContext context, VariableDeclaration node, ) { var lazy = get(node); if (lazy != null) { return context.getInformativeData(lazy.data)?.codeOffset ?? 0; } VariableDeclarationList parent = node.parent; if (parent.variables[0] == node) { return parent.offset; } else { return node.offset; } } static DartType getType( AstBinaryReader reader, VariableDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasType) { var type = reader.readType(lazy.data.actualType); LazyAst.setType(node, type); lazy._hasType = true; } return LazyAst.getType(node); } static TopLevelInferenceError getTypeInferenceError( VariableDeclaration node) { var lazy = get(node); if (lazy != null && !lazy._hasTypeInferenceError) { var error = lazy.data.topLevelTypeInferenceError; LazyAst.setTypeInferenceError(node, error); lazy._hasTypeInferenceError = true; } return LazyAst.getTypeInferenceError(node); } static bool hasInitializer(VariableDeclaration node) { var lazy = get(node); if (lazy != null) { return AstBinaryFlags.hasInitializer(lazy.data.flags); } else { return node.initializer != null; } } static void readInitializer( AstBinaryReader reader, VariableDeclaration node, ) { var lazy = get(node); if (lazy != null && !lazy._hasInitializer) { node.initializer = reader.readNode( lazy.data.variableDeclaration_initializer, ); lazy._hasInitializer = true; } } static void setData(VariableDeclaration node, LinkedNode data) { node.setProperty(_key, LazyVariableDeclaration(data)); } } class LazyVariableDeclarationList { static const _key = 'lazyAst'; final LinkedNode data; bool _hasTypeNode = false; LazyVariableDeclarationList(this.data); static LazyVariableDeclarationList get(VariableDeclarationList node) { return node.getProperty(_key); } static void readTypeNode( AstBinaryReader reader, VariableDeclarationList node, ) { var lazy = get(node); if (lazy != null && !lazy._hasTypeNode) { node.type = reader.readNode( lazy.data.variableDeclarationList_type, ); lazy._hasTypeNode = true; } } static void setData(VariableDeclarationList node, LinkedNode data) { node.setProperty(_key, LazyVariableDeclarationList(data)); } }
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/summary2/constructor_initializer_resolver.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/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/builder.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/summary2/ast_resolver.dart'; import 'package:analyzer/src/summary2/link.dart'; import 'package:analyzer/src/summary2/linking_node_scope.dart'; class ConstructorInitializerResolver { final Linker _linker; final LibraryElementImpl _libraryElement; CompilationUnitElement _unitElement; ClassElement _classElement; ConstructorElement _constructorElement; ConstructorDeclarationImpl _constructorNode; AstResolver _astResolver; ConstructorInitializerResolver(this._linker, this._libraryElement); void resolve() { for (var unit in _libraryElement.units) { _unitElement = unit; for (var classElement in unit.types) { _classElement = classElement; for (var constructorElement in classElement.constructors) { _constructor(constructorElement); } } } } void _constructor(ConstructorElementImpl constructorElement) { if (constructorElement.isSynthetic) return; _constructorElement = constructorElement; _constructorNode = constructorElement.linkedNode; var functionScope = LinkingNodeContext.get(_constructorNode).scope; var initializerScope = ConstructorInitializerScope( functionScope, constructorElement, ); _astResolver = AstResolver(_linker, _libraryElement, initializerScope); FunctionBodyImpl body = _constructorNode.body; body.localVariableInfo = LocalVariableInfo(); _initializers(); _redirectedConstructor(); } void _initializers() { var initializers = _constructorNode.initializers; var isConst = _constructorNode.constKeyword != null; if (!isConst) { initializers.clear(); return; } var holder = ElementHolder(); var elementBuilder = LocalElementBuilder(holder, _unitElement); initializers.accept(elementBuilder); for (var initializer in initializers) { _astResolver.resolve( initializer, enclosingClassElement: _classElement, enclosingExecutableElement: _constructorElement, enclosingFunctionBody: _constructorNode.body, ); } } void _redirectedConstructor() { var redirected = _constructorNode.redirectedConstructor; if (redirected != null) { _astResolver.resolve( redirected, enclosingClassElement: _classElement, enclosingExecutableElement: _constructorElement, ); } } }
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/summary2/types_builder.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/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/type_system.dart'; import 'package:analyzer/src/summary2/default_types_builder.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/type_builder.dart'; class NodesToBuildType { final List<AstNode> declarations = []; final List<TypeBuilder> typeBuilders = []; void addDeclaration(AstNode node) { declarations.add(node); } void addTypeBuilder(TypeBuilder builder) { typeBuilders.add(builder); } } class TypesBuilder { final Dart2TypeSystem typeSystem; TypesBuilder(this.typeSystem); DynamicTypeImpl get _dynamicType => DynamicTypeImpl.instance; VoidTypeImpl get _voidType => VoidTypeImpl.instance; /// Build types for all type annotations, and set types for declarations. void build(NodesToBuildType nodes) { DefaultTypesBuilder(typeSystem).build(nodes.declarations); for (var builder in nodes.typeBuilders) { builder.build(); } _MixinsInference(typeSystem).perform(nodes.declarations); for (var declaration in nodes.declarations) { _declaration(declaration); } } FunctionType _buildFunctionType( TypeParameterList typeParameterList, TypeAnnotation returnTypeNode, FormalParameterList parameterList, ) { var returnType = returnTypeNode?.type ?? _dynamicType; List<TypeParameterElement> typeParameters; if (typeParameterList != null) { typeParameters = typeParameterList.typeParameters .map<TypeParameterElement>((p) => p.declaredElement) .toList(); } else { typeParameters = const <TypeParameterElement>[]; } var formalParameters = parameterList.parameters.map((parameter) { return ParameterElementImpl.synthetic( parameter.identifier?.name ?? '', _getType(parameter), // ignore: deprecated_member_use_from_same_package parameter.kind, ); }).toList(); return FunctionTypeImpl.synthetic( returnType, typeParameters, formalParameters, ); } void _classDeclaration(ClassDeclaration node) {} void _classTypeAlias(ClassTypeAlias node) {} void _declaration(AstNode node) { if (node is ClassDeclaration) { _classDeclaration(node); } else if (node is ClassTypeAlias) { _classTypeAlias(node); } else if (node is ExtensionDeclaration) { _extensionDeclaration(node); } else if (node is FieldFormalParameter) { _fieldFormalParameter(node); } else if (node is FunctionDeclaration) { var returnType = node.returnType?.type; if (returnType == null) { if (node.isSetter) { returnType = _voidType; } else { returnType = _dynamicType; } } LazyAst.setReturnType(node, returnType); } else if (node is FunctionTypeAlias) { _functionTypeAlias(node); } else if (node is FunctionTypedFormalParameter) { _functionTypedFormalParameter(node); } else if (node is GenericTypeAlias) { // TODO(scheglov) ??? } else if (node is MethodDeclaration) { var returnType = node.returnType?.type; if (returnType == null) { if (node.isSetter) { returnType = _voidType; } else if (node.isOperator && node.name.name == '[]=') { returnType = _voidType; } else { returnType = _dynamicType; } } LazyAst.setReturnType(node, returnType); } else if (node is MixinDeclaration) { // TODO(scheglov) ??? } else if (node is SimpleFormalParameter) { LazyAst.setType(node, node.type?.type ?? _dynamicType); } else if (node is VariableDeclarationList) { var type = node.type?.type; if (type != null) { for (var variable in node.variables) { LazyAst.setType(variable, type); } } } else { throw UnimplementedError('${node.runtimeType}'); } } void _extensionDeclaration(ExtensionDeclaration node) {} void _fieldFormalParameter(FieldFormalParameter node) { var parameterList = node.parameters; if (parameterList != null) { var type = _buildFunctionType( node.typeParameters, node.type, parameterList, ); LazyAst.setType(node, type); } else { LazyAst.setType(node, node.type?.type ?? _dynamicType); } } void _functionTypeAlias(FunctionTypeAlias node) { var returnTypeNode = node.returnType; LazyAst.setReturnType(node, returnTypeNode?.type ?? _dynamicType); } void _functionTypedFormalParameter(FunctionTypedFormalParameter node) { var type = _buildFunctionType( node.typeParameters, node.returnType, node.parameters, ); LazyAst.setType(node, type); } static DartType _getType(FormalParameter node) { if (node is DefaultFormalParameter) { return _getType(node.parameter); } return LazyAst.getType(node); } } /// Performs mixins inference in a [ClassDeclaration]. class _MixinInference { final Dart2TypeSystem typeSystem; final FeatureSet featureSet; final InterfaceType classType; List<InterfaceType> mixinTypes = []; List<InterfaceType> supertypesForMixinInference; _MixinInference(this.typeSystem, this.featureSet, this.classType); NullabilitySuffix get _noneOrStarSuffix { return _nonNullableEnabled ? NullabilitySuffix.none : NullabilitySuffix.star; } bool get _nonNullableEnabled => featureSet.isEnabled(Feature.non_nullable); void perform(WithClause withClause) { if (withClause == null) return; for (var mixinNode in withClause.mixinTypes) { var mixinType = _inferSingle(mixinNode); mixinTypes.add(mixinType); _addSupertypes(mixinType); } } void _addSupertypes(InterfaceType type) { if (supertypesForMixinInference != null) { ClassElementImpl.collectAllSupertypes( supertypesForMixinInference, type, classType, ); } } InterfaceType _findInterfaceTypeForElement( ClassElement element, List<InterfaceType> interfaceTypes, ) { for (var interfaceType in interfaceTypes) { if (interfaceType.element == element) return interfaceType; } return null; } List<InterfaceType> _findInterfaceTypesForConstraints( List<InterfaceType> constraints, List<InterfaceType> interfaceTypes, ) { var result = <InterfaceType>[]; for (var constraint in constraints) { var interfaceType = _findInterfaceTypeForElement( constraint.element, interfaceTypes, ); // No matching interface type found, so inference fails. if (interfaceType == null) { return null; } result.add(interfaceType); } return result; } InterfaceType _inferSingle(TypeName mixinNode) { var mixinType = _interfaceType(mixinNode.type); if (mixinNode.typeArguments != null) { return mixinType; } var mixinElement = mixinType.element; if (mixinElement.typeParameters.isEmpty) { return mixinType; } var mixinSupertypeConstraints = typeSystem.gatherMixinSupertypeConstraintsForInference(mixinElement); if (mixinSupertypeConstraints.isEmpty) { return mixinType; } if (supertypesForMixinInference == null) { supertypesForMixinInference = <InterfaceType>[]; _addSupertypes(classType.superclass); for (var previousMixinType in mixinTypes) { _addSupertypes(previousMixinType); } } var matchingInterfaceTypes = _findInterfaceTypesForConstraints( mixinSupertypeConstraints, supertypesForMixinInference, ); // Note: if matchingInterfaceType is null, that's an error. Also, // if there are multiple matching interface types that use // different type parameters, that's also an error. But we can't // report errors from the linker, so we just use the // first matching interface type (if there is one). The error // detection logic is implemented in the ErrorVerifier. if (matchingInterfaceTypes == null) { return mixinType; } // Try to pattern match matchingInterfaceTypes against // mixinSupertypeConstraints to find the correct set of type // parameters to apply to the mixin. var inferredTypeArguments = typeSystem.matchSupertypeConstraints( mixinElement, mixinSupertypeConstraints, matchingInterfaceTypes, ); if (inferredTypeArguments != null) { var inferredMixin = mixinElement.instantiate( typeArguments: inferredTypeArguments, nullabilitySuffix: _noneOrStarSuffix, ); mixinType = inferredMixin; mixinNode.type = inferredMixin; } return mixinType; } InterfaceType _interfaceType(DartType type) { if (type is InterfaceType && !type.element.isEnum) { return type; } return typeSystem.typeProvider.objectType; } } /// Performs mixin inference for all declarations. class _MixinsInference { final Dart2TypeSystem typeSystem; _MixinsInference(this.typeSystem); void perform(List<AstNode> declarations) { for (var node in declarations) { if (node is ClassDeclaration || node is ClassTypeAlias) { ClassElementImpl element = (node as Declaration).declaredElement; element.linkedMixinInferenceCallback = _callbackWhenRecursion; } } for (var declaration in declarations) { _inferDeclaration(declaration); } } /// This method is invoked when mixins are asked from the [element], and /// we are inferring the [element] now, i.e. there is a loop. /// /// This is an error. So, we return the empty list, and break the loop. List<InterfaceType> _callbackWhenLoop(ClassElementImpl element) { element.linkedMixinInferenceCallback = null; return <InterfaceType>[]; } /// This method is invoked when mixins are asked from the [element], and /// we are not inferring the [element] now, i.e. there is no loop. List<InterfaceType> _callbackWhenRecursion(ClassElementImpl element) { _inferDeclaration(element.linkedNode); // The inference was successful, let the element return actual mixins. return null; } void _infer(ClassElementImpl element, WithClause withClause) { element.linkedMixinInferenceCallback = _callbackWhenLoop; try { var featureSet = _unitFeatureSet(element); _MixinInference(typeSystem, featureSet, element.thisType) .perform(withClause); } finally { element.linkedMixinInferenceCallback = null; } } void _inferDeclaration(AstNode node) { if (node is ClassDeclaration) { _infer(node.declaredElement, node.withClause); } else if (node is ClassTypeAlias) { _infer(node.declaredElement, node.withClause); } } static FeatureSet _unitFeatureSet(ClassElementImpl element) { var unit = element.linkedNode.parent as CompilationUnit; return unit.featureSet; } }
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/summary2/core_types.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/src/summary2/linked_element_factory.dart'; class CoreTypes { final LinkedElementFactory _elementFactory; LibraryElement _coreLibrary; ClassElement _objectClass; CoreTypes(this._elementFactory); LibraryElement get coreLibrary { return _coreLibrary ??= _elementFactory.libraryOfUri('dart:core'); } ClassElement get objectClass { return _objectClass ??= _getCoreClass('Object'); } ClassElement _getCoreClass(String name) { return coreLibrary.getType(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/summary2/tokens_writer.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/token.dart'; import 'package:analyzer/src/summary/idl.dart'; class TokensWriter { static UnlinkedTokenType astToBinaryTokenType(TokenType type) { if (type == Keyword.ABSTRACT) { return UnlinkedTokenType.ABSTRACT; } else if (type == TokenType.AMPERSAND) { return UnlinkedTokenType.AMPERSAND; } else if (type == TokenType.AMPERSAND_AMPERSAND) { return UnlinkedTokenType.AMPERSAND_AMPERSAND; } else if (type == TokenType.AMPERSAND_EQ) { return UnlinkedTokenType.AMPERSAND_EQ; } else if (type == TokenType.AS) { return UnlinkedTokenType.AS; } else if (type == Keyword.ASSERT) { return UnlinkedTokenType.ASSERT; } else if (type == Keyword.ASYNC) { return UnlinkedTokenType.ASYNC; } else if (type == TokenType.AT) { return UnlinkedTokenType.AT; } else if (type == Keyword.AWAIT) { return UnlinkedTokenType.AWAIT; } else if (type == TokenType.BACKPING) { return UnlinkedTokenType.BACKPING; } else if (type == TokenType.BACKSLASH) { return UnlinkedTokenType.BACKSLASH; } else if (type == TokenType.BANG) { return UnlinkedTokenType.BANG; } else if (type == TokenType.BANG_EQ) { return UnlinkedTokenType.BANG_EQ; } else if (type == TokenType.BANG_EQ_EQ) { return UnlinkedTokenType.BANG_EQ_EQ; } else if (type == TokenType.BAR) { return UnlinkedTokenType.BAR; } else if (type == TokenType.BAR_BAR) { return UnlinkedTokenType.BAR_BAR; } else if (type == TokenType.BAR_EQ) { return UnlinkedTokenType.BAR_EQ; } else if (type == Keyword.BREAK) { return UnlinkedTokenType.BREAK; } else if (type == TokenType.CARET) { return UnlinkedTokenType.CARET; } else if (type == TokenType.CARET_EQ) { return UnlinkedTokenType.CARET_EQ; } else if (type == Keyword.CASE) { return UnlinkedTokenType.CASE; } else if (type == Keyword.CATCH) { return UnlinkedTokenType.CATCH; } else if (type == Keyword.CLASS) { return UnlinkedTokenType.CLASS; } else if (type == TokenType.CLOSE_CURLY_BRACKET) { return UnlinkedTokenType.CLOSE_CURLY_BRACKET; } else if (type == TokenType.CLOSE_PAREN) { return UnlinkedTokenType.CLOSE_PAREN; } else if (type == TokenType.CLOSE_SQUARE_BRACKET) { return UnlinkedTokenType.CLOSE_SQUARE_BRACKET; } else if (type == TokenType.COLON) { return UnlinkedTokenType.COLON; } else if (type == TokenType.COMMA) { return UnlinkedTokenType.COMMA; } else if (type == Keyword.CONST) { return UnlinkedTokenType.CONST; } else if (type == Keyword.CONTINUE) { return UnlinkedTokenType.CONTINUE; } else if (type == Keyword.COVARIANT) { return UnlinkedTokenType.COVARIANT; } else if (type == Keyword.DEFAULT) { return UnlinkedTokenType.DEFAULT; } else if (type == Keyword.DEFERRED) { return UnlinkedTokenType.DEFERRED; } else if (type == Keyword.DO) { return UnlinkedTokenType.DO; } else if (type == TokenType.DOUBLE) { return UnlinkedTokenType.DOUBLE; } else if (type == Keyword.DYNAMIC) { return UnlinkedTokenType.DYNAMIC; } else if (type == Keyword.ELSE) { return UnlinkedTokenType.ELSE; } else if (type == Keyword.ENUM) { return UnlinkedTokenType.ENUM; } else if (type == TokenType.EOF) { return UnlinkedTokenType.EOF; } else if (type == TokenType.EQ) { return UnlinkedTokenType.EQ; } else if (type == TokenType.EQ_EQ) { return UnlinkedTokenType.EQ_EQ; } else if (type == TokenType.EQ_EQ_EQ) { return UnlinkedTokenType.EQ_EQ_EQ; } else if (type == Keyword.EXPORT) { return UnlinkedTokenType.EXPORT; } else if (type == Keyword.EXTENDS) { return UnlinkedTokenType.EXTENDS; } else if (type == Keyword.EXTERNAL) { return UnlinkedTokenType.EXTERNAL; } else if (type == Keyword.FACTORY) { return UnlinkedTokenType.FACTORY; } else if (type == Keyword.FALSE) { return UnlinkedTokenType.FALSE; } else if (type == Keyword.FINAL) { return UnlinkedTokenType.FINAL; } else if (type == Keyword.FINALLY) { return UnlinkedTokenType.FINALLY; } else if (type == Keyword.FOR) { return UnlinkedTokenType.FOR; } else if (type == Keyword.FUNCTION) { return UnlinkedTokenType.FUNCTION_KEYWORD; } else if (type == TokenType.FUNCTION) { return UnlinkedTokenType.FUNCTION; } else if (type == Keyword.GET) { return UnlinkedTokenType.GET; } else if (type == TokenType.GT) { return UnlinkedTokenType.GT; } else if (type == TokenType.GT_EQ) { return UnlinkedTokenType.GT_EQ; } else if (type == TokenType.GT_GT) { return UnlinkedTokenType.GT_GT; } else if (type == TokenType.GT_GT_EQ) { return UnlinkedTokenType.GT_GT_EQ; } else if (type == TokenType.GT_GT_GT) { return UnlinkedTokenType.GT_GT_GT; } else if (type == TokenType.GT_GT_GT_EQ) { return UnlinkedTokenType.GT_GT_GT_EQ; } else if (type == TokenType.HASH) { return UnlinkedTokenType.HASH; } else if (type == TokenType.HEXADECIMAL) { return UnlinkedTokenType.HEXADECIMAL; } else if (type == Keyword.HIDE) { return UnlinkedTokenType.HIDE; } else if (type == TokenType.IDENTIFIER) { return UnlinkedTokenType.IDENTIFIER; } else if (type == Keyword.IF) { return UnlinkedTokenType.IF; } else if (type == Keyword.IMPLEMENTS) { return UnlinkedTokenType.IMPLEMENTS; } else if (type == Keyword.IMPORT) { return UnlinkedTokenType.IMPORT; } else if (type == Keyword.IN) { return UnlinkedTokenType.IN; } else if (type == TokenType.INDEX) { return UnlinkedTokenType.INDEX; } else if (type == TokenType.INDEX_EQ) { return UnlinkedTokenType.INDEX_EQ; } else if (type == TokenType.INT) { return UnlinkedTokenType.INT; } else if (type == Keyword.INTERFACE) { return UnlinkedTokenType.INTERFACE; } else if (type == TokenType.IS) { return UnlinkedTokenType.IS; } else if (type == Keyword.LATE) { return UnlinkedTokenType.LATE; } else if (type == Keyword.LIBRARY) { return UnlinkedTokenType.LIBRARY; } else if (type == TokenType.LT) { return UnlinkedTokenType.LT; } else if (type == TokenType.LT_EQ) { return UnlinkedTokenType.LT_EQ; } else if (type == TokenType.LT_LT) { return UnlinkedTokenType.LT_LT; } else if (type == TokenType.LT_LT_EQ) { return UnlinkedTokenType.LT_LT_EQ; } else if (type == TokenType.MINUS) { return UnlinkedTokenType.MINUS; } else if (type == TokenType.MINUS_EQ) { return UnlinkedTokenType.MINUS_EQ; } else if (type == TokenType.MINUS_MINUS) { return UnlinkedTokenType.MINUS_MINUS; } else if (type == Keyword.MIXIN) { return UnlinkedTokenType.MIXIN; } else if (type == TokenType.MULTI_LINE_COMMENT) { return UnlinkedTokenType.MULTI_LINE_COMMENT; } else if (type == Keyword.NATIVE) { return UnlinkedTokenType.NATIVE; } else if (type == Keyword.NEW) { return UnlinkedTokenType.NEW; } else if (type == Keyword.NULL) { return UnlinkedTokenType.NULL; } else if (type == Keyword.OF) { return UnlinkedTokenType.OF; } else if (type == Keyword.ON) { return UnlinkedTokenType.ON; } else if (type == TokenType.OPEN_CURLY_BRACKET) { return UnlinkedTokenType.OPEN_CURLY_BRACKET; } else if (type == TokenType.OPEN_PAREN) { return UnlinkedTokenType.OPEN_PAREN; } else if (type == TokenType.OPEN_SQUARE_BRACKET) { return UnlinkedTokenType.OPEN_SQUARE_BRACKET; } else if (type == Keyword.OPERATOR) { return UnlinkedTokenType.OPERATOR; } else if (type == Keyword.PART) { return UnlinkedTokenType.PART; } else if (type == Keyword.PATCH) { return UnlinkedTokenType.PATCH; } else if (type == TokenType.PERCENT) { return UnlinkedTokenType.PERCENT; } else if (type == TokenType.PERCENT_EQ) { return UnlinkedTokenType.PERCENT_EQ; } else if (type == TokenType.PERIOD) { return UnlinkedTokenType.PERIOD; } else if (type == TokenType.PERIOD_PERIOD) { return UnlinkedTokenType.PERIOD_PERIOD; } else if (type == TokenType.PERIOD_PERIOD_PERIOD) { return UnlinkedTokenType.PERIOD_PERIOD_PERIOD; } else if (type == TokenType.PERIOD_PERIOD_PERIOD_QUESTION) { return UnlinkedTokenType.PERIOD_PERIOD_PERIOD_QUESTION; } else if (type == TokenType.PLUS) { return UnlinkedTokenType.PLUS; } else if (type == TokenType.PLUS_EQ) { return UnlinkedTokenType.PLUS_EQ; } else if (type == TokenType.PLUS_PLUS) { return UnlinkedTokenType.PLUS_PLUS; } else if (type == TokenType.QUESTION) { return UnlinkedTokenType.QUESTION; } else if (type == TokenType.QUESTION_PERIOD) { return UnlinkedTokenType.QUESTION_PERIOD; } else if (type == TokenType.QUESTION_QUESTION) { return UnlinkedTokenType.QUESTION_QUESTION; } else if (type == TokenType.QUESTION_QUESTION_EQ) { return UnlinkedTokenType.QUESTION_QUESTION_EQ; } else if (type == Keyword.REQUIRED) { return UnlinkedTokenType.REQUIRED; } else if (type == Keyword.RETHROW) { return UnlinkedTokenType.RETHROW; } else if (type == Keyword.RETURN) { return UnlinkedTokenType.RETURN; } else if (type == TokenType.SCRIPT_TAG) { return UnlinkedTokenType.SCRIPT_TAG; } else if (type == TokenType.SEMICOLON) { return UnlinkedTokenType.SEMICOLON; } else if (type == Keyword.SET) { return UnlinkedTokenType.SET; } else if (type == Keyword.SHOW) { return UnlinkedTokenType.SHOW; } else if (type == TokenType.SINGLE_LINE_COMMENT) { return UnlinkedTokenType.SINGLE_LINE_COMMENT; } else if (type == TokenType.SLASH) { return UnlinkedTokenType.SLASH; } else if (type == TokenType.SLASH_EQ) { return UnlinkedTokenType.SLASH_EQ; } else if (type == Keyword.SOURCE) { return UnlinkedTokenType.SOURCE; } else if (type == TokenType.STAR) { return UnlinkedTokenType.STAR; } else if (type == TokenType.STAR_EQ) { return UnlinkedTokenType.STAR_EQ; } else if (type == Keyword.STATIC) { return UnlinkedTokenType.STATIC; } else if (type == TokenType.STRING) { return UnlinkedTokenType.STRING; } else if (type == TokenType.STRING_INTERPOLATION_EXPRESSION) { return UnlinkedTokenType.STRING_INTERPOLATION_EXPRESSION; } else if (type == TokenType.STRING_INTERPOLATION_IDENTIFIER) { return UnlinkedTokenType.STRING_INTERPOLATION_IDENTIFIER; } else if (type == Keyword.SUPER) { return UnlinkedTokenType.SUPER; } else if (type == Keyword.SWITCH) { return UnlinkedTokenType.SWITCH; } else if (type == Keyword.SYNC) { return UnlinkedTokenType.SYNC; } else if (type == Keyword.THIS) { return UnlinkedTokenType.THIS; } else if (type == Keyword.THROW) { return UnlinkedTokenType.THROW; } else if (type == TokenType.TILDE) { return UnlinkedTokenType.TILDE; } else if (type == TokenType.TILDE_SLASH) { return UnlinkedTokenType.TILDE_SLASH; } else if (type == TokenType.TILDE_SLASH_EQ) { return UnlinkedTokenType.TILDE_SLASH_EQ; } else if (type == Keyword.TRUE) { return UnlinkedTokenType.TRUE; } else if (type == Keyword.TRY) { return UnlinkedTokenType.TRY; } else if (type == Keyword.TYPEDEF) { return UnlinkedTokenType.TYPEDEF; } else if (type == Keyword.VAR) { return UnlinkedTokenType.VAR; } else if (type == Keyword.VOID) { return UnlinkedTokenType.VOID; } else if (type == Keyword.WHILE) { return UnlinkedTokenType.WHILE; } else if (type == Keyword.WITH) { return UnlinkedTokenType.WITH; } else if (type == Keyword.YIELD) { return UnlinkedTokenType.YIELD; } else { throw StateError('Unexpected type: $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/summary2/ast_binary_writer.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/ast/ast.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/ast_binary_flags.dart'; import 'package:analyzer/src/summary2/informative_data.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/linking_bundle_context.dart'; import 'package:analyzer/src/summary2/tokens_writer.dart'; var timerAstBinaryWriter = Stopwatch(); var timerAstBinaryWriterClass = Stopwatch(); var timerAstBinaryWriterDirective = Stopwatch(); var timerAstBinaryWriterFunctionBody = Stopwatch(); var timerAstBinaryWriterMixin = Stopwatch(); var timerAstBinaryWriterTopVar = Stopwatch(); var timerAstBinaryWriterTypedef = Stopwatch(); /// Serializer of fully resolved ASTs into flat buffers. class AstBinaryWriter extends ThrowingAstVisitor<LinkedNodeBuilder> { final LinkingBundleContext _linkingContext; /// Is `true` if the current [ClassDeclaration] has a const constructor, /// so initializers of final fields should be written. bool _hasConstConstructor = false; AstBinaryWriter(this._linkingContext); @override LinkedNodeBuilder visitAdjacentStrings(AdjacentStrings node) { return LinkedNodeBuilder.adjacentStrings( adjacentStrings_strings: _writeNodeList(node.strings), ); } @override LinkedNodeBuilder visitAnnotation(Annotation node) { var elementComponents = _componentsOfElement(node.element); LinkedNodeBuilder storedArguments; var arguments = node.arguments; if (arguments != null) { if (arguments.arguments.every(_isSerializableExpression)) { storedArguments = arguments.accept(this); } else { storedArguments = LinkedNodeBuilder.argumentList(); } } return LinkedNodeBuilder.annotation( annotation_arguments: storedArguments, annotation_constructorName: node.constructorName?.accept(this), annotation_element: elementComponents.rawElement, annotation_substitution: elementComponents.substitution, annotation_name: node.name?.accept(this), ); } @override LinkedNodeBuilder visitArgumentList(ArgumentList node) { return LinkedNodeBuilder.argumentList( argumentList_arguments: _writeNodeList(node.arguments), ); } @override LinkedNodeBuilder visitAsExpression(AsExpression node) { return LinkedNodeBuilder.asExpression( asExpression_expression: node.expression.accept(this), asExpression_type: node.type.accept(this), ); } @override LinkedNodeBuilder visitAssertInitializer(AssertInitializer node) { return LinkedNodeBuilder.assertInitializer( assertInitializer_condition: node.condition.accept(this), assertInitializer_message: node.message?.accept(this), ); } @override LinkedNodeBuilder visitAssertStatement(AssertStatement node) { var builder = LinkedNodeBuilder.assertStatement( assertStatement_condition: node.condition.accept(this), assertStatement_message: node.message?.accept(this), ); _storeStatement(builder, node); return builder; } @override LinkedNodeBuilder visitAssignmentExpression(AssignmentExpression node) { var elementComponents = _componentsOfElement(node.staticElement); return LinkedNodeBuilder.assignmentExpression( assignmentExpression_element: elementComponents.rawElement, assignmentExpression_substitution: elementComponents.substitution, assignmentExpression_leftHandSide: node.leftHandSide.accept(this), assignmentExpression_operator: TokensWriter.astToBinaryTokenType( node.operator.type, ), assignmentExpression_rightHandSide: node.rightHandSide.accept(this), expression_type: _writeType(node.staticType), ); } @override LinkedNodeBuilder visitAwaitExpression(AwaitExpression node) { return LinkedNodeBuilder.awaitExpression( awaitExpression_expression: node.expression.accept(this), expression_type: _writeType(node.staticType), ); } @override LinkedNodeBuilder visitBinaryExpression(BinaryExpression node) { var elementComponents = _componentsOfElement(node.staticElement); return LinkedNodeBuilder.binaryExpression( binaryExpression_element: elementComponents.rawElement, binaryExpression_substitution: elementComponents.substitution, binaryExpression_leftOperand: node.leftOperand.accept(this), binaryExpression_operator: TokensWriter.astToBinaryTokenType( node.operator.type, ), binaryExpression_rightOperand: node.rightOperand.accept(this), expression_type: _writeType(node.staticType), ); } @override LinkedNodeBuilder visitBlock(Block node) { return LinkedNodeBuilder.block( block_statements: _writeNodeList(node.statements), ); } @override LinkedNodeBuilder visitBlockFunctionBody(BlockFunctionBody node) { timerAstBinaryWriterFunctionBody.start(); try { var builder = LinkedNodeBuilder.blockFunctionBody( blockFunctionBody_block: node.block.accept(this), ); builder.flags = AstBinaryFlags.encode( isAsync: node.keyword?.keyword == Keyword.ASYNC, isStar: node.star != null, isSync: node.keyword?.keyword == Keyword.SYNC, ); return builder; } finally { timerAstBinaryWriterFunctionBody.stop(); } } @override LinkedNodeBuilder visitBooleanLiteral(BooleanLiteral node) { return LinkedNodeBuilder.booleanLiteral( booleanLiteral_value: node.value, ); } @override LinkedNodeBuilder visitBreakStatement(BreakStatement node) { var builder = LinkedNodeBuilder.breakStatement( breakStatement_label: node.label?.accept(this), ); _storeStatement(builder, node); return builder; } @override LinkedNodeBuilder visitCascadeExpression(CascadeExpression node) { var builder = LinkedNodeBuilder.cascadeExpression( cascadeExpression_target: node.target.accept(this), cascadeExpression_sections: _writeNodeList(node.cascadeSections), ); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitCatchClause(CatchClause node) { return LinkedNodeBuilder.catchClause( catchClause_body: node.body.accept(this), catchClause_exceptionParameter: node.exceptionParameter?.accept(this), catchClause_exceptionType: node.exceptionType?.accept(this), catchClause_stackTraceParameter: node.stackTraceParameter?.accept(this), ); } @override LinkedNodeBuilder visitClassDeclaration(ClassDeclaration node) { try { timerAstBinaryWriterClass.start(); _hasConstConstructor = false; for (var member in node.members) { if (member is ConstructorDeclaration && member.constKeyword != null) { _hasConstConstructor = true; break; } } var builder = LinkedNodeBuilder.classDeclaration( classDeclaration_extendsClause: node.extendsClause?.accept(this), classDeclaration_nativeClause: node.nativeClause?.accept(this), classDeclaration_withClause: node.withClause?.accept(this), ); builder.flags = AstBinaryFlags.encode( isAbstract: node.abstractKeyword != null, ); _storeClassOrMixinDeclaration(builder, node); return builder; } finally { timerAstBinaryWriterClass.stop(); } } @override LinkedNodeBuilder visitClassTypeAlias(ClassTypeAlias node) { timerAstBinaryWriterClass.start(); try { var builder = LinkedNodeBuilder.classTypeAlias( classTypeAlias_implementsClause: node.implementsClause?.accept(this), classTypeAlias_superclass: node.superclass.accept(this), classTypeAlias_typeParameters: node.typeParameters?.accept(this), classTypeAlias_withClause: node.withClause.accept(this), ); builder.flags = AstBinaryFlags.encode( isAbstract: node.abstractKeyword != null, ); _storeTypeAlias(builder, node); _storeIsSimpleBounded(builder, node); return builder; } finally { timerAstBinaryWriterClass.stop(); } } @override LinkedNodeBuilder visitComment(Comment node) { LinkedNodeCommentType type; if (node.isBlock) { type = LinkedNodeCommentType.block; } else if (node.isDocumentation) { type = LinkedNodeCommentType.documentation; } else if (node.isEndOfLine) { type = LinkedNodeCommentType.endOfLine; } return LinkedNodeBuilder.comment( comment_tokens: node.tokens.map((t) => t.lexeme).toList(), comment_type: type, // TODO(scheglov) restore // comment_references: _writeNodeList(node.references), ); } @override LinkedNodeBuilder visitCommentReference(CommentReference node) { // var identifier = node.identifier; // _tokensWriter.writeTokens( // node.newKeyword ?? identifier.beginToken, // identifier.endToken, // ); // // return LinkedNodeBuilder.commentReference( // commentReference_identifier: identifier.accept(this), // commentReference_newKeyword: _getToken(node.newKeyword), // ); return null; } @override LinkedNodeBuilder visitCompilationUnit(CompilationUnit node) { var builder = LinkedNodeBuilder.compilationUnit( compilationUnit_declarations: _writeNodeList(node.declarations), compilationUnit_directives: _writeNodeList(node.directives), compilationUnit_scriptTag: node.scriptTag?.accept(this), informativeId: getInformativeId(node), ); return builder; } @override LinkedNodeBuilder visitConditionalExpression(ConditionalExpression node) { var builder = LinkedNodeBuilder.conditionalExpression( conditionalExpression_condition: node.condition.accept(this), conditionalExpression_elseExpression: node.elseExpression.accept(this), conditionalExpression_thenExpression: node.thenExpression.accept(this), ); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitConfiguration(Configuration node) { var builder = LinkedNodeBuilder.configuration( configuration_name: node.name?.accept(this), configuration_value: node.value?.accept(this), configuration_uri: node.uri?.accept(this), ); builder.flags = AstBinaryFlags.encode( hasEqual: node.equalToken != null, ); return builder; } @override LinkedNodeBuilder visitConstructorDeclaration(ConstructorDeclaration node) { var builder = LinkedNodeBuilder.constructorDeclaration( constructorDeclaration_initializers: _writeNodeList(node.initializers), constructorDeclaration_parameters: node.parameters.accept(this), constructorDeclaration_redirectedConstructor: node.redirectedConstructor?.accept(this), constructorDeclaration_returnType: node.returnType.accept(this), informativeId: getInformativeId(node), ); builder.flags = AstBinaryFlags.encode( hasName: node.name != null, hasSeparatorColon: node.separator?.type == TokenType.COLON, hasSeparatorEquals: node.separator?.type == TokenType.EQ, isAbstract: node.body is EmptyFunctionBody, isConst: node.constKeyword != null, isExternal: node.externalKeyword != null, isFactory: node.factoryKeyword != null, ); builder.name = node.name?.name; _storeClassMember(builder, node); return builder; } @override LinkedNodeBuilder visitConstructorFieldInitializer( ConstructorFieldInitializer node) { var builder = LinkedNodeBuilder.constructorFieldInitializer( constructorFieldInitializer_expression: node.expression.accept(this), constructorFieldInitializer_fieldName: node.fieldName.accept(this), ); builder.flags = AstBinaryFlags.encode( hasThis: node.thisKeyword != null, ); _storeConstructorInitializer(builder, node); return builder; } @override LinkedNodeBuilder visitConstructorName(ConstructorName node) { var elementComponents = _componentsOfElement(node.staticElement); return LinkedNodeBuilder.constructorName( constructorName_element: elementComponents.rawElement, constructorName_substitution: elementComponents.substitution, constructorName_name: node.name?.accept(this), constructorName_type: node.type.accept(this), ); } @override LinkedNodeBuilder visitContinueStatement(ContinueStatement node) { var builder = LinkedNodeBuilder.continueStatement( continueStatement_label: node.label?.accept(this), ); _storeStatement(builder, node); return builder; } @override LinkedNodeBuilder visitDeclaredIdentifier(DeclaredIdentifier node) { var builder = LinkedNodeBuilder.declaredIdentifier( declaredIdentifier_identifier: node.identifier.accept(this), declaredIdentifier_type: node.type?.accept(this), ); builder.flags = AstBinaryFlags.encode( isConst: node.keyword?.keyword == Keyword.CONST, isFinal: node.keyword?.keyword == Keyword.FINAL, isVar: node.keyword?.keyword == Keyword.VAR, ); _storeDeclaration(builder, node); return builder; } @override LinkedNodeBuilder visitDefaultFormalParameter(DefaultFormalParameter node) { var defaultValue = node.defaultValue; if (!_isSerializableExpression(defaultValue)) { defaultValue = null; } var builder = LinkedNodeBuilder.defaultFormalParameter( defaultFormalParameter_defaultValue: defaultValue?.accept(this), defaultFormalParameter_kind: _toParameterKind(node), defaultFormalParameter_parameter: node.parameter.accept(this), informativeId: getInformativeId(node), ); builder.flags = AstBinaryFlags.encode( hasInitializer: node.defaultValue != null, ); return builder; } @override LinkedNodeBuilder visitDoStatement(DoStatement node) { return LinkedNodeBuilder.doStatement( doStatement_body: node.body.accept(this), doStatement_condition: node.condition.accept(this), ); } @override LinkedNodeBuilder visitDottedName(DottedName node) { return LinkedNodeBuilder.dottedName( dottedName_components: _writeNodeList(node.components), ); } @override LinkedNodeBuilder visitDoubleLiteral(DoubleLiteral node) { return LinkedNodeBuilder.doubleLiteral( doubleLiteral_value: node.value, ); } @override LinkedNodeBuilder visitEmptyFunctionBody(EmptyFunctionBody node) { var builder = LinkedNodeBuilder.emptyFunctionBody(); _storeFunctionBody(builder, node); return builder; } @override LinkedNodeBuilder visitEmptyStatement(EmptyStatement node) { return LinkedNodeBuilder.emptyStatement(); } @override LinkedNodeBuilder visitEnumConstantDeclaration(EnumConstantDeclaration node) { var builder = LinkedNodeBuilder.enumConstantDeclaration( informativeId: getInformativeId(node), ); builder..name = node.name.name; _storeDeclaration(builder, node); return builder; } @override LinkedNodeBuilder visitEnumDeclaration(EnumDeclaration node) { var builder = LinkedNodeBuilder.enumDeclaration( enumDeclaration_constants: _writeNodeList(node.constants), ); _storeNamedCompilationUnitMember(builder, node); return builder; } @override LinkedNodeBuilder visitExportDirective(ExportDirective node) { timerAstBinaryWriterDirective.start(); try { var builder = LinkedNodeBuilder.exportDirective(); _storeNamespaceDirective(builder, node); return builder; } finally { timerAstBinaryWriterDirective.stop(); } } @override LinkedNodeBuilder visitExpressionFunctionBody(ExpressionFunctionBody node) { timerAstBinaryWriterFunctionBody.start(); try { var builder = LinkedNodeBuilder.expressionFunctionBody( expressionFunctionBody_expression: node.expression.accept(this), ); builder.flags = AstBinaryFlags.encode( isAsync: node.keyword?.keyword == Keyword.ASYNC, isSync: node.keyword?.keyword == Keyword.SYNC, ); return builder; } finally { timerAstBinaryWriterFunctionBody.stop(); } } @override LinkedNodeBuilder visitExpressionStatement(ExpressionStatement node) { return LinkedNodeBuilder.expressionStatement( expressionStatement_expression: node.expression.accept(this), ); } @override LinkedNodeBuilder visitExtendsClause(ExtendsClause node) { return LinkedNodeBuilder.extendsClause( extendsClause_superclass: node.superclass.accept(this), ); } @override LinkedNodeBuilder visitExtensionDeclaration(ExtensionDeclaration node) { var builder = LinkedNodeBuilder.extensionDeclaration( extensionDeclaration_extendedType: node.extendedType.accept(this), extensionDeclaration_members: _writeNodeList(node.members), extensionDeclaration_typeParameters: node.typeParameters?.accept(this), ); _storeCompilationUnitMember(builder, node); _storeInformativeId(builder, node); builder.name = node.name?.name; LazyExtensionDeclaration.get(node).put(builder); return builder; } @override LinkedNodeBuilder visitExtensionOverride(ExtensionOverride node) { var builder = LinkedNodeBuilder.extensionOverride( extensionOverride_arguments: _writeNodeList( node.argumentList.arguments, ), extensionOverride_extensionName: node.extensionName.accept(this), extensionOverride_typeArguments: node.typeArguments?.accept(this), extensionOverride_typeArgumentTypes: node.typeArgumentTypes.map(_writeType).toList(), extensionOverride_extendedType: _writeType(node.extendedType), ); return builder; } @override LinkedNodeBuilder visitFieldDeclaration(FieldDeclaration node) { var builder = LinkedNodeBuilder.fieldDeclaration( fieldDeclaration_fields: node.fields.accept(this), informativeId: getInformativeId(node), ); builder.flags = AstBinaryFlags.encode( isCovariant: node.covariantKeyword != null, isStatic: node.staticKeyword != null, ); _storeClassMember(builder, node); return builder; } @override LinkedNodeBuilder visitFieldFormalParameter(FieldFormalParameter node) { var builder = LinkedNodeBuilder.fieldFormalParameter( fieldFormalParameter_formalParameters: node.parameters?.accept(this), fieldFormalParameter_type: node.type?.accept(this), fieldFormalParameter_typeParameters: node.typeParameters?.accept(this), ); _storeNormalFormalParameter(builder, node, node.keyword); return builder; } @override LinkedNodeBuilder visitForEachPartsWithDeclaration( ForEachPartsWithDeclaration node) { var builder = LinkedNodeBuilder.forEachPartsWithDeclaration( forEachPartsWithDeclaration_loopVariable: node.loopVariable.accept(this), ); _storeForEachParts(builder, node); return builder; } @override LinkedNodeBuilder visitForEachPartsWithIdentifier( ForEachPartsWithIdentifier node) { var builder = LinkedNodeBuilder.forEachPartsWithIdentifier( forEachPartsWithIdentifier_identifier: node.identifier.accept(this), ); _storeForEachParts(builder, node); return builder; } @override LinkedNodeBuilder visitForElement(ForElement node) { var builder = LinkedNodeBuilder.forElement( forElement_body: node.body.accept(this), ); _storeForMixin(builder, node as ForElementImpl); return builder; } @override LinkedNodeBuilder visitFormalParameterList(FormalParameterList node) { var builder = LinkedNodeBuilder.formalParameterList( formalParameterList_parameters: _writeNodeList(node.parameters), ); builder.flags = AstBinaryFlags.encode( isDelimiterCurly: node.leftDelimiter?.type == TokenType.OPEN_CURLY_BRACKET, isDelimiterSquare: node.leftDelimiter?.type == TokenType.OPEN_SQUARE_BRACKET, ); return builder; } @override LinkedNodeBuilder visitForPartsWithDeclarations( ForPartsWithDeclarations node) { var builder = LinkedNodeBuilder.forPartsWithDeclarations( forPartsWithDeclarations_variables: node.variables.accept(this), ); _storeForParts(builder, node); return builder; } @override LinkedNodeBuilder visitForPartsWithExpression(ForPartsWithExpression node) { var builder = LinkedNodeBuilder.forPartsWithExpression( forPartsWithExpression_initialization: node.initialization?.accept(this), ); _storeForParts(builder, node); return builder; } @override LinkedNodeBuilder visitForStatement(ForStatement node) { var builder = LinkedNodeBuilder.forStatement( forStatement_body: node.body.accept(this), ); _storeForMixin(builder, node as ForStatementImpl); return builder; } @override LinkedNodeBuilder visitFunctionDeclaration(FunctionDeclaration node) { var builder = LinkedNodeBuilder.functionDeclaration( functionDeclaration_returnType: node.returnType?.accept(this), functionDeclaration_functionExpression: node.functionExpression?.accept(this), ); builder.flags = AstBinaryFlags.encode( isExternal: node.externalKeyword != null, isGet: node.isGetter, isSet: node.isSetter, ); _storeNamedCompilationUnitMember(builder, node); _writeActualReturnType(builder, node); return builder; } @override LinkedNodeBuilder visitFunctionDeclarationStatement( FunctionDeclarationStatement node) { return LinkedNodeBuilder.functionDeclarationStatement( functionDeclarationStatement_functionDeclaration: node.functionDeclaration.accept(this), ); } @override LinkedNodeBuilder visitFunctionExpression(FunctionExpression node) { var bodyToStore = node.body; if (node.parent.parent is CompilationUnit) { bodyToStore = null; } var builder = LinkedNodeBuilder.functionExpression( functionExpression_typeParameters: node.typeParameters?.accept(this), functionExpression_formalParameters: node.parameters?.accept(this), functionExpression_body: bodyToStore?.accept(this), ); builder.flags = AstBinaryFlags.encode( isAsync: node.body?.isAsynchronous ?? false, isGenerator: node.body?.isGenerator ?? false, ); return builder; } @override LinkedNodeBuilder visitFunctionExpressionInvocation( FunctionExpressionInvocation node) { var builder = LinkedNodeBuilder.functionExpressionInvocation( functionExpressionInvocation_function: node.function?.accept(this), ); _storeInvocationExpression(builder, node); return builder; } @override LinkedNodeBuilder visitFunctionTypeAlias(FunctionTypeAlias node) { timerAstBinaryWriterTypedef.start(); try { var builder = LinkedNodeBuilder.functionTypeAlias( functionTypeAlias_formalParameters: node.parameters.accept(this), functionTypeAlias_returnType: node.returnType?.accept(this), functionTypeAlias_typeParameters: node.typeParameters?.accept(this), typeAlias_hasSelfReference: LazyFunctionTypeAlias.getHasSelfReference(node), ); _storeTypeAlias(builder, node); _writeActualReturnType(builder, node); _storeIsSimpleBounded(builder, node); return builder; } finally { timerAstBinaryWriterTypedef.stop(); } } @override LinkedNodeBuilder visitFunctionTypedFormalParameter( FunctionTypedFormalParameter node) { var builder = LinkedNodeBuilder.functionTypedFormalParameter( functionTypedFormalParameter_formalParameters: node.parameters.accept(this), functionTypedFormalParameter_returnType: node.returnType?.accept(this), functionTypedFormalParameter_typeParameters: node.typeParameters?.accept(this), ); _storeNormalFormalParameter(builder, node, null); return builder; } @override LinkedNodeBuilder visitGenericFunctionType(GenericFunctionType node) { var id = LazyAst.getGenericFunctionTypeId(node); assert(id != null); var builder = LinkedNodeBuilder.genericFunctionType( genericFunctionType_id: id, genericFunctionType_returnType: node.returnType?.accept(this), genericFunctionType_typeParameters: node.typeParameters?.accept(this), genericFunctionType_formalParameters: node.parameters.accept(this), genericFunctionType_type: _writeType(node.type), ); builder.flags = AstBinaryFlags.encode( hasQuestion: node.question != null, ); _writeActualReturnType(builder, node); return builder; } @override LinkedNodeBuilder visitGenericTypeAlias(GenericTypeAlias node) { timerAstBinaryWriterTypedef.start(); try { var builder = LinkedNodeBuilder.genericTypeAlias( genericTypeAlias_typeParameters: node.typeParameters?.accept(this), genericTypeAlias_functionType: node.functionType?.accept(this), typeAlias_hasSelfReference: LazyGenericTypeAlias.getHasSelfReference(node), ); _storeTypeAlias(builder, node); _storeIsSimpleBounded(builder, node); return builder; } finally { timerAstBinaryWriterTypedef.stop(); } } @override LinkedNodeBuilder visitHideCombinator(HideCombinator node) { var builder = LinkedNodeBuilder.hideCombinator( names: node.hiddenNames.map((id) => id.name).toList(), ); _storeInformativeId(builder, node); return builder; } @override LinkedNodeBuilder visitIfElement(IfElement node) { var builder = LinkedNodeBuilder.ifElement( ifMixin_condition: node.condition.accept(this), ifElement_elseElement: node.elseElement?.accept(this), ifElement_thenElement: node.thenElement.accept(this), ); return builder; } @override LinkedNodeBuilder visitIfStatement(IfStatement node) { var builder = LinkedNodeBuilder.ifStatement( ifMixin_condition: node.condition.accept(this), ifStatement_elseStatement: node.elseStatement?.accept(this), ifStatement_thenStatement: node.thenStatement.accept(this), ); return builder; } @override LinkedNodeBuilder visitImplementsClause(ImplementsClause node) { return LinkedNodeBuilder.implementsClause( implementsClause_interfaces: _writeNodeList(node.interfaces), ); } @override LinkedNodeBuilder visitImportDirective(ImportDirective node) { timerAstBinaryWriterDirective.start(); try { var builder = LinkedNodeBuilder.importDirective( importDirective_prefix: node.prefix?.name, ); builder.flags = AstBinaryFlags.encode( isDeferred: node.deferredKeyword != null, ); _storeNamespaceDirective(builder, node); return builder; } finally { timerAstBinaryWriterDirective.stop(); } } @override LinkedNodeBuilder visitIndexExpression(IndexExpression node) { var elementComponents = _componentsOfElement(node.staticElement); var builder = LinkedNodeBuilder.indexExpression( indexExpression_element: elementComponents.rawElement, indexExpression_substitution: elementComponents.substitution, indexExpression_index: node.index.accept(this), indexExpression_target: node.target?.accept(this), expression_type: _writeType(node.staticType), ); builder.flags = AstBinaryFlags.encode( hasPeriod: node.period != null, ); return builder; } @override LinkedNodeBuilder visitInstanceCreationExpression( InstanceCreationExpression node) { InstanceCreationExpressionImpl nodeImpl = node; var builder = LinkedNodeBuilder.instanceCreationExpression( instanceCreationExpression_arguments: _writeNodeList( node.argumentList.arguments, ), instanceCreationExpression_constructorName: node.constructorName.accept(this), instanceCreationExpression_typeArguments: nodeImpl.typeArguments?.accept(this), expression_type: _writeType(node.staticType), ); builder.flags = AstBinaryFlags.encode( isConst: node.keyword?.type == Keyword.CONST, isNew: node.keyword?.type == Keyword.NEW, ); return builder; } @override LinkedNodeBuilder visitIntegerLiteral(IntegerLiteral node) { return LinkedNodeBuilder.integerLiteral( expression_type: _writeType(node.staticType), integerLiteral_value: node.value, ); } @override LinkedNodeBuilder visitInterpolationExpression(InterpolationExpression node) { return LinkedNodeBuilder.interpolationExpression( interpolationExpression_expression: node.expression.accept(this), )..flags = AstBinaryFlags.encode( isStringInterpolationIdentifier: node.leftBracket.type == TokenType.STRING_INTERPOLATION_IDENTIFIER, ); } @override LinkedNodeBuilder visitInterpolationString(InterpolationString node) { return LinkedNodeBuilder.interpolationString( interpolationString_value: node.value, ); } @override LinkedNodeBuilder visitIsExpression(IsExpression node) { var builder = LinkedNodeBuilder.isExpression( isExpression_expression: node.expression.accept(this), isExpression_type: node.type.accept(this), ); builder.flags = AstBinaryFlags.encode( hasNot: node.notOperator != null, ); return builder; } @override LinkedNodeBuilder visitLabel(Label node) { return LinkedNodeBuilder.label( label_label: node.label.accept(this), ); } @override LinkedNodeBuilder visitLabeledStatement(LabeledStatement node) { return LinkedNodeBuilder.labeledStatement( labeledStatement_labels: _writeNodeList(node.labels), labeledStatement_statement: node.statement.accept(this), ); } @override LinkedNodeBuilder visitLibraryDirective(LibraryDirective node) { timerAstBinaryWriterDirective.start(); try { var builder = LinkedNodeBuilder.libraryDirective( informativeId: getInformativeId(node), libraryDirective_name: node.name.accept(this), ); _storeDirective(builder, node); return builder; } finally { timerAstBinaryWriterDirective.stop(); } } @override LinkedNodeBuilder visitLibraryIdentifier(LibraryIdentifier node) { return LinkedNodeBuilder.libraryIdentifier( libraryIdentifier_components: _writeNodeList(node.components), ); } @override LinkedNodeBuilder visitListLiteral(ListLiteral node) { var builder = LinkedNodeBuilder.listLiteral( listLiteral_elements: _writeNodeList(node.elements), ); _storeTypedLiteral(builder, node); return builder; } @override LinkedNodeBuilder visitMapLiteralEntry(MapLiteralEntry node) { return LinkedNodeBuilder.mapLiteralEntry( mapLiteralEntry_key: node.key.accept(this), mapLiteralEntry_value: node.value.accept(this), ); } @override LinkedNodeBuilder visitMethodDeclaration(MethodDeclaration node) { var builder = LinkedNodeBuilder.methodDeclaration( methodDeclaration_returnType: node.returnType?.accept(this), methodDeclaration_typeParameters: node.typeParameters?.accept(this), methodDeclaration_formalParameters: node.parameters?.accept(this), ); builder.name = node.name.name; builder.flags = AstBinaryFlags.encode( isAbstract: node.body is EmptyFunctionBody, isAsync: node.body?.isAsynchronous ?? false, isExternal: node.externalKeyword != null, isGenerator: node.body?.isGenerator ?? false, isGet: node.isGetter, isNative: node.body is NativeFunctionBody, isOperator: node.operatorKeyword != null, isSet: node.isSetter, isStatic: node.isStatic, ); _storeClassMember(builder, node); _storeInformativeId(builder, node); _writeActualReturnType(builder, node); return builder; } @override LinkedNodeBuilder visitMethodInvocation(MethodInvocation node) { var builder = LinkedNodeBuilder.methodInvocation( methodInvocation_methodName: node.methodName?.accept(this), methodInvocation_target: node.target?.accept(this), ); builder.flags = AstBinaryFlags.encode( hasPeriod: node.operator?.type == TokenType.PERIOD, hasPeriod2: node.operator?.type == TokenType.PERIOD_PERIOD, ); _storeInvocationExpression(builder, node); return builder; } @override LinkedNodeBuilder visitMixinDeclaration(MixinDeclaration node) { timerAstBinaryWriterMixin.start(); try { var builder = LinkedNodeBuilder.mixinDeclaration( mixinDeclaration_onClause: node.onClause?.accept(this), ); _storeClassOrMixinDeclaration(builder, node); LazyMixinDeclaration.get(node).put(builder); return builder; } finally { timerAstBinaryWriterMixin.stop(); } } @override LinkedNodeBuilder visitNamedExpression(NamedExpression node) { return LinkedNodeBuilder.namedExpression( namedExpression_expression: node.expression.accept(this), namedExpression_name: node.name.accept(this), ); } @override LinkedNodeBuilder visitNativeClause(NativeClause node) { return LinkedNodeBuilder.nativeClause( nativeClause_name: node.name.accept(this), ); } @override LinkedNodeBuilder visitNativeFunctionBody(NativeFunctionBody node) { return LinkedNodeBuilder.nativeFunctionBody( nativeFunctionBody_stringLiteral: node.stringLiteral?.accept(this), ); } @override LinkedNodeBuilder visitNullLiteral(NullLiteral node) { return LinkedNodeBuilder.nullLiteral(); } @override LinkedNodeBuilder visitOnClause(OnClause node) { return LinkedNodeBuilder.onClause( onClause_superclassConstraints: _writeNodeList(node.superclassConstraints), ); } @override LinkedNodeBuilder visitParenthesizedExpression(ParenthesizedExpression node) { var builder = LinkedNodeBuilder.parenthesizedExpression( parenthesizedExpression_expression: node.expression.accept(this), ); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitPartDirective(PartDirective node) { timerAstBinaryWriterDirective.start(); try { var builder = LinkedNodeBuilder.partDirective(); _storeUriBasedDirective(builder, node); return builder; } finally { timerAstBinaryWriterDirective.stop(); } } @override LinkedNodeBuilder visitPartOfDirective(PartOfDirective node) { timerAstBinaryWriterDirective.start(); try { var builder = LinkedNodeBuilder.partOfDirective( partOfDirective_libraryName: node.libraryName?.accept(this), partOfDirective_uri: node.uri?.accept(this), ); _storeDirective(builder, node); return builder; } finally { timerAstBinaryWriterDirective.stop(); } } @override LinkedNodeBuilder visitPostfixExpression(PostfixExpression node) { var elementComponents = _componentsOfElement(node.staticElement); return LinkedNodeBuilder.postfixExpression( expression_type: _writeType(node.staticType), postfixExpression_element: elementComponents.rawElement, postfixExpression_substitution: elementComponents.substitution, postfixExpression_operand: node.operand.accept(this), postfixExpression_operator: TokensWriter.astToBinaryTokenType( node.operator.type, ), ); } @override LinkedNodeBuilder visitPrefixedIdentifier(PrefixedIdentifier node) { return LinkedNodeBuilder.prefixedIdentifier( prefixedIdentifier_identifier: node.identifier.accept(this), prefixedIdentifier_prefix: node.prefix.accept(this), expression_type: _writeType(node.staticType), ); } @override LinkedNodeBuilder visitPrefixExpression(PrefixExpression node) { var elementComponents = _componentsOfElement(node.staticElement); return LinkedNodeBuilder.prefixExpression( expression_type: _writeType(node.staticType), prefixExpression_element: elementComponents.rawElement, prefixExpression_substitution: elementComponents.substitution, prefixExpression_operand: node.operand.accept(this), prefixExpression_operator: TokensWriter.astToBinaryTokenType( node.operator.type, ), ); } @override LinkedNodeBuilder visitPropertyAccess(PropertyAccess node) { var builder = LinkedNodeBuilder.propertyAccess( propertyAccess_operator: TokensWriter.astToBinaryTokenType( node.operator.type, ), propertyAccess_propertyName: node.propertyName.accept(this), propertyAccess_target: node.target?.accept(this), ); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { var elementComponents = _componentsOfElement(node.staticElement); var builder = LinkedNodeBuilder.redirectingConstructorInvocation( redirectingConstructorInvocation_arguments: node.argumentList.accept(this), redirectingConstructorInvocation_constructorName: node.constructorName?.accept(this), redirectingConstructorInvocation_element: elementComponents.rawElement, redirectingConstructorInvocation_substitution: elementComponents.substitution, ); builder.flags = AstBinaryFlags.encode( hasThis: node.thisKeyword != null, ); _storeConstructorInitializer(builder, node); return builder; } @override LinkedNodeBuilder visitRethrowExpression(RethrowExpression node) { return LinkedNodeBuilder.rethrowExpression( expression_type: _writeType(node.staticType), ); } @override LinkedNodeBuilder visitReturnStatement(ReturnStatement node) { return LinkedNodeBuilder.returnStatement( returnStatement_expression: node.expression?.accept(this), ); } @override LinkedNodeBuilder visitScriptTag(ScriptTag node) { return null; } @override LinkedNodeBuilder visitSetOrMapLiteral(SetOrMapLiteral node) { var builder = LinkedNodeBuilder.setOrMapLiteral( setOrMapLiteral_elements: _writeNodeList(node.elements), ); _storeTypedLiteral(builder, node, isMap: node.isMap, isSet: node.isSet); return builder; } @override LinkedNodeBuilder visitShowCombinator(ShowCombinator node) { var builder = LinkedNodeBuilder.showCombinator( names: node.shownNames.map((id) => id.name).toList(), ); _storeInformativeId(builder, node); return builder; } @override LinkedNodeBuilder visitSimpleFormalParameter(SimpleFormalParameter node) { var builder = LinkedNodeBuilder.simpleFormalParameter( simpleFormalParameter_type: node.type?.accept(this), ); builder.topLevelTypeInferenceError = LazyAst.getTypeInferenceError(node); _storeNormalFormalParameter(builder, node, node.keyword); _storeInheritsCovariant(builder, node); return builder; } @override LinkedNodeBuilder visitSimpleIdentifier(SimpleIdentifier node) { Element element; if (!node.inDeclarationContext()) { element = node.staticElement; if (element is MultiplyDefinedElement) { element = null; } } var elementComponents = _componentsOfElement(element); var builder = LinkedNodeBuilder.simpleIdentifier( simpleIdentifier_element: elementComponents.rawElement, simpleIdentifier_substitution: elementComponents.substitution, expression_type: _writeType(node.staticType), ); builder.flags = AstBinaryFlags.encode( isDeclaration: node is DeclaredSimpleIdentifier, ); builder.name = node.name; return builder; } @override LinkedNodeBuilder visitSimpleStringLiteral(SimpleStringLiteral node) { var builder = LinkedNodeBuilder.simpleStringLiteral( simpleStringLiteral_value: node.value, ); return builder; } @override LinkedNodeBuilder visitSpreadElement(SpreadElement node) { return LinkedNodeBuilder.spreadElement( spreadElement_expression: node.expression.accept(this), spreadElement_spreadOperator: TokensWriter.astToBinaryTokenType( node.spreadOperator.type, ), ); } @override LinkedNodeBuilder visitStringInterpolation(StringInterpolation node) { return LinkedNodeBuilder.stringInterpolation( stringInterpolation_elements: _writeNodeList(node.elements), ); } @override LinkedNodeBuilder visitSuperConstructorInvocation( SuperConstructorInvocation node) { var elementComponents = _componentsOfElement(node.staticElement); var builder = LinkedNodeBuilder.superConstructorInvocation( superConstructorInvocation_arguments: node.argumentList.accept(this), superConstructorInvocation_constructorName: node.constructorName?.accept(this), superConstructorInvocation_element: elementComponents.rawElement, superConstructorInvocation_substitution: elementComponents.substitution, ); _storeConstructorInitializer(builder, node); return builder; } @override LinkedNodeBuilder visitSuperExpression(SuperExpression node) { var builder = LinkedNodeBuilder.superExpression(); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitSwitchCase(SwitchCase node) { var builder = LinkedNodeBuilder.switchCase( switchCase_expression: node.expression.accept(this), ); _storeSwitchMember(builder, node); return builder; } @override LinkedNodeBuilder visitSwitchDefault(SwitchDefault node) { var builder = LinkedNodeBuilder.switchDefault(); _storeSwitchMember(builder, node); return builder; } @override LinkedNodeBuilder visitSwitchStatement(SwitchStatement node) { return LinkedNodeBuilder.switchStatement( switchStatement_expression: node.expression.accept(this), switchStatement_members: _writeNodeList(node.members), ); } @override LinkedNodeBuilder visitSymbolLiteral(SymbolLiteral node) { var builder = LinkedNodeBuilder.symbolLiteral( names: node.components.map((t) => t.lexeme).toList(), ); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitThisExpression(ThisExpression node) { var builder = LinkedNodeBuilder.thisExpression(); _storeExpression(builder, node); return builder; } @override LinkedNodeBuilder visitThrowExpression(ThrowExpression node) { return LinkedNodeBuilder.throwExpression( throwExpression_expression: node.expression.accept(this), expression_type: _writeType(node.staticType), ); } @override LinkedNodeBuilder visitTopLevelVariableDeclaration( TopLevelVariableDeclaration node) { timerAstBinaryWriterTopVar.start(); try { var builder = LinkedNodeBuilder.topLevelVariableDeclaration( informativeId: getInformativeId(node), topLevelVariableDeclaration_variableList: node.variables?.accept(this), ); _storeCompilationUnitMember(builder, node); return builder; } finally { timerAstBinaryWriterTopVar.stop(); } } @override LinkedNodeBuilder visitTryStatement(TryStatement node) { return LinkedNodeBuilder.tryStatement( tryStatement_body: node.body.accept(this), tryStatement_catchClauses: _writeNodeList(node.catchClauses), tryStatement_finallyBlock: node.finallyBlock?.accept(this), ); } @override LinkedNodeBuilder visitTypeArgumentList(TypeArgumentList node) { return LinkedNodeBuilder.typeArgumentList( typeArgumentList_arguments: _writeNodeList(node.arguments), ); } @override LinkedNodeBuilder visitTypeName(TypeName node) { return LinkedNodeBuilder.typeName( typeName_name: node.name.accept(this), typeName_type: _writeType(node.type), typeName_typeArguments: _writeNodeList( node.typeArguments?.arguments, ), )..flags = AstBinaryFlags.encode( hasQuestion: node.question != null, hasTypeArguments: node.typeArguments != null, ); } @override LinkedNodeBuilder visitTypeParameter(TypeParameter node) { var builder = LinkedNodeBuilder.typeParameter( typeParameter_bound: node.bound?.accept(this), typeParameter_defaultType: _writeType(LazyAst.getDefaultType(node)), informativeId: getInformativeId(node), ); builder.name = node.name.name; _storeDeclaration(builder, node); return builder; } @override LinkedNodeBuilder visitTypeParameterList(TypeParameterList node) { return LinkedNodeBuilder.typeParameterList( typeParameterList_typeParameters: _writeNodeList(node.typeParameters), ); } @override LinkedNodeBuilder visitVariableDeclaration(VariableDeclaration node) { var initializer = node.initializer; var declarationList = node.parent as VariableDeclarationList; var declaration = declarationList.parent; if (declaration is TopLevelVariableDeclaration) { if (!declarationList.isConst) { initializer = null; } } else if (declaration is FieldDeclaration) { if (!(declarationList.isConst || !declaration.isStatic && declarationList.isFinal && _hasConstConstructor)) { initializer = null; } } if (!_isSerializableExpression(initializer)) { initializer = null; } var builder = LinkedNodeBuilder.variableDeclaration( informativeId: getInformativeId(node), variableDeclaration_initializer: initializer?.accept(this), ); builder.flags = AstBinaryFlags.encode( hasInitializer: node.initializer != null, ); builder.name = node.name.name; builder.topLevelTypeInferenceError = LazyAst.getTypeInferenceError(node); _writeActualType(builder, node); _storeInheritsCovariant(builder, node); return builder; } @override LinkedNodeBuilder visitVariableDeclarationList(VariableDeclarationList node) { var builder = LinkedNodeBuilder.variableDeclarationList( variableDeclarationList_type: node.type?.accept(this), variableDeclarationList_variables: _writeNodeList(node.variables), ); builder.flags = AstBinaryFlags.encode( isConst: node.isConst, isFinal: node.isFinal, isLate: node.lateKeyword != null, isVar: node.keyword?.keyword == Keyword.VAR, ); _storeAnnotatedNode(builder, node); return builder; } @override LinkedNodeBuilder visitVariableDeclarationStatement( VariableDeclarationStatement node) { return LinkedNodeBuilder.variableDeclarationStatement( variableDeclarationStatement_variables: node.variables.accept(this), ); } @override LinkedNodeBuilder visitWhileStatement(WhileStatement node) { return LinkedNodeBuilder.whileStatement( whileStatement_body: node.body.accept(this), whileStatement_condition: node.condition.accept(this), ); } @override LinkedNodeBuilder visitWithClause(WithClause node) { return LinkedNodeBuilder.withClause( withClause_mixinTypes: _writeNodeList(node.mixinTypes), ); } @override LinkedNodeBuilder visitYieldStatement(YieldStatement node) { var builder = LinkedNodeBuilder.yieldStatement( yieldStatement_expression: node.expression.accept(this), ); builder.flags = AstBinaryFlags.encode( isStar: node.star != null, ); _storeStatement(builder, node); return builder; } LinkedNodeBuilder writeUnit(CompilationUnit unit) { timerAstBinaryWriter.start(); try { return unit.accept(this); } finally { timerAstBinaryWriter.stop(); } } _ElementComponents _componentsOfElement(Element element) { while (element is ParameterMember) { element = (element as ParameterMember).baseElement; } if (element is Member) { var elementIndex = _indexOfElement(element.baseElement); var substitution = element.substitution.map; var substitutionBuilder = LinkedNodeTypeSubstitutionBuilder( typeParameters: substitution.keys.map(_indexOfElement).toList(), typeArguments: substitution.values.map(_writeType).toList(), ); return _ElementComponents(elementIndex, substitutionBuilder); } var elementIndex = _indexOfElement(element); return _ElementComponents(elementIndex, null); } int _indexOfElement(Element element) { return _linkingContext.indexOfElement(element); } void _storeAnnotatedNode(LinkedNodeBuilder builder, AnnotatedNode node) { builder.annotatedNode_metadata = _writeNodeList(node.metadata); } void _storeClassMember(LinkedNodeBuilder builder, ClassMember node) { _storeDeclaration(builder, node); } void _storeClassOrMixinDeclaration( LinkedNodeBuilder builder, ClassOrMixinDeclaration node) { builder ..classOrMixinDeclaration_implementsClause = node.implementsClause?.accept(this) ..classOrMixinDeclaration_members = _writeNodeList(node.members) ..classOrMixinDeclaration_typeParameters = node.typeParameters?.accept(this); _storeNamedCompilationUnitMember(builder, node); _storeIsSimpleBounded(builder, node); } void _storeCompilationUnitMember( LinkedNodeBuilder builder, CompilationUnitMember node) { _storeDeclaration(builder, node); } void _storeConstructorInitializer( LinkedNodeBuilder builder, ConstructorInitializer node) {} void _storeDeclaration(LinkedNodeBuilder builder, Declaration node) { _storeAnnotatedNode(builder, node); } void _storeDirective(LinkedNodeBuilder builder, Directive node) { _storeAnnotatedNode(builder, node); _storeInformativeId(builder, node); } void _storeExpression(LinkedNodeBuilder builder, Expression node) { builder.expression_type = _writeType(node.staticType); } void _storeForEachParts(LinkedNodeBuilder builder, ForEachParts node) { _storeForLoopParts(builder, node); builder..forEachParts_iterable = node.iterable?.accept(this); } void _storeForLoopParts(LinkedNodeBuilder builder, ForLoopParts node) {} void _storeFormalParameter(LinkedNodeBuilder builder, FormalParameter node) { _writeActualType(builder, node); } void _storeForMixin(LinkedNodeBuilder builder, ForMixin node) { builder.flags = AstBinaryFlags.encode( hasAwait: node.awaitKeyword != null, ); builder..forMixin_forLoopParts = node.forLoopParts.accept(this); } void _storeForParts(LinkedNodeBuilder builder, ForParts node) { _storeForLoopParts(builder, node); builder ..forParts_condition = node.condition?.accept(this) ..forParts_updaters = _writeNodeList(node.updaters); } void _storeFunctionBody(LinkedNodeBuilder builder, FunctionBody node) {} void _storeInformativeId(LinkedNodeBuilder builder, AstNode node) { builder.informativeId = getInformativeId(node); } void _storeInheritsCovariant(LinkedNodeBuilder builder, AstNode node) { var value = LazyAst.getInheritsCovariant(node); builder.inheritsCovariant = value; } void _storeInvocationExpression( LinkedNodeBuilder builder, InvocationExpression node) { _storeExpression(builder, node); builder ..invocationExpression_arguments = node.argumentList.accept(this) ..invocationExpression_invokeType = _writeType(node.staticInvokeType) ..invocationExpression_typeArguments = node.typeArguments?.accept(this); } void _storeIsSimpleBounded(LinkedNodeBuilder builder, AstNode node) { var flag = LazyAst.isSimplyBounded(node); // TODO(scheglov) Check for `null` when writing resolved AST. builder.simplyBoundable_isSimplyBounded = flag; } void _storeNamedCompilationUnitMember( LinkedNodeBuilder builder, NamedCompilationUnitMember node) { _storeCompilationUnitMember(builder, node); _storeInformativeId(builder, node); builder.name = node.name.name; } void _storeNamespaceDirective( LinkedNodeBuilder builder, NamespaceDirective node) { _storeUriBasedDirective(builder, node); builder ..namespaceDirective_combinators = _writeNodeList(node.combinators) ..namespaceDirective_configurations = _writeNodeList(node.configurations) ..namespaceDirective_selectedUri = LazyDirective.getSelectedUri(node); } void _storeNormalFormalParameter( LinkedNodeBuilder builder, NormalFormalParameter node, Token keyword) { _storeFormalParameter(builder, node); builder ..flags = AstBinaryFlags.encode( isConst: keyword?.type == Keyword.CONST, isCovariant: node.covariantKeyword != null, isFinal: keyword?.type == Keyword.FINAL, isRequired: node.requiredKeyword != null, isVar: keyword?.type == Keyword.VAR, ) ..informativeId = getInformativeId(node) ..name = node.identifier?.name ..normalFormalParameter_metadata = _writeNodeList(node.metadata); } void _storeStatement(LinkedNodeBuilder builder, Statement node) {} void _storeSwitchMember(LinkedNodeBuilder builder, SwitchMember node) { builder.switchMember_labels = _writeNodeList(node.labels); builder.switchMember_statements = _writeNodeList(node.statements); } void _storeTypeAlias(LinkedNodeBuilder builder, TypeAlias node) { _storeNamedCompilationUnitMember(builder, node); } void _storeTypedLiteral(LinkedNodeBuilder builder, TypedLiteral node, {bool isMap: false, bool isSet: false}) { _storeExpression(builder, node); builder ..flags = AstBinaryFlags.encode( hasTypeArguments: node.typeArguments != null, isConst: node.constKeyword != null, isMap: isMap, isSet: isSet, ) ..typedLiteral_typeArguments = _writeNodeList( node.typeArguments?.arguments, ); } void _storeUriBasedDirective( LinkedNodeBuilder builder, UriBasedDirective node) { _storeDirective(builder, node); builder ..uriBasedDirective_uri = node.uri.accept(this) ..uriBasedDirective_uriContent = node.uriContent ..uriBasedDirective_uriElement = _indexOfElement(node.uriElement); } void _writeActualReturnType(LinkedNodeBuilder builder, AstNode node) { var type = LazyAst.getReturnType(node); // TODO(scheglov) Check for `null` when writing resolved AST. builder.actualReturnType = _writeType(type); } void _writeActualType(LinkedNodeBuilder builder, AstNode node) { var type = LazyAst.getType(node); // TODO(scheglov) Check for `null` when writing resolved AST. builder.actualType = _writeType(type); } List<LinkedNodeBuilder> _writeNodeList(List<AstNode> nodeList) { if (nodeList == null) { return const <LinkedNodeBuilder>[]; } var result = List<LinkedNodeBuilder>.filled( nodeList.length, null, growable: true, ); for (var i = 0; i < nodeList.length; ++i) { result[i] = nodeList[i].accept(this); } return result; } LinkedNodeTypeBuilder _writeType(DartType type) { return _linkingContext.writeType(type); } /// Return `true` if the expression might be successfully serialized. /// /// This does not mean that the expression is constant, it just means that /// we know that it might be serialized and deserialized. For example /// function expressions are problematic, and are not necessary to /// deserialize, so we choose not to do this. static bool _isSerializableExpression(Expression node) { if (node == null) return false; var visitor = _IsSerializableExpressionVisitor(); node.accept(visitor); return visitor.result; } static LinkedNodeFormalParameterKind _toParameterKind(FormalParameter node) { if (node.isRequiredPositional) { return LinkedNodeFormalParameterKind.requiredPositional; } else if (node.isRequiredNamed) { return LinkedNodeFormalParameterKind.requiredNamed; } else if (node.isOptionalPositional) { return LinkedNodeFormalParameterKind.optionalPositional; } else if (node.isOptionalNamed) { return LinkedNodeFormalParameterKind.optionalNamed; } else { throw new StateError('Unknown kind of parameter'); } } } /// Components of a [Member] - the raw element, and the substitution. class _ElementComponents { final int rawElement; final LinkedNodeTypeSubstitutionBuilder substitution; _ElementComponents(this.rawElement, this.substitution); } class _IsSerializableExpressionVisitor extends RecursiveAstVisitor<void> { bool result = true; @override void visitFunctionExpression(FunctionExpression node) { result = 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/summary2/reference_resolver.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/nullability_suffix.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/function_type_builder.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/linked_element_factory.dart'; import 'package:analyzer/src/summary2/linking_node_scope.dart'; import 'package:analyzer/src/summary2/named_type_builder.dart'; import 'package:analyzer/src/summary2/reference.dart'; import 'package:analyzer/src/summary2/types_builder.dart'; /// Recursive visitor of [LinkedNode]s that resolves explicit type annotations /// in outlines. This includes resolving element references in identifiers /// in type annotation, and setting [LinkedNodeType]s for corresponding type /// annotation nodes. /// /// Declarations that have type annotations, e.g. return types of methods, get /// the corresponding type set (so, if there is an explicit type annotation, /// the type is set, otherwise we keep it empty, so we will attempt to infer /// it later). class ReferenceResolver extends ThrowingAstVisitor<void> { final NodesToBuildType nodesToBuildType; final LinkedElementFactory elementFactory; final LibraryElement _libraryElement; final Reference unitReference; /// Indicates whether the library is opted into NNBD. final bool isNNBD; /// The depth-first number of the next [GenericFunctionType] node. int _nextGenericFunctionTypeId = 0; Reference reference; Scope scope; /// Is `true` if the current [ClassDeclaration] has a const constructor. bool _hasConstConstructor = false; ReferenceResolver( this.nodesToBuildType, this.elementFactory, this._libraryElement, this.unitReference, this.isNNBD, this.scope, ) : reference = unitReference; @override void visitBlockFunctionBody(BlockFunctionBody node) {} @override void visitClassDeclaration(ClassDeclaration node) { var outerScope = scope; var outerReference = reference; var name = node.name.name; reference = reference.getChild('@class').getChild(name); ClassElementImpl element = reference.element; node.name.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new TypeParameterScope(scope, element); node.typeParameters?.accept(this); node.extendsClause?.accept(this); node.implementsClause?.accept(this); node.withClause?.accept(this); scope = new ClassScope(scope, element); LinkingNodeContext(node, scope); _hasConstConstructor = false; for (var member in node.members) { if (member is ConstructorDeclaration && member.constKeyword != null) { _hasConstConstructor = true; break; } } node.members.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitClassTypeAlias(ClassTypeAlias node) { var outerScope = scope; var outerReference = reference; var name = node.name.name; reference = reference.getChild('@class').getChild(name); ClassElementImpl element = reference.element; node.name.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new TypeParameterScope(scope, element); scope = new ClassScope(scope, element); LinkingNodeContext(node, scope); node.typeParameters?.accept(this); node.superclass?.accept(this); node.withClause?.accept(this); node.implementsClause?.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitCompilationUnit(CompilationUnit node) { LinkingNodeContext(node, scope); node.declarations.accept(this); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { var outerScope = scope; var outerReference = reference; var name = node.name?.name ?? ''; reference = reference.getChild('@constructor').getChild(name); var element = ConstructorElementImpl.forLinkedNode( outerReference.element, reference, node, ); var functionScope = FunctionScope(scope, element); functionScope.defineParameters(); LinkingNodeContext(node, functionScope); node.parameters?.accept(this); node.initializers.accept( _SetGenericFunctionTypeIdVisitor(this), ); scope = outerScope; reference = outerReference; } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { node.parameter.accept(this); node.defaultValue?.accept( _SetGenericFunctionTypeIdVisitor(this), ); } @override void visitEnumDeclaration(EnumDeclaration node) {} @override void visitExpressionFunctionBody(ExpressionFunctionBody node) {} @override void visitExtendsClause(ExtendsClause node) { node.superclass.accept(this); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { var outerScope = scope; var outerReference = reference; var refName = LazyExtensionDeclaration.get(node).refName; reference = reference.getChild('@extension').getChild(refName); ExtensionElementImpl element = reference.element; node.name?.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new TypeParameterScope(scope, element); node.typeParameters?.accept(this); node.extendedType.accept(this); scope = new ExtensionScope(scope, element); LinkingNodeContext(node, scope); node.members.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitFieldDeclaration(FieldDeclaration node) { node.fields.accept(this); if (node.fields.isConst || !node.isStatic && node.fields.isFinal && _hasConstConstructor) { var visitor = _SetGenericFunctionTypeIdVisitor(this); node.fields.variables.accept(visitor); } } @override void visitFieldFormalParameter(FieldFormalParameter node) { var outerScope = scope; var outerReference = reference; var name = node.identifier.name; reference = reference.getChild('@parameter').getChild(name); reference.node = node; var element = ParameterElementImpl.forLinkedNode( outerReference.element, reference, node, ); node.identifier.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new EnclosedScope(scope); for (var typeParameter in element.typeParameters) { scope.define(typeParameter); } node.type?.accept(this); node.typeParameters?.accept(this); node.parameters?.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitFormalParameterList(FormalParameterList node) { node.parameters.accept(this); } @override void visitFunctionDeclaration(FunctionDeclaration node) { var outerScope = scope; var outerReference = reference; var container = '@function'; var propertyKeyword = node.propertyKeyword?.keyword; if (propertyKeyword == Keyword.GET) { container = '@getter'; } else if (propertyKeyword == Keyword.SET) { container = '@setter'; } var name = node.name.name; reference = reference.getChild(container).getChild(name); ExecutableElementImpl element = reference.element; node.name.staticElement = element; _createTypeParameterElements(node.functionExpression.typeParameters); scope = new FunctionScope(scope, element); LinkingNodeContext(node, scope); node.returnType?.accept(this); node.functionExpression.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitFunctionExpression(FunctionExpression node) { node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { var outerScope = scope; var outerReference = reference; var name = node.name.name; reference = reference.getChild('@typeAlias').getChild(name); GenericTypeAliasElementImpl element = reference.element; node.name.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = FunctionTypeScope(outerScope, element); node.returnType?.accept(this); node.typeParameters?.accept(this); reference = reference.getChild('@function'); reference.element = element; node.parameters.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { var outerScope = scope; var outerReference = reference; var name = node.identifier.name; reference = reference.getChild('@parameter').getChild(name); reference.node = node; var element = ParameterElementImpl.forLinkedNode( outerReference.element, reference, node, ); node.identifier.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new EnclosedScope(scope); for (var typeParameter in element.typeParameters) { scope.define(typeParameter); } node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitGenericFunctionType(GenericFunctionType node) { var outerScope = scope; var outerReference = reference; var id = _nextGenericFunctionTypeId++; LazyAst.setGenericFunctionTypeId(node, id); var containerRef = unitReference.getChild('@genericFunctionType'); reference = containerRef.getChild('$id'); var element = GenericFunctionTypeElementImpl.forLinkedNode( unitReference.element, reference, node, ); (node as GenericFunctionTypeImpl).declaredElement = element; _createTypeParameterElements(node.typeParameters); scope = TypeParameterScope(outerScope, element); node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters.accept(this); var nullabilitySuffix = _getNullabilitySuffix(node.question != null); var builder = FunctionTypeBuilder.of(isNNBD, node, nullabilitySuffix); (node as GenericFunctionTypeImpl).type = builder; nodesToBuildType.addTypeBuilder(builder); scope = outerScope; reference = outerReference; } @override void visitGenericTypeAlias(GenericTypeAlias node) { var outerScope = scope; var outerReference = reference; var name = node.name.name; reference = reference.getChild('@typeAlias').getChild(name); GenericTypeAliasElementImpl element = reference.element; node.name.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = TypeParameterScope(outerScope, element); node.typeParameters?.accept(this); node.functionType?.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitImplementsClause(ImplementsClause node) { node.interfaces.accept(this); } @override void visitMethodDeclaration(MethodDeclaration node) { var outerScope = scope; var outerReference = reference; var container = '@method'; var propertyKeyword = node.propertyKeyword?.keyword; if (propertyKeyword == Keyword.GET) { container = '@getter'; } else if (propertyKeyword == Keyword.SET) { container = '@setter'; } var name = node.name.name; reference = reference.getChild(container).getChild(name); var element = MethodElementImpl.forLinkedNode( outerReference.element, reference, node, ); node.name.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new FunctionScope(scope, element); LinkingNodeContext(node, scope); node.returnType?.accept(this); node.typeParameters?.accept(this); node.parameters?.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitMixinDeclaration(MixinDeclaration node) { var outerScope = scope; var outerReference = reference; var name = node.name.name; reference = reference.getChild('@mixin').getChild(name); MixinElementImpl element = reference.element; node.name.staticElement = element; _createTypeParameterElements(node.typeParameters); scope = new TypeParameterScope(scope, element); node.typeParameters?.accept(this); node.onClause?.accept(this); node.implementsClause?.accept(this); scope = new ClassScope(scope, element); LinkingNodeContext(node, scope); node.members.accept(this); nodesToBuildType.addDeclaration(node); scope = outerScope; reference = outerReference; } @override void visitOnClause(OnClause node) { node.superclassConstraints.accept(this); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { node.type?.accept(this); nodesToBuildType.addDeclaration(node); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { node.variables.accept(this); if (node.variables.isConst) { var visitor = _SetGenericFunctionTypeIdVisitor(this); node.variables.variables.accept(visitor); } } @override void visitTypeArgumentList(TypeArgumentList node) { node.arguments.accept(this); } @override void visitTypeName(TypeName node) { var typeName = node.name; if (typeName is SimpleIdentifier && typeName.name == 'void') { node.type = VoidTypeImpl.instance; return; } var element = scope.lookup(typeName, _libraryElement); if (typeName is SimpleIdentifier) { typeName.staticElement = element; } else if (typeName is PrefixedIdentifier) { typeName.identifier.staticElement = element; SimpleIdentifier prefix = typeName.prefix; prefix.staticElement = scope.lookup(prefix, _libraryElement); } node.typeArguments?.accept(this); var nullabilitySuffix = _getNullabilitySuffix(node.question != null); if (element is TypeParameterElement) { node.type = TypeParameterTypeImpl( element, nullabilitySuffix: nullabilitySuffix, ); } else { var builder = NamedTypeBuilder.of( node, element, nullabilitySuffix, ); node.type = builder; nodesToBuildType.addTypeBuilder(builder); } } @override void visitTypeParameter(TypeParameter node) { node.bound?.accept(this); } @override void visitTypeParameterList(TypeParameterList node) { node.typeParameters.accept(this); } @override void visitVariableDeclarationList(VariableDeclarationList node) { node.type?.accept(this); nodesToBuildType.addDeclaration(node); } @override void visitWithClause(WithClause node) { node.mixinTypes.accept(this); } void _createTypeParameterElement(TypeParameter node) { var outerReference = this.reference; var containerRef = outerReference.getChild('@typeParameter'); var reference = containerRef.getChild(node.name.name); reference.node = node; var element = TypeParameterElementImpl.forLinkedNode( outerReference.element, reference, node, ); node.name.staticElement = element; } void _createTypeParameterElements(TypeParameterList typeParameterList) { if (typeParameterList == null) return; for (var typeParameter in typeParameterList.typeParameters) { _createTypeParameterElement(typeParameter); } } NullabilitySuffix _getNullabilitySuffix(bool hasQuestion) { if (isNNBD) { if (hasQuestion) { return NullabilitySuffix.question; } else { return NullabilitySuffix.none; } } else { return NullabilitySuffix.star; } } } /// For consistency we set identifiers for [GenericFunctionType]s in constant /// variable initializers, and instance final fields of classes with constant /// constructors. class _SetGenericFunctionTypeIdVisitor extends RecursiveAstVisitor<void> { final ReferenceResolver resolver; _SetGenericFunctionTypeIdVisitor(this.resolver); @override void visitGenericFunctionType(GenericFunctionType node) { var id = resolver._nextGenericFunctionTypeId++; LazyAst.setGenericFunctionTypeId(node, id); super.visitGenericFunctionType(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/summary2/library_builder.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' as ast; import 'package:analyzer/src/dart/ast/mixin_super_invoked_names.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/resolver/scope.dart' show LibraryScope; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/combinator.dart'; import 'package:analyzer/src/summary2/constructor_initializer_resolver.dart'; import 'package:analyzer/src/summary2/default_value_resolver.dart'; import 'package:analyzer/src/summary2/export.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/link.dart'; import 'package:analyzer/src/summary2/linked_bundle_context.dart'; import 'package:analyzer/src/summary2/linked_unit_context.dart'; import 'package:analyzer/src/summary2/metadata_resolver.dart'; import 'package:analyzer/src/summary2/reference.dart'; import 'package:analyzer/src/summary2/reference_resolver.dart'; import 'package:analyzer/src/summary2/scope.dart'; import 'package:analyzer/src/summary2/types_builder.dart'; class LibraryBuilder { final Linker linker; final Uri uri; final Reference reference; final LinkedNodeLibraryBuilder node; LinkedLibraryContext context; LibraryElementImpl element; LibraryScope scope; /// Local declarations. final Scope localScope = Scope.top(); /// The export scope of the library. final Scope exportScope = Scope.top(); final List<Export> exporters = []; LibraryBuilder(this.linker, this.uri, this.reference, this.node); void addExporters() { var unitContext = context.units[0]; for (var directive in unitContext.unit_withDirectives.directives) { if (directive is ast.ExportDirective) { Uri uri; try { uri = _selectAbsoluteUri(directive); if (uri == null) continue; } on FormatException { continue; } var combinators = directive.combinators.map((node) { if (node is ast.ShowCombinator) { var nameList = node.shownNames.map((i) => i.name).toList(); return Combinator.show(nameList); } else if (node is ast.HideCombinator) { var nameList = node.hiddenNames.map((i) => i.name).toList(); return Combinator.hide(nameList); } return null; }).toList(); var exported = linker.builders[uri]; var export = Export(this, exported, combinators); if (exported != null) { exported.exporters.add(export); } else { var references = linker.elementFactory.exportsOfLibrary('$uri'); for (var reference in references) { var name = reference.name; if (reference.isSetter) { export.addToExportScope('$name=', reference); } else { export.addToExportScope(name, reference); } } } } } } /// Add top-level declaration of the library units to the local scope. void addLocalDeclarations() { for (var unitContext in context.units) { var unitRef = reference.getChild('@unit').getChild(unitContext.uriStr); var classRef = unitRef.getChild('@class'); var enumRef = unitRef.getChild('@enum'); var extensionRef = unitRef.getChild('@extension'); var functionRef = unitRef.getChild('@function'); var mixinRef = unitRef.getChild('@mixin'); var typeAliasRef = unitRef.getChild('@typeAlias'); var getterRef = unitRef.getChild('@getter'); var setterRef = unitRef.getChild('@setter'); var variableRef = unitRef.getChild('@variable'); var nextUnnamedExtensionId = 0; for (var node in unitContext.unit.declarations) { if (node is ast.ClassDeclaration) { var name = node.name.name; var reference = classRef.getChild(name); reference.node ??= node; localScope.declare(name, reference); } else if (node is ast.ClassTypeAlias) { var name = node.name.name; var reference = classRef.getChild(name); reference.node ??= node; localScope.declare(name, reference); } else if (node is ast.EnumDeclaration) { var name = node.name.name; var reference = enumRef.getChild(name); reference.node ??= node; localScope.declare(name, reference); } else if (node is ast.ExtensionDeclaration) { var name = node.name?.name; var refName = name ?? 'extension-${nextUnnamedExtensionId++}'; LazyExtensionDeclaration.get(node).setRefName(refName); var reference = extensionRef.getChild(refName); reference.node ??= node; if (name != null) { localScope.declare(name, reference); } } else if (node is ast.FunctionDeclaration) { var name = node.name.name; Reference containerRef; if (node.isGetter) { containerRef = getterRef; } else if (node.isSetter) { containerRef = setterRef; } else { containerRef = functionRef; } var reference = containerRef.getChild(name); reference.node ??= node; if (node.isSetter) { localScope.declare('$name=', reference); } else { localScope.declare(name, reference); } } else if (node is ast.FunctionTypeAlias) { var name = node.name.name; var reference = typeAliasRef.getChild(name); reference.node ??= node; localScope.declare(name, reference); } else if (node is ast.GenericTypeAlias) { var name = node.name.name; var reference = typeAliasRef.getChild(name); reference.node = node; localScope.declare(name, reference); } else if (node is ast.MixinDeclaration) { var name = node.name.name; var reference = mixinRef.getChild(name); reference.node ??= node; localScope.declare(name, reference); } else if (node is ast.TopLevelVariableDeclaration) { for (var variable in node.variables.variables) { var name = variable.name.name; var reference = variableRef.getChild(name); reference.node ??= node; var getter = getterRef.getChild(name); localScope.declare(name, getter); if (!variable.isConst && !variable.isFinal) { var setter = setterRef.getChild(name); localScope.declare('$name=', setter); } } } else { // TODO(scheglov) implement throw UnimplementedError('${node.runtimeType}'); } } } if ('$uri' == 'dart:core') { localScope.declare('dynamic', reference.getChild('dynamic')); localScope.declare('Never', reference.getChild('Never')); } } /// Return `true` if the export scope was modified. bool addToExportScope(String name, Reference reference) { if (name.startsWith('_')) return false; if (reference.isPrefix) return false; var existing = exportScope.map[name]; if (existing == reference) return false; // Ambiguous declaration detected. if (existing != null) return false; exportScope.map[name] = reference; return true; } void buildElement() { element = linker.elementFactory.libraryOfUri('$uri'); scope = LibraryScope(element); } void buildInitialExportScope() { localScope.forEach((name, reference) { addToExportScope(name, reference); }); } void collectMixinSuperInvokedNames() { for (var unitContext in context.units) { for (var declaration in unitContext.unit.declarations) { if (declaration is ast.MixinDeclaration) { var names = Set<String>(); var collector = MixinSuperInvokedNamesCollector(names); for (var executable in declaration.members) { if (executable is ast.MethodDeclaration) { executable.body.accept(collector); } } var lazy = LazyMixinDeclaration.get(declaration); lazy.setSuperInvokedNames(names.toList()); } } } } void resolveConstructors() { ConstructorInitializerResolver(linker, element).resolve(); } void resolveDefaultValues() { DefaultValueResolver(linker, element).resolve(); } void resolveMetadata() { for (CompilationUnitElementImpl unit in element.units) { var resolver = MetadataResolver(linker, element, scope, unit); unit.linkedNode.accept(resolver); } } void resolveTypes(NodesToBuildType nodesToBuildType) { for (var unitContext in context.units) { var unitRef = reference.getChild('@unit'); var unitReference = unitRef.getChild(unitContext.uriStr); var resolver = ReferenceResolver( nodesToBuildType, linker.elementFactory, element, unitReference, unitContext.unit.featureSet.isEnabled(Feature.non_nullable), scope, ); unitContext.unit.accept(resolver); } } void resolveUriDirectives() { var unitContext = context.units[0]; for (var directive in unitContext.unit.directives) { if (directive is ast.NamespaceDirective) { try { var uri = _selectAbsoluteUri(directive); if (uri != null) { LazyDirective.setSelectedUri(directive, '$uri'); } } on FormatException {} } } } void storeExportScope() { var linkingBundleContext = linker.linkingBundleContext; for (var reference in exportScope.map.values) { var index = linkingBundleContext.indexOfReference(reference); node.exports.add(index); } } Uri _selectAbsoluteUri(ast.NamespaceDirective directive) { var relativeUriStr = _selectRelativeUri( directive.configurations, directive.uri.stringValue, ); if (relativeUriStr == null || relativeUriStr.isEmpty) { return null; } var relativeUri = Uri.parse(relativeUriStr); return resolveRelativeUri(this.uri, relativeUri); } String _selectRelativeUri( List<ast.Configuration> configurations, String defaultUri, ) { for (var configuration in configurations) { var name = configuration.name.components.join('.'); var value = configuration.value?.stringValue ?? 'true'; if (linker.declaredVariables.get(name) == value) { return configuration.uri.stringValue; } } return defaultUri; } static void build(Linker linker, LinkInputLibrary inputLibrary) { var libraryUri = inputLibrary.source.uri; var libraryUriStr = '$libraryUri'; var libraryReference = linker.rootReference.getChild(libraryUriStr); var libraryNode = LinkedNodeLibraryBuilder( uriStr: libraryUriStr, ); var definingUnit = inputLibrary.units[0].unit; for (var directive in definingUnit.directives) { if (directive is ast.LibraryDirective) { var name = directive.name; libraryNode.name = name.components.map((id) => id.name).join('.'); libraryNode.nameOffset = name.offset; libraryNode.nameLength = name.length; break; } } var builder = LibraryBuilder( linker, libraryUri, libraryReference, libraryNode, ); linker.builders[builder.uri] = builder; builder.context = linker.bundleContext.addLinkingLibrary( libraryUriStr, libraryNode, inputLibrary, ); } } class UnitBuilder { final Uri uri; final LinkedUnitContext context; final LinkedNode node; UnitBuilder(this.uri, this.context, this.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/summary2/type_alias.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/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/link.dart'; class TypeAliasSelfReferenceFinder { /// Check typedefs and mark the ones having self references. void perform(Linker linker) { for (var builder in linker.builders.values) { for (var unitContext in builder.context.units) { for (var node in unitContext.unit.declarations) { if (node is FunctionTypeAlias) { var finder = _Finder(node); finder.functionTypeAlias(node); LazyFunctionTypeAlias.setHasSelfReference( node, finder.hasSelfReference, ); } else if (node is GenericTypeAlias) { var finder = _Finder(node); finder.genericTypeAlias(node); LazyGenericTypeAlias.setHasSelfReference( node, finder.hasSelfReference, ); if (finder.hasSelfReference) { _sanitizeGenericTypeAlias(node); } } } } } } void _sanitizeGenericTypeAlias(GenericTypeAlias node) { var typeParameterList = node.typeParameters; if (typeParameterList != null) { for (var typeParameter in typeParameterList.typeParameters) { typeParameter.bound = null; } } node.functionType.returnType = null; node.functionType.parameters.parameters.clear(); (node.functionType as GenericFunctionTypeImpl).type = FunctionTypeImpl.synthetic(DynamicTypeImpl.instance, [], []); } } class _Finder { final AstNode self; final Set<AstNode> visited = Set.identity(); bool hasSelfReference = false; _Finder(this.self); void functionTypeAlias(FunctionTypeAlias node) { _typeParameterList(node.typeParameters); _formalParameterList(node.parameters); _visit(node.returnType); } void genericTypeAlias(GenericTypeAlias node) { var functionType = node.functionType; if (functionType != null) { _typeParameterList(functionType.typeParameters); _formalParameterList(functionType.parameters); _visit(functionType.returnType); } } void _argumentList(TypeArgumentList node) { if (node != null) { for (var argument in node.arguments) { _visit(argument); } } } void _formalParameter(FormalParameter node) { if (node is DefaultFormalParameter) { _formalParameter(node.parameter); } else if (node is FunctionTypedFormalParameter) { _visit(node.returnType); _formalParameterList(node.parameters); } else if (node is SimpleFormalParameter) { _visit(node.type); } } void _formalParameterList(FormalParameterList node) { for (var parameter in node.parameters) { _formalParameter(parameter); } } void _typeParameterList(TypeParameterList node) { if (node != null) { for (var parameter in node.typeParameters) { _visit(parameter.bound); } } } void _visit(TypeAnnotation node) { if (hasSelfReference) return; if (node == null) return; if (node is TypeName) { var element = node.name.staticElement; if (element is ElementImpl && element.enclosingElement != null && element.linkedContext.isLinking) { var typeNode = element.linkedNode; if (typeNode == self) { hasSelfReference = true; return; } if (typeNode is ClassDeclaration) { if (visited.add(typeNode)) { _typeParameterList(typeNode.typeParameters); } } else if (typeNode is ClassTypeAlias) { if (visited.add(typeNode)) { _typeParameterList(typeNode.typeParameters); } } else if (typeNode is FunctionTypeAlias) { if (visited.add(typeNode)) { functionTypeAlias(typeNode); } } else if (typeNode is GenericTypeAlias) { if (visited.add(typeNode)) { genericTypeAlias(typeNode); } } else if (typeNode is MixinDeclaration) { if (visited.add(typeNode)) { _typeParameterList(typeNode.typeParameters); } } } _argumentList(node.typeArguments); } else if (node is GenericFunctionType) { _typeParameterList(node.typeParameters); _formalParameterList(node.parameters); _visit(node.returnType); } else { throw UnimplementedError('(${node.runtimeType}) $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/summary2/combinator.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. class Combinator { final bool isShow; final Set<String> names; Combinator(this.isShow, this.names); Combinator.hide(Iterable<String> names) : this(false, names.toSet()); Combinator.show(Iterable<String> names) : this(true, names.toSet()); bool get isHide => !isShow; bool matches(String name) { if (name.endsWith('=')) { name = name.substring(0, name.length - 1); } return names.contains(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/summary2/scope.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/src/summary2/reference.dart'; class Scope { final Scope parent; final Map<String, Reference> map; Scope(this.parent, this.map); Scope.top() : this(null, <String, Reference>{}); void declare(String name, Reference reference) { map[name] = reference; } void forEach(f(String name, Reference reference)) { map.forEach(f); } Reference lookup(String name) { var reference = map[name]; if (reference != null) return reference; if (parent == null) return null; return parent.lookup(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/summary2/named_type_builder.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/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/dart/element/type_algebra.dart'; import 'package:analyzer/src/summary2/type_builder.dart'; /// The type builder for a [TypeName]. class NamedTypeBuilder extends TypeBuilder { static DynamicTypeImpl get _dynamicType => DynamicTypeImpl.instance; final Element element; final List<DartType> arguments; final NullabilitySuffix nullabilitySuffix; /// The node for which this builder is created, or `null` if the builder /// was detached from its node, e.g. during computing default types for /// type parameters. final TypeName node; /// The actual built type, not a [TypeBuilder] anymore. /// /// When [build] is called, the type is built, stored into this field, /// and set for the [node]. DartType _type; NamedTypeBuilder(this.element, this.arguments, this.nullabilitySuffix, {this.node}); factory NamedTypeBuilder.of( TypeName node, Element element, NullabilitySuffix nullabilitySuffix, ) { List<DartType> arguments; var argumentList = node.typeArguments; if (argumentList != null) { arguments = argumentList.arguments.map((n) => n.type).toList(); } else { arguments = <DartType>[]; } return NamedTypeBuilder(element, arguments, nullabilitySuffix, node: node); } @override DartType build() { if (_type != null) { return _type; } var element = this.element; if (element is ClassElement) { var parameters = element.typeParameters; var arguments = _buildArguments(parameters); _type = element.instantiate( typeArguments: arguments, nullabilitySuffix: nullabilitySuffix, ); } else if (element is GenericTypeAliasElement) { // Break a possible recursion. _type = _dynamicType; var rawType = _getRawFunctionType(element); var parameters = element.typeParameters; if (parameters.isEmpty) { _type = rawType; } else { var arguments = _buildArguments(parameters); var substitution = Substitution.fromPairs(parameters, arguments); _type = substitution.substituteType(rawType); } } else if (element is NeverElementImpl) { _type = BottomTypeImpl.instance.withNullability(nullabilitySuffix); } else if (element is TypeParameterElement) { _type = TypeParameterTypeImpl( element, nullabilitySuffix: nullabilitySuffix, ); } else { _type = _dynamicType; } node?.type = _type; return _type; } @override String toString() { var buffer = StringBuffer(); buffer.write(element.displayName); if (arguments.isNotEmpty) { buffer.write('<'); buffer.write(arguments.join(', ')); buffer.write('>'); } return buffer.toString(); } /// Build arguments that correspond to the type [parameters]. List<DartType> _buildArguments(List<TypeParameterElement> parameters) { if (parameters.isEmpty) { return const <DartType>[]; } else if (arguments.isNotEmpty) { if (arguments.length == parameters.length) { var result = List<DartType>(parameters.length); for (int i = 0; i < result.length; ++i) { var type = arguments[i]; result[i] = _buildType(type); } return result; } else { return _listOfDynamic(parameters.length); } } else { var result = List<DartType>(parameters.length); for (int i = 0; i < result.length; ++i) { TypeParameterElementImpl parameter = parameters[i]; var defaultType = parameter.defaultType; defaultType = _buildType(defaultType); result[i] = defaultType; } return result; } } DartType _buildFormalParameterType(FormalParameter node) { if (node is DefaultFormalParameter) { return _buildFormalParameterType(node.parameter); } else if (node is FunctionTypedFormalParameter) { return _buildFunctionType( null, null, node.typeParameters, node.returnType, node.parameters, ); } else if (node is SimpleFormalParameter) { return _buildNodeType(node.type); } else { throw UnimplementedError('(${node.runtimeType}) $node'); } } FunctionType _buildFunctionType( GenericTypeAliasElement typedefElement, List<DartType> typedefTypeParameterTypes, TypeParameterList typeParameterList, TypeAnnotation returnTypeNode, FormalParameterList parameterList, ) { var returnType = _buildNodeType(returnTypeNode); var typeParameters = _typeParameters(typeParameterList); var formalParameters = parameterList.parameters.map((parameter) { return ParameterElementImpl.synthetic( parameter.identifier?.name ?? '', _buildFormalParameterType(parameter), // ignore: deprecated_member_use_from_same_package parameter.kind, ); }).toList(); return FunctionTypeImpl.synthetic( returnType, typeParameters, formalParameters, element: typedefElement, typeArguments: typedefTypeParameterTypes, ); } DartType _buildNodeType(TypeAnnotation node) { if (node == null) { return _dynamicType; } else { return _buildType(node.type); } } DartType _getRawFunctionType(GenericTypeAliasElementImpl element) { // If the element is not being linked, there is no reason (or a way, // because the linked node might be read only partially) to go through // its node - all its types have already been built. if (!element.linkedContext.isLinking) { var function = element.function; if (function != null) { return function.type; } else { return _dynamicType; } } var typedefNode = element.linkedNode; if (typedefNode is FunctionTypeAlias) { return _buildFunctionType( element, _typeParameterTypes(typedefNode.typeParameters), null, typedefNode.returnType, typedefNode.parameters, ); } else if (typedefNode is GenericTypeAlias) { var functionNode = typedefNode.functionType; var functionType = _buildType(functionNode?.type); if (functionType is FunctionType) { return FunctionTypeImpl.synthetic( functionType.returnType, functionType.typeFormals, functionType.parameters, element: element, typeArguments: _typeParameterTypes(typedefNode.typeParameters), ); } return _dynamicType; } else { throw StateError('(${element.runtimeType}) $element'); } } /// If the [type] is a [TypeBuilder], build it; otherwise return as is. static DartType _buildType(DartType type) { if (type is TypeBuilder) { return type.build(); } else { return type; } } static List<DartType> _listOfDynamic(int length) { return List<DartType>.filled(length, _dynamicType); } static List<TypeParameterElement> _typeParameters(TypeParameterList node) { if (node != null) { return node.typeParameters .map<TypeParameterElement>((p) => p.declaredElement) .toList(); } else { return const <TypeParameterElement>[]; } } static List<DartType> _typeParameterTypes(TypeParameterList node) { var elements = _typeParameters(node); return TypeParameterTypeImpl.getTypes(elements); } }
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/summary2/default_value_resolver.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/dart/element/type.dart'; import 'package:analyzer/src/dart/element/builder.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/summary2/ast_resolver.dart'; import 'package:analyzer/src/summary2/link.dart'; import 'package:analyzer/src/summary2/linking_node_scope.dart'; class DefaultValueResolver { final Linker _linker; final LibraryElementImpl _libraryElement; ClassElement _classElement; ExecutableElement _executableElement; Scope _scope; AstResolver _astResolver; DefaultValueResolver(this._linker, this._libraryElement); void resolve() { for (CompilationUnitElementImpl unit in _libraryElement.units) { for (var extensionElement in unit.extensions) { _extension(extensionElement); } for (var classElement in unit.mixins) { _class(classElement); } for (var classElement in unit.types) { _class(classElement); } for (var element in unit.functions) { _function(element); } } } void _class(ClassElement classElement) { _classElement = classElement; for (var element in classElement.constructors) { _constructor(element); } for (var element in classElement.methods) { _setScopeFromElement(element); _method(element); } _classElement = null; } void _constructor(ConstructorElementImpl element) { if (element.isSynthetic) return; _astResolver = null; _executableElement = element; _setScopeFromElement(element); _parameters(element.parameters); } void _extension(ExtensionElement extensionElement) { for (var element in extensionElement.methods) { _setScopeFromElement(element); _method(element); } } void _function(FunctionElementImpl element) { _astResolver = null; _executableElement = element; _setScopeFromElement(element); _parameters(element.parameters); } void _method(MethodElementImpl element) { _astResolver = null; _executableElement = element; _setScopeFromElement(element); _parameters(element.parameters); } void _parameter(ParameterElementImpl parameter) { Expression defaultValue; var node = parameter.linkedNode; if (node is DefaultFormalParameter) { defaultValue = node.defaultValue; } if (defaultValue == null) return; var holder = ElementHolder(); defaultValue.accept(LocalElementBuilder(holder, null)); parameter.encloseElements(holder.localVariables); var contextType = TypeVariableEliminator(_linker.typeProvider) .substituteType(parameter.type); InferenceContext.setType(defaultValue, contextType); _astResolver ??= AstResolver(_linker, _libraryElement, _scope); _astResolver.resolve( defaultValue, enclosingClassElement: _classElement, enclosingExecutableElement: _executableElement, ); } void _parameters(List<ParameterElement> parameters) { for (var parameter in parameters) { _parameter(parameter); } } void _setScopeFromElement(Element element) { _scope = LinkingNodeContext.get((element as ElementImpl).linkedNode).scope; } } class TypeVariableEliminator extends Substitution { final TypeProvider _typeProvider; TypeVariableEliminator(this._typeProvider); @override DartType getSubstitute(TypeParameterElement parameter, bool upperBound) { return upperBound ? _typeProvider.nullType : _typeProvider.objectType; } }
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/summary2/function_type_builder.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/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/type.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/type_builder.dart'; /// The type builder for a [GenericFunctionType]. class FunctionTypeBuilder extends TypeBuilder { static DynamicTypeImpl get _dynamicType => DynamicTypeImpl.instance; final List<TypeParameterElement> typeFormals; final List<ParameterElement> parameters; final DartType returnType; final NullabilitySuffix nullabilitySuffix; /// The node for which this builder is created, or `null` if the builder /// was detached from its node, e.g. during computing default types for /// type parameters. final GenericFunctionTypeImpl node; /// The actual built type, not a [TypeBuilder] anymore. /// /// When [build] is called, the type is built, stored into this field, /// and set for the [node]. DartType _type; FunctionTypeBuilder( this.typeFormals, this.parameters, this.returnType, this.nullabilitySuffix, { this.node, }); /// [isNNBD] indicates whether the containing library is opted into NNBD. factory FunctionTypeBuilder.of( bool isNNBD, GenericFunctionType node, NullabilitySuffix nullabilitySuffix, ) { return FunctionTypeBuilder( _getTypeParameters(node.typeParameters), _getParameters(isNNBD, node.parameters), _getNodeType(node.returnType), nullabilitySuffix, node: node, ); } @override Element get element => null; @override DartType build() { if (_type != null) { return _type; } for (TypeParameterElementImpl typeParameter in typeFormals) { typeParameter.bound = _buildType(typeParameter.bound); } for (ParameterElementImpl parameter in parameters) { parameter.type = _buildType(parameter.type); } var builtReturnType = _buildType(returnType); _type = FunctionTypeImpl.synthetic( builtReturnType, typeFormals, parameters, nullabilitySuffix: nullabilitySuffix, ); if (node != null) { node.type = _type; LazyAst.setReturnType(node, builtReturnType ?? _dynamicType); } return _type; } @override String toString() { var buffer = StringBuffer(); if (typeFormals.isNotEmpty) { buffer.write('<'); buffer.write(typeFormals.join(', ')); buffer.write('>'); } buffer.write('('); buffer.write(parameters.join(', ')); buffer.write(')'); buffer.write(' → '); buffer.write(returnType); return buffer.toString(); } /// If the [type] is a [TypeBuilder], build it; otherwise return as is. static DartType _buildType(DartType type) { if (type is TypeBuilder) { return type.build(); } else { return type; } } /// Return the type of the [node] as is, possibly a [TypeBuilder]. static DartType _getNodeType(TypeAnnotation node) { if (node == null) { return _dynamicType; } else { return node.type; } } /// [isNNBD] indicates whether the containing library is opted into NNBD. static List<ParameterElementImpl> _getParameters( bool isNNBD, FormalParameterList node, ) { return node.parameters.map((parameter) { return ParameterElementImpl.synthetic( parameter.identifier?.name ?? '', _getParameterType(isNNBD, parameter), // ignore: deprecated_member_use_from_same_package parameter.kind, ); }).toList(); } /// Return the type of the [node] as is, possibly a [TypeBuilder]. /// /// [isNNBD] indicates whether the containing library is opted into NNBD. static DartType _getParameterType(bool isNNBD, FormalParameter node) { if (node is DefaultFormalParameter) { return _getParameterType(isNNBD, node.parameter); } else if (node is SimpleFormalParameter) { return _getNodeType(node.type); } else if (node is FunctionTypedFormalParameter) { NullabilitySuffix nullabilitySuffix; if (node.question != null) { nullabilitySuffix = NullabilitySuffix.question; } else if (isNNBD) { nullabilitySuffix = NullabilitySuffix.none; } else { nullabilitySuffix = NullabilitySuffix.question; } return FunctionTypeBuilder( _getTypeParameters(node.typeParameters), _getParameters(isNNBD, node.parameters), _getNodeType(node.returnType), nullabilitySuffix, ); } else { throw UnimplementedError('(${node.runtimeType}) $node'); } } static List<TypeParameterElement> _getTypeParameters(TypeParameterList node) { if (node == null) return const []; return node.typeParameters.map((n) => n.declaredElement).toList(); } }
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/summary2/informative_data.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/src/summary/format.dart'; /// Create informative data for nodes that need it, and set IDs of this /// data to the nodes. List<UnlinkedInformativeDataBuilder> createInformativeData( CompilationUnit unit) { var visitor = _SetInformativeId(); unit.accept(visitor); return visitor.dataList; } /// If [createInformativeData] set the informative data identifier for the /// [node], return it, otherwise return zero. int getInformativeId(AstNode node) { int id = node.getProperty(_SetInformativeId.ID); return id ?? 0; } class _SetInformativeId extends SimpleAstVisitor<void> { static final String ID = 'informativeId'; final List<UnlinkedInformativeDataBuilder> dataList = []; void setData(AstNode node, UnlinkedInformativeDataBuilder data) { var id = 1 + dataList.length; node.setProperty(ID, id); dataList.add(data); } @override void visitClassDeclaration(ClassDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.classDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.typeParameters?.accept(this); node.members.accept(this); } @override void visitClassTypeAlias(ClassTypeAlias node) { setData( node, UnlinkedInformativeDataBuilder.classTypeAlias( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.typeParameters?.accept(this); } @override void visitCompilationUnit(CompilationUnit node) { setData( node, UnlinkedInformativeDataBuilder.compilationUnit( codeOffset: node.offset, codeLength: node.length, compilationUnit_lineStarts: node.lineInfo.lineStarts, ), ); node.directives.accept(this); node.declarations.accept(this); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.constructorDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name?.offset ?? 0, constructorDeclaration_periodOffset: node.period?.offset ?? 0, constructorDeclaration_returnTypeOffset: node.returnType.offset, ), ); node.parameters?.accept(this); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { var defaultValueCode = node.defaultValue?.toSource(); setData( node, UnlinkedInformativeDataBuilder.defaultFormalParameter( codeOffset: node.offset, codeLength: node.length, defaultFormalParameter_defaultValueCode: defaultValueCode, ), ); node.parameter.accept(this); } @override void visitEnumConstantDeclaration(EnumConstantDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.enumConstantDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); } @override void visitEnumDeclaration(EnumDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.enumDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.constants.accept(this); } @override void visitExportDirective(ExportDirective node) { setData( node, UnlinkedInformativeDataBuilder.exportDirective( directiveKeywordOffset: node.keyword.offset, ), ); node.combinators.accept(this); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.extensionDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name?.offset ?? 0, ), ); node.typeParameters?.accept(this); node.members.accept(this); } @override void visitFieldDeclaration(FieldDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.fieldDeclaration( documentationComment_tokens: _nodeCommentTokens(node), ), ); node.fields.accept(this); } @override void visitFieldFormalParameter(FieldFormalParameter node) { setData( node, UnlinkedInformativeDataBuilder.fieldFormalParameter( codeOffset: node.offset, codeLength: node.length, nameOffset: node.identifier.offset, ), ); } @override void visitFormalParameterList(FormalParameterList node) { node.parameters.accept(this); } @override void visitFunctionDeclaration(FunctionDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.functionDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.functionExpression.accept(this); } @override void visitFunctionExpression(FunctionExpression node) { node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { setData( node, UnlinkedInformativeDataBuilder.functionTypeAlias( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { setData( node, UnlinkedInformativeDataBuilder.functionTypedFormalParameter( codeOffset: node.offset, codeLength: node.length, nameOffset: node.identifier.offset, ), ); } @override void visitGenericFunctionType(GenericFunctionType node) { node.typeParameters?.accept(this); node.parameters.accept(this); } @override void visitGenericTypeAlias(GenericTypeAlias node) { setData( node, UnlinkedInformativeDataBuilder.genericTypeAlias( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.typeParameters?.accept(this); node.functionType?.accept(this); } @override void visitHideCombinator(HideCombinator node) { setData( node, UnlinkedInformativeDataBuilder.hideCombinator( combinatorEnd: node.end, combinatorKeywordOffset: node.offset, ), ); } @override void visitImportDirective(ImportDirective node) { setData( node, UnlinkedInformativeDataBuilder.importDirective( directiveKeywordOffset: node.keyword.offset, importDirective_prefixOffset: node.prefix?.offset ?? 0, ), ); node.combinators.accept(this); } @override void visitLibraryDirective(LibraryDirective node) { setData( node, UnlinkedInformativeDataBuilder.libraryDirective( documentationComment_tokens: _nodeCommentTokens(node), ), ); } @override void visitMethodDeclaration(MethodDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.methodDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.typeParameters?.accept(this); node.parameters?.accept(this); } @override void visitMixinDeclaration(MixinDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.mixinDeclaration( codeOffset: node.offset, codeLength: node.length, documentationComment_tokens: _nodeCommentTokens(node), nameOffset: node.name.offset, ), ); node.typeParameters?.accept(this); node.members.accept(this); } @override void visitPartDirective(PartDirective node) { setData( node, UnlinkedInformativeDataBuilder.partDirective( directiveKeywordOffset: node.keyword.offset, ), ); } @override void visitPartOfDirective(PartOfDirective node) { setData( node, UnlinkedInformativeDataBuilder.partDirective( directiveKeywordOffset: node.keyword.offset, ), ); } @override void visitShowCombinator(ShowCombinator node) { setData( node, UnlinkedInformativeDataBuilder.showCombinator( combinatorEnd: node.end, combinatorKeywordOffset: node.offset, ), ); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { setData( node, UnlinkedInformativeDataBuilder.simpleFormalParameter( codeOffset: node.offset, codeLength: node.length, nameOffset: node.identifier?.offset ?? 0, ), ); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { setData( node, UnlinkedInformativeDataBuilder.topLevelVariableDeclaration( documentationComment_tokens: _nodeCommentTokens(node), ), ); node.variables.accept(this); } @override void visitTypeParameter(TypeParameter node) { setData( node, UnlinkedInformativeDataBuilder.typeParameter( codeOffset: node.offset, codeLength: node.length, nameOffset: node.name.offset, ), ); } @override void visitTypeParameterList(TypeParameterList node) { node.typeParameters.accept(this); } @override void visitVariableDeclaration(VariableDeclaration node) { var variableList = node.parent as VariableDeclarationList; var isFirst = identical(variableList.variables[0], node); var codeOffset = (isFirst ? variableList.parent : node).offset; var codeLength = node.end - codeOffset; setData( node, UnlinkedInformativeDataBuilder.variableDeclaration( codeOffset: codeOffset, codeLength: codeLength, nameOffset: node.name.offset, ), ); } @override void visitVariableDeclarationList(VariableDeclarationList node) { node.variables.accept(this); } static List<String> _commentTokens(Comment comment) { if (comment == null) return null; return comment.tokens.map((token) => token.lexeme).toList(); } static List<String> _nodeCommentTokens(AnnotatedNode node) { return _commentTokens(node.documentationComment); } }
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/summary2/linked_bundle_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/element/element.dart'; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/informative_data.dart'; import 'package:analyzer/src/summary2/link.dart'; import 'package:analyzer/src/summary2/linked_element_factory.dart'; import 'package:analyzer/src/summary2/linked_unit_context.dart'; import 'package:analyzer/src/summary2/reference.dart'; /// The context of a linked bundle, with shared references. class LinkedBundleContext { final LinkedElementFactory elementFactory; final LinkedNodeBundle _bundle; final List<Reference> _references; final Map<String, LinkedLibraryContext> libraryMap = {}; LinkedBundleContext(this.elementFactory, this._bundle) : _references = List<Reference>(_bundle.references.name.length) { for (var library in _bundle.libraries) { var uriStr = library.uriStr; var reference = elementFactory.rootReference.getChild(uriStr); var libraryContext = LinkedLibraryContext( this, uriStr, reference, library, ); libraryMap[uriStr] = libraryContext; var unitRef = reference.getChild('@unit'); var units = library.units; for (var unitIndex = 0; unitIndex < units.length; ++unitIndex) { var unit = units[unitIndex]; var uriStr = unit.uriStr; var reference = unitRef.getChild(uriStr); var unitContext = LinkedUnitContext( this, libraryContext, unitIndex, unit.partUriStr, uriStr, reference, unit.isSynthetic, unit, ); libraryContext.units.add(unitContext); } } } LinkedBundleContext.forAst(this.elementFactory, this._references) : _bundle = null; /// Return `true` if this bundle is being linked. bool get isLinking => _bundle == null; LinkedLibraryContext addLinkingLibrary( String uriStr, LinkedNodeLibraryBuilder data, LinkInputLibrary inputLibrary, ) { var uriStr = data.uriStr; var reference = elementFactory.rootReference.getChild(uriStr); var libraryContext = LinkedLibraryContext(this, uriStr, reference, data); libraryMap[uriStr] = libraryContext; var unitRef = reference.getChild('@unit'); var unitIndex = 0; for (var inputUnit in inputLibrary.units) { var source = inputUnit.source; var uriStr = source != null ? '${source.uri}' : ''; var reference = unitRef.getChild(uriStr); createInformativeData(inputUnit.unit); libraryContext.units.add( LinkedUnitContext( this, libraryContext, unitIndex++, inputUnit.partUriStr, uriStr, reference, inputUnit.isSynthetic, null, unit: inputUnit.unit, ), ); } return libraryContext; } T elementOfIndex<T extends Element>(int index) { var reference = referenceOfIndex(index); return elementFactory.elementOfReference(reference); } List<T> elementsOfIndexes<T extends Element>(List<int> indexList) { var result = List<T>(indexList.length); for (var i = 0; i < indexList.length; ++i) { var index = indexList[i]; result[i] = elementOfIndex(index); } return result; } Reference referenceOfIndex(int index) { var reference = _references[index]; if (reference != null) return reference; if (index == 0) { reference = elementFactory.rootReference; _references[index] = reference; return reference; } var parentIndex = _bundle.references.parent[index]; var parent = referenceOfIndex(parentIndex); var name = _bundle.references.name[index]; reference = parent.getChild(name); _references[index] = reference; return reference; } } class LinkedLibraryContext { final LinkedBundleContext context; final String uriStr; final Reference reference; final LinkedNodeLibrary node; final List<LinkedUnitContext> units = []; LinkedLibraryContext(this.context, this.uriStr, this.reference, this.node); LinkedUnitContext get definingUnit => units.first; }
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/summary2/default_types_builder.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/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/generated/type_system.dart'; import 'package:analyzer/src/summary2/function_type_builder.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/named_type_builder.dart'; import 'package:analyzer/src/summary2/type_builder.dart'; import 'package:kernel/util/graph.dart' show Graph, computeStrongComponents; class DefaultTypesBuilder { final Dart2TypeSystem typeSystem; DefaultTypesBuilder(this.typeSystem); void build(List<AstNode> nodes) { for (var node in nodes) { if (node is ClassDeclaration) { _breakRawTypeCycles(node.declaredElement, node.typeParameters); _computeBounds(node.typeParameters); } else if (node is ClassTypeAlias) { _breakRawTypeCycles(node.declaredElement, node.typeParameters); _computeBounds(node.typeParameters); } else if (node is FunctionTypeAlias) { _breakRawTypeCycles(node.declaredElement, node.typeParameters); _computeBounds(node.typeParameters); } else if (node is GenericTypeAlias) { _breakRawTypeCycles(node.declaredElement, node.typeParameters); _computeBounds(node.typeParameters); } else if (node is MixinDeclaration) { _breakRawTypeCycles(node.declaredElement, node.typeParameters); _computeBounds(node.typeParameters); } } for (var node in nodes) { if (node is ClassDeclaration) { _build(node.typeParameters); } else if (node is ClassTypeAlias) { _build(node.typeParameters); } else if (node is FunctionTypeAlias) { _build(node.typeParameters); } else if (node is GenericTypeAlias) { _build(node.typeParameters); } else if (node is MixinDeclaration) { _build(node.typeParameters); } } } void _breakRawTypeCycles( Element declarationElement, TypeParameterList parameterList, ) { if (parameterList == null) return; var allCycles = <List<_CycleElement>>[]; for (var parameter in parameterList.typeParameters) { var boundNode = parameter.bound; if (boundNode == null) continue; var cycles = _findRawTypePathsToDeclaration( parameter, boundNode.type, declarationElement, Set<Element>.identity(), ); allCycles.addAll(cycles); } for (var cycle in allCycles) { for (var element in cycle) { var boundNode = element.parameter.bound; if (boundNode is TypeName) { boundNode.type = DynamicTypeImpl.instance; } else { throw UnimplementedError('(${boundNode.runtimeType}) $boundNode'); } } } } /// Build actual default type [DartType]s from computed [TypeBuilder]s. void _build(TypeParameterList parameterList) { if (parameterList == null) return; for (var parameter in parameterList.typeParameters) { var defaultType = LazyAst.getDefaultType(parameter); if (defaultType is TypeBuilder) { var builtType = defaultType.build(); LazyAst.setDefaultType(parameter, builtType); } } } /// Compute bounds to be provided as type arguments in place of missing type /// arguments on raw types with the given type parameters. void _computeBounds(TypeParameterList parameterList) { if (parameterList == null) return; var dynamicType = typeSystem.typeProvider.dynamicType; var nullType = typeSystem.typeProvider.nullType; var nodes = parameterList.typeParameters; var length = nodes.length; var elements = List<TypeParameterElement>(length); var bounds = List<DartType>(length); for (int i = 0; i < length; i++) { var node = nodes[i]; elements[i] = node.declaredElement; bounds[i] = node.bound?.type ?? dynamicType; } var graph = _TypeParametersGraph(elements, bounds); var stronglyConnected = computeStrongComponents(graph); for (var component in stronglyConnected) { var dynamicSubstitution = <TypeParameterElement, DartType>{}; var nullSubstitution = <TypeParameterElement, DartType>{}; for (var i in component) { var element = elements[i]; dynamicSubstitution[element] = dynamicType; nullSubstitution[element] = nullType; } var substitution = Substitution.fromUpperAndLowerBounds( dynamicSubstitution, nullSubstitution, ); for (var i in component) { bounds[i] = substitution.substituteType(bounds[i]); } } for (var i = 0; i < length; i++) { var thisSubstitution = <TypeParameterElement, DartType>{}; var nullSubstitution = <TypeParameterElement, DartType>{}; var element = elements[i]; thisSubstitution[element] = bounds[i]; nullSubstitution[element] = nullType; var substitution = Substitution.fromUpperAndLowerBounds( thisSubstitution, nullSubstitution, ); for (var j = 0; j < length; j++) { bounds[j] = substitution.substituteType(bounds[j]); } } // Set computed TypeBuilder(s) as default types. for (var i = 0; i < length; i++) { LazyAst.setDefaultType(nodes[i], bounds[i]); } } /// Finds raw type paths starting with the [startParameter] and a /// [startType] that is used in its bound, and ending with [end]. List<List<_CycleElement>> _findRawTypePathsToDeclaration( TypeParameter startParameter, DartType startType, Element end, Set<Element> visited, ) { var paths = <List<_CycleElement>>[]; if (startType is NamedTypeBuilder) { var declaration = startType.element; if (startType.arguments.isEmpty) { if (startType.element == end) { paths.add([ _CycleElement(startParameter, startType), ]); } else if (visited.add(startType.element)) { void recurseParameters(List<TypeParameterElement> parameters) { for (TypeParameterElementImpl parameter in parameters) { TypeParameter parameterNode = parameter.linkedNode; var bound = parameterNode.bound; if (bound != null) { var tails = _findRawTypePathsToDeclaration( parameterNode, bound.type, end, visited, ); for (var tail in tails) { paths.add(<_CycleElement>[ _CycleElement(startParameter, startType), ]..addAll(tail)); } } } } if (declaration is ClassElement) { recurseParameters(declaration.typeParameters); } else if (declaration is GenericTypeAliasElement) { recurseParameters(declaration.typeParameters); } visited.remove(startType.element); } } else { for (var argument in startType.arguments) { paths.addAll( _findRawTypePathsToDeclaration( startParameter, argument, end, visited, ), ); } } } else if (startType is FunctionTypeBuilder) { paths.addAll( _findRawTypePathsToDeclaration( startParameter, startType.returnType, end, visited, ), ); for (var formalParameter in startType.parameters) { paths.addAll( _findRawTypePathsToDeclaration( startParameter, formalParameter.type, end, visited, ), ); } } return paths; } } class _CycleElement { final TypeParameter parameter; final DartType type; _CycleElement(this.parameter, this.type); } /// Graph of mutual dependencies of type parameters from the same declaration. /// Type parameters are represented by their indices in the corresponding /// declaration. class _TypeParametersGraph implements Graph<int> { @override List<int> vertices; // Each `edges[i]` is the list of indices of type parameters that reference // the type parameter with the index `i` in their bounds. List<List<int>> _edges; Map<TypeParameterElement, int> _parameterToIndex = Map.identity(); _TypeParametersGraph( List<TypeParameterElement> parameters, List<DartType> bounds, ) { assert(parameters.length == bounds.length); vertices = List<int>(parameters.length); _edges = List<List<int>>(parameters.length); for (int i = 0; i < vertices.length; i++) { vertices[i] = i; _edges[i] = <int>[]; _parameterToIndex[parameters[i]] = i; } for (int i = 0; i < vertices.length; i++) { _collectReferencesFrom(i, bounds[i]); } } /// Return type parameters that depend on the [index]th type parameter. @override Iterable<int> neighborsOf(int index) { return _edges[index]; } /// Collect references to the [index]th type parameter from the [type]. void _collectReferencesFrom(int index, DartType type) { if (type is FunctionTypeBuilder) { for (var parameter in type.typeFormals) { _collectReferencesFrom(index, parameter.bound); } for (var parameter in type.parameters) { _collectReferencesFrom(index, parameter.type); } _collectReferencesFrom(index, type.returnType); } else if (type is NamedTypeBuilder) { for (var argument in type.arguments) { _collectReferencesFrom(index, argument); } } else if (type is TypeParameterType) { var typeIndex = _parameterToIndex[type.element]; if (typeIndex != null) { _edges[typeIndex].add(index); } } } }
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/summary2/linked_element_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/analysis/session.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisContext; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/core_types.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; import 'package:analyzer/src/summary2/linked_bundle_context.dart'; import 'package:analyzer/src/summary2/linked_unit_context.dart'; import 'package:analyzer/src/summary2/reference.dart'; class LinkedElementFactory { final AnalysisContext analysisContext; final AnalysisSession analysisSession; final Reference rootReference; final Map<String, LinkedLibraryContext> libraryMap = {}; CoreTypes _coreTypes; LinkedElementFactory( this.analysisContext, this.analysisSession, this.rootReference, ) { var dartCoreRef = rootReference.getChild('dart:core'); dartCoreRef.getChild('dynamic').element = DynamicElementImpl.instance; dartCoreRef.getChild('Never').element = NeverElementImpl.instance; } CoreTypes get coreTypes { return _coreTypes ??= CoreTypes(this); } Reference get dynamicRef { return rootReference.getChild('dart:core').getChild('dynamic'); } bool get hasDartCore { return libraryMap.containsKey('dart:core'); } void addBundle(LinkedBundleContext context) { libraryMap.addAll(context.libraryMap); } Namespace buildExportNamespace(Uri uri) { var exportedNames = <String, Element>{}; var exportedReferences = exportsOfLibrary('$uri'); for (var exportedReference in exportedReferences) { var element = elementOfReference(exportedReference); exportedNames[element.name] = element; } return Namespace(exportedNames); } Element elementOfReference(Reference reference) { if (reference.element != null) { return reference.element; } if (reference.parent == null) { return null; } return _ElementRequest(this, reference).elementOfReference(reference); } List<Reference> exportsOfLibrary(String uriStr) { var library = libraryMap[uriStr]; if (library == null) return const []; // Ask for source to trigger dependency tracking. // // Usually we record a dependency because we request an element from a // library, so we build its library element, so request its source. // However if a library is just exported, and the exporting library is not // imported itself, we just copy references, without computing elements. analysisContext.sourceFactory.forUri(uriStr); var exportIndexList = library.node.exports; var exportReferences = List<Reference>(exportIndexList.length); for (var i = 0; i < exportIndexList.length; ++i) { var index = exportIndexList[i]; var reference = library.context.referenceOfIndex(index); exportReferences[i] = reference; } return exportReferences; } bool isLibraryUri(String uriStr) { var libraryContext = libraryMap[uriStr]; return !libraryContext.definingUnit.hasPartOfDirective; } LibraryElementImpl libraryOfUri(String uriStr) { var reference = rootReference.getChild(uriStr); return elementOfReference(reference); } /// We have linked the bundle, and need to disconnect its libraries, so /// that the client can re-add the bundle, this time read from bytes. void removeBundle(LinkedBundleContext context) { for (var uriStr in context.libraryMap.keys) { libraryMap.remove(uriStr); rootReference.removeChild(uriStr); } } /// Set optional informative data for the unit. void setInformativeData( String libraryUriStr, String unitUriStr, List<UnlinkedInformativeData> informativeData, ) { var libraryContext = libraryMap[libraryUriStr]; if (libraryContext != null) { for (var unitContext in libraryContext.units) { if (unitContext.uriStr == unitUriStr) { unitContext.informativeData = informativeData; return; } } } } } class _ElementRequest { final LinkedElementFactory elementFactory; final Reference input; _ElementRequest(this.elementFactory, this.input); ElementImpl elementOfReference(Reference reference) { if (reference.element != null) { return reference.element; } var parent2 = reference.parent.parent; if (parent2 == null) { return _createLibraryElement(reference); } var parentName = reference.parent.name; if (parentName == '@class') { var unit = elementOfReference(parent2); return _class(unit, reference); } if (parentName == '@constructor') { var class_ = elementOfReference(parent2); return _constructor(class_, reference); } if (parentName == '@enum') { var unit = elementOfReference(parent2); return _enum(unit, reference); } if (parentName == '@extension') { var unit = elementOfReference(parent2); return _extension(unit, reference); } if (parentName == '@field') { var enclosing = elementOfReference(parent2); return _field(enclosing, reference); } if (parentName == '@function') { CompilationUnitElementImpl enclosing = elementOfReference(parent2); return _function(enclosing, reference); } if (parentName == '@getter' || parentName == '@setter') { var enclosing = elementOfReference(parent2); return _accessor(enclosing, reference); } if (parentName == '@method') { var enclosing = elementOfReference(parent2); return _method(enclosing, reference); } if (parentName == '@mixin') { var unit = elementOfReference(parent2); return _mixin(unit, reference); } if (parentName == '@parameter') { ExecutableElementImpl enclosing = elementOfReference(parent2); return _parameter(enclosing, reference); } if (parentName == '@prefix') { LibraryElementImpl enclosing = elementOfReference(parent2); return _prefix(enclosing, reference); } if (parentName == '@typeAlias') { var unit = elementOfReference(parent2); return _typeAlias(unit, reference); } if (parentName == '@typeParameter') { var enclosing = elementOfReference(parent2); if (enclosing is ParameterElement) { (enclosing as ParameterElement).typeParameters; } else { (enclosing as TypeParameterizedElement).typeParameters; } assert(reference.element != null); return reference.element; } if (parentName == '@unit') { elementOfReference(parent2); // Creating a library fills all its units. assert(reference.element != null); return reference.element; } if (reference.name == '@function' && parent2.name == '@typeAlias') { var parent = reference.parent; GenericTypeAliasElementImpl alias = elementOfReference(parent); return alias.function; } throw StateError('Not found: $input'); } PropertyAccessorElementImpl _accessor( ElementImpl enclosing, Reference reference) { if (enclosing is ClassElementImpl) { enclosing.accessors; // Requesting accessors sets elements for accessors and fields. assert(reference.element != null); return reference.element; } if (enclosing is CompilationUnitElementImpl) { enclosing.accessors; // Requesting accessors sets elements for accessors and variables. assert(reference.element != null); return reference.element; } if (enclosing is EnumElementImpl) { enclosing.accessors; // Requesting accessors sets elements for accessors and variables. assert(reference.element != null); return reference.element; } // Only classes and units have accessors. throw StateError('${enclosing.runtimeType}'); } ClassElementImpl _class( CompilationUnitElementImpl unit, Reference reference) { if (reference.node == null) { _indexUnitElementDeclarations(unit); assert(reference.node != null, '$reference'); } ClassElementImpl.forLinkedNode(unit, reference, reference.node); return reference.element; } ConstructorElementImpl _constructor( ClassElementImpl enclosing, Reference reference) { enclosing.constructors; // Requesting constructors sets elements for all of them. assert(reference.element != null); return reference.element; } LibraryElementImpl _createLibraryElement(Reference reference) { var uriStr = reference.name; var sourceFactory = elementFactory.analysisContext.sourceFactory; var librarySource = sourceFactory.forUri(uriStr); // The URI cannot be resolved, we don't know the library. if (librarySource == null) return null; var libraryContext = elementFactory.libraryMap[uriStr]; if (libraryContext == null) { throw ArgumentError( 'Missing library: $uriStr\n' 'Available libraries: ${elementFactory.libraryMap.keys.toList()}', ); } var libraryNode = libraryContext.node; var hasName = libraryNode.name.isNotEmpty; var definingUnitContext = libraryContext.definingUnit; var libraryElement = LibraryElementImpl.forLinkedNode( elementFactory.analysisContext, elementFactory.analysisSession, libraryNode.name, hasName ? libraryNode.nameOffset : -1, libraryNode.nameLength, definingUnitContext, reference, definingUnitContext.unit_withDeclarations, ); var units = <CompilationUnitElementImpl>[]; var unitContainerRef = reference.getChild('@unit'); for (var unitContext in libraryContext.units) { var unitNode = unitContext.unit_withDeclarations; var unitSource = sourceFactory.forUri(unitContext.uriStr); var unitElement = CompilationUnitElementImpl.forLinkedNode( libraryElement, unitContext, unitContext.reference, unitNode, ); unitElement.lineInfo = unitNode.lineInfo; unitElement.source = unitSource; unitElement.librarySource = librarySource; unitElement.uri = unitContext.partUriStr; units.add(unitElement); unitContainerRef.getChild(unitContext.uriStr).element = unitElement; } libraryElement.definingCompilationUnit = units[0]; libraryElement.parts = units.skip(1).toList(); reference.element = libraryElement; var typeProvider = elementFactory.analysisContext.typeProvider; if (typeProvider != null) { libraryElement.createLoadLibraryFunction(typeProvider); } return libraryElement; } EnumElementImpl _enum(CompilationUnitElementImpl unit, Reference reference) { if (reference.node == null) { _indexUnitElementDeclarations(unit); assert(reference.node != null, '$reference'); } EnumElementImpl.forLinkedNode(unit, reference, reference.node); return reference.element; } ExtensionElementImpl _extension( CompilationUnitElementImpl unit, Reference reference) { if (reference.node == null) { _indexUnitElementDeclarations(unit); assert(reference.node != null, '$reference'); } ExtensionElementImpl.forLinkedNode(unit, reference, reference.node); return reference.element; } FieldElementImpl _field(ClassElementImpl enclosing, Reference reference) { enclosing.fields; // Requesting fields sets elements for all fields. assert(reference.element != null); return reference.element; } Element _function(CompilationUnitElementImpl enclosing, Reference reference) { enclosing.functions; assert(reference.element != null); return reference.element; } void _indexUnitElementDeclarations(CompilationUnitElementImpl unit) { var unitContext = unit.linkedContext; var unitRef = unit.reference; var unitNode = unit.linkedNode; _indexUnitDeclarations(unitContext, unitRef, unitNode); } MethodElementImpl _method(ElementImpl enclosing, Reference reference) { if (enclosing is ClassElementImpl) { enclosing.methods; } else if (enclosing is ExtensionElementImpl) { enclosing.methods; } else { throw StateError('${enclosing.runtimeType}'); } // Requesting methods sets elements for all of them. assert(reference.element != null); return reference.element; } MixinElementImpl _mixin( CompilationUnitElementImpl unit, Reference reference) { if (reference.node == null) { _indexUnitElementDeclarations(unit); assert(reference.node != null, '$reference'); } MixinElementImpl.forLinkedNode(unit, reference, reference.node); return reference.element; } Element _parameter(ExecutableElementImpl enclosing, Reference reference) { enclosing.parameters; assert(reference.element != null); return reference.element; } PrefixElementImpl _prefix(LibraryElementImpl library, Reference reference) { for (var import in library.imports) { import.prefix; } assert(reference.element != null); return reference.element; } GenericTypeAliasElementImpl _typeAlias( CompilationUnitElementImpl unit, Reference reference) { if (reference.node == null) { _indexUnitElementDeclarations(unit); assert(reference.node != null, '$reference'); } GenericTypeAliasElementImpl.forLinkedNode(unit, reference, reference.node); return reference.element; } /// Index nodes for which we choose to create elements individually, /// for example [ClassDeclaration], so that its [Reference] has the node, /// and we can call the [ClassElementImpl] constructor. static void _indexUnitDeclarations( LinkedUnitContext unitContext, Reference unitRef, CompilationUnit unitNode, ) { var classRef = unitRef.getChild('@class'); var enumRef = unitRef.getChild('@enum'); var extensionRef = unitRef.getChild('@extension'); var functionRef = unitRef.getChild('@function'); var mixinRef = unitRef.getChild('@mixin'); var typeAliasRef = unitRef.getChild('@typeAlias'); var variableRef = unitRef.getChild('@variable'); for (var declaration in unitNode.declarations) { if (declaration is ClassDeclaration) { var name = declaration.name.name; classRef.getChild(name).node = declaration; } else if (declaration is ClassTypeAlias) { var name = declaration.name.name; classRef.getChild(name).node = declaration; } else if (declaration is ExtensionDeclaration) { var refName = LazyExtensionDeclaration.get(declaration).refName; extensionRef.getChild(refName).node = declaration; } else if (declaration is EnumDeclaration) { var name = declaration.name.name; enumRef.getChild(name).node = declaration; } else if (declaration is FunctionDeclaration) { var name = declaration.name.name; functionRef.getChild(name).node = declaration; } else if (declaration is FunctionTypeAlias) { var name = declaration.name.name; typeAliasRef.getChild(name).node = declaration; } else if (declaration is GenericTypeAlias) { var name = declaration.name.name; typeAliasRef.getChild(name).node = declaration; } else if (declaration is MixinDeclaration) { var name = declaration.name.name; mixinRef.getChild(name).node = declaration; } else if (declaration is TopLevelVariableDeclaration) { for (var variable in declaration.variables.variables) { var name = variable.name.name; variableRef.getChild(name).node = declaration; } } } } }
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/summary2/type_builder.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/type.dart'; /// The builder for a [DartType] represented by a node. abstract class TypeBuilder implements DartType { /// Build the type, and set it for the corresponding node. /// Does nothing if the type has been already built. /// /// Return the built type. DartType build(); noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } }
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/summary2/export.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/src/summary2/combinator.dart'; import 'package:analyzer/src/summary2/library_builder.dart'; import 'package:analyzer/src/summary2/reference.dart'; class Export { final LibraryBuilder exporter; final LibraryBuilder exported; final List<Combinator> combinators; Export(this.exporter, this.exported, this.combinators); bool addToExportScope(String name, Reference reference) { if (combinators != null) { for (Combinator combinator in combinators) { if (combinator.isShow && !combinator.matches(name)) return false; if (combinator.isHide && combinator.matches(name)) return false; } } return exporter.addToExportScope(name, reference); } }
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/fasta/error_converter.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 'package:analyzer/dart/ast/token.dart' show Token; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/error/syntactic_errors.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:front_end/src/fasta/messages.dart' show Code, Message; /// An error reporter that knows how to convert a Fasta error into an analyzer /// error. class FastaErrorReporter { /// The underlying error reporter to which errors are reported. final ErrorReporter errorReporter; /// Initialize a newly created error reporter to report errors to the given /// [errorReporter]. FastaErrorReporter(this.errorReporter); void reportByCode( String analyzerCode, int offset, int length, Message message) { Map<String, dynamic> arguments = message.arguments; String lexeme() => (arguments['token'] as Token).lexeme; switch (analyzerCode) { case "ASYNC_FOR_IN_WRONG_CONTEXT": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT, offset, length); return; case "ASYNC_KEYWORD_USED_AS_IDENTIFIER": errorReporter?.reportErrorForOffset( ParserErrorCode.ASYNC_KEYWORD_USED_AS_IDENTIFIER, offset, length); return; case "AWAIT_IN_WRONG_CONTEXT": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.AWAIT_IN_WRONG_CONTEXT, offset, length); return; case "BUILT_IN_IDENTIFIER_AS_TYPE": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE, offset, length, [lexeme()]); return; case "CONCRETE_CLASS_WITH_ABSTRACT_MEMBER": errorReporter?.reportErrorForOffset( StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER, offset, length); return; case "CONST_CONSTRUCTOR_WITH_BODY": errorReporter?.reportErrorForOffset( ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY, offset, length); return; case "CONST_NOT_INITIALIZED": String name = arguments['name']; errorReporter?.reportErrorForOffset( CompileTimeErrorCode.CONST_NOT_INITIALIZED, offset, length, [name]); return; case "DEFAULT_VALUE_IN_FUNCTION_TYPE": errorReporter?.reportErrorForOffset( ParserErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE, offset, length); return; case "LABEL_UNDEFINED": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.LABEL_UNDEFINED, offset, length, [arguments['name']]); return; case "EMPTY_ENUM_BODY": errorReporter?.reportErrorForOffset( ParserErrorCode.EMPTY_ENUM_BODY, offset, length); return; case "EXPECTED_CLASS_MEMBER": errorReporter?.reportErrorForOffset( ParserErrorCode.EXPECTED_CLASS_MEMBER, offset, length); return; case "EXPECTED_EXECUTABLE": errorReporter?.reportErrorForOffset( ParserErrorCode.EXPECTED_EXECUTABLE, offset, length); return; case "EXPECTED_STRING_LITERAL": errorReporter?.reportErrorForOffset( ParserErrorCode.EXPECTED_STRING_LITERAL, offset, length); return; case "EXPECTED_TOKEN": errorReporter?.reportErrorForOffset(ParserErrorCode.EXPECTED_TOKEN, offset, length, [arguments['string']]); return; case "EXPECTED_TYPE_NAME": errorReporter?.reportErrorForOffset( ParserErrorCode.EXPECTED_TYPE_NAME, offset, length); return; case "FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR, offset, length); return; case "FINAL_NOT_INITIALIZED": String name = arguments['name']; errorReporter?.reportErrorForOffset( StaticWarningCode.FINAL_NOT_INITIALIZED, offset, length, [name]); return; case "FINAL_NOT_INITIALIZED_CONSTRUCTOR_1": String name = arguments['name']; errorReporter?.reportErrorForOffset( StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1, offset, length, [name]); return; case "FUNCTION_TYPED_PARAMETER_VAR": errorReporter?.reportErrorForOffset( ParserErrorCode.FUNCTION_TYPED_PARAMETER_VAR, offset, length); return; case "GETTER_WITH_PARAMETERS": errorReporter?.reportErrorForOffset( ParserErrorCode.GETTER_WITH_PARAMETERS, offset, length); return; case "ILLEGAL_CHARACTER": errorReporter?.reportErrorForOffset( ScannerErrorCode.ILLEGAL_CHARACTER, offset, length); return; case "INVALID_ASSIGNMENT": var type1 = arguments['type']; var type2 = arguments['type2']; errorReporter?.reportErrorForOffset( StaticTypeWarningCode.INVALID_ASSIGNMENT, offset, length, [type1, type2]); return; case "INVALID_INLINE_FUNCTION_TYPE": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.INVALID_INLINE_FUNCTION_TYPE, offset, length); return; case "INVALID_LITERAL_IN_CONFIGURATION": errorReporter?.reportErrorForOffset( ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION, offset, length); return; case "IMPORT_OF_NON_LIBRARY": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY, offset, length); return; case "INVALID_CAST_FUNCTION": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_CAST_FUNCTION, offset, length); return; case "INVALID_CAST_FUNCTION_EXPR": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_CAST_FUNCTION_EXPR, offset, length); return; case "INVALID_CAST_LITERAL_LIST": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_CAST_LITERAL_LIST, offset, length); return; case "INVALID_CAST_LITERAL_MAP": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_CAST_LITERAL_MAP, offset, length); return; case "INVALID_CAST_METHOD": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_CAST_METHOD, offset, length); return; case "INVALID_CAST_NEW_EXPR": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_CAST_NEW_EXPR, offset, length); return; case "INVALID_CODE_POINT": errorReporter?.reportErrorForOffset( ParserErrorCode.INVALID_CODE_POINT, offset, length, ['\\u{...}']); return; case "INVALID_CONSTRUCTOR_NAME": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME, offset, length); return; case "INVALID_GENERIC_FUNCTION_TYPE": errorReporter?.reportErrorForOffset( ParserErrorCode.INVALID_GENERIC_FUNCTION_TYPE, offset, length); return; case "INVALID_METHOD_OVERRIDE": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.INVALID_OVERRIDE, offset, length); return; case "INVALID_MODIFIER_ON_SETTER": _reportByCode(CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER, message, offset, length); return; case "INVALID_OPERATOR_FOR_SUPER": _reportByCode(ParserErrorCode.INVALID_OPERATOR_FOR_SUPER, message, offset, length); return; case "INVALID_SUPER_INVOCATION": errorReporter?.reportErrorForOffset( StrongModeCode.INVALID_SUPER_INVOCATION, offset, length); return; case "MISSING_DIGIT": errorReporter?.reportErrorForOffset( ScannerErrorCode.MISSING_DIGIT, offset, length); return; case "MISSING_ENUM_BODY": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_ENUM_BODY, offset, length); return; case "MISSING_FUNCTION_BODY": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_FUNCTION_BODY, offset, length); return; case "MISSING_FUNCTION_PARAMETERS": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_FUNCTION_PARAMETERS, offset, length); return; case "MISSING_HEX_DIGIT": errorReporter?.reportErrorForOffset( ScannerErrorCode.MISSING_HEX_DIGIT, offset, length); return; case "MISSING_IDENTIFIER": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_IDENTIFIER, offset, length); return; case "MISSING_METHOD_PARAMETERS": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_METHOD_PARAMETERS, offset, length); return; case "MISSING_STAR_AFTER_SYNC": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_STAR_AFTER_SYNC, offset, length); return; case "MISSING_TYPEDEF_PARAMETERS": errorReporter?.reportErrorForOffset( ParserErrorCode.MISSING_TYPEDEF_PARAMETERS, offset, length); return; case "MULTIPLE_IMPLEMENTS_CLAUSES": errorReporter?.reportErrorForOffset( ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES, offset, length); return; case "NAMED_FUNCTION_EXPRESSION": errorReporter?.reportErrorForOffset( ParserErrorCode.NAMED_FUNCTION_EXPRESSION, offset, length); return; case "NAMED_PARAMETER_OUTSIDE_GROUP": errorReporter?.reportErrorForOffset( ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP, offset, length); return; case "NON_PART_OF_DIRECTIVE_IN_PART": errorReporter?.reportErrorForOffset( ParserErrorCode.NON_PART_OF_DIRECTIVE_IN_PART, offset, length); return; case "NON_SYNC_FACTORY": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.NON_SYNC_FACTORY, offset, length); return; case "POSITIONAL_AFTER_NAMED_ARGUMENT": errorReporter?.reportErrorForOffset( ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT, offset, length); return; case "RECURSIVE_CONSTRUCTOR_REDIRECT": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.RECURSIVE_CONSTRUCTOR_REDIRECT, offset, length); return; case "RETURN_IN_GENERATOR": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.RETURN_IN_GENERATOR, offset, length, // TODO(danrubel): Update the parser to report the modifier // involved in this error... either async* or sync* ['async*']); return; case "SUPER_IN_REDIRECTING_CONSTRUCTOR": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR, offset, length); return; case "TYPE_PARAMETER_ON_CONSTRUCTOR": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.TYPE_PARAMETER_ON_CONSTRUCTOR, offset, length); return; case "UNDEFINED_CLASS": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.UNDEFINED_CLASS, offset, length); return; case "UNDEFINED_GETTER": errorReporter?.reportErrorForOffset( StaticTypeWarningCode.UNDEFINED_GETTER, offset, length); return; case "UNDEFINED_METHOD": errorReporter?.reportErrorForOffset( StaticTypeWarningCode.UNDEFINED_METHOD, offset, length); return; case "UNDEFINED_SETTER": errorReporter?.reportErrorForOffset( StaticTypeWarningCode.UNDEFINED_SETTER, offset, length); return; case "UNEXPECTED_DOLLAR_IN_STRING": errorReporter?.reportErrorForOffset( ScannerErrorCode.UNEXPECTED_DOLLAR_IN_STRING, offset, length); return; case "UNEXPECTED_TOKEN": errorReporter?.reportErrorForOffset( ParserErrorCode.UNEXPECTED_TOKEN, offset, length, [lexeme()]); return; case "UNTERMINATED_MULTI_LINE_COMMENT": errorReporter?.reportErrorForOffset( ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT, offset, length); return; case "UNTERMINATED_STRING_LITERAL": errorReporter?.reportErrorForOffset( ScannerErrorCode.UNTERMINATED_STRING_LITERAL, offset, length); return; case "WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER, offset, length); return; case "WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR": errorReporter?.reportErrorMessage( StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR, offset, length, message); return; case "WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER": errorReporter?.reportErrorForOffset( ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER, offset, length); return; case "YIELD_IN_NON_GENERATOR": errorReporter?.reportErrorForOffset( CompileTimeErrorCode.YIELD_IN_NON_GENERATOR, offset, length); return; default: // fall through } } /// Report an error based on the given [message] whose range is described by /// the given [offset] and [length]. void reportMessage(Message message, int offset, int length) { Code code = message.code; int index = code.index; if (index != null && index > 0 && index < fastaAnalyzerErrorCodes.length) { ErrorCode errorCode = fastaAnalyzerErrorCodes[index]; if (errorCode != null) { errorReporter.reportError(new AnalysisError.forValues( errorReporter.source, offset, length, errorCode, message.message, message.tip)); return; } } reportByCode(code.analyzerCodes?.first, offset, length, message); } void reportScannerError( ScannerErrorCode errorCode, int offset, List<Object> arguments) { // TODO(danrubel): update client to pass length in addition to offset. int length = 1; errorReporter?.reportErrorForOffset(errorCode, offset, length, arguments); } void _reportByCode( ErrorCode errorCode, Message message, int offset, int length) { if (errorReporter != null) { errorReporter.reportError(new AnalysisError.forValues( errorReporter.source, offset, length, errorCode, message.message, 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/fasta/token_utils.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 'package:front_end/src/scanner/token.dart' show CommentToken, Token; /// Search for the token before [target] starting the search with [start]. /// Return `null` if [target] is a comment token /// or the previous token cannot be found. Token findPrevious(Token start, Token target) { if (start == target || target is CommentToken) { return null; } Token token = start is CommentToken ? start.parent : start; do { Token next = token.next; if (next == target) { return token; } token = next; } while (!token.isEof); return 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/fasta/ast_builder.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 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/ast_factory.dart' show AstFactory; import 'package:analyzer/dart/ast/standard_ast_factory.dart' as standard; import 'package:analyzer/dart/ast/token.dart' show Token, TokenType; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/analysis/experiments.dart'; import 'package:analyzer/src/dart/ast/ast.dart' show ClassDeclarationImpl, CompilationUnitImpl, ExtensionDeclarationImpl, MixinDeclarationImpl; import 'package:analyzer/src/fasta/error_converter.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:front_end/src/fasta/messages.dart' show LocatedMessage, Message, MessageCode, messageConstConstructorWithBody, messageConstructorWithReturnType, messageConstructorWithTypeParameters, messageDirectiveAfterDeclaration, messageExpectedStatement, messageFieldInitializerOutsideConstructor, messageIllegalAssignmentToNonAssignable, messageInterpolationInUri, messageInvalidInitializer, messageInvalidSuperInInitializer, messageInvalidThisInInitializer, messageMissingAssignableSelector, messageNativeClauseShouldBeAnnotation, messageTypedefNotFunction, templateDuplicateLabelInSwitchStatement, templateExpectedButGot, templateExpectedIdentifier, templateExperimentNotEnabled, templateUnexpectedToken; import 'package:front_end/src/fasta/parser.dart' show Assert, DeclarationKind, FormalParameterKind, IdentifierContext, MemberKind, optional, Parser; import 'package:front_end/src/fasta/problems.dart' show unhandled; import 'package:front_end/src/fasta/quote.dart'; import 'package:front_end/src/fasta/scanner.dart' hide StringToken; import 'package:front_end/src/fasta/scanner/token_constants.dart'; import 'package:front_end/src/fasta/source/stack_listener.dart' show NullValue, StackListener; import 'package:front_end/src/scanner/errors.dart' show translateErrorToken; import 'package:front_end/src/scanner/token.dart' show SyntheticStringToken, SyntheticToken; import 'package:kernel/ast.dart' show AsyncMarker; const _invalidCollectionElement = const _InvalidCollectionElement._(); /// A parser listener that builds the analyzer's AST structure. class AstBuilder extends StackListener { final AstFactory ast = standard.astFactory; final FastaErrorReporter errorReporter; final Uri fileUri; ScriptTag scriptTag; final List<Directive> directives = <Directive>[]; final List<CompilationUnitMember> declarations = <CompilationUnitMember>[]; final localDeclarations = <int, AstNode>{}; @override final Uri uri; /// The parser that uses this listener, used to parse optional parts, e.g. /// `native` support. Parser parser; /// The class currently being parsed, or `null` if no class is being parsed. ClassDeclarationImpl classDeclaration; /// The mixin currently being parsed, or `null` if no mixin is being parsed. MixinDeclarationImpl mixinDeclaration; /// The extension currently being parsed, or `null` if none. ExtensionDeclarationImpl extensionDeclaration; /// If true, this is building a full AST. Otherwise, only create method /// bodies. final bool isFullAst; /// `true` if the `native` clause is allowed /// in class, method, and function declarations. /// /// This is being replaced by the @native(...) annotation. // // TODO(danrubel) Move this flag to a better location // and should only be true if either: // * The current library is a platform library // * The current library has an import that uses the scheme "dart-ext". bool allowNativeClause = false; StringLiteral nativeName; bool parseFunctionBodies = true; /// `true` if non-nullable behavior is enabled. final bool enableNonNullable; /// `true` if spread-collections behavior is enabled final bool enableSpreadCollections; /// `true` if control-flow-collections behavior is enabled final bool enableControlFlowCollections; /// `true` if triple-shift behavior is enabled final bool enableTripleShift; /// `true` if variance behavior is enabled final bool enableVariance; final FeatureSet _featureSet; AstBuilder(ErrorReporter errorReporter, this.fileUri, this.isFullAst, this._featureSet, [Uri uri]) : this.errorReporter = new FastaErrorReporter(errorReporter), this.enableNonNullable = _featureSet.isEnabled(Feature.non_nullable), this.enableSpreadCollections = _featureSet.isEnabled(Feature.spread_collections), this.enableControlFlowCollections = _featureSet.isEnabled(Feature.control_flow_collections), this.enableTripleShift = _featureSet.isEnabled(Feature.triple_shift), this.enableVariance = _featureSet.isEnabled(Feature.variance), uri = uri ?? fileUri; NodeList<ClassMember> get currentDeclarationMembers { if (classDeclaration != null) { return classDeclaration.members; } else if (mixinDeclaration != null) { return mixinDeclaration.members; } else { return extensionDeclaration.members; } } SimpleIdentifier get currentDeclarationName { if (classDeclaration != null) { return classDeclaration.name; } else if (mixinDeclaration != null) { return mixinDeclaration.name; } else { return extensionDeclaration.name; } } @override void addProblem(Message message, int charOffset, int length, {bool wasHandled: false, List<LocatedMessage> context}) { if (directives.isEmpty && (message.code.analyzerCodes ?.contains('NON_PART_OF_DIRECTIVE_IN_PART') ?? false)) { message = messageDirectiveAfterDeclaration; } errorReporter.reportMessage(message, charOffset, length); } void beginCascade(Token token) { assert(optional('..', token) || optional('?..', token)); debugEvent("beginCascade"); Expression expression = pop(); push(token); if (expression is CascadeExpression) { push(expression); } else { push(ast.cascadeExpression(expression, <Expression>[])); } push(NullValue.CascadeReceiver); } @override void beginClassDeclaration(Token begin, Token abstractToken, Token name) { assert(classDeclaration == null && mixinDeclaration == null && extensionDeclaration == null); push(new _Modifiers()..abstractKeyword = abstractToken); } @override void beginCompilationUnit(Token token) { push(token); } @override void beginExtensionDeclaration(Token extensionKeyword, Token nameToken) { assert(optional('extension', extensionKeyword)); assert(classDeclaration == null && mixinDeclaration == null && extensionDeclaration == null); debugEvent("ExtensionHeader"); TypeParameterList typeParameters = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, extensionKeyword); SimpleIdentifier name; if (nameToken != null) { name = ast.simpleIdentifier(nameToken, isDeclaration: true); } extensionDeclaration = ast.extensionDeclaration( comment: comment, metadata: metadata, extensionKeyword: extensionKeyword, name: name, typeParameters: typeParameters, extendedType: null, // extendedType is set in [endExtensionDeclaration] ) as ExtensionDeclarationImpl; declarations.add(extensionDeclaration); } @override void beginFactoryMethod( Token lastConsumed, Token externalToken, Token constToken) { push(new _Modifiers() ..externalKeyword = externalToken ..finalConstOrVarKeyword = constToken); } @override void beginFormalParameter(Token token, MemberKind kind, Token requiredToken, Token covariantToken, Token varFinalOrConst) { push(new _Modifiers() ..covariantKeyword = covariantToken ..finalConstOrVarKeyword = varFinalOrConst ..requiredToken = requiredToken); } @override void beginFormalParameterDefaultValueExpression() {} void beginIfControlFlow(Token ifToken) { push(ifToken); } void beginLiteralString(Token literalString) { assert(identical(literalString.kind, STRING_TOKEN)); debugEvent("beginLiteralString"); push(literalString); } @override void beginMetadataStar(Token token) { debugEvent("beginMetadataStar"); } @override void beginMethod(Token externalToken, Token staticToken, Token covariantToken, Token varFinalOrConst, Token getOrSet, Token name) { _Modifiers modifiers = new _Modifiers(); if (externalToken != null) { assert(externalToken.isModifier); modifiers.externalKeyword = externalToken; } if (staticToken != null) { assert(staticToken.isModifier); String className = classDeclaration != null ? classDeclaration.name.name : (mixinDeclaration != null ? mixinDeclaration.name.name : extensionDeclaration.name?.name); if (name?.lexeme != className || getOrSet != null) { modifiers.staticKeyword = staticToken; } } if (covariantToken != null) { assert(covariantToken.isModifier); modifiers.covariantKeyword = covariantToken; } if (varFinalOrConst != null) { assert(varFinalOrConst.isModifier); modifiers.finalConstOrVarKeyword = varFinalOrConst; } push(modifiers); } @override void beginMixinDeclaration(Token mixinKeyword, Token name) { assert(classDeclaration == null && mixinDeclaration == null && extensionDeclaration == null); } @override void beginNamedMixinApplication( Token begin, Token abstractToken, Token name) { push(new _Modifiers()..abstractKeyword = abstractToken); } void beginTopLevelMethod(Token lastConsumed, Token externalToken) { push(new _Modifiers()..externalKeyword = externalToken); } @override void beginTypeVariable(Token token) { debugEvent("beginTypeVariable"); SimpleIdentifier name = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, name.beginToken); var typeParameter = ast.typeParameter(comment, metadata, name, null, null); localDeclarations[name.offset] = typeParameter; push(typeParameter); } @override void beginVariablesDeclaration( Token token, Token lateToken, Token varFinalOrConst) { debugEvent("beginVariablesDeclaration"); if (varFinalOrConst != null || lateToken != null) { push(new _Modifiers() ..finalConstOrVarKeyword = varFinalOrConst ..lateToken = lateToken); } else { push(NullValue.Modifiers); } } ConstructorInitializer buildInitializer(Object initializerObject) { if (initializerObject is FunctionExpressionInvocation) { Expression function = initializerObject.function; if (function is SuperExpression) { return ast.superConstructorInvocation( function.superKeyword, null, null, initializerObject.argumentList); } if (function is ThisExpression) { return ast.redirectingConstructorInvocation( function.thisKeyword, null, null, initializerObject.argumentList); } return null; } if (initializerObject is MethodInvocation) { Expression target = initializerObject.target; if (target is SuperExpression) { return ast.superConstructorInvocation( target.superKeyword, initializerObject.operator, initializerObject.methodName, initializerObject.argumentList); } if (target is ThisExpression) { return ast.redirectingConstructorInvocation( target.thisKeyword, initializerObject.operator, initializerObject.methodName, initializerObject.argumentList); } return buildInitializerTargetExpressionRecovery( target, initializerObject); } if (initializerObject is PropertyAccess) { return buildInitializerTargetExpressionRecovery( initializerObject.target, initializerObject); } if (initializerObject is AssignmentExpression) { Token thisKeyword; Token period; SimpleIdentifier fieldName; Expression left = initializerObject.leftHandSide; if (left is PropertyAccess) { Expression target = left.target; if (target is ThisExpression) { thisKeyword = target.thisKeyword; period = left.operator; } else { assert(target is SuperExpression); // Recovery: // Parser has reported FieldInitializedOutsideDeclaringClass. } fieldName = left.propertyName; } else if (left is SimpleIdentifier) { fieldName = left; } else { // Recovery: // Parser has reported invalid assignment. SuperExpression superExpression = left; fieldName = ast.simpleIdentifier(superExpression.superKeyword); } return ast.constructorFieldInitializer(thisKeyword, period, fieldName, initializerObject.operator, initializerObject.rightHandSide); } if (initializerObject is AssertInitializer) { return initializerObject; } if (initializerObject is IndexExpression) { return buildInitializerTargetExpressionRecovery( initializerObject.target, initializerObject); } if (initializerObject is CascadeExpression) { return buildInitializerTargetExpressionRecovery( initializerObject.target, initializerObject); } return null; } AstNode buildInitializerTargetExpressionRecovery( Expression target, Object initializerObject) { ArgumentList argumentList; while (true) { if (target is FunctionExpressionInvocation) { argumentList = (target as FunctionExpressionInvocation).argumentList; target = (target as FunctionExpressionInvocation).function; } else if (target is MethodInvocation) { argumentList = (target as MethodInvocation).argumentList; target = (target as MethodInvocation).target; } else if (target is PropertyAccess) { argumentList = null; target = (target as PropertyAccess).target; } else { break; } } if (target is SuperExpression) { // TODO(danrubel): Consider generating this error in the parser // This error is also reported in the body builder handleRecoverableError(messageInvalidSuperInInitializer, target.superKeyword, target.superKeyword); return ast.superConstructorInvocation( target.superKeyword, null, null, argumentList); } else if (target is ThisExpression) { // TODO(danrubel): Consider generating this error in the parser // This error is also reported in the body builder handleRecoverableError(messageInvalidThisInInitializer, target.thisKeyword, target.thisKeyword); return ast.redirectingConstructorInvocation( target.thisKeyword, null, null, argumentList); } return null; } void checkFieldFormalParameters(FormalParameterList parameters) { if (parameters?.parameters != null) { parameters.parameters.forEach((FormalParameter param) { if (param is FieldFormalParameter) { // This error is reported in the BodyBuilder.endFormalParameter. handleRecoverableError(messageFieldInitializerOutsideConstructor, param.thisKeyword, param.thisKeyword); } }); } } @override void debugEvent(String name) { // printEvent('AstBuilder: $name'); } @override void discardTypeReplacedWithCommentTypeAssign() { pop(); } void doDotExpression(Token dot) { Expression identifierOrInvoke = pop(); Expression receiver = pop(); if (identifierOrInvoke is SimpleIdentifier) { if (receiver is SimpleIdentifier && identical('.', dot.stringValue)) { push(ast.prefixedIdentifier(receiver, dot, identifierOrInvoke)); } else { push(ast.propertyAccess(receiver, dot, identifierOrInvoke)); } } else if (identifierOrInvoke is MethodInvocation) { assert(identifierOrInvoke.target == null); identifierOrInvoke ..target = receiver ..operator = dot; push(identifierOrInvoke); } else { // This same error is reported in BodyBuilder.doDotOrCascadeExpression Token token = identifierOrInvoke.beginToken; // TODO(danrubel): Consider specializing the error message based // upon the type of expression. e.g. "x.this" -> templateThisAsIdentifier handleRecoverableError( templateExpectedIdentifier.withArguments(token), token, token); SimpleIdentifier identifier = ast.simpleIdentifier(token, isDeclaration: false); push(ast.propertyAccess(receiver, dot, identifier)); } } void doInvocation( TypeArgumentList typeArguments, MethodInvocation arguments) { Expression receiver = pop(); if (receiver is SimpleIdentifier) { arguments.methodName = receiver; if (typeArguments != null) { arguments.typeArguments = typeArguments; } push(arguments); } else { push(ast.functionExpressionInvocation( receiver, typeArguments, arguments.argumentList)); } } void doPropertyGet() {} void endArguments(int count, Token leftParenthesis, Token rightParenthesis) { assert(optional('(', leftParenthesis)); assert(optional(')', rightParenthesis)); debugEvent("Arguments"); List<Expression> expressions = popTypedList(count); ArgumentList arguments = ast.argumentList(leftParenthesis, expressions, rightParenthesis); push(ast.methodInvocation(null, null, null, null, arguments)); } @override void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis, Token comma, Token semicolon) { assert(optional('assert', assertKeyword)); assert(optional('(', leftParenthesis)); assert(optionalOrNull(',', comma)); assert(kind != Assert.Statement || optionalOrNull(';', semicolon)); debugEvent("Assert"); Expression message = popIfNotNull(comma); Expression condition = pop(); switch (kind) { case Assert.Expression: // The parser has already reported an error indicating that assert // cannot be used in an expression. Insert a placeholder. List<Expression> arguments = <Expression>[condition]; if (message != null) { arguments.add(message); } push(ast.functionExpressionInvocation( ast.simpleIdentifier(assertKeyword), null, ast.argumentList( leftParenthesis, arguments, leftParenthesis?.endGroup))); break; case Assert.Initializer: push(ast.assertInitializer(assertKeyword, leftParenthesis, condition, comma, message, leftParenthesis?.endGroup)); break; case Assert.Statement: push(ast.assertStatement(assertKeyword, leftParenthesis, condition, comma, message, leftParenthesis?.endGroup, semicolon)); break; } } void endAwaitExpression(Token awaitKeyword, Token endToken) { assert(optional('await', awaitKeyword)); debugEvent("AwaitExpression"); push(ast.awaitExpression(awaitKeyword, pop())); } @override void endBinaryExpression(Token operatorToken) { assert(operatorToken.isOperator || optional('.', operatorToken) || optional('?.', operatorToken) || optional('..', operatorToken) || optional('?..', operatorToken)); debugEvent("BinaryExpression"); if (identical(".", operatorToken.stringValue) || identical("?.", operatorToken.stringValue) || identical("..", operatorToken.stringValue) || identical("?..", operatorToken.stringValue)) { doDotExpression(operatorToken); } else { Expression right = pop(); Expression left = pop(); reportErrorIfSuper(right); push(ast.binaryExpression(left, operatorToken, right)); if (!enableTripleShift && operatorToken.type == TokenType.GT_GT_GT) { handleRecoverableError( templateExperimentNotEnabled .withArguments(EnableString.triple_shift), operatorToken, operatorToken); } } } void endBlock(int count, Token leftBracket, Token rightBracket) { assert(optional('{', leftBracket)); assert(optional('}', rightBracket)); debugEvent("Block"); List<Statement> statements = popTypedList(count) ?? <Statement>[]; push(ast.block(leftBracket, statements, rightBracket)); } void endBlockFunctionBody(int count, Token leftBracket, Token rightBracket) { assert(optional('{', leftBracket)); assert(optional('}', rightBracket)); debugEvent("BlockFunctionBody"); List<Statement> statements = popTypedList(count); Block block = ast.block(leftBracket, statements, rightBracket); Token star = pop(); Token asyncKeyword = pop(); if (parseFunctionBodies) { push(ast.blockFunctionBody(asyncKeyword, star, block)); } else { // TODO(danrubel): Skip the block rather than parsing it. push(ast.emptyFunctionBody( new SyntheticToken(TokenType.SEMICOLON, leftBracket.charOffset))); } } void endCascade() { debugEvent("Cascade"); Expression expression = pop(); CascadeExpression receiver = pop(); pop(); // Token. receiver.cascadeSections.add(expression); push(receiver); } @override void endClassConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { assert(getOrSet == null || optional('get', getOrSet) || optional('set', getOrSet)); debugEvent("ClassConstructor"); var bodyObject = pop(); List<ConstructorInitializer> initializers = pop() ?? const []; Token separator = pop(); FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); var name = pop(); TypeAnnotation returnType = pop(); _Modifiers modifiers = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); assert(parameters != null || optional('get', getOrSet)); ConstructorName redirectedConstructor; FunctionBody body; if (bodyObject is FunctionBody) { body = bodyObject; } else if (bodyObject is _RedirectingFactoryBody) { separator = bodyObject.equalToken; redirectedConstructor = bodyObject.constructorName; body = ast.emptyFunctionBody(endToken); } else { unhandled("${bodyObject.runtimeType}", "bodyObject", beginToken.charOffset, uri); } SimpleIdentifier prefixOrName; Token period; SimpleIdentifier nameOrNull; if (name is SimpleIdentifier) { prefixOrName = name; } else if (name is PrefixedIdentifier) { prefixOrName = name.prefix; period = name.period; nameOrNull = name.identifier; } else { throw new UnimplementedError( 'name is an instance of ${name.runtimeType} in endClassConstructor'); } if (typeParameters != null) { // Outline builder also reports this error message. handleRecoverableError(messageConstructorWithTypeParameters, typeParameters.beginToken, typeParameters.endToken); } if (modifiers?.constKeyword != null && body != null && (body.length > 1 || body.beginToken?.lexeme != ';')) { // This error is also reported in BodyBuilder.finishFunction Token bodyToken = body.beginToken ?? modifiers.constKeyword; handleRecoverableError( messageConstConstructorWithBody, bodyToken, bodyToken); } if (returnType != null) { // This error is also reported in OutlineBuilder.endMethod handleRecoverableError(messageConstructorWithReturnType, returnType.beginToken, returnType.beginToken); } ConstructorDeclaration constructor = ast.constructorDeclaration( comment, metadata, modifiers?.externalKeyword, modifiers?.finalConstOrVarKeyword, null, // TODO(paulberry): factoryKeyword ast.simpleIdentifier(prefixOrName.token), period, nameOrNull, parameters, separator, initializers, redirectedConstructor, body); currentDeclarationMembers.add(constructor); if (mixinDeclaration != null) { // TODO (danrubel): Report an error if this is a mixin declaration. } } @override void endClassDeclaration(Token beginToken, Token endToken) { debugEvent("ClassDeclaration"); classDeclaration = null; } @override void endClassFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { assert(optional('factory', factoryKeyword)); assert(optional(';', endToken) || optional('}', endToken)); debugEvent("ClassFactoryMethod"); FunctionBody body; Token separator; ConstructorName redirectedConstructor; Object bodyObject = pop(); if (bodyObject is FunctionBody) { body = bodyObject; } else if (bodyObject is _RedirectingFactoryBody) { separator = bodyObject.equalToken; redirectedConstructor = bodyObject.constructorName; body = ast.emptyFunctionBody(endToken); } else { unhandled("${bodyObject.runtimeType}", "bodyObject", beginToken.charOffset, uri); } FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); Object constructorName = pop(); _Modifiers modifiers = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); assert(parameters != null); if (typeParameters != null) { // TODO(danrubel): Update OutlineBuilder to report this error message. handleRecoverableError(messageConstructorWithTypeParameters, typeParameters.beginToken, typeParameters.endToken); } // Decompose the preliminary ConstructorName into the type name and // the actual constructor name. SimpleIdentifier returnType; Token period; SimpleIdentifier name; Identifier typeName = constructorName; if (typeName is SimpleIdentifier) { returnType = typeName; } else if (typeName is PrefixedIdentifier) { returnType = typeName.prefix; period = typeName.period; name = ast.simpleIdentifier(typeName.identifier.token, isDeclaration: true); } currentDeclarationMembers.add(ast.constructorDeclaration( comment, metadata, modifiers?.externalKeyword, modifiers?.finalConstOrVarKeyword, factoryKeyword, ast.simpleIdentifier(returnType.token), period, name, parameters, separator, null, redirectedConstructor, body)); } @override void endClassFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token semicolon) { assert(optional(';', semicolon)); debugEvent("Fields"); List<VariableDeclaration> variables = popTypedList(count); TypeAnnotation type = pop(); var variableList = ast.variableDeclarationList2( lateKeyword: lateToken, keyword: varFinalOrConst, type: type, variables: variables, ); Token covariantKeyword = covariantToken; List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); currentDeclarationMembers.add(ast.fieldDeclaration2( comment: comment, metadata: metadata, covariantKeyword: covariantKeyword, staticKeyword: staticToken, fieldList: variableList, semicolon: semicolon)); } @override void endClassMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { assert(getOrSet == null || optional('get', getOrSet) || optional('set', getOrSet)); debugEvent("ClassMethod"); var bodyObject = pop(); pop(); // initializers pop(); // separator FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); var name = pop(); TypeAnnotation returnType = pop(); _Modifiers modifiers = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); assert(parameters != null || optional('get', getOrSet)); FunctionBody body; if (bodyObject is FunctionBody) { body = bodyObject; } else if (bodyObject is _RedirectingFactoryBody) { body = ast.emptyFunctionBody(endToken); } else { unhandled("${bodyObject.runtimeType}", "bodyObject", beginToken.charOffset, uri); } Token operatorKeyword; SimpleIdentifier nameId; if (name is SimpleIdentifier) { nameId = name; } else if (name is _OperatorName) { operatorKeyword = name.operatorKeyword; nameId = name.name; } else { throw new UnimplementedError( 'name is an instance of ${name.runtimeType} in endClassMethod'); } checkFieldFormalParameters(parameters); currentDeclarationMembers.add(ast.methodDeclaration( comment, metadata, modifiers?.externalKeyword, modifiers?.abstractKeyword ?? modifiers?.staticKeyword, returnType, getOrSet, operatorKeyword, nameId, typeParameters, parameters, body)); } @override void endClassOrMixinBody(DeclarationKind kind, int memberCount, Token leftBracket, Token rightBracket) { // TODO(danrubel): consider renaming endClassOrMixinBody // to endClassOrMixinOrExtensionBody assert(optional('{', leftBracket)); assert(optional('}', rightBracket)); debugEvent("ClassOrMixinBody"); if (classDeclaration != null) { classDeclaration ..leftBracket = leftBracket ..rightBracket = rightBracket; } else if (mixinDeclaration != null) { mixinDeclaration ..leftBracket = leftBracket ..rightBracket = rightBracket; } else { extensionDeclaration ..leftBracket = leftBracket ..rightBracket = rightBracket; } } @override void endCombinators(int count) { debugEvent("Combinators"); push(popTypedList<Combinator>(count) ?? NullValue.Combinators); } @override void endCompilationUnit(int count, Token endToken) { debugEvent("CompilationUnit"); Token beginToken = pop(); checkEmpty(endToken.charOffset); CompilationUnitImpl unit = ast.compilationUnit( beginToken: beginToken, scriptTag: scriptTag, directives: directives, declarations: declarations, endToken: endToken, featureSet: _featureSet) as CompilationUnitImpl; push(unit); } void endConditionalExpression(Token question, Token colon) { assert(optional('?', question)); assert(optional(':', colon)); debugEvent("ConditionalExpression"); Expression elseExpression = pop(); Expression thenExpression = pop(); Expression condition = pop(); reportErrorIfSuper(elseExpression); reportErrorIfSuper(thenExpression); push(ast.conditionalExpression( condition, question, thenExpression, colon, elseExpression)); } void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) { assert(optional('if', ifKeyword)); assert(optionalOrNull('(', leftParen)); assert(optionalOrNull('==', equalSign)); debugEvent("ConditionalUri"); StringLiteral libraryUri = pop(); StringLiteral value = popIfNotNull(equalSign); if (value is StringInterpolation) { for (var child in value.childEntities) { if (child is InterpolationExpression) { // This error is reported in OutlineBuilder.endLiteralString handleRecoverableError( messageInterpolationInUri, child.beginToken, child.endToken); break; } } } DottedName name = pop(); push(ast.configuration(ifKeyword, leftParen, name, equalSign, value, leftParen?.endGroup, libraryUri)); } @override void endConditionalUris(int count) { debugEvent("ConditionalUris"); push(popTypedList<Configuration>(count) ?? NullValue.ConditionalUris); } @override void endConstExpression(Token constKeyword) { assert(optional('const', constKeyword)); debugEvent("ConstExpression"); _handleInstanceCreation(constKeyword); } @override void endConstLiteral(Token token) { debugEvent("endConstLiteral"); } @override void endConstructorReference( Token start, Token periodBeforeName, Token endToken) { assert(optionalOrNull('.', periodBeforeName)); debugEvent("ConstructorReference"); SimpleIdentifier constructorName = pop(); TypeArgumentList typeArguments = pop(); Identifier typeNameIdentifier = pop(); push(ast.constructorName(ast.typeName(typeNameIdentifier, typeArguments), periodBeforeName, constructorName)); } @override void endDoWhileStatement( Token doKeyword, Token whileKeyword, Token semicolon) { assert(optional('do', doKeyword)); assert(optional('while', whileKeyword)); assert(optional(';', semicolon)); debugEvent("DoWhileStatement"); ParenthesizedExpression condition = pop(); Statement body = pop(); push(ast.doStatement( doKeyword, body, whileKeyword, condition.leftParenthesis, condition.expression, condition.rightParenthesis, semicolon)); } @override void endDoWhileStatementBody(Token token) { debugEvent("endDoWhileStatementBody"); } @override void endElseStatement(Token token) { debugEvent("endElseStatement"); } @override void endEnum(Token enumKeyword, Token leftBrace, int count) { assert(optional('enum', enumKeyword)); assert(optional('{', leftBrace)); debugEvent("Enum"); List<EnumConstantDeclaration> constants = popTypedList(count); SimpleIdentifier name = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, enumKeyword); declarations.add(ast.enumDeclaration(comment, metadata, enumKeyword, name, leftBrace, constants, leftBrace?.endGroup)); } void endExport(Token exportKeyword, Token semicolon) { assert(optional('export', exportKeyword)); assert(optional(';', semicolon)); debugEvent("Export"); List<Combinator> combinators = pop(); List<Configuration> configurations = pop(); StringLiteral uri = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, exportKeyword); directives.add(ast.exportDirective(comment, metadata, exportKeyword, uri, configurations, combinators, semicolon)); } @override void endExtensionConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("ExtensionConstructor"); // TODO(danrubel) Decide how to handle constructor declarations within // extensions. They are invalid and the parser has already reported an // error at this point. In the future, we should include them in order // to get navigation, search, etc. pop(); // body pop(); // initializers pop(); // separator pop(); // parameters pop(); // typeParameters pop(); // name pop(); // returnType pop(); // modifiers pop(); // metadata } @override void endExtensionDeclaration( Token extensionKeyword, Token onKeyword, Token token) { TypeAnnotation type = pop(); extensionDeclaration ..extendedType = type ..onKeyword = onKeyword; extensionDeclaration = null; } @override void endExtensionFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { assert(optional('factory', factoryKeyword)); assert(optional(';', endToken) || optional('}', endToken)); debugEvent("ExtensionFactoryMethod"); Object bodyObject = pop(); FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); Object constructorName = pop(); _Modifiers modifiers = pop(); List<Annotation> metadata = pop(); FunctionBody body; if (bodyObject is FunctionBody) { body = bodyObject; } else if (bodyObject is _RedirectingFactoryBody) { body = ast.emptyFunctionBody(endToken); } else { // Unhandled situation which should never happen. // Since this event handler is just a recovery attempt, // don't bother adding this declaration to the AST. return; } Comment comment = _findComment(metadata, beginToken); assert(parameters != null); // Constructor declarations within extensions are invalid and the parser // has already reported an error at this point, but we include them in as // a method declaration in order to get navigation, search, etc. SimpleIdentifier methodName; if (constructorName is SimpleIdentifier) { methodName = constructorName; } else if (constructorName is PrefixedIdentifier) { methodName = constructorName.identifier; } else { // Unsure what the method name should be in this situation. // Since this event handler is just a recovery attempt, // don't bother adding this declaration to the AST. return; } currentDeclarationMembers.add(ast.methodDeclaration( comment, metadata, modifiers?.externalKeyword, modifiers?.abstractKeyword ?? modifiers?.staticKeyword, null, // returnType null, // getOrSet null, // operatorKeyword methodName, typeParameters, parameters, body)); } @override void endExtensionFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { if (staticToken == null) { // TODO(danrubel) Decide how to handle instance field declarations // within extensions. They are invalid and the parser has already reported // an error at this point, but we include them in order to get navigation, // search, etc. } endClassFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } @override void endExtensionMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("ExtensionMethod"); endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } void endFieldInitializer(Token assignment, Token token) { assert(optional('=', assignment)); debugEvent("FieldInitializer"); Expression initializer = pop(); SimpleIdentifier name = pop(); push(_makeVariableDeclaration(name, assignment, initializer)); } @override void endForControlFlow(Token token) { debugEvent("endForControlFlow"); var entry = pop(); ForParts forLoopParts = pop(); Token leftParen = pop(); Token forToken = pop(); pushForControlFlowInfo(null, forToken, leftParen, forLoopParts, entry); } @override void endForIn(Token endToken) { debugEvent("ForInExpression"); Statement body = pop(); ForEachParts forLoopParts = pop(); Token leftParenthesis = pop(); Token forToken = pop(); Token awaitToken = pop(NullValue.AwaitToken); push(ast.forStatement( awaitKeyword: awaitToken, forKeyword: forToken, leftParenthesis: leftParenthesis, forLoopParts: forLoopParts, rightParenthesis: leftParenthesis.endGroup, body: body, )); } @override void endForInBody(Token token) { debugEvent("endForInBody"); } @override void endForInControlFlow(Token token) { debugEvent("endForInControlFlow"); var entry = pop(); ForEachParts forLoopParts = pop(); Token leftParenthesis = pop(); Token forToken = pop(); Token awaitToken = pop(NullValue.AwaitToken); pushForControlFlowInfo( awaitToken, forToken, leftParenthesis, forLoopParts, entry); } @override void endForInExpression(Token token) { debugEvent("ForInExpression"); } @override void endFormalParameter( Token thisKeyword, Token periodAfterThis, Token nameToken, Token initializerStart, Token initializerEnd, FormalParameterKind kind, MemberKind memberKind) { assert(optionalOrNull('this', thisKeyword)); assert(thisKeyword == null ? periodAfterThis == null : optional('.', periodAfterThis)); debugEvent("FormalParameter"); _ParameterDefaultValue defaultValue = pop(); SimpleIdentifier name = pop(); AstNode typeOrFunctionTypedParameter = pop(); _Modifiers modifiers = pop(); Token keyword = modifiers?.finalConstOrVarKeyword; Token covariantKeyword = modifiers?.covariantKeyword; Token requiredKeyword = modifiers?.requiredToken; if (!enableNonNullable) { reportNonNullableModifierError(requiredKeyword); } List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, thisKeyword ?? typeOrFunctionTypedParameter?.beginToken ?? nameToken); NormalFormalParameter node; if (typeOrFunctionTypedParameter is FunctionTypedFormalParameter) { // This is a temporary AST node that was constructed in // [endFunctionTypedFormalParameter]. We now deconstruct it and create // the final AST node. if (thisKeyword == null) { node = ast.functionTypedFormalParameter2( identifier: name, comment: comment, metadata: metadata, covariantKeyword: covariantKeyword, requiredKeyword: requiredKeyword, returnType: typeOrFunctionTypedParameter.returnType, typeParameters: typeOrFunctionTypedParameter.typeParameters, parameters: typeOrFunctionTypedParameter.parameters, question: typeOrFunctionTypedParameter.question); } else { node = ast.fieldFormalParameter2( identifier: name, comment: comment, metadata: metadata, covariantKeyword: covariantKeyword, requiredKeyword: requiredKeyword, type: typeOrFunctionTypedParameter.returnType, thisKeyword: thisKeyword, period: periodAfterThis, typeParameters: typeOrFunctionTypedParameter.typeParameters, parameters: typeOrFunctionTypedParameter.parameters); } } else { TypeAnnotation type = typeOrFunctionTypedParameter; if (thisKeyword == null) { node = ast.simpleFormalParameter2( comment: comment, metadata: metadata, covariantKeyword: covariantKeyword, requiredKeyword: requiredKeyword, keyword: keyword, type: type, identifier: name); } else { node = ast.fieldFormalParameter2( comment: comment, metadata: metadata, covariantKeyword: covariantKeyword, requiredKeyword: requiredKeyword, keyword: keyword, type: type, thisKeyword: thisKeyword, period: thisKeyword.next, identifier: name); } } ParameterKind analyzerKind = _toAnalyzerParameterKind(kind, requiredKeyword); FormalParameter parameter = node; if (analyzerKind != ParameterKind.REQUIRED) { parameter = ast.defaultFormalParameter( node, analyzerKind, defaultValue?.separator, defaultValue?.value); } else if (defaultValue != null) { // An error is reported if a required parameter has a default value. // Record it as named parameter for recovery. parameter = ast.defaultFormalParameter(node, ParameterKind.NAMED, defaultValue.separator, defaultValue.value); } localDeclarations[nameToken.offset] = parameter; push(parameter); } @override void endFormalParameterDefaultValueExpression() { debugEvent("FormalParameterDefaultValueExpression"); } void endFormalParameters( int count, Token leftParen, Token rightParen, MemberKind kind) { assert(optional('(', leftParen)); assert(optional(')', rightParen)); debugEvent("FormalParameters"); List<Object> rawParameters = popTypedList(count) ?? const <Object>[]; List<FormalParameter> parameters = <FormalParameter>[]; Token leftDelimiter; Token rightDelimiter; for (Object raw in rawParameters) { if (raw is _OptionalFormalParameters) { parameters.addAll(raw.parameters ?? const <FormalParameter>[]); leftDelimiter = raw.leftDelimiter; rightDelimiter = raw.rightDelimiter; } else { parameters.add(raw as FormalParameter); } } push(ast.formalParameterList( leftParen, parameters, leftDelimiter, rightDelimiter, rightParen)); } @override void endForStatement(Token endToken) { debugEvent("ForStatement"); Statement body = pop(); ForParts forLoopParts = pop(); Token leftParen = pop(); Token forToken = pop(); push(ast.forStatement( forKeyword: forToken, leftParenthesis: leftParen, forLoopParts: forLoopParts, rightParenthesis: leftParen.endGroup, body: body, )); } @override void endForStatementBody(Token token) { debugEvent("endForStatementBody"); } @override void endFunctionExpression(Token beginToken, Token token) { // TODO(paulberry): set up scopes properly to resolve parameters and type // variables. Note that this is tricky due to the handling of initializers // in constructors, so the logic should be shared with BodyBuilder as much // as possible. debugEvent("FunctionExpression"); FunctionBody body = pop(); FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); push(ast.functionExpression(typeParameters, parameters, body)); } @override void endFunctionName(Token beginToken, Token token) { debugEvent("FunctionName"); } @override void endFunctionType(Token functionToken, Token questionMark) { assert(optional('Function', functionToken)); debugEvent("FunctionType"); if (!enableNonNullable) { reportErrorIfNullableType(questionMark); } FormalParameterList parameters = pop(); TypeAnnotation returnType = pop(); TypeParameterList typeParameters = pop(); push(ast.genericFunctionType( returnType, functionToken, typeParameters, parameters, question: questionMark)); } @override void endFunctionTypeAlias( Token typedefKeyword, Token equals, Token semicolon) { assert(optional('typedef', typedefKeyword)); assert(optionalOrNull('=', equals)); assert(optional(';', semicolon)); debugEvent("FunctionTypeAlias"); if (equals == null) { FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); SimpleIdentifier name = pop(); TypeAnnotation returnType = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, typedefKeyword); declarations.add(ast.functionTypeAlias(comment, metadata, typedefKeyword, returnType, name, typeParameters, parameters, semicolon)); } else { TypeAnnotation type = pop(); TypeParameterList templateParameters = pop(); SimpleIdentifier name = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, typedefKeyword); if (type is! GenericFunctionType) { // This error is also reported in the OutlineBuilder. handleRecoverableError(messageTypedefNotFunction, equals, equals); type = null; } declarations.add(ast.genericTypeAlias( comment, metadata, typedefKeyword, name, templateParameters, equals, type as GenericFunctionType, semicolon)); } } @override void endFunctionTypedFormalParameter(Token nameToken, Token question) { debugEvent("FunctionTypedFormalParameter"); FormalParameterList formalParameters = pop(); TypeAnnotation returnType = pop(); TypeParameterList typeParameters = pop(); // Create a temporary formal parameter that will be dissected later in // [endFormalParameter]. push(ast.functionTypedFormalParameter2( identifier: null, returnType: returnType, typeParameters: typeParameters, parameters: formalParameters, question: question)); } @override void endHide(Token hideKeyword) { assert(optional('hide', hideKeyword)); debugEvent("Hide"); List<SimpleIdentifier> hiddenNames = pop(); push(ast.hideCombinator(hideKeyword, hiddenNames)); } @override void endIfControlFlow(Token token) { CollectionElement thenElement = pop(); ParenthesizedExpression condition = pop(); Token ifToken = pop(); pushIfControlFlowInfo(ifToken, condition, thenElement, null, null); } @override void endIfElseControlFlow(Token token) { CollectionElement elseElement = pop(); Token elseToken = pop(); CollectionElement thenElement = pop(); ParenthesizedExpression condition = pop(); Token ifToken = pop(); pushIfControlFlowInfo( ifToken, condition, thenElement, elseToken, elseElement); } void endIfStatement(Token ifToken, Token elseToken) { assert(optional('if', ifToken)); assert(optionalOrNull('else', elseToken)); Statement elsePart = popIfNotNull(elseToken); Statement thenPart = pop(); ParenthesizedExpression condition = pop(); push(ast.ifStatement( ifToken, condition.leftParenthesis, condition.expression, condition.rightParenthesis, thenPart, elseToken, elsePart)); } @override void endImplicitCreationExpression(Token token) { debugEvent("ImplicitCreationExpression"); _handleInstanceCreation(null); } @override void endImport(Token importKeyword, Token semicolon) { assert(optional('import', importKeyword)); assert(optionalOrNull(';', semicolon)); debugEvent("Import"); List<Combinator> combinators = pop(); Token deferredKeyword = pop(NullValue.Deferred); Token asKeyword = pop(NullValue.As); SimpleIdentifier prefix = pop(NullValue.Prefix); List<Configuration> configurations = pop(); StringLiteral uri = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, importKeyword); directives.add(ast.importDirective( comment, metadata, importKeyword, uri, configurations, deferredKeyword, asKeyword, prefix, combinators, semicolon)); } void endInitializedIdentifier(Token nameToken) { debugEvent("InitializedIdentifier"); AstNode node = pop(); VariableDeclaration variable; // TODO(paulberry): This seems kludgy. It would be preferable if we // could respond to a "handleNoVariableInitializer" event by converting a // SimpleIdentifier into a VariableDeclaration, and then when this code was // reached, node would always be a VariableDeclaration. if (node is VariableDeclaration) { variable = node; } else if (node is SimpleIdentifier) { variable = _makeVariableDeclaration(node, null, null); } else { unhandled("${node.runtimeType}", "identifier", nameToken.charOffset, uri); } push(variable); } void endInitializers(int count, Token colon, Token endToken) { assert(optional(':', colon)); debugEvent("Initializers"); List<Object> initializerObjects = popTypedList(count) ?? const []; if (!isFullAst) return; push(colon); var initializers = <ConstructorInitializer>[]; for (Object initializerObject in initializerObjects) { ConstructorInitializer initializer = buildInitializer(initializerObject); if (initializer != null) { initializers.add(initializer); } else { handleRecoverableError( messageInvalidInitializer, initializerObject is AstNode ? initializerObject.beginToken : colon, initializerObject is AstNode ? initializerObject.endToken : colon); } } push(initializers); } void endInvalidAwaitExpression( Token awaitKeyword, Token endToken, MessageCode errorCode) { debugEvent("InvalidAwaitExpression"); endAwaitExpression(awaitKeyword, endToken); } @override void endLabeledStatement(int labelCount) { debugEvent("LabeledStatement"); Statement statement = pop(); List<Label> labels = popTypedList(labelCount); push(ast.labeledStatement(labels, statement)); } @override void endLibraryName(Token libraryKeyword, Token semicolon) { assert(optional('library', libraryKeyword)); assert(optional(';', semicolon)); debugEvent("LibraryName"); List<SimpleIdentifier> libraryName = pop(); var name = ast.libraryIdentifier(libraryName); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, libraryKeyword); directives.add(ast.libraryDirective( comment, metadata, libraryKeyword, name, semicolon)); } @override void endLiteralString(int interpolationCount, Token endToken) { debugEvent("endLiteralString"); if (interpolationCount == 0) { Token token = pop(); String value = unescapeString(token.lexeme, token, this); push(ast.simpleStringLiteral(token, value)); } else { List<Object> parts = popTypedList(1 + interpolationCount * 2); Token first = parts.first; Token last = parts.last; Quote quote = analyzeQuote(first.lexeme); List<InterpolationElement> elements = <InterpolationElement>[]; elements.add(ast.interpolationString( first, unescapeFirstStringPart(first.lexeme, quote, first, this))); for (int i = 1; i < parts.length - 1; i++) { var part = parts[i]; if (part is Token) { elements.add(ast.interpolationString( part, unescape(part.lexeme, quote, part, this))); } else if (part is InterpolationExpression) { elements.add(part); } else { unhandled("${part.runtimeType}", "string interpolation", first.charOffset, uri); } } elements.add(ast.interpolationString( last, unescapeLastStringPart( last.lexeme, quote, last, last.isSynthetic, this))); push(ast.stringInterpolation(elements)); } } void endLiteralSymbol(Token hashToken, int tokenCount) { assert(optional('#', hashToken)); debugEvent("LiteralSymbol"); List<Token> components = popTypedList(tokenCount); push(ast.symbolLiteral(hashToken, components)); } @override void endLocalFunctionDeclaration(Token token) { debugEvent("LocalFunctionDeclaration"); FunctionBody body = pop(); if (isFullAst) { pop(); // constructor initializers pop(); // separator before constructor initializers } FormalParameterList parameters = pop(); checkFieldFormalParameters(parameters); SimpleIdentifier name = pop(); TypeAnnotation returnType = pop(); TypeParameterList typeParameters = pop(); List<Annotation> metadata = pop(NullValue.Metadata); FunctionExpression functionExpression = ast.functionExpression(typeParameters, parameters, body); var functionDeclaration = ast.functionDeclaration( null, metadata, null, returnType, null, name, functionExpression); localDeclarations[name.offset] = functionDeclaration; push(ast.functionDeclarationStatement(functionDeclaration)); } @override void endMember() { debugEvent("Member"); } @override void endMetadata(Token atSign, Token periodBeforeName, Token endToken) { assert(optional('@', atSign)); assert(optionalOrNull('.', periodBeforeName)); debugEvent("Metadata"); MethodInvocation invocation = pop(); SimpleIdentifier constructorName = periodBeforeName != null ? pop() : null; pop(); // Type arguments, not allowed. Identifier name = pop(); push(ast.annotation(atSign, name, periodBeforeName, constructorName, invocation?.argumentList)); } @override void endMetadataStar(int count) { debugEvent("MetadataStar"); push(popTypedList<Annotation>(count) ?? NullValue.Metadata); } @override void endMixinConstructor(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("MixinConstructor"); // TODO(danrubel) Decide how to handle constructor declarations within // mixins. They are invalid, but we include them in order to get navigation, // search, etc. Currently the error is reported by multiple listeners, // but should be moved into the parser. endClassConstructor( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endMixinDeclaration(Token mixinKeyword, Token endToken) { debugEvent("MixinDeclaration"); mixinDeclaration = null; } @override void endMixinFactoryMethod( Token beginToken, Token factoryKeyword, Token endToken) { debugEvent("MixinFactoryMethod"); endClassFactoryMethod(beginToken, factoryKeyword, endToken); } @override void endMixinFields(Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token endToken) { endClassFields(staticToken, covariantToken, lateToken, varFinalOrConst, count, beginToken, endToken); } @override void endMixinMethod(Token getOrSet, Token beginToken, Token beginParam, Token beginInitializers, Token endToken) { debugEvent("MixinMethod"); endClassMethod( getOrSet, beginToken, beginParam, beginInitializers, endToken); } @override void endNamedFunctionExpression(Token endToken) { debugEvent("NamedFunctionExpression"); FunctionBody body = pop(); if (isFullAst) { pop(); // constructor initializers pop(); // separator before constructor initializers } FormalParameterList parameters = pop(); pop(); // name pop(); // returnType TypeParameterList typeParameters = pop(); push(ast.functionExpression(typeParameters, parameters, body)); } @override void endNamedMixinApplication(Token beginToken, Token classKeyword, Token equalsToken, Token implementsKeyword, Token semicolon) { assert(optional('class', classKeyword)); assert(optionalOrNull('=', equalsToken)); assert(optionalOrNull('implements', implementsKeyword)); assert(optional(';', semicolon)); debugEvent("NamedMixinApplication"); ImplementsClause implementsClause; if (implementsKeyword != null) { List<TypeName> interfaces = pop(); implementsClause = ast.implementsClause(implementsKeyword, interfaces); } WithClause withClause = pop(NullValue.WithClause); TypeName superclass = pop(); _Modifiers modifiers = pop(); TypeParameterList typeParameters = pop(); SimpleIdentifier name = pop(); Token abstractKeyword = modifiers?.abstractKeyword; List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); declarations.add(ast.classTypeAlias( comment, metadata, classKeyword, name, typeParameters, equalsToken, abstractKeyword, superclass, withClause, implementsClause, semicolon)); } @override void endNewExpression(Token newKeyword) { assert(optional('new', newKeyword)); debugEvent("NewExpression"); _handleInstanceCreation(newKeyword); } @override void endOptionalFormalParameters( int count, Token leftDelimeter, Token rightDelimeter) { assert((optional('[', leftDelimeter) && optional(']', rightDelimeter)) || (optional('{', leftDelimeter) && optional('}', rightDelimeter))); debugEvent("OptionalFormalParameters"); push(new _OptionalFormalParameters( popTypedList(count), leftDelimeter, rightDelimeter)); } @override void endPart(Token partKeyword, Token semicolon) { assert(optional('part', partKeyword)); assert(optional(';', semicolon)); debugEvent("Part"); StringLiteral uri = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, partKeyword); directives .add(ast.partDirective(comment, metadata, partKeyword, uri, semicolon)); } @override void endPartOf( Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) { assert(optional('part', partKeyword)); assert(optional('of', ofKeyword)); assert(optional(';', semicolon)); debugEvent("PartOf"); var libraryNameOrUri = pop(); LibraryIdentifier name; StringLiteral uri; if (libraryNameOrUri is StringLiteral) { uri = libraryNameOrUri; } else { name = ast.libraryIdentifier(libraryNameOrUri as List<SimpleIdentifier>); } List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, partKeyword); directives.add(ast.partOfDirective( comment, metadata, partKeyword, ofKeyword, uri, name, semicolon)); } @override void endRedirectingFactoryBody(Token equalToken, Token endToken) { assert(optional('=', equalToken)); debugEvent("RedirectingFactoryBody"); ConstructorName constructorName = pop(); Token starToken = pop(); Token asyncToken = pop(); push(new _RedirectingFactoryBody( asyncToken, starToken, equalToken, constructorName)); } @override void endRethrowStatement(Token rethrowToken, Token semicolon) { assert(optional('rethrow', rethrowToken)); assert(optional(';', semicolon)); debugEvent("RethrowStatement"); RethrowExpression expression = ast.rethrowExpression(rethrowToken); // TODO(scheglov) According to the specification, 'rethrow' is a statement. push(ast.expressionStatement(expression, semicolon)); } void endReturnStatement( bool hasExpression, Token returnKeyword, Token semicolon) { assert(optional('return', returnKeyword)); assert(optional(';', semicolon)); debugEvent("ReturnStatement"); Expression expression = hasExpression ? pop() : null; push(ast.returnStatement(returnKeyword, expression, semicolon)); } @override void endShow(Token showKeyword) { assert(optional('show', showKeyword)); debugEvent("Show"); List<SimpleIdentifier> shownNames = pop(); push(ast.showCombinator(showKeyword, shownNames)); } @override void endSwitchBlock(int caseCount, Token leftBracket, Token rightBracket) { assert(optional('{', leftBracket)); assert(optional('}', rightBracket)); debugEvent("SwitchBlock"); List<List<SwitchMember>> membersList = popTypedList(caseCount); List<SwitchMember> members = membersList?.expand((members) => members)?.toList() ?? <SwitchMember>[]; Set<String> labels = new Set<String>(); for (SwitchMember member in members) { for (Label label in member.labels) { if (!labels.add(label.label.name)) { handleRecoverableError( templateDuplicateLabelInSwitchStatement .withArguments(label.label.name), label.beginToken, label.beginToken); } } } push(leftBracket); push(members); push(rightBracket); } @override void endSwitchCase( int labelCount, int expressionCount, Token defaultKeyword, Token colonAfterDefault, int statementCount, Token firstToken, Token endToken) { assert(optionalOrNull('default', defaultKeyword)); assert(defaultKeyword == null ? colonAfterDefault == null : optional(':', colonAfterDefault)); debugEvent("SwitchCase"); List<Statement> statements = popTypedList(statementCount); List<SwitchMember> members; if (labelCount == 0 && defaultKeyword == null) { // Common situation: case with no default and no labels. members = popTypedList<SwitchMember>(expressionCount) ?? []; } else { // Labels and case statements may be intertwined if (defaultKeyword != null) { SwitchDefault member = ast.switchDefault( <Label>[], defaultKeyword, colonAfterDefault, <Statement>[]); while (peek() is Label) { member.labels.insert(0, pop()); --labelCount; } members = new List<SwitchMember>(expressionCount + 1); members[expressionCount] = member; } else { members = new List<SwitchMember>(expressionCount); } for (int index = expressionCount - 1; index >= 0; --index) { SwitchMember member = pop(); while (peek() is Label) { member.labels.insert(0, pop()); --labelCount; } members[index] = member; } assert(labelCount == 0); } if (members.isNotEmpty) { members.last.statements.addAll(statements); } push(members); } @override void endSwitchStatement(Token switchKeyword, Token endToken) { assert(optional('switch', switchKeyword)); debugEvent("SwitchStatement"); Token rightBracket = pop(); List<SwitchMember> members = pop(); Token leftBracket = pop(); ParenthesizedExpression expression = pop(); push(ast.switchStatement( switchKeyword, expression.leftParenthesis, expression.expression, expression.rightParenthesis, leftBracket, members, rightBracket)); } @override void endThenStatement(Token token) { debugEvent("endThenStatement"); } @override void endTopLevelDeclaration(Token token) { debugEvent("TopLevelDeclaration"); } void endTopLevelFields( Token staticToken, Token covariantToken, Token lateToken, Token varFinalOrConst, int count, Token beginToken, Token semicolon) { assert(optional(';', semicolon)); debugEvent("TopLevelFields"); List<VariableDeclaration> variables = popTypedList(count); TypeAnnotation type = pop(); var variableList = ast.variableDeclarationList2( lateKeyword: lateToken, keyword: varFinalOrConst, type: type, variables: variables, ); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); declarations.add(ast.topLevelVariableDeclaration( comment, metadata, variableList, semicolon)); } void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) { // TODO(paulberry): set up scopes properly to resolve parameters and type // variables. assert(getOrSet == null || optional('get', getOrSet) || optional('set', getOrSet)); debugEvent("TopLevelMethod"); FunctionBody body = pop(); FormalParameterList parameters = pop(); TypeParameterList typeParameters = pop(); SimpleIdentifier name = pop(); TypeAnnotation returnType = pop(); _Modifiers modifiers = pop(); Token externalKeyword = modifiers?.externalKeyword; List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, beginToken); declarations.add(ast.functionDeclaration( comment, metadata, externalKeyword, returnType, getOrSet, name, ast.functionExpression(typeParameters, parameters, body))); } void endTryStatement(int catchCount, Token tryKeyword, Token finallyKeyword) { assert(optional('try', tryKeyword)); assert(optionalOrNull('finally', finallyKeyword)); debugEvent("TryStatement"); Block finallyBlock = popIfNotNull(finallyKeyword); List<CatchClause> catchClauses = popTypedList(catchCount); Block body = pop(); push(ast.tryStatement( tryKeyword, body, catchClauses, finallyKeyword, finallyBlock)); } @override void endTypeArguments(int count, Token leftBracket, Token rightBracket) { assert(optional('<', leftBracket)); assert(optional('>', rightBracket)); debugEvent("TypeArguments"); List<TypeAnnotation> arguments = popTypedList(count); push(ast.typeArgumentList(leftBracket, arguments, rightBracket)); } @override void endTypeList(int count) { debugEvent("TypeList"); push(popTypedList<TypeName>(count) ?? NullValue.TypeList); } @override void endTypeVariable( Token token, int index, Token extendsOrSuper, Token variance) { debugEvent("TypeVariable"); assert(extendsOrSuper == null || optional('extends', extendsOrSuper) || optional('super', extendsOrSuper)); TypeAnnotation bound = pop(); // Peek to leave type parameters on top of stack. List<TypeParameter> typeParameters = peek(); typeParameters[index] ..extendsKeyword = extendsOrSuper ..bound = bound; } @override void endTypeVariables(Token beginToken, Token endToken) { assert(optional('<', beginToken)); assert(optional('>', endToken)); debugEvent("TypeVariables"); List<TypeParameter> typeParameters = pop(); push(ast.typeParameterList(beginToken, typeParameters, endToken)); } void endVariableInitializer(Token assignmentOperator) { assert(optionalOrNull('=', assignmentOperator)); debugEvent("VariableInitializer"); Expression initializer = pop(); SimpleIdentifier identifier = pop(); // TODO(ahe): Don't push initializers, instead install them. push(_makeVariableDeclaration(identifier, assignmentOperator, initializer)); } @override void endVariablesDeclaration(int count, Token semicolon) { assert(optionalOrNull(';', semicolon)); debugEvent("VariablesDeclaration"); List<VariableDeclaration> variables = popTypedList(count); _Modifiers modifiers = pop(NullValue.Modifiers); TypeAnnotation type = pop(); Token keyword = modifiers?.finalConstOrVarKeyword; List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, variables[0].beginToken ?? type?.beginToken ?? modifiers.beginToken); push(ast.variableDeclarationStatement( ast.variableDeclarationList2( comment: comment, metadata: metadata, lateKeyword: modifiers?.lateToken, keyword: keyword, type: type, variables: variables, ), semicolon)); } @override void endWhileStatement(Token whileKeyword, Token endToken) { assert(optional('while', whileKeyword)); debugEvent("WhileStatement"); Statement body = pop(); ParenthesizedExpression condition = pop(); push(ast.whileStatement(whileKeyword, condition.leftParenthesis, condition.expression, condition.rightParenthesis, body)); } @override void endWhileStatementBody(Token token) { debugEvent("endWhileStatementBody"); } @override void endYieldStatement(Token yieldToken, Token starToken, Token semicolon) { assert(optional('yield', yieldToken)); assert(optionalOrNull('*', starToken)); assert(optional(';', semicolon)); debugEvent("YieldStatement"); Expression expression = pop(); push(ast.yieldStatement(yieldToken, starToken, expression, semicolon)); } @override void exitLocalScope() {} @override AstNode finishFields() { debugEvent("finishFields"); if (classDeclaration != null) { return classDeclaration.members .removeAt(classDeclaration.members.length - 1); } else if (mixinDeclaration != null) { return mixinDeclaration.members .removeAt(mixinDeclaration.members.length - 1); } else { return declarations.removeLast(); } } void finishFunction(formals, AsyncMarker asyncModifier, FunctionBody body) { debugEvent("finishFunction"); Statement bodyStatement; if (body is EmptyFunctionBody) { bodyStatement = ast.emptyStatement(body.semicolon); } else if (body is NativeFunctionBody) { // TODO(danrubel): what do we need to do with NativeFunctionBody? } else if (body is ExpressionFunctionBody) { bodyStatement = ast.returnStatement(null, body.expression, null); } else { bodyStatement = (body as BlockFunctionBody).block; } // TODO(paulberry): what do we need to do with bodyStatement at this point? bodyStatement; // Suppress "unused local variable" hint } void handleAsOperator(Token asOperator) { assert(optional('as', asOperator)); debugEvent("AsOperator"); TypeAnnotation type = pop(); Expression expression = pop(); push(ast.asExpression(expression, asOperator, type)); } void handleAssignmentExpression(Token token) { assert(token.type.isAssignmentOperator); debugEvent("AssignmentExpression"); Expression rhs = pop(); Expression lhs = pop(); if (!lhs.isAssignable) { // TODO(danrubel): Update the BodyBuilder to report this error. handleRecoverableError( messageMissingAssignableSelector, lhs.beginToken, lhs.endToken); } push(ast.assignmentExpression(lhs, token, rhs)); if (!enableTripleShift && token.type == TokenType.GT_GT_GT_EQ) { handleRecoverableError( templateExperimentNotEnabled.withArguments(EnableString.triple_shift), token, token); } } void handleAsyncModifier(Token asyncToken, Token starToken) { assert(asyncToken == null || optional('async', asyncToken) || optional('sync', asyncToken)); assert(optionalOrNull('*', starToken)); debugEvent("AsyncModifier"); push(asyncToken ?? NullValue.FunctionBodyAsyncToken); push(starToken ?? NullValue.FunctionBodyStarToken); } @override void handleBreakStatement( bool hasTarget, Token breakKeyword, Token semicolon) { assert(optional('break', breakKeyword)); assert(optional(';', semicolon)); debugEvent("BreakStatement"); SimpleIdentifier label = hasTarget ? pop() : null; push(ast.breakStatement(breakKeyword, label, semicolon)); } @override void handleCaseMatch(Token caseKeyword, Token colon) { assert(optional('case', caseKeyword)); assert(optional(':', colon)); debugEvent("CaseMatch"); Expression expression = pop(); push(ast.switchCase( <Label>[], caseKeyword, expression, colon, <Statement>[])); } void handleCatchBlock(Token onKeyword, Token catchKeyword, Token comma) { assert(optionalOrNull('on', onKeyword)); assert(optionalOrNull('catch', catchKeyword)); assert(optionalOrNull(',', comma)); debugEvent("CatchBlock"); Block body = pop(); FormalParameterList catchParameterList = popIfNotNull(catchKeyword); TypeAnnotation type = popIfNotNull(onKeyword); SimpleIdentifier exception; SimpleIdentifier stackTrace; if (catchParameterList != null) { List<FormalParameter> catchParameters = catchParameterList.parameters; if (catchParameters.isNotEmpty) { exception = catchParameters[0].identifier; localDeclarations[exception.offset] = exception; } if (catchParameters.length > 1) { stackTrace = catchParameters[1].identifier; localDeclarations[stackTrace.offset] = stackTrace; } } push(ast.catchClause( onKeyword, type, catchKeyword, catchParameterList?.leftParenthesis, exception, comma, stackTrace, catchParameterList?.rightParenthesis, body)); } @override void handleClassExtends(Token extendsKeyword) { assert(extendsKeyword == null || extendsKeyword.isKeywordOrIdentifier); debugEvent("ClassExtends"); TypeName supertype = pop(); if (supertype != null) { push(ast.extendsClause(extendsKeyword, supertype)); } else { push(NullValue.ExtendsClause); } } @override void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) { assert(optional('class', classKeyword)); assert(optionalOrNull('native', nativeToken)); assert(classDeclaration == null && mixinDeclaration == null); debugEvent("ClassHeader"); NativeClause nativeClause; if (nativeToken != null) { nativeClause = ast.nativeClause(nativeToken, nativeName); } ImplementsClause implementsClause = pop(NullValue.IdentifierList); WithClause withClause = pop(NullValue.WithClause); ExtendsClause extendsClause = pop(NullValue.ExtendsClause); _Modifiers modifiers = pop(); TypeParameterList typeParameters = pop(); SimpleIdentifier name = pop(); Token abstractKeyword = modifiers?.abstractKeyword; List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, begin); // leftBracket, members, and rightBracket // are set in [endClassOrMixinBody]. classDeclaration = ast.classDeclaration( comment, metadata, abstractKeyword, classKeyword, name, typeParameters, extendsClause, withClause, implementsClause, null, // leftBracket <ClassMember>[], null, // rightBracket ); classDeclaration.nativeClause = nativeClause; declarations.add(classDeclaration); } @override void handleClassNoWithClause() { push(NullValue.WithClause); } @override void handleClassOrMixinImplements( Token implementsKeyword, int interfacesCount) { assert(optionalOrNull('implements', implementsKeyword)); debugEvent("ClassImplements"); if (implementsKeyword != null) { List<TypeName> interfaces = popTypedList(interfacesCount); push(ast.implementsClause(implementsKeyword, interfaces)); } else { push(NullValue.IdentifierList); } } @override void handleClassWithClause(Token withKeyword) { assert(optional('with', withKeyword)); List<TypeName> mixinTypes = pop(); push(ast.withClause(withKeyword, mixinTypes)); } @override void handleCommentReference( Token newKeyword, Token prefix, Token period, Token token) { Identifier identifier = ast.simpleIdentifier(token); if (prefix != null) { identifier = ast.prefixedIdentifier( ast.simpleIdentifier(prefix), period, identifier); } push(ast.commentReference(newKeyword, identifier)); } @override void handleCommentReferenceText(String referenceSource, int referenceOffset) { push(referenceSource); push(referenceOffset); } @override void handleContinueStatement( bool hasTarget, Token continueKeyword, Token semicolon) { assert(optional('continue', continueKeyword)); assert(optional(';', semicolon)); debugEvent("ContinueStatement"); SimpleIdentifier label = hasTarget ? pop() : null; push(ast.continueStatement(continueKeyword, label, semicolon)); } @override void handleDottedName(int count, Token firstIdentifier) { assert(firstIdentifier.isIdentifier); debugEvent("DottedName"); List<SimpleIdentifier> components = popTypedList(count); push(ast.dottedName(components)); } @override void handleElseControlFlow(Token elseToken) { push(elseToken); } @override void handleEmptyFunctionBody(Token semicolon) { assert(optional(';', semicolon)); debugEvent("EmptyFunctionBody"); // TODO(scheglov) Change the parser to not produce these modifiers. pop(); // star pop(); // async push(ast.emptyFunctionBody(semicolon)); } @override void handleEmptyStatement(Token semicolon) { assert(optional(';', semicolon)); debugEvent("EmptyStatement"); push(ast.emptyStatement(semicolon)); } @override void handleErrorToken(ErrorToken token) { translateErrorToken(token, errorReporter.reportScannerError); } void handleExpressionFunctionBody(Token arrowToken, Token semicolon) { assert(optional('=>', arrowToken) || optional('=', arrowToken)); assert(optionalOrNull(';', semicolon)); debugEvent("ExpressionFunctionBody"); Expression expression = pop(); pop(); // star (*) Token asyncKeyword = pop(); if (parseFunctionBodies) { push(ast.expressionFunctionBody( asyncKeyword, arrowToken, expression, semicolon)); } else { push(ast.emptyFunctionBody(semicolon)); } } void handleExpressionStatement(Token semicolon) { assert(optional(';', semicolon)); debugEvent("ExpressionStatement"); Expression expression = pop(); reportErrorIfSuper(expression); if (expression is SimpleIdentifier && expression.token?.keyword?.isBuiltInOrPseudo == false) { // This error is also reported by the body builder. handleRecoverableError( messageExpectedStatement, expression.beginToken, expression.endToken); } if (expression is AssignmentExpression) { if (!expression.leftHandSide.isAssignable) { // This error is also reported by the body builder. handleRecoverableError( messageIllegalAssignmentToNonAssignable, expression.leftHandSide.beginToken, expression.leftHandSide.endToken); } } push(ast.expressionStatement(expression, semicolon)); } @override void handleFinallyBlock(Token finallyKeyword) { debugEvent("FinallyBlock"); // The finally block is popped in "endTryStatement". } @override void handleForInitializerEmptyStatement(Token token) { debugEvent("ForInitializerEmptyStatement"); push(NullValue.Expression); } @override void handleForInitializerExpressionStatement(Token token) { debugEvent("ForInitializerExpressionStatement"); } @override void handleForInitializerLocalVariableDeclaration(Token token) { debugEvent("ForInitializerLocalVariableDeclaration"); } @override void handleForInLoopParts(Token awaitToken, Token forToken, Token leftParenthesis, Token inKeyword) { assert(optionalOrNull('await', awaitToken)); assert(optional('for', forToken)); assert(optional('(', leftParenthesis)); assert(optional('in', inKeyword) || optional(':', inKeyword)); Expression iterator = pop(); Object variableOrDeclaration = pop(); ForEachParts forLoopParts; if (variableOrDeclaration is VariableDeclarationStatement) { VariableDeclarationList variableList = variableOrDeclaration.variables; forLoopParts = ast.forEachPartsWithDeclaration( loopVariable: ast.declaredIdentifier( variableList.documentationComment, variableList.metadata, variableList.keyword, variableList.type, variableList.variables.first.name), inKeyword: inKeyword, iterable: iterator, ); } else { if (variableOrDeclaration is! SimpleIdentifier) { // Parser has already reported the error. if (!leftParenthesis.next.isIdentifier) { parser.rewriter.insertSyntheticIdentifier(leftParenthesis); } variableOrDeclaration = ast.simpleIdentifier(leftParenthesis.next); } forLoopParts = ast.forEachPartsWithIdentifier( identifier: variableOrDeclaration, inKeyword: inKeyword, iterable: iterator, ); } push(awaitToken ?? NullValue.AwaitToken); push(forToken); push(leftParenthesis); push(forLoopParts); } @override void handleForLoopParts(Token forKeyword, Token leftParen, Token leftSeparator, int updateExpressionCount) { assert(optional('for', forKeyword)); assert(optional('(', leftParen)); assert(optional(';', leftSeparator)); assert(updateExpressionCount >= 0); List<Expression> updates = popTypedList(updateExpressionCount); Statement conditionStatement = pop(); Object initializerPart = pop(); Expression condition; Token rightSeparator; if (conditionStatement is ExpressionStatement) { condition = conditionStatement.expression; rightSeparator = conditionStatement.semicolon; } else { rightSeparator = (conditionStatement as EmptyStatement).semicolon; } ForParts forLoopParts; if (initializerPart is VariableDeclarationStatement) { forLoopParts = ast.forPartsWithDeclarations( variables: initializerPart.variables, leftSeparator: leftSeparator, condition: condition, rightSeparator: rightSeparator, updaters: updates, ); } else { forLoopParts = ast.forPartsWithExpression( initialization: initializerPart as Expression, leftSeparator: leftSeparator, condition: condition, rightSeparator: rightSeparator, updaters: updates, ); } push(forKeyword); push(leftParen); push(forLoopParts); } void handleFormalParameterWithoutValue(Token token) { debugEvent("FormalParameterWithoutValue"); push(NullValue.ParameterDefaultValue); } void handleIdentifier(Token token, IdentifierContext context) { assert(token.isKeywordOrIdentifier); debugEvent("handleIdentifier"); if (context.inSymbol) { push(token); return; } SimpleIdentifier identifier = ast.simpleIdentifier(token, isDeclaration: context.inDeclaration); if (context.inLibraryOrPartOfDeclaration) { if (!context.isContinuation) { push([identifier]); } else { push(identifier); } } else if (context == IdentifierContext.enumValueDeclaration) { List<Annotation> metadata = pop(); Comment comment = _findComment(null, token); push(ast.enumConstantDeclaration(comment, metadata, identifier)); } else { push(identifier); } } @override void handleIdentifierList(int count) { debugEvent("IdentifierList"); push(popTypedList<SimpleIdentifier>(count) ?? NullValue.IdentifierList); } @override void handleImportPrefix(Token deferredKeyword, Token asKeyword) { assert(optionalOrNull('deferred', deferredKeyword)); assert(optionalOrNull('as', asKeyword)); debugEvent("ImportPrefix"); if (asKeyword == null) { // If asKeyword is null, then no prefix has been pushed on the stack. // Push a placeholder indicating that there is no prefix. push(NullValue.Prefix); push(NullValue.As); } else { push(asKeyword); } push(deferredKeyword ?? NullValue.Deferred); } void handleIndexedExpression(Token leftBracket, Token rightBracket) { assert(optional('[', leftBracket) || (enableNonNullable && optional('?.[', leftBracket))); assert(optional(']', rightBracket)); debugEvent("IndexedExpression"); Expression index = pop(); Expression target = pop(); if (target == null) { CascadeExpression receiver = pop(); Token token = peek(); push(receiver); IndexExpression expression = ast.indexExpressionForCascade( token, leftBracket, index, rightBracket); assert(expression.isCascaded); push(expression); } else { push(ast.indexExpressionForTarget( target, leftBracket, index, rightBracket)); } } @override void handleInterpolationExpression(Token leftBracket, Token rightBracket) { Expression expression = pop(); push(ast.interpolationExpression(leftBracket, expression, rightBracket)); } @override void handleInvalidExpression(Token token) { debugEvent("InvalidExpression"); } @override void handleInvalidFunctionBody(Token leftBracket) { assert(optional('{', leftBracket)); assert(optional('}', leftBracket.endGroup)); debugEvent("InvalidFunctionBody"); Block block = ast.block(leftBracket, [], leftBracket.endGroup); Token star = pop(); Token asyncKeyword = pop(); push(ast.blockFunctionBody(asyncKeyword, star, block)); } @override void handleInvalidMember(Token endToken) { debugEvent("InvalidMember"); pop(); // metadata star } @override void handleInvalidOperatorName(Token operatorKeyword, Token token) { assert(optional('operator', operatorKeyword)); debugEvent("InvalidOperatorName"); push(new _OperatorName( operatorKeyword, ast.simpleIdentifier(token, isDeclaration: true))); } void handleInvalidTopLevelBlock(Token token) { // TODO(danrubel): Consider improved recovery by adding this block // as part of a synthetic top level function. pop(); // block } @override void handleInvalidTopLevelDeclaration(Token endToken) { debugEvent("InvalidTopLevelDeclaration"); pop(); // metadata star // TODO(danrubel): consider creating a AST node // representing the invalid declaration to better support code completion, // quick fixes, etc, rather than discarding the metadata and token } @override void handleInvalidTypeArguments(Token token) { TypeArgumentList invalidTypeArgs = pop(); var node = pop(); if (node is ConstructorName) { push(new _ConstructorNameWithInvalidTypeArgs(node, invalidTypeArgs)); } else { throw new UnimplementedError( 'node is an instance of ${node.runtimeType} in handleInvalidTypeArguments'); } } void handleIsOperator(Token isOperator, Token not) { assert(optional('is', isOperator)); assert(optionalOrNull('!', not)); debugEvent("IsOperator"); TypeAnnotation type = pop(); Expression expression = pop(); push(ast.isExpression(expression, isOperator, not, type)); } @override void handleLabel(Token colon) { assert(optionalOrNull(':', colon)); debugEvent("Label"); SimpleIdentifier name = pop(); push(ast.label(name, colon)); } void handleLiteralBool(Token token) { bool value = identical(token.stringValue, "true"); assert(value || identical(token.stringValue, "false")); debugEvent("LiteralBool"); push(ast.booleanLiteral(token, value)); } void handleLiteralDouble(Token token) { assert(token.type == TokenType.DOUBLE); debugEvent("LiteralDouble"); push(ast.doubleLiteral(token, double.parse(token.lexeme))); } void handleLiteralInt(Token token) { assert(identical(token.kind, INT_TOKEN) || identical(token.kind, HEXADECIMAL_TOKEN)); debugEvent("LiteralInt"); push(ast.integerLiteral(token, int.tryParse(token.lexeme))); } void handleLiteralList( int count, Token leftBracket, Token constKeyword, Token rightBracket) { assert(optional('[', leftBracket)); assert(optionalOrNull('const', constKeyword)); assert(optional(']', rightBracket)); debugEvent("LiteralList"); if (enableControlFlowCollections || enableSpreadCollections) { List<CollectionElement> elements = popCollectionElements(count); TypeArgumentList typeArguments = pop(); // TODO(danrubel): Remove this and _InvalidCollectionElement // once control flow and spread collection support is enabled by default elements.removeWhere((e) => e == _invalidCollectionElement); push(ast.listLiteral( constKeyword, typeArguments, leftBracket, elements, rightBracket)); } else { List<dynamic> elements = popTypedList(count); TypeArgumentList typeArguments = pop(); List<Expression> expressions = <Expression>[]; if (elements != null) { for (var elem in elements) { if (elem is Expression) { expressions.add(elem); } } } push(ast.listLiteral( constKeyword, typeArguments, leftBracket, expressions, rightBracket)); } } void handleLiteralMapEntry(Token colon, Token endToken) { assert(optional(':', colon)); debugEvent("LiteralMapEntry"); Expression value = pop(); Expression key = pop(); push(ast.mapLiteralEntry(key, colon, value)); } void handleLiteralNull(Token token) { assert(optional('null', token)); debugEvent("LiteralNull"); push(ast.nullLiteral(token)); } @override void handleLiteralSetOrMap( int count, Token leftBrace, Token constKeyword, Token rightBrace, // TODO(danrubel): hasSetEntry parameter exists for replicating existing // behavior and will be removed once unified collection has been enabled bool hasSetEntry, ) { if (enableControlFlowCollections || enableSpreadCollections) { List<CollectionElement> elements = popCollectionElements(count); // TODO(danrubel): Remove this and _InvalidCollectionElement // once control flow and spread collection support is enabled by default elements.removeWhere((e) => e == _invalidCollectionElement); TypeArgumentList typeArguments = pop(); push(ast.setOrMapLiteral( constKeyword: constKeyword, typeArguments: typeArguments, leftBracket: leftBrace, elements: elements, rightBracket: rightBrace, )); } else { List<dynamic> elements = popTypedList(count); TypeArgumentList typeArguments = pop(); // Replicate existing behavior that has been removed from the parser. // This will be removed once control flow collections // and spread collections are enabled by default. // Determine if this is a set or map based on type args and content final typeArgCount = typeArguments?.arguments?.length; bool isSet = typeArgCount == 1 ? true : typeArgCount != null ? false : null; isSet ??= hasSetEntry; // Build the set or map if (isSet) { final setEntries = <Expression>[]; if (elements != null) { for (var elem in elements) { if (elem is MapLiteralEntry) { setEntries.add(elem.key); handleRecoverableError( templateUnexpectedToken.withArguments(elem.separator), elem.separator, elem.separator); } else if (elem is Expression) { setEntries.add(elem); } } } push(ast.setOrMapLiteral( constKeyword: constKeyword, typeArguments: typeArguments, leftBracket: leftBrace, elements: setEntries, rightBracket: rightBrace, )); } else { final mapEntries = <MapLiteralEntry>[]; if (elements != null) { for (var elem in elements) { if (elem is MapLiteralEntry) { mapEntries.add(elem); } else if (elem is Expression) { Token next = elem.endToken.next; int offset = next.offset; handleRecoverableError( templateExpectedButGot.withArguments(':'), next, next); handleRecoverableError( templateExpectedIdentifier.withArguments(next), next, next); Token separator = SyntheticToken(TokenType.COLON, offset); Expression value = ast.simpleIdentifier( SyntheticStringToken(TokenType.IDENTIFIER, '', offset)); mapEntries.add(ast.mapLiteralEntry(elem, separator, value)); } } } push(ast.setOrMapLiteral( constKeyword: constKeyword, typeArguments: typeArguments, leftBracket: leftBrace, elements: mapEntries, rightBracket: rightBrace, )); } } } @override void handleMixinHeader(Token mixinKeyword) { assert(optional('mixin', mixinKeyword)); assert(classDeclaration == null && mixinDeclaration == null && extensionDeclaration == null); debugEvent("MixinHeader"); ImplementsClause implementsClause = pop(NullValue.IdentifierList); OnClause onClause = pop(NullValue.IdentifierList); TypeParameterList typeParameters = pop(); SimpleIdentifier name = pop(); List<Annotation> metadata = pop(); Comment comment = _findComment(metadata, mixinKeyword); mixinDeclaration = ast.mixinDeclaration( comment, metadata, mixinKeyword, name, typeParameters, onClause, implementsClause, null, // leftBracket <ClassMember>[], null, // rightBracket ); declarations.add(mixinDeclaration); } @override void handleMixinOn(Token onKeyword, int typeCount) { assert(onKeyword == null || onKeyword.isKeywordOrIdentifier); debugEvent("MixinOn"); if (onKeyword != null) { List<TypeName> types = popTypedList(typeCount); push(ast.onClause(onKeyword, types)); } else { push(NullValue.IdentifierList); } } void handleNamedArgument(Token colon) { assert(optional(':', colon)); debugEvent("NamedArgument"); Expression expression = pop(); SimpleIdentifier name = pop(); push(ast.namedExpression(ast.label(name, colon), expression)); } @override void handleNamedMixinApplicationWithClause(Token withKeyword) { assert(optionalOrNull('with', withKeyword)); List<TypeName> mixinTypes = pop(); push(ast.withClause(withKeyword, mixinTypes)); } @override void handleNativeClause(Token nativeToken, bool hasName) { debugEvent("NativeClause"); if (hasName) { nativeName = pop(); // StringLiteral } else { nativeName = null; } } @override void handleNativeFunctionBody(Token nativeToken, Token semicolon) { assert(optional('native', nativeToken)); assert(optional(';', semicolon)); debugEvent("NativeFunctionBody"); // TODO(danrubel) Change the parser to not produce these modifiers. pop(); // star pop(); // async push(ast.nativeFunctionBody(nativeToken, nativeName, semicolon)); } @override void handleNoConstructorReferenceContinuationAfterTypeArguments(Token token) { debugEvent("NoConstructorReferenceContinuationAfterTypeArguments"); push(NullValue.ConstructorReferenceContinuationAfterTypeArguments); } @override void handleNoFieldInitializer(Token token) { debugEvent("NoFieldInitializer"); SimpleIdentifier name = pop(); push(_makeVariableDeclaration(name, null, null)); } void handleNoInitializers() { debugEvent("NoInitializers"); if (!isFullAst) return; push(NullValue.ConstructorInitializerSeparator); push(NullValue.ConstructorInitializers); } @override void handleNonNullAssertExpression(Token bang) { debugEvent('NonNullAssertExpression'); if (!enableNonNullable) { reportNonNullAssertExpressionNotEnabled(bang); } else { push(ast.postfixExpression(pop(), bang)); } } @override void handleNoVariableInitializer(Token token) { debugEvent("NoVariableInitializer"); } void handleOperator(Token operatorToken) { assert(operatorToken.isUserDefinableOperator); debugEvent("Operator"); push(operatorToken); } @override void handleOperatorName(Token operatorKeyword, Token token) { assert(optional('operator', operatorKeyword)); assert(token.type.isUserDefinableOperator); debugEvent("OperatorName"); push(new _OperatorName( operatorKeyword, ast.simpleIdentifier(token, isDeclaration: true))); } @override void handleParenthesizedCondition(Token leftParenthesis) { // TODO(danrubel): Implement rather than forwarding. handleParenthesizedExpression(leftParenthesis); } @override void handleParenthesizedExpression(Token leftParenthesis) { assert(optional('(', leftParenthesis)); debugEvent("ParenthesizedExpression"); Expression expression = pop(); push(ast.parenthesizedExpression( leftParenthesis, expression, leftParenthesis?.endGroup)); } @override void handleQualified(Token period) { assert(optional('.', period)); SimpleIdentifier identifier = pop(); var prefix = pop(); if (prefix is List) { // We're just accumulating components into a list. prefix.add(identifier); push(prefix); } else if (prefix is SimpleIdentifier) { // TODO(paulberry): resolve [identifier]. Note that BodyBuilder handles // this situation using SendAccessGenerator. push(ast.prefixedIdentifier(prefix, period, identifier)); } else { // TODO(paulberry): implement. logEvent('Qualified with >1 dot'); } } @override void handleRecoverableError( Message message, Token startToken, Token endToken) { /// TODO(danrubel): Ignore this error until we deprecate `native` support. if (message == messageNativeClauseShouldBeAnnotation && allowNativeClause) { return; } debugEvent("Error: ${message.message}"); if (message.code.analyzerCodes == null && startToken is ErrorToken) { translateErrorToken(startToken, errorReporter.reportScannerError); } else { int offset = startToken.offset; int length = endToken.end - offset; addProblem(message, offset, length); } } @override void handleRecoverClassHeader() { debugEvent("RecoverClassHeader"); ImplementsClause implementsClause = pop(NullValue.IdentifierList); WithClause withClause = pop(NullValue.WithClause); ExtendsClause extendsClause = pop(NullValue.ExtendsClause); ClassDeclaration declaration = declarations.last; if (extendsClause != null) { if (declaration.extendsClause?.superclass == null) { declaration.extendsClause = extendsClause; } } if (withClause != null) { if (declaration.withClause == null) { declaration.withClause = withClause; } else { declaration.withClause.mixinTypes.addAll(withClause.mixinTypes); } } if (implementsClause != null) { if (declaration.implementsClause == null) { declaration.implementsClause = implementsClause; } else { declaration.implementsClause.interfaces .addAll(implementsClause.interfaces); } } } @override void handleRecoverImport(Token semicolon) { assert(optionalOrNull(';', semicolon)); debugEvent("RecoverImport"); List<Combinator> combinators = pop(); Token deferredKeyword = pop(NullValue.Deferred); Token asKeyword = pop(NullValue.As); SimpleIdentifier prefix = pop(NullValue.Prefix); List<Configuration> configurations = pop(); ImportDirective directive = directives.last; if (combinators != null) { directive.combinators.addAll(combinators); } directive.deferredKeyword ??= deferredKeyword; if (directive.asKeyword == null && asKeyword != null) { directive.asKeyword = asKeyword; directive.prefix = prefix; } if (configurations != null) { directive.configurations.addAll(configurations); } directive.semicolon = semicolon; } @override void handleRecoverMixinHeader() { ImplementsClause implementsClause = pop(NullValue.IdentifierList); OnClause onClause = pop(NullValue.IdentifierList); if (onClause != null) { if (mixinDeclaration.onClause == null) { mixinDeclaration.onClause = onClause; } else { mixinDeclaration.onClause.superclassConstraints .addAll(onClause.superclassConstraints); } } if (implementsClause != null) { if (mixinDeclaration.implementsClause == null) { mixinDeclaration.implementsClause = implementsClause; } else { mixinDeclaration.implementsClause.interfaces .addAll(implementsClause.interfaces); } } } void handleScript(Token token) { assert(identical(token.type, TokenType.SCRIPT_TAG)); debugEvent("Script"); scriptTag = ast.scriptTag(token); } void handleSend(Token beginToken, Token endToken) { debugEvent("Send"); MethodInvocation arguments = pop(); TypeArgumentList typeArguments = pop(); if (arguments != null) { doInvocation(typeArguments, arguments); } else { doPropertyGet(); } } @override void handleSpreadExpression(Token spreadToken) { var expression = pop(); if (enableSpreadCollections) { push(ast.spreadElement( spreadOperator: spreadToken, expression: expression)); } else { handleRecoverableError( templateExperimentNotEnabled .withArguments(EnableString.spread_collections), spreadToken, spreadToken); push(_invalidCollectionElement); } } void handleStringJuxtaposition(int literalCount) { debugEvent("StringJuxtaposition"); push(ast.adjacentStrings(popTypedList(literalCount))); } @override void handleStringPart(Token literalString) { assert(identical(literalString.kind, STRING_TOKEN)); debugEvent("StringPart"); push(literalString); } @override void handleSuperExpression(Token superKeyword, IdentifierContext context) { assert(optional('super', superKeyword)); debugEvent("SuperExpression"); push(ast.superExpression(superKeyword)); } void handleSymbolVoid(Token voidKeyword) { assert(optional('void', voidKeyword)); debugEvent("SymbolVoid"); push(voidKeyword); } @override void handleThisExpression(Token thisKeyword, IdentifierContext context) { assert(optional('this', thisKeyword)); debugEvent("ThisExpression"); push(ast.thisExpression(thisKeyword)); } void handleThrowExpression(Token throwToken, Token endToken) { assert(optional('throw', throwToken)); debugEvent("ThrowExpression"); push(ast.throwExpression(throwToken, pop())); } @override void handleType(Token beginToken, Token questionMark) { debugEvent("Type"); if (!enableNonNullable) { reportErrorIfNullableType(questionMark); } TypeArgumentList arguments = pop(); Identifier name = pop(); push(ast.typeName(name, arguments, question: questionMark)); } @override void handleTypeVariablesDefined(Token token, int count) { debugEvent("handleTypeVariablesDefined"); assert(count > 0); push(popTypedList(count, new List<TypeParameter>(count))); } void handleUnaryPostfixAssignmentExpression(Token operator) { assert(operator.type.isUnaryPostfixOperator); debugEvent("UnaryPostfixAssignmentExpression"); Expression expression = pop(); if (!expression.isAssignable) { // This error is also reported by the body builder. handleRecoverableError( messageIllegalAssignmentToNonAssignable, operator, operator); } push(ast.postfixExpression(expression, operator)); } void handleUnaryPrefixAssignmentExpression(Token operator) { assert(operator.type.isUnaryPrefixOperator); debugEvent("UnaryPrefixAssignmentExpression"); Expression expression = pop(); if (!expression.isAssignable) { // This error is also reported by the body builder. handleRecoverableError(messageMissingAssignableSelector, expression.endToken, expression.endToken); } push(ast.prefixExpression(operator, expression)); } void handleUnaryPrefixExpression(Token operator) { assert(operator.type.isUnaryPrefixOperator); debugEvent("UnaryPrefixExpression"); push(ast.prefixExpression(operator, pop())); } void handleValuedFormalParameter(Token equals, Token token) { assert(optional('=', equals) || optional(':', equals)); debugEvent("ValuedFormalParameter"); Expression value = pop(); push(new _ParameterDefaultValue(equals, value)); } @override void handleVarianceModifier(Token variance) { debugEvent('VarianceModifier'); if (!enableVariance) { reportVarianceModifierNotEnabled(variance); } } @override void handleVoidKeyword(Token voidKeyword) { assert(optional('void', voidKeyword)); debugEvent("VoidKeyword"); // TODO(paulberry): is this sufficient, or do we need to hook the "void" // keyword up to an element? handleIdentifier(voidKeyword, IdentifierContext.typeReference); handleNoTypeArguments(voidKeyword); handleType(voidKeyword, null); } /// Return `true` if [token] is either `null` or is the symbol or keyword /// [value]. bool optionalOrNull(String value, Token token) { return token == null || identical(value, token.stringValue); } List<CommentReference> parseCommentReferences(Token dartdoc) { // Parse dartdoc into potential comment reference source/offset pairs int count = parser.parseCommentReferences(dartdoc); List sourcesAndOffsets = new List(count * 2); popList(count * 2, sourcesAndOffsets); // Parse each of the source/offset pairs into actual comment references count = 0; int index = 0; while (index < sourcesAndOffsets.length) { String referenceSource = sourcesAndOffsets[index++]; int referenceOffset = sourcesAndOffsets[index++]; ScannerResult result = scanString(referenceSource); if (!result.hasErrors) { Token token = result.tokens; if (parser.parseOneCommentReference(token, referenceOffset)) { ++count; } } } final references = new List<CommentReference>(count); popTypedList(count, references); return references; } List<CollectionElement> popCollectionElements(int count) { final elements = new List<CollectionElement>()..length = count; for (int index = count - 1; index >= 0; --index) { var element = pop(); elements[index] = element as CollectionElement; } return elements; } List popList(int n, List list) { if (n == 0) return null; return stack.popList(n, list, null); } List<T> popTypedList<T>(int count, [List<T> list]) { if (count == 0) return null; assert(stack.arrayLength >= count); final table = stack.array; final length = stack.arrayLength; final tailList = list ?? new List<T>.filled(count, null, growable: true); final startIndex = length - count; for (int i = 0; i < count; i++) { final value = table[startIndex + i]; tailList[i] = value is NullValue ? null : value; table[startIndex + i] = null; } stack.arrayLength -= count; return tailList; } void pushForControlFlowInfo(Token awaitToken, Token forToken, Token leftParenthesis, ForLoopParts forLoopParts, Object entry) { if (entry == _invalidCollectionElement) { push(_invalidCollectionElement); } else if (enableControlFlowCollections) { push(ast.forElement( awaitKeyword: awaitToken, forKeyword: forToken, leftParenthesis: leftParenthesis, forLoopParts: forLoopParts, rightParenthesis: leftParenthesis.endGroup, body: entry as CollectionElement, )); } else { handleRecoverableError( templateExperimentNotEnabled .withArguments(EnableString.control_flow_collections), forToken, forToken); push(_invalidCollectionElement); } } void pushIfControlFlowInfo( Token ifToken, ParenthesizedExpression condition, CollectionElement thenElement, Token elseToken, CollectionElement elseElement) { if (thenElement == _invalidCollectionElement || elseElement == _invalidCollectionElement) { push(_invalidCollectionElement); } else if (enableControlFlowCollections) { push(ast.ifElement( ifKeyword: ifToken, leftParenthesis: condition.leftParenthesis, condition: condition.expression, rightParenthesis: condition.rightParenthesis, thenElement: thenElement, elseKeyword: elseToken, elseElement: elseElement, )); } else { handleRecoverableError( templateExperimentNotEnabled .withArguments(EnableString.control_flow_collections), ifToken, ifToken); push(_invalidCollectionElement); } } void reportErrorIfSuper(Expression expression) { if (expression is SuperExpression) { // This error is also reported by the body builder. handleRecoverableError(messageMissingAssignableSelector, expression.beginToken, expression.endToken); } } Comment _findComment(List<Annotation> metadata, Token tokenAfterMetadata) { // Find the dartdoc tokens Token dartdoc = parser.findDartDoc(tokenAfterMetadata); if (dartdoc == null) { if (metadata == null) { return null; } int index = metadata.length; while (true) { if (index == 0) { return null; } --index; dartdoc = parser.findDartDoc(metadata[index].beginToken); if (dartdoc != null) { break; } } } // Build and return the comment List<CommentReference> references = parseCommentReferences(dartdoc); List<Token> tokens = <Token>[dartdoc]; if (dartdoc.lexeme.startsWith('///')) { dartdoc = dartdoc.next; while (dartdoc != null) { if (dartdoc.lexeme.startsWith('///')) { tokens.add(dartdoc); } dartdoc = dartdoc.next; } } return ast.documentationComment(tokens, references); } void _handleInstanceCreation(Token token) { MethodInvocation arguments = pop(); ConstructorName constructorName; TypeArgumentList typeArguments; var object = pop(); if (object is _ConstructorNameWithInvalidTypeArgs) { constructorName = object.name; typeArguments = object.invalidTypeArgs; } else { constructorName = object; } push(ast.instanceCreationExpression( token, constructorName, arguments.argumentList, typeArguments: typeArguments)); } VariableDeclaration _makeVariableDeclaration( SimpleIdentifier name, Token equals, Expression initializer) { var variableDeclaration = ast.variableDeclaration(name, equals, initializer); localDeclarations[name.offset] = variableDeclaration; return variableDeclaration; } ParameterKind _toAnalyzerParameterKind( FormalParameterKind type, Token requiredKeyword) { if (type == FormalParameterKind.optionalPositional) { return ParameterKind.POSITIONAL; } else if (type == FormalParameterKind.optionalNamed) { if (requiredKeyword != null) { return ParameterKind.NAMED_REQUIRED; } return ParameterKind.NAMED; } else { return ParameterKind.REQUIRED; } } } class _ConstructorNameWithInvalidTypeArgs { final ConstructorName name; final TypeArgumentList invalidTypeArgs; _ConstructorNameWithInvalidTypeArgs(this.name, this.invalidTypeArgs); } /// When [enableSpreadCollections] and/or [enableControlFlowCollections] /// are false, this class is pushed on the stack when a disabled /// [CollectionElement] has been parsed. class _InvalidCollectionElement implements CollectionElement { // TODO(danrubel): Remove this once control flow and spread collections // have been enabled by default. const _InvalidCollectionElement._(); noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } /// Data structure placed on the stack to represent a non-empty sequence /// of modifiers. class _Modifiers { Token abstractKeyword; Token externalKeyword; Token finalConstOrVarKeyword; Token staticKeyword; Token covariantKeyword; Token requiredToken; Token lateToken; /// Return the token that is lexically first. Token get beginToken { Token firstToken; for (Token token in [ abstractKeyword, externalKeyword, finalConstOrVarKeyword, staticKeyword, covariantKeyword, requiredToken, lateToken, ]) { if (firstToken == null) { firstToken = token; } else if (token != null) { if (token.offset < firstToken.offset) { firstToken = token; } } } return firstToken; } /// Return the `const` keyword or `null`. Token get constKeyword { return identical('const', finalConstOrVarKeyword?.lexeme) ? finalConstOrVarKeyword : null; } } /// Data structure placed on the stack to represent the keyword "operator" /// followed by a token. class _OperatorName { final Token operatorKeyword; final SimpleIdentifier name; _OperatorName(this.operatorKeyword, this.name); } /// Data structure placed on the stack as a container for optional parameters. class _OptionalFormalParameters { final List<FormalParameter> parameters; final Token leftDelimiter; final Token rightDelimiter; _OptionalFormalParameters( this.parameters, this.leftDelimiter, this.rightDelimiter); } /// Data structure placed on the stack to represent the default parameter /// value with the separator token. class _ParameterDefaultValue { final Token separator; final Expression value; _ParameterDefaultValue(this.separator, this.value); } /// Data structure placed on stack to represent the redirected constructor. class _RedirectingFactoryBody { final Token asyncKeyword; final Token starKeyword; final Token equalToken; final ConstructorName constructorName; _RedirectingFactoryBody(this.asyncKeyword, this.starKeyword, this.equalToken, this.constructorName); }
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/util/utilities_timing.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. /** * A `CountedStopwatch` is a [Stopwatch] that counts the number of times the * stop method has been invoked. */ class CountedStopwatch extends Stopwatch { /** * The number of times the [stop] method has been invoked. */ int stopCount = 0; /** * Initialize a newly created stopwatch. */ CountedStopwatch(); /** * The average number of millisecond that were recorded each time the [start] * and [stop] methods were invoked. */ int get averageMilliseconds => elapsedMilliseconds ~/ stopCount; @override void reset() { super.reset(); stopCount = 0; } @override void stop() { super.stop(); stopCount++; } }
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/util/glob.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. /** * A pattern that matches against filesystem path-like strings with wildcards. * * The pattern matches strings as follows: * * The pattern must use `/` as the path separator. * * The whole string must match, not a substring. * * Any non wildcard is matched as a literal. * * '*' matches one or more characters except '/'. * * '?' matches exactly one character except '/'. * * '**' matches one or more characters including '/'. */ class Glob { /** * The special characters are: \ ^ $ . | + [ ] ( ) { } * as defined here: http://ecma-international.org/ecma-262/5.1/#sec-15.10 */ static final RegExp _specialChars = new RegExp(r'([\\\^\$\.\|\+\[\]\(\)\{\}])'); /** * The path separator used to separate components in file paths. */ final String _separator; /** * The pattern string. */ final String _pattern; String _suffix; RegExp _regex; Glob(this._separator, this._pattern) { if (_hasJustPrefix(_pattern, '**/*')) { _suffix = _pattern.substring(4).toLowerCase(); } else if (_hasJustPrefix(_pattern, '**')) { _suffix = _pattern.substring(2).toLowerCase(); } else { _regex = _regexpFromGlobPattern(_pattern); } } @override int get hashCode => _pattern.hashCode; bool operator ==(other) => other is Glob && _pattern == other._pattern; /** * Return `true` if the given [path] matches this glob. * The given [path] must use the same [_separator] as the glob. */ bool matches(String path) { String posixPath = _toPosixPath(path); if (_suffix != null) { return posixPath.toLowerCase().endsWith(_suffix); } return _regex.matchAsPrefix(posixPath) != null; } @override String toString() => _pattern; /** * Return the Posix version of the given [path]. */ String _toPosixPath(String path) { if (_separator == '/') { return path; } return path.replaceAll(_separator, '/'); } /** * Return `true` if the [pattern] start with the given [prefix] and does * not have `*` or `?` characters after the [prefix]. */ static bool _hasJustPrefix(String pattern, String prefix) { if (pattern.startsWith(prefix)) { int prefixLength = prefix.length; return !pattern.contains('*', prefixLength) && !pattern.contains('?', prefixLength); } return false; } static RegExp _regexpFromGlobPattern(String pattern) { StringBuffer sb = new StringBuffer(); sb.write('^'); List<String> chars = pattern.split(''); for (int i = 0; i < chars.length; i++) { String c = chars[i]; if (_specialChars.hasMatch(c)) { sb.write(r'\'); sb.write(c); } else if (c == '*') { if (i + 1 < chars.length && chars[i + 1] == '*') { sb.write('.*'); i++; } else { sb.write('[^/]*'); } } else if (c == '?') { sb.write('[^/]'); } else { sb.write(c); } } sb.write(r'$'); return new RegExp(sb.toString(), caseSensitive: 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/util/lru_map.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'; /** * This handler is notified when an item is evicted from the cache. */ typedef EvictionHandler<K, V>(K key, V value); /** * A hash-table based cache implementation. * * When it reaches the specified number of items, the item that has not been * accessed (both get and put) recently is evicted. */ class LRUMap<K, V> { final LinkedHashMap<K, V> _map = new LinkedHashMap<K, V>(); final int _maxSize; final EvictionHandler<K, V> _handler; LRUMap(this._maxSize, [this._handler]); /** * Returns the value for the given [key] or null if [key] is not * in the cache. */ V get(K key) { V value = _map.remove(key); if (value != null) { _map[key] = value; } return value; } /** * Associates the [key] with the given [value]. * * If the cache is full, an item that has not been accessed recently is * evicted. */ void put(K key, V value) { _map.remove(key); _map[key] = value; if (_map.length > _maxSize) { K evictedKey = _map.keys.first; V evictedValue = _map.remove(evictedKey); if (_handler != null) { _handler(evictedKey, evictedValue); } } } /** * Removes the association for the given [key]. */ void remove(K key) { _map.remove(key); } }
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/util/yaml.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:yaml/src/event.dart'; import 'package:yaml/yaml.dart'; /// Given a [map], return the [YamlNode] associated with the given [key], or /// `null` if there is no matching key. YamlNode getKey(YamlMap map, String key) { for (YamlNode k in map.nodes.keys) { if (k is YamlScalar && k.value == key) { return k; } } return null; } /// Given a [map], return the value associated with the key whose value matches /// the given [key], or `null` if there is no matching key. YamlNode getValue(YamlMap map, String key) { for (var k in map.nodes.keys) { if (k is YamlScalar && k.value == key) { return map.nodes[k]; } } return null; } /// If all of the elements of [list] are strings, return a list of strings /// containing the same elements. Otherwise, return `null`. List<String> toStringList(List list) { if (list == null) { return null; } List<String> stringList = <String>[]; for (var element in list) { if (element is String) { stringList.add(element); } else { return null; } } return stringList; } bool _contains(YamlList l1, YamlNode n2) { for (YamlNode n1 in l1.nodes) { if (n1.value == n2.value) { return true; } } return false; } /// Merges two maps (of yaml) with simple override semantics, suitable for /// merging two maps where one map defines default values that are added to /// (and possibly overridden) by an overriding map. class Merger { /// Merges a default [o1] with an overriding object [o2]. /// /// * 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. /// YamlNode merge(YamlNode o1, YamlNode o2) { // Handle promotion first. YamlMap listToMap(YamlList list) { Map<YamlNode, YamlNode> map = new HashMap<YamlNode, YamlNode>(); // equals: _equals, hashCode: _hashCode ScalarEvent event = new ScalarEvent(null, 'true', ScalarStyle.PLAIN); for (var element in list.nodes) { map[element] = new YamlScalar.internal(true, event); } return new YamlMap.internal(map, null, CollectionStyle.BLOCK); } if (isListOfString(o1) && isMapToBools(o2)) { o1 = listToMap(o1 as YamlList); } else if (isMapToBools(o1) && isListOfString(o2)) { o2 = listToMap(o2 as YamlList); } if (o1 is YamlMap && o2 is YamlMap) { return mergeMap(o1, o2); } if (o1 is YamlList && o2 is YamlList) { return mergeList(o1, o2); } // Default to override, unless the overriding value is `null`. return o2 ?? o1; } /// Merge lists, avoiding duplicates. YamlList mergeList(YamlList l1, YamlList l2) { List<YamlNode> list = <YamlNode>[]; list.addAll(l1.nodes); for (YamlNode n2 in l2.nodes) { if (!_contains(l1, n2)) { list.add(n2); } } return new YamlList.internal(list, null, CollectionStyle.BLOCK); } /// Merge maps (recursively). YamlMap mergeMap(YamlMap m1, YamlMap m2) { Map<YamlNode, YamlNode> merged = new HashMap<YamlNode, YamlNode>(); // equals: _equals, hashCode: _hashCode m1.nodes.forEach((k, v) { merged[k] = v; }); m2.nodes.forEach((k, v) { YamlScalar mergedKey = merged.keys .firstWhere((key) => key.value == k.value, orElse: () => k); merged[mergedKey] = merge(merged[mergedKey], v); }); return new YamlMap.internal(merged, null, CollectionStyle.BLOCK); } static bool isListOfString(Object o) => o is YamlList && o.nodes.every((e) => e is YamlScalar && e.value is String); static bool isMapToBools(Object o) => o is YamlMap && o.nodes.values.every((v) => v is YamlScalar && v.value is bool); }
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/util/ast_data_extractor.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/element/element.dart'; import 'package:front_end/src/testing/id.dart' show ActualData, DataRegistry, Id, IdKind, MemberId, NodeId; /// Abstract IR visitor for computing data corresponding to a node or element, /// and record it with a generic [Id] /// TODO(paulberry): if I try to extend GeneralizingAstVisitor<void>, the VM /// crashes. abstract class AstDataExtractor<T> extends GeneralizingAstVisitor<dynamic> with DataRegistry<T> { final Uri uri; @override final Map<Id, ActualData<T>> actualMap; AstDataExtractor(this.uri, this.actualMap); NodeId computeDefaultNodeId(AstNode node) => NodeId(_nodeOffset(node), IdKind.node); void computeForExpression(Expression node, NodeId id) { if (id == null) return; T value = computeNodeValue(id, node); registerValue(uri, node.offset, id, value, node); } void computeForMember(Declaration node, Id id) { if (id == null) return; T value = computeNodeValue(id, node); registerValue(uri, node.offset, id, value, node); } void computeForStatement(Statement node, NodeId id) { if (id == null) return; T value = computeNodeValue(id, node); registerValue(uri, node.offset, id, value, node); } /// Implement this to compute the data corresponding to [node]. /// /// If `null` is returned, [node] has no associated data. T computeNodeValue(Id id, AstNode node); Id createMemberId(Declaration node) { var element = node.declaredElement; if (element.enclosingElement is CompilationUnitElement) { var memberName = element.name; if (element is PropertyAccessorElement && element.isSetter) { memberName += '='; } return MemberId.internal(memberName); } throw UnimplementedError( 'TODO(paulberry): $element (${element.runtimeType})'); } NodeId createStatementId(Statement node) => NodeId(_nodeOffset(node), IdKind.stmt); @override void fail(String message) { throw _Failure(message); } @override void report(Uri uri, int offset, String message) { // TODO(paulberry): find a way to print the error more nicely. print('$uri:$offset: $message'); } void run(CompilationUnit unit) { unit.accept(this); } @override visitExpression(Expression node) { computeForExpression(node, computeDefaultNodeId(node)); super.visitExpression(node); } @override visitFunctionDeclaration(FunctionDeclaration node) { if (node.parent is CompilationUnit) { computeForMember(node, createMemberId(node)); } return super.visitFunctionDeclaration(node); } @override visitStatement(Statement node) { computeForStatement(node, createStatementId(node)); super.visitStatement(node); } int _nodeOffset(AstNode node) { var offset = node.offset; assert(offset != null && offset >= 0, "No fileOffset on $node (${node.runtimeType})"); return offset; } } class _Failure implements Exception { final String message; _Failure([this.message]); String toString() { if (message == null) return "Exception"; return "Exception: $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/util/asserts.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. /** * Ensures that the given [value] is not null. * Otherwise throws an [ArgumentError]. * An optional [description] is used in the error message. */ void notNull(Object value, [String description]) { if (value == null) { if (description == null) { throw new ArgumentError('Must not be null'); } else { throw new ArgumentError('Must not be null: $description'); } } }
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/util/comment.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'; /// Return the raw text of the given comment node. String getCommentNodeRawText(Comment node) { if (node == null) return null; return node.tokens .map((token) => token.lexeme) .join('\n') .replaceAll('\r\n', '\n'); } /// Return the plain text from the given DartDoc [rawText], without delimiters. String getDartDocPlainText(String rawText) { if (rawText == null) return null; // Remove /** */. if (rawText.startsWith('/**')) { rawText = rawText.substring(3); } if (rawText.endsWith('*/')) { rawText = rawText.substring(0, rawText.length - 2); } rawText = rawText.trim(); // Remove leading '* ' and '/// '. var result = new StringBuffer(); var lines = rawText.split('\n'); for (var line in lines) { line = line.trim(); if (line.startsWith('*')) { line = line.substring(1); if (line.startsWith(' ')) { line = line.substring(1); } } else if (line.startsWith('///')) { line = line.substring(3); if (line.startsWith(' ')) { line = line.substring(1); } } if (result.isNotEmpty) { result.write('\n'); } result.write(line); } return result.toString(); } /// Return the DartDoc summary, i.e. the portion before the first empty line. String getDartDocSummary(String completeText) { if (completeText == null) return null; var result = new StringBuffer(); var lines = completeText.split('\n'); for (var line in lines) { if (result.isNotEmpty) { if (line.isEmpty) { return result.toString(); } result.write('\n'); } result.write(line); } return result.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/util/uri.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:path/path.dart'; String fileUriToNormalizedPath(Context context, Uri fileUri) { assert(fileUri.isScheme('file')); var path = context.fromUri(fileUri); path = context.normalize(path); return path; }
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/util/sdk.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 'dart:io'; import 'package:path/path.dart' as path; /// Return `true` if the given [sdkPath] is valid, i.e. has all required /// artifacts. String computePlatformBinariesPath(String sdkPath) { // Try the given SDK path. { String location = path.join(sdkPath, 'lib', '_internal'); if (new File(path.join(location, 'vm_platform_strong.dill')).existsSync()) { return location; } } // The given SDK path does not work. // Then we're probably running on bots, in 'xcodebuild/ReleaseX64'. // In this case 'vm_platform_strong.dill' is next to the 'dart'. return path.dirname(Platform.resolvedExecutable); } String getSdkPath([List<String> args]) { // Look for --dart-sdk on the command line. if (args != null) { int index = args.indexOf('--dart-sdk'); if (index != -1 && (index + 1 < args.length)) { return args[index + 1]; } for (String arg in args) { if (arg.startsWith('--dart-sdk=')) { return arg.substring('--dart-sdk='.length); } } } // Look in env['DART_SDK'] if (Platform.environment['DART_SDK'] != null) { return Platform.environment['DART_SDK']; } // Use Platform.resolvedExecutable. return path.dirname(path.dirname(Platform.resolvedExecutable)); }
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/ast.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. /** * This library is deprecated. Please convert all references to this library to * reference one of the following public libraries: * * package:analyzer/dart/ast/ast.dart * * package:analyzer/dart/ast/visitor.dart * * If your code is using APIs not available in these public libraries, please * contact the analyzer team to either find an alternate API or have the API you * depend on added to the public API. */ @deprecated library analyzer.src.generated.ast; export 'package:analyzer/dart/ast/ast.dart'; export 'package:analyzer/dart/ast/visitor.dart'; export 'package:analyzer/src/dart/ast/utilities.dart';
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/parser_fasta.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. part of analyzer.parser; /** * Proxy implementation of the analyzer parser, implemented in terms of the * Fasta parser. */ abstract class ParserAdapter implements Parser { @override Token currentToken; /** * The fasta parser being wrapped. */ final fasta.Parser fastaParser; /** * The builder which creates the analyzer AST data structures * based on the Fasta parser. */ final AstBuilder astBuilder; ParserAdapter(this.currentToken, ErrorReporter errorReporter, Uri fileUri, FeatureSet featureSet, {bool allowNativeClause: false}) : fastaParser = new fasta.Parser(null), astBuilder = new AstBuilder(errorReporter, fileUri, true, featureSet) { fastaParser.listener = astBuilder; astBuilder.parser = fastaParser; astBuilder.allowNativeClause = allowNativeClause; } @override set allowNativeClause(bool value) { astBuilder.allowNativeClause = value; } @override bool get enableOptionalNewAndConst => false; @override void set enableOptionalNewAndConst(bool enable) {} @override void set enableSetLiterals(bool value) { // TODO(danrubel): Remove this method once the reference to this flag // has been removed from dartfmt. } @override void set parseFunctionBodies(bool parseFunctionBodies) { astBuilder.parseFunctionBodies = parseFunctionBodies; } @override set parseGenericMethods(_) {} /// Append the given token to the end of the token stream, /// and update the token's offset. appendToken(Token token, Token newToken) { while (!token.next.isEof) { token = token.next; } newToken ..offset = token.end ..setNext(token.next); token.setNext(newToken); } @override Expression parseAdditiveExpression() => parseExpression2(); @override Annotation parseAnnotation() { currentToken = fastaParser .parseMetadata(fastaParser.syntheticPreviousToken(currentToken)) .next; return astBuilder.pop(); } @override Expression parseArgument() { currentToken = new SimpleToken(TokenType.OPEN_PAREN, 0) ..setNext(currentToken); appendToken(currentToken, new SimpleToken(TokenType.CLOSE_PAREN, 0)); currentToken = fastaParser .parseArguments(fastaParser.syntheticPreviousToken(currentToken)) .next; MethodInvocation invocation = astBuilder.pop(); return invocation.argumentList.arguments[0]; } @override ArgumentList parseArgumentList() { currentToken = fastaParser .parseArguments(fastaParser.syntheticPreviousToken(currentToken)) .next; var result = astBuilder.pop(); return result is MethodInvocation ? result.argumentList : result; } @override Expression parseAssignableExpression(bool primaryAllowed) => parseExpression2(); @override Expression parseBitwiseAndExpression() => parseExpression2(); @override Expression parseBitwiseOrExpression() => parseExpression2(); @override Expression parseBitwiseXorExpression() => parseExpression2(); @override ClassMember parseClassMember(String className) { astBuilder.classDeclaration = astFactory.classDeclaration( null, null, null, new Token(Keyword.CLASS, 0), astFactory.simpleIdentifier( new fasta.StringToken.fromString(TokenType.IDENTIFIER, className, 6)), null, null, null, null, null /* leftBracket */, <ClassMember>[], null /* rightBracket */, ); // TODO(danrubel): disambiguate between class and mixin currentToken = fastaParser.parseClassMember(currentToken, className); //currentToken = fastaParser.parseMixinMember(currentToken); ClassDeclaration declaration = astBuilder.classDeclaration; astBuilder.classDeclaration = null; return declaration.members.isNotEmpty ? declaration.members[0] : null; } @override List<Combinator> parseCombinators() { currentToken = fastaParser .parseCombinatorStar(fastaParser.syntheticPreviousToken(currentToken)) .next; return astBuilder.pop(); } @override CompilationUnit parseCompilationUnit(Token token) { currentToken = token; return parseCompilationUnit2(); } @override CompilationUnit parseCompilationUnit2() { currentToken = fastaParser.parseUnit(currentToken); CompilationUnitImpl compilationUnit = astBuilder.pop(); compilationUnit.localDeclarations = astBuilder.localDeclarations; return compilationUnit; } @override Expression parseConditionalExpression() => parseExpression2(); @override Configuration parseConfiguration() { currentToken = fastaParser .parseConditionalUri(fastaParser.syntheticPreviousToken(currentToken)) .next; return astBuilder.pop(); } @override Expression parseConstExpression() => parseExpression2(); @override CompilationUnit parseDirectives(Token token) { currentToken = token; return parseDirectives2(); } @override CompilationUnit parseDirectives2() { currentToken = fastaParser.parseDirectives(currentToken); return astBuilder.pop(); } @override DottedName parseDottedName() { currentToken = fastaParser .parseDottedName(fastaParser.syntheticPreviousToken(currentToken)) .next; return astBuilder.pop(); } @override Expression parseEqualityExpression() => parseExpression2(); @override Expression parseExpression(Token token) { currentToken = token; return parseExpression2(); } @override Expression parseExpression2() { currentToken = fastaParser .parseExpression(fastaParser.syntheticPreviousToken(currentToken)) .next; return astBuilder.pop(); } @override Expression parseExpressionWithoutCascade() => parseExpression2(); @override FormalParameterList parseFormalParameterList({bool inFunctionType: false}) { currentToken = fastaParser .parseFormalParametersRequiredOpt( fastaParser.syntheticPreviousToken(currentToken), inFunctionType ? fasta.MemberKind.GeneralizedFunctionType : fasta.MemberKind.NonStaticMethod) .next; return astBuilder.pop(); } @override FunctionBody parseFunctionBody( bool mayBeEmpty, ParserErrorCode emptyErrorCode, bool inExpression) { currentToken = fastaParser.parseAsyncModifierOpt( fastaParser.syntheticPreviousToken(currentToken)); currentToken = fastaParser.parseFunctionBody(currentToken, inExpression, mayBeEmpty); return astBuilder.pop(); } @override FunctionExpression parseFunctionExpression() => parseExpression2(); @override Expression parseLogicalAndExpression() => parseExpression2(); @override Expression parseLogicalOrExpression() => parseExpression2(); @override Expression parseMultiplicativeExpression() => parseExpression2(); @override InstanceCreationExpression parseNewExpression() => parseExpression2(); @override Expression parsePostfixExpression() => parseExpression2(); @override Identifier parsePrefixedIdentifier() => parseExpression2(); @override Expression parsePrimaryExpression() { currentToken = fastaParser .parsePrimary(fastaParser.syntheticPreviousToken(currentToken), fasta.IdentifierContext.expression) .next; return astBuilder.pop(); } @override Expression parseRelationalExpression() => parseExpression2(); @override Expression parseRethrowExpression() => parseExpression2(); @override Expression parseShiftExpression() => parseExpression2(); @override SimpleIdentifier parseSimpleIdentifier( {bool allowKeyword: false, bool isDeclaration: false}) => parseExpression2(); @override Statement parseStatement(Token token) { currentToken = token; return parseStatement2(); } @override Statement parseStatement2() { currentToken = fastaParser .parseStatement(fastaParser.syntheticPreviousToken(currentToken)) .next; return astBuilder.pop(); } @override StringLiteral parseStringLiteral() => parseExpression2(); @override SymbolLiteral parseSymbolLiteral() => parseExpression2(); @override Expression parseThrowExpression() => parseExpression2(); @override Expression parseThrowExpressionWithoutCascade() => parseExpression2(); AnnotatedNode parseTopLevelDeclaration(bool isDirective) { currentToken = fastaParser.parseTopLevelDeclaration(currentToken); return (isDirective ? astBuilder.directives : astBuilder.declarations) .removeLast(); } @override TypeAnnotation parseTypeAnnotation(bool inExpression) { Token previous = fastaParser.syntheticPreviousToken(currentToken); currentToken = fasta .computeType(previous, true, !inExpression) .parseType(previous, fastaParser) .next; return astBuilder.pop(); } @override TypeArgumentList parseTypeArgumentList() { Token previous = fastaParser.syntheticPreviousToken(currentToken); currentToken = fasta .computeTypeParamOrArg(previous) .parseArguments(previous, fastaParser) .next; return astBuilder.pop(); } @override TypeName parseTypeName(bool inExpression) { Token previous = fastaParser.syntheticPreviousToken(currentToken); currentToken = fasta .computeType(previous, true, !inExpression) .parseType(previous, fastaParser) .next; return astBuilder.pop(); } @override TypeParameter parseTypeParameter() { currentToken = new SyntheticBeginToken(TokenType.LT, 0) ..endGroup = new SyntheticToken(TokenType.GT, 0) ..setNext(currentToken); appendToken(currentToken, currentToken.endGroup); TypeParameterList typeParams = parseTypeParameterList(); return typeParams.typeParameters[0]; } @override TypeParameterList parseTypeParameterList() { Token token = fastaParser.syntheticPreviousToken(currentToken); currentToken = fasta .computeTypeParamOrArg(token, true) .parseVariables(token, fastaParser) .next; return astBuilder.pop(); } @override Expression parseUnaryExpression() => parseExpression2(); } /** * Replacement parser based on Fasta. */ class _Parser2 extends ParserAdapter { /** * The source being parsed. */ final Source _source; @override bool enableUriInPartOf = true; factory _Parser2( Source source, AnalysisErrorListener errorListener, FeatureSet featureSet, {bool allowNativeClause: false}) { var errorReporter = new ErrorReporter(errorListener, source); return new _Parser2._(source, errorReporter, source.uri, featureSet, allowNativeClause: allowNativeClause); } _Parser2._(this._source, ErrorReporter errorReporter, Uri fileUri, FeatureSet featureSet, {bool allowNativeClause: false}) : super(null, errorReporter, fileUri, featureSet, allowNativeClause: allowNativeClause); noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); }
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/element_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/ast/precedence.dart'; import 'package:analyzer/dart/ast/syntactic_entity.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/error.dart'; import 'package:analyzer/src/dart/ast/ast.dart' show ChildEntities, IdentifierImpl, PrefixedIdentifierImpl, SimpleIdentifierImpl; import 'package:analyzer/src/dart/ast/token.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/dart/resolver/extension_member_resolver.dart'; import 'package:analyzer/src/dart/resolver/method_invocation_resolver.dart'; import 'package:analyzer/src/dart/resolver/resolution_result.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/super_context.dart'; import 'package:analyzer/src/task/strong/checker.dart'; /** * An object used by instances of [ResolverVisitor] to resolve references within * the AST structure to the elements being referenced. The requirements for the * element resolver are: * * 1. Every [SimpleIdentifier] should be resolved to the element to which it * refers. Specifically: * * An identifier within the declaration of that name should resolve to the * element being declared. * * An identifier denoting a prefix should resolve to the element * representing the import that defines the prefix (an [ImportElement]). * * An identifier denoting a variable should resolve to the element * representing the variable (a [VariableElement]). * * An identifier denoting a parameter should resolve to the element * representing the parameter (a [ParameterElement]). * * An identifier denoting a field should resolve to the element * representing the getter or setter being invoked (a * [PropertyAccessorElement]). * * An identifier denoting the name of a method or function being invoked * should resolve to the element representing the method or function (an * [ExecutableElement]). * * An identifier denoting a label should resolve to the element * representing the label (a [LabelElement]). * The identifiers within directives are exceptions to this rule and are * covered below. * 2. Every node containing a token representing an operator that can be * overridden ( [BinaryExpression], [PrefixExpression], [PostfixExpression]) * should resolve to the element representing the method invoked by that * operator (a [MethodElement]). * 3. Every [FunctionExpressionInvocation] should resolve to the element * representing the function being invoked (a [FunctionElement]). This will * be the same element as that to which the name is resolved if the function * has a name, but is provided for those cases where an unnamed function is * being invoked. * 4. Every [LibraryDirective] and [PartOfDirective] should resolve to the * element representing the library being specified by the directive (a * [LibraryElement]) unless, in the case of a part-of directive, the * specified library does not exist. * 5. Every [ImportDirective] and [ExportDirective] should resolve to the * element representing the library being specified by the directive unless * the specified library does not exist (an [ImportElement] or * [ExportElement]). * 6. The identifier representing the prefix in an [ImportDirective] should * resolve to the element representing the prefix (a [PrefixElement]). * 7. The identifiers in the hide and show combinators in [ImportDirective]s * and [ExportDirective]s should resolve to the elements that are being * hidden or shown, respectively, unless those names are not defined in the * specified library (or the specified library does not exist). * 8. Every [PartDirective] should resolve to the element representing the * compilation unit being specified by the string unless the specified * compilation unit does not exist (a [CompilationUnitElement]). * * Note that AST nodes that would represent elements that are not defined are * not resolved to anything. This includes such things as references to * undeclared variables (which is an error) and names in hide and show * combinators that are not defined in the imported library (which is not an * error). */ class ElementResolver extends SimpleAstVisitor<void> { /** * The manager for the inheritance mappings. */ final InheritanceManager3 _inheritance; /** * The resolver driving this participant. */ final ResolverVisitor _resolver; /** * The element for the library containing the compilation unit being visited. */ final LibraryElement _definingLibrary; /** * The type representing the type 'dynamic'. */ DartType _dynamicType; /** * The type representing the type 'Type'. */ InterfaceType _typeType; /// Whether constant evaluation errors should be reported during resolution. @Deprecated('This field is no longer used') final bool reportConstEvaluationErrors; /// Helper for extension method resolution. final ExtensionMemberResolver _extensionResolver; final MethodInvocationResolver _methodInvocationResolver; /** * Initialize a newly created visitor to work for the given [_resolver] to * resolve the nodes in a compilation unit. */ ElementResolver(this._resolver, {this.reportConstEvaluationErrors: true}) : _inheritance = _resolver.inheritance, _definingLibrary = _resolver.definingLibrary, _extensionResolver = _resolver.extensionResolver, _methodInvocationResolver = new MethodInvocationResolver(_resolver) { _dynamicType = _resolver.typeProvider.dynamicType; _typeType = _resolver.typeProvider.typeType; } /** * Return `true` iff the current enclosing function is a constant constructor * declaration. */ bool get isInConstConstructor { ExecutableElement function = _resolver.enclosingFunction; if (function is ConstructorElement) { return function.isConst; } return false; } @override void visitAssignmentExpression(AssignmentExpression node) { Token operator = node.operator; TokenType operatorType = operator.type; Expression leftHandSide = node.leftHandSide; DartType staticType = _getStaticType(leftHandSide, read: true); // For any compound assignments to a void or nullable variable, report it. // Example: `y += voidFn()`, not allowed. if (operatorType != TokenType.EQ) { if (staticType != null && staticType.isVoid) { _recordUndefinedToken( null, StaticWarningCode.USE_OF_VOID_RESULT, operator, []); return; } } if (operatorType != TokenType.AMPERSAND_AMPERSAND_EQ && operatorType != TokenType.BAR_BAR_EQ && operatorType != TokenType.EQ && operatorType != TokenType.QUESTION_QUESTION_EQ) { operatorType = operatorFromCompoundAssignment(operatorType); if (leftHandSide != null) { String methodName = operatorType.lexeme; // TODO(brianwilkerson) Change the [methodNameNode] from the left hand // side to the operator. var result = _newPropertyResolver() .resolve(leftHandSide, staticType, methodName, leftHandSide); node.staticElement = result.getter; if (_shouldReportInvalidMember(staticType, result)) { _recordUndefinedToken( staticType.element, StaticTypeWarningCode.UNDEFINED_OPERATOR, operator, [methodName, staticType.displayName]); } } } } @override void visitBinaryExpression(BinaryExpression node) { Token operator = node.operator; if (operator.isUserDefinableOperator) { _resolveBinaryExpression(node, operator.lexeme); } else if (operator.type == TokenType.BANG_EQ) { _resolveBinaryExpression(node, TokenType.EQ_EQ.lexeme); } } @override void visitBreakStatement(BreakStatement node) { node.target = _lookupBreakOrContinueTarget(node, node.label, false); } @override void visitClassDeclaration(ClassDeclaration node) { resolveMetadata(node); } @override void visitClassTypeAlias(ClassTypeAlias node) { resolveMetadata(node); } @override void visitCommentReference(CommentReference node) { Identifier identifier = node.identifier; if (identifier is SimpleIdentifier) { Element element = _resolveSimpleIdentifier(identifier); if (element == null) { // TODO(brianwilkerson) Report this error? // resolver.reportError( // StaticWarningCode.UNDEFINED_IDENTIFIER, // simpleIdentifier, // simpleIdentifier.getName()); } else { if (element.library == null || element.library != _definingLibrary) { // TODO(brianwilkerson) Report this error? } identifier.staticElement = element; if (node.newKeyword != null) { if (element is ClassElement) { ConstructorElement constructor = element.unnamedConstructor; if (constructor == null) { // TODO(brianwilkerson) Report this error. } else { identifier.staticElement = constructor; } } else { // TODO(brianwilkerson) Report this error. } } } } else if (identifier is PrefixedIdentifier) { SimpleIdentifier prefix = identifier.prefix; SimpleIdentifier name = identifier.identifier; Element element = _resolveSimpleIdentifier(prefix); if (element == null) { // resolver.reportError(StaticWarningCode.UNDEFINED_IDENTIFIER, prefix, prefix.getName()); } else { prefix.staticElement = element; if (element is PrefixElement) { // TODO(brianwilkerson) Report this error? element = _resolver.nameScope.lookup(identifier, _definingLibrary); name.staticElement = element; return; } LibraryElement library = element.library; if (library == null) { // TODO(brianwilkerson) We need to understand how the library could // ever be null. AnalysisEngine.instance.logger .logError("Found element with null library: ${element.name}"); } else if (library != _definingLibrary) { // TODO(brianwilkerson) Report this error. } if (node.newKeyword == null) { if (element is ClassElement) { name.staticElement = element.getMethod(name.name) ?? element.getGetter(name.name) ?? element.getSetter(name.name) ?? element.getNamedConstructor(name.name); } else { // TODO(brianwilkerson) Report this error. } } else { if (element is ClassElement) { ConstructorElement constructor = element.getNamedConstructor(name.name); if (constructor == null) { // TODO(brianwilkerson) Report this error. } else { name.staticElement = constructor; } } else { // TODO(brianwilkerson) Report this error. } } } } } @override void visitConstructorDeclaration(ConstructorDeclaration node) { super.visitConstructorDeclaration(node); ConstructorElement element = node.declaredElement; if (element is ConstructorElementImpl) { ConstructorName redirectedNode = node.redirectedConstructor; if (redirectedNode != null) { // set redirected factory constructor ConstructorElement redirectedElement = redirectedNode.staticElement; element.redirectedConstructor = redirectedElement; } else { // set redirected generative constructor for (ConstructorInitializer initializer in node.initializers) { if (initializer is RedirectingConstructorInvocation) { ConstructorElement redirectedElement = initializer.staticElement; element.redirectedConstructor = redirectedElement; } } } resolveMetadata(node); } } @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { SimpleIdentifier fieldName = node.fieldName; ClassElement enclosingClass = _resolver.enclosingClass; FieldElement fieldElement = enclosingClass.getField(fieldName.name); fieldName.staticElement = fieldElement; } @override void visitConstructorName(ConstructorName node) { DartType type = node.type.type; if (type != null && type.isDynamic) { // Nothing to do. } else if (type is InterfaceType) { // look up ConstructorElement ConstructorElement constructor; SimpleIdentifier name = node.name; if (name == null) { constructor = type.lookUpConstructor(null, _definingLibrary); } else { constructor = type.lookUpConstructor(name.name, _definingLibrary); name.staticElement = constructor; } node.staticElement = constructor; } else { // TODO(brianwilkerson) Report these errors. // ASTNode parent = node.getParent(); // if (parent instanceof InstanceCreationExpression) { // if (((InstanceCreationExpression) parent).isConst()) { // // CompileTimeErrorCode.CONST_WITH_NON_TYPE // } else { // // StaticWarningCode.NEW_WITH_NON_TYPE // } // } else { // // This is part of a redirecting factory constructor; not sure which error code to use // } } } @override void visitContinueStatement(ContinueStatement node) { node.target = _lookupBreakOrContinueTarget(node, node.label, true); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { resolveMetadata(node); } @override void visitEnumDeclaration(EnumDeclaration node) { resolveMetadata(node); } @override void visitExportDirective(ExportDirective node) { ExportElement exportElement = node.element; if (exportElement != null) { // The element is null when the URI is invalid // TODO(brianwilkerson) Figure out whether the element can ever be // something other than an ExportElement _resolveCombinators(exportElement.exportedLibrary, node.combinators); resolveMetadata(node); } } @override void visitFieldFormalParameter(FieldFormalParameter node) { _resolveMetadataForParameter(node); super.visitFieldFormalParameter(node); } @override void visitFunctionDeclaration(FunctionDeclaration node) { resolveMetadata(node); } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { Expression function = node.function; DartType functionType; if (function is ExtensionOverride) { var result = _extensionResolver.getOverrideMember(function, 'call'); var member = result.getter; if (member == null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVOCATION_OF_EXTENSION_WITHOUT_CALL, function, [function.extensionName.name]); functionType = _resolver.typeProvider.dynamicType; } else { if (member.isStatic) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.EXTENSION_OVERRIDE_ACCESS_TO_STATIC_MEMBER, node.argumentList); } node.staticElement = member; functionType = member.type; } } else { functionType = function.staticType; } DartType staticInvokeType = _instantiateGenericMethod(functionType, node.typeArguments, node); node.staticInvokeType = staticInvokeType; List<ParameterElement> parameters = _computeCorrespondingParameters(node, staticInvokeType); if (parameters != null) { node.argumentList.correspondingStaticParameters = parameters; } } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { resolveMetadata(node); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { _resolveMetadataForParameter(node); } @override void visitGenericTypeAlias(GenericTypeAlias node) { resolveMetadata(node); return null; } @override void visitImportDirective(ImportDirective node) { SimpleIdentifier prefixNode = node.prefix; if (prefixNode != null) { String prefixName = prefixNode.name; List<PrefixElement> prefixes = _definingLibrary.prefixes; int count = prefixes.length; for (int i = 0; i < count; i++) { PrefixElement prefixElement = prefixes[i]; if (prefixElement.displayName == prefixName) { prefixNode.staticElement = prefixElement; break; } } } ImportElement importElement = node.element; if (importElement != null) { // The element is null when the URI is invalid LibraryElement library = importElement.importedLibrary; if (library != null) { _resolveCombinators(library, node.combinators); } resolveMetadata(node); } } @override void visitIndexExpression(IndexExpression node) { Expression target = node.realTarget; DartType staticType = _getStaticType(target); String getterMethodName = TokenType.INDEX.lexeme; String setterMethodName = TokenType.INDEX_EQ.lexeme; ResolutionResult result; if (target is ExtensionOverride) { result = _extensionResolver.getOverrideMember(target, getterMethodName); } else { result = _newPropertyResolver() .resolve(target, staticType, getterMethodName, target); } bool isInGetterContext = node.inGetterContext(); bool isInSetterContext = node.inSetterContext(); if (isInGetterContext && isInSetterContext) { node.staticElement = result.setter; node.auxiliaryElements = AuxiliaryElements(result.getter, null); } else if (isInGetterContext) { node.staticElement = result.getter; } else if (isInSetterContext) { node.staticElement = result.setter; } if (isInGetterContext) { _checkForUndefinedIndexOperator( node, target, getterMethodName, result, result.getter, staticType); } if (isInSetterContext) { _checkForUndefinedIndexOperator( node, target, setterMethodName, result, result.setter, staticType); } } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { ConstructorElement invokedConstructor = node.constructorName.staticElement; node.staticElement = invokedConstructor; ArgumentList argumentList = node.argumentList; List<ParameterElement> parameters = _resolveArgumentsToFunction(argumentList, invokedConstructor); if (parameters != null) { argumentList.correspondingStaticParameters = parameters; } } @override void visitLibraryDirective(LibraryDirective node) { resolveMetadata(node); } @override void visitMethodDeclaration(MethodDeclaration node) { resolveMetadata(node); } @override void visitMethodInvocation(MethodInvocation node) { _methodInvocationResolver.resolve(node); } @override void visitMixinDeclaration(MixinDeclaration node) { resolveMetadata(node); } @override void visitPartDirective(PartDirective node) { resolveMetadata(node); } @override void visitPostfixExpression(PostfixExpression node) { Expression operand = node.operand; if (node.operator.type == TokenType.BANG) { // Null-assertion operator (`!`). There's nothing to do, since this is a // built-in operation (there's no associated operator declaration). return; } String methodName = _getPostfixOperator(node); DartType staticType = _getStaticType(operand); var result = _newPropertyResolver() .resolve(operand, staticType, methodName, operand); node.staticElement = result.getter; if (_shouldReportInvalidMember(staticType, result)) { if (operand is SuperExpression) { _recordUndefinedToken( staticType.element, StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR, node.operator, [methodName, staticType.displayName]); } else { _recordUndefinedToken( staticType.element, StaticTypeWarningCode.UNDEFINED_OPERATOR, node.operator, [methodName, staticType.displayName]); } } } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { SimpleIdentifier prefix = node.prefix; SimpleIdentifier identifier = node.identifier; // // First, check the "lib.loadLibrary" case // if (identifier.name == FunctionElement.LOAD_LIBRARY_NAME && _isDeferredPrefix(prefix)) { LibraryElement importedLibrary = _getImportedLibrary(prefix); identifier.staticElement = importedLibrary?.loadLibraryFunction; return; } // // Check to see whether the prefix is really a prefix. // Element prefixElement = prefix.staticElement; if (prefixElement is PrefixElement) { Element element = _resolver.nameScope.lookup(node, _definingLibrary); if (element == null && identifier.inSetterContext()) { Identifier setterName = new PrefixedIdentifierImpl.temp( node.prefix, new SimpleIdentifierImpl(new StringToken(TokenType.STRING, "${node.identifier.name}=", node.identifier.offset - 1))); element = _resolver.nameScope.lookup(setterName, _definingLibrary); } if (element == null && _resolver.nameScope.shouldIgnoreUndefined(node)) { return; } if (element == null) { AstNode parent = node.parent; if (parent is Annotation) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_ANNOTATION, parent, [identifier.name]); } else { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_PREFIXED_NAME, identifier, [identifier.name, prefixElement.name]); } return; } Element accessor = element; if (accessor is PropertyAccessorElement && identifier.inSetterContext()) { PropertyInducingElement variable = accessor.variable; if (variable != null) { PropertyAccessorElement setter = variable.setter; if (setter != null) { element = setter; } } } // TODO(brianwilkerson) The prefix needs to be resolved to the element for // the import that defines the prefix, not the prefix's element. identifier.staticElement = element; // Validate annotation element. AstNode parent = node.parent; if (parent is Annotation) { _resolveAnnotationElement(parent); } return; } // May be annotation, resolve invocation of "const" constructor. AstNode parent = node.parent; if (parent is Annotation) { _resolveAnnotationElement(parent); return; } // // Otherwise, the prefix is really an expression that happens to be a simple // identifier and this is really equivalent to a property access node. // _resolvePropertyAccess(prefix, identifier, false); } @override void visitPrefixExpression(PrefixExpression node) { Token operator = node.operator; TokenType operatorType = operator.type; if (operatorType.isUserDefinableOperator || operatorType == TokenType.PLUS_PLUS || operatorType == TokenType.MINUS_MINUS) { Expression operand = node.operand; String methodName = _getPrefixOperator(node); DartType staticType = _getStaticType(operand, read: true); var result = _newPropertyResolver() .resolve(operand, staticType, methodName, operand); node.staticElement = result.getter; if (_shouldReportInvalidMember(staticType, result)) { if (operand is SuperExpression) { _recordUndefinedToken( staticType.element, StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR, operator, [methodName, staticType.displayName]); } else { _recordUndefinedToken( staticType.element, StaticTypeWarningCode.UNDEFINED_OPERATOR, operator, [methodName, staticType.displayName]); } } } } @override void visitPropertyAccess(PropertyAccess node) { Expression target = node.realTarget; if (target is SuperExpression && SuperContext.of(target) != SuperContext.valid) { return; } else if (target is ExtensionOverride) { if (node.isCascaded) { // Report this error and recover by treating it like a non-cascade. _resolver.errorReporter.reportErrorForToken( CompileTimeErrorCode.EXTENSION_OVERRIDE_WITH_CASCADE, node.operator); } ExtensionElement element = target.extensionName.staticElement; SimpleIdentifier propertyName = node.propertyName; String memberName = propertyName.name; ExecutableElement member; var result = _extensionResolver.getOverrideMember(target, memberName); if (propertyName.inSetterContext()) { member = result.setter; if (member == null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_EXTENSION_SETTER, propertyName, [memberName, element.name]); } if (propertyName.inGetterContext()) { ExecutableElement getter = result.getter; if (getter == null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_EXTENSION_GETTER, propertyName, [memberName, element.name]); } propertyName.auxiliaryElements = AuxiliaryElements(getter, null); } } else if (propertyName.inGetterContext()) { member = result.getter; if (member == null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_EXTENSION_GETTER, propertyName, [memberName, element.name]); } } if (member != null && member.isStatic) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.EXTENSION_OVERRIDE_ACCESS_TO_STATIC_MEMBER, propertyName); } propertyName.staticElement = member; return; } SimpleIdentifier propertyName = node.propertyName; _resolvePropertyAccess(target, propertyName, node.isCascaded); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { ClassElement enclosingClass = _resolver.enclosingClass; if (enclosingClass == null) { // TODO(brianwilkerson) Report this error. return; } SimpleIdentifier name = node.constructorName; ConstructorElement element; if (name == null) { element = enclosingClass.unnamedConstructor; } else { element = enclosingClass.getNamedConstructor(name.name); } if (element == null) { // TODO(brianwilkerson) Report this error and decide what element to // associate with the node. return; } if (name != null) { name.staticElement = element; } node.staticElement = element; ArgumentList argumentList = node.argumentList; List<ParameterElement> parameters = _resolveArgumentsToFunction(argumentList, element); if (parameters != null) { argumentList.correspondingStaticParameters = parameters; } } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { _resolveMetadataForParameter(node); } @override void visitSimpleIdentifier(SimpleIdentifier node) { // // Synthetic identifiers have been already reported during parsing. // if (node.isSynthetic) { return; } // // Ignore nodes that should have been resolved before getting here. // if (node.inDeclarationContext()) { return; } if (node.staticElement is LocalVariableElement || node.staticElement is ParameterElement) { return; } AstNode parent = node.parent; if (parent is FieldFormalParameter) { return; } else if (parent is ConstructorFieldInitializer && parent.fieldName == node) { return; } else if (parent is Annotation && parent.constructorName == node) { return; } // // The name dynamic denotes a Type object even though dynamic is not a // class. // if (node.name == _dynamicType.name) { node.staticElement = _dynamicType.element; node.staticType = _typeType; return; } // // Otherwise, the node should be resolved. // Element element = _resolveSimpleIdentifier(node); ClassElement enclosingClass = _resolver.enclosingClass; if (_isFactoryConstructorReturnType(node) && !identical(element, enclosingClass)) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_FACTORY_NAME_NOT_A_CLASS, node); } else if (_isConstructorReturnType(node) && !identical(element, enclosingClass)) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME, node); element = null; } else if (element == null || (element is PrefixElement && !_isValidAsPrefix(node))) { // TODO(brianwilkerson) Recover from this error. if (_isConstructorReturnType(node)) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME, node); } else if (parent is Annotation) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_ANNOTATION, parent, [node.name]); } else if (element != null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT, node, [element.name]); } else if (node.name == "await" && _resolver.enclosingFunction != null) { _recordUndefinedNode( _resolver.enclosingClass, StaticWarningCode.UNDEFINED_IDENTIFIER_AWAIT, node, [_resolver.enclosingFunction.displayName]); } else if (!_resolver.nameScope.shouldIgnoreUndefined(node)) { _recordUndefinedNode(_resolver.enclosingClass, StaticWarningCode.UNDEFINED_IDENTIFIER, node, [node.name]); } } node.staticElement = element; if (node.inSetterContext() && node.inGetterContext() && enclosingClass != null) { InterfaceType enclosingType = enclosingClass.thisType; var propertyResolver = _newPropertyResolver(); propertyResolver.resolve(null, enclosingType, node.name, node); node.auxiliaryElements = AuxiliaryElements( propertyResolver.result.getter, null, ); } // // Validate annotation element. // if (parent is Annotation) { _resolveAnnotationElement(parent); } } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { ClassElementImpl enclosingClass = AbstractClassElementImpl.getImpl(_resolver.enclosingClass); if (enclosingClass == null) { // TODO(brianwilkerson) Report this error. return; } InterfaceType superType = enclosingClass.supertype; if (superType == null) { // TODO(brianwilkerson) Report this error. return; } SimpleIdentifier name = node.constructorName; String superName = name?.name; ConstructorElement element = superType.lookUpConstructor(superName, _definingLibrary); if (element == null || !element.isAccessibleIn(_definingLibrary)) { if (name != null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER, node, [superType.displayName, name]); } else { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT, node, [superType.displayName]); } return; } else { if (element.isFactory) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR, node, [element]); } } if (name != null) { name.staticElement = element; } node.staticElement = element; // TODO(brianwilkerson) Defer this check until we know there's an error (by // in-lining _resolveArgumentsToFunction below). ClassDeclaration declaration = node.thisOrAncestorOfType<ClassDeclaration>(); Identifier superclassName = declaration?.extendsClause?.superclass?.name; if (superclassName != null && _resolver.nameScope.shouldIgnoreUndefined(superclassName)) { return; } ArgumentList argumentList = node.argumentList; List<ParameterElement> parameters = _resolveArgumentsToFunction(argumentList, element); if (parameters != null) { argumentList.correspondingStaticParameters = parameters; } } @override void visitSuperExpression(SuperExpression node) { var context = SuperContext.of(node); if (context == SuperContext.static) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.SUPER_IN_INVALID_CONTEXT, node); } else if (context == SuperContext.extension) { _resolver.errorReporter .reportErrorForNode(CompileTimeErrorCode.SUPER_IN_EXTENSION, node); } super.visitSuperExpression(node); } @override void visitTypeParameter(TypeParameter node) { resolveMetadata(node); } @override void visitVariableDeclaration(VariableDeclaration node) { resolveMetadata(node); } /// If the [element] is not static, report the error on the [identifier]. void _checkForStaticAccessToInstanceMember( SimpleIdentifier identifier, ExecutableElement element, ) { if (element.isStatic) return; _resolver.errorReporter.reportErrorForNode( StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER, identifier, [identifier.name], ); } /** * Check that the given index [expression] was resolved, otherwise a * [StaticTypeWarningCode.UNDEFINED_OPERATOR] is generated. The [target] is * the target of the expression. The [methodName] is the name of the operator * associated with the context of using of the given index expression. */ void _checkForUndefinedIndexOperator( IndexExpression expression, Expression target, String methodName, ResolutionResult result, ExecutableElement element, DartType staticType) { if (result.isAmbiguous) { return; } if (element != null) { return; } if (target is! ExtensionOverride) { if (staticType == null || staticType.isDynamic) { return; } } var leftBracket = expression.leftBracket; var rightBracket = expression.rightBracket; var offset = leftBracket.offset; var length = rightBracket.end - offset; if (target is ExtensionOverride) { _resolver.errorReporter.reportErrorForOffset( CompileTimeErrorCode.UNDEFINED_EXTENSION_OPERATOR, offset, length, [methodName, target.staticElement.name], ); } else if (target is SuperExpression) { _resolver.errorReporter.reportErrorForOffset( StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR, offset, length, [methodName, staticType.displayName], ); } else if (staticType.isVoid) { _resolver.errorReporter.reportErrorForOffset( StaticWarningCode.USE_OF_VOID_RESULT, offset, length, ); } else { _resolver.errorReporter.reportErrorForOffset( StaticTypeWarningCode.UNDEFINED_OPERATOR, offset, length, [methodName, staticType.displayName], ); } } /** * Given an [argumentList] and the executable [element] that will be invoked * using those arguments, compute the list of parameters that correspond to * the list of arguments. Return the parameters that correspond to the * arguments, or `null` if no correspondence could be computed. */ List<ParameterElement> _computeCorrespondingParameters( FunctionExpressionInvocation invocation, DartType type) { ArgumentList argumentList = invocation.argumentList; if (type is InterfaceType) { MethodElement callMethod = invocation.staticElement; if (callMethod != null) { return _resolveArgumentsToFunction(argumentList, callMethod); } } else if (type is FunctionType) { return _resolveArgumentsToParameters(argumentList, type.parameters); } return null; } /** * Assuming that the given [identifier] is a prefix for a deferred import, * return the library that is being imported. */ LibraryElement _getImportedLibrary(SimpleIdentifier identifier) { PrefixElement prefixElement = identifier.staticElement as PrefixElement; List<ImportElement> imports = prefixElement.enclosingElement.getImportsWithPrefix(prefixElement); return imports[0].importedLibrary; } /** * Return the name of the method invoked by the given postfix [expression]. */ String _getPostfixOperator(PostfixExpression expression) { if (expression.operator.type == TokenType.PLUS_PLUS) { return TokenType.PLUS.lexeme; } else if (expression.operator.type == TokenType.MINUS_MINUS) { return TokenType.MINUS.lexeme; } else { throw new UnsupportedError( 'Unsupported postfix operator ${expression.operator.lexeme}'); } } /** * Return the name of the method invoked by the given postfix [expression]. */ String _getPrefixOperator(PrefixExpression expression) { Token operator = expression.operator; TokenType operatorType = operator.type; if (operatorType == TokenType.PLUS_PLUS) { return TokenType.PLUS.lexeme; } else if (operatorType == TokenType.MINUS_MINUS) { return TokenType.MINUS.lexeme; } else if (operatorType == TokenType.MINUS) { return "unary-"; } else { return operator.lexeme; } } /** * Return the static type of the given [expression] that is to be used for * type analysis. */ DartType _getStaticType(Expression expression, {bool read: false}) { if (expression is NullLiteral) { return _resolver.typeProvider.nullType; } DartType type = read ? getReadType(expression) : expression.staticType; return _resolveTypeParameter(type); } InterfaceType _instantiateAnnotationClass(ClassElement element) { return element.instantiate( typeArguments: List.filled( element.typeParameters.length, _dynamicType, ), nullabilitySuffix: _resolver.noneOrStarSuffix, ); } /** * Check for a generic method & apply type arguments if any were passed. */ DartType _instantiateGenericMethod(DartType invokeType, TypeArgumentList typeArguments, FunctionExpressionInvocation invocation) { DartType parameterizableType; List<TypeParameterElement> parameters; if (invokeType is FunctionType) { parameterizableType = invokeType; parameters = invokeType.typeFormals; } else if (invokeType is InterfaceType) { var propertyResolver = _newPropertyResolver(); propertyResolver.resolve(null, invokeType, FunctionElement.CALL_METHOD_NAME, invocation.function); ExecutableElement callMethod = propertyResolver.result.getter; invocation.staticElement = callMethod; parameterizableType = callMethod?.type; parameters = (parameterizableType as FunctionType)?.typeFormals; } if (parameterizableType is ParameterizedType) { NodeList<TypeAnnotation> arguments = typeArguments?.arguments; if (arguments != null && arguments.length != parameters.length) { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS_METHOD, invocation, [parameterizableType, parameters.length, arguments?.length ?? 0]); // Wrong number of type arguments. Ignore them. arguments = null; } if (parameters.isNotEmpty) { if (arguments == null) { return _resolver.typeSystem.instantiateToBounds(parameterizableType); } else { return parameterizableType .instantiate(arguments.map((n) => n.type).toList()); } } return parameterizableType; } return invokeType; } /** * Return `true` if the given [expression] is a prefix for a deferred import. */ bool _isDeferredPrefix(Expression expression) { if (expression is SimpleIdentifier) { Element element = expression.staticElement; if (element is PrefixElement) { List<ImportElement> imports = element.enclosingElement.getImportsWithPrefix(element); if (imports.length != 1) { return false; } return imports[0].isDeferred; } } return false; } /** * Return `true` if the given [node] can validly be resolved to a prefix: * * it is the prefix in an import directive, or * * it is the prefix in a prefixed identifier. */ bool _isValidAsPrefix(SimpleIdentifier node) { AstNode parent = node.parent; if (parent is ImportDirective) { return identical(parent.prefix, node); } else if (parent is PrefixedIdentifier) { return true; } else if (parent is MethodInvocation) { return identical(parent.target, node) && parent.operator?.type == TokenType.PERIOD; } return false; } /** * Return the target of a break or continue statement, and update the static * element of its label (if any). The [parentNode] is the AST node of the * break or continue statement. The [labelNode] is the label contained in that * statement (if any). The flag [isContinue] is `true` if the node being * visited is a continue statement. */ AstNode _lookupBreakOrContinueTarget( AstNode parentNode, SimpleIdentifier labelNode, bool isContinue) { if (labelNode == null) { return _resolver.implicitLabelScope.getTarget(isContinue); } else { LabelScope labelScope = _resolver.labelScope; if (labelScope == null) { // There are no labels in scope, so by definition the label is // undefined. _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.LABEL_UNDEFINED, labelNode, [labelNode.name]); return null; } LabelScope definingScope = labelScope.lookup(labelNode.name); if (definingScope == null) { // No definition of the given label name could be found in any // enclosing scope. _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.LABEL_UNDEFINED, labelNode, [labelNode.name]); return null; } // The target has been found. labelNode.staticElement = definingScope.element; ExecutableElement labelContainer = definingScope.element .getAncestor((element) => element is ExecutableElement); if (!identical(labelContainer, _resolver.enclosingFunction)) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.LABEL_IN_OUTER_SCOPE, labelNode, [labelNode.name]); } return definingScope.node; } } _PropertyResolver _newPropertyResolver() { return _PropertyResolver(_resolver.typeProvider, _inheritance, _definingLibrary, _extensionResolver); } /** * Record that the given [node] is undefined, causing an error to be reported * if appropriate. The [declaringElement] is the element inside which no * declaration was found. If this element is a proxy, no error will be * reported. If null, then an error will always be reported. The [errorCode] * is the error code to report. The [arguments] are the arguments to the error * message. */ void _recordUndefinedNode(Element declaringElement, ErrorCode errorCode, AstNode node, List<Object> arguments) { _resolver.errorReporter.reportErrorForNode(errorCode, node, arguments); } /** * Record that the given [token] is undefined, causing an error to be reported * if appropriate. The [declaringElement] is the element inside which no * declaration was found. If this element is a proxy, no error will be * reported. If null, then an error will always be reported. The [errorCode] * is the error code to report. The [arguments] are arguments to the error * message. */ void _recordUndefinedToken(Element declaringElement, ErrorCode errorCode, Token token, List<Object> arguments) { _resolver.errorReporter.reportErrorForToken(errorCode, token, arguments); } void _resolveAnnotationConstructorInvocationArguments( Annotation annotation, ConstructorElement constructor) { ArgumentList argumentList = annotation.arguments; // error will be reported in ConstantVerifier if (argumentList == null) { return; } // resolve arguments to parameters List<ParameterElement> parameters = _resolveArgumentsToFunction(argumentList, constructor); if (parameters != null) { argumentList.correspondingStaticParameters = parameters; } } /** * Continues resolution of the given [annotation]. */ void _resolveAnnotationElement(Annotation annotation) { SimpleIdentifier nameNode1; SimpleIdentifier nameNode2; { Identifier annName = annotation.name; if (annName is PrefixedIdentifier) { nameNode1 = annName.prefix; nameNode2 = annName.identifier; } else { nameNode1 = annName as SimpleIdentifier; nameNode2 = null; } } SimpleIdentifier nameNode3 = annotation.constructorName; ConstructorElement constructor; bool undefined = false; // // CONST or Class(args) // if (nameNode1 != null && nameNode2 == null && nameNode3 == null) { Element element1 = nameNode1.staticElement; // CONST if (element1 is PropertyAccessorElement) { _resolveAnnotationElementGetter(annotation, element1); return; } // Class(args) if (element1 is ClassElement) { constructor = _instantiateAnnotationClass(element1) .lookUpConstructor(null, _definingLibrary); } else if (element1 == null) { undefined = true; } } // // prefix.CONST or prefix.Class() or Class.CONST or Class.constructor(args) // if (nameNode1 != null && nameNode2 != null && nameNode3 == null) { Element element1 = nameNode1.staticElement; Element element2 = nameNode2.staticElement; // Class.CONST - not resolved yet if (element1 is ClassElement) { element2 = element1.lookUpGetter(nameNode2.name, _definingLibrary); } // prefix.CONST or Class.CONST if (element2 is PropertyAccessorElement) { nameNode2.staticElement = element2; annotation.element = element2; _resolveAnnotationElementGetter(annotation, element2); return; } // prefix.Class() if (element2 is ClassElement) { constructor = element2.unnamedConstructor; } // Class.constructor(args) if (element1 is ClassElement) { constructor = _instantiateAnnotationClass(element1) .lookUpConstructor(nameNode2.name, _definingLibrary); nameNode2.staticElement = constructor; } if (element1 == null && element2 == null) { undefined = true; } } // // prefix.Class.CONST or prefix.Class.constructor(args) // if (nameNode1 != null && nameNode2 != null && nameNode3 != null) { Element element2 = nameNode2.staticElement; // element2 should be ClassElement if (element2 is ClassElement) { String name3 = nameNode3.name; // prefix.Class.CONST PropertyAccessorElement getter = element2.lookUpGetter(name3, _definingLibrary); if (getter != null) { nameNode3.staticElement = getter; annotation.element = getter; _resolveAnnotationElementGetter(annotation, getter); return; } // prefix.Class.constructor(args) constructor = _instantiateAnnotationClass(element2) .lookUpConstructor(name3, _definingLibrary); nameNode3.staticElement = constructor; } else if (element2 == null) { undefined = true; } } // we need constructor if (constructor == null) { if (!undefined) { // If the class was not found then we've already reported the error. _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_ANNOTATION, annotation); } return; } // record element annotation.element = constructor; // resolve arguments _resolveAnnotationConstructorInvocationArguments(annotation, constructor); } void _resolveAnnotationElementGetter( Annotation annotation, PropertyAccessorElement accessorElement) { // accessor should be synthetic if (!accessorElement.isSynthetic) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_ANNOTATION_GETTER, annotation); return; } // variable should be constant VariableElement variableElement = accessorElement.variable; if (!variableElement.isConst) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_ANNOTATION, annotation); return; } // no arguments if (annotation.arguments != null) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.ANNOTATION_WITH_NON_CLASS, annotation.name, [annotation.name]); } // OK return; } /** * Given an [argumentList] and the [executableElement] that will be invoked * using those argument, compute the list of parameters that correspond to the * list of arguments. An error will be reported if any of the arguments cannot * be matched to a parameter. Return the parameters that correspond to the * arguments, or `null` if no correspondence could be computed. */ List<ParameterElement> _resolveArgumentsToFunction( ArgumentList argumentList, ExecutableElement executableElement) { if (executableElement == null) { return null; } List<ParameterElement> parameters = executableElement.parameters; return _resolveArgumentsToParameters(argumentList, parameters); } /** * Given an [argumentList] and the [parameters] related to the element that * will be invoked using those arguments, compute the list of parameters that * correspond to the list of arguments. An error will be reported if any of * the arguments cannot be matched to a parameter. Return the parameters that * correspond to the arguments. */ List<ParameterElement> _resolveArgumentsToParameters( ArgumentList argumentList, List<ParameterElement> parameters) { return ResolverVisitor.resolveArgumentsToParameters( argumentList, parameters, _resolver.errorReporter.reportErrorForNode); } void _resolveBinaryExpression(BinaryExpression node, String methodName) { Expression leftOperand = node.leftOperand; if (leftOperand != null) { if (leftOperand is ExtensionOverride) { ExtensionElement element = leftOperand.extensionName.staticElement; MethodElement member = element.getMethod(methodName); if (member == null) { _resolver.errorReporter.reportErrorForToken( CompileTimeErrorCode.UNDEFINED_EXTENSION_OPERATOR, node.operator, [methodName, element.name]); } node.staticElement = member; return; } DartType leftType = _getStaticType(leftOperand); ResolutionResult result = _newPropertyResolver() .resolve(leftOperand, leftType, methodName, node); node.staticElement = result.getter; node.staticInvokeType = result.getter?.type; if (_shouldReportInvalidMember(leftType, result)) { if (leftOperand is SuperExpression) { _recordUndefinedToken( leftType.element, StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR, node.operator, [methodName, leftType.displayName]); } else { _recordUndefinedToken( leftType.element, StaticTypeWarningCode.UNDEFINED_OPERATOR, node.operator, [methodName, leftType.displayName]); } } } } /** * Resolve the names in the given [combinators] in the scope of the given * [library]. */ void _resolveCombinators( LibraryElement library, NodeList<Combinator> combinators) { if (library == null) { // // The library will be null if the directive containing the combinators // has a URI that is not valid. // return; } Namespace namespace = new NamespaceBuilder().createExportNamespaceForLibrary(library); for (Combinator combinator in combinators) { NodeList<SimpleIdentifier> names; if (combinator is HideCombinator) { names = combinator.hiddenNames; } else { names = (combinator as ShowCombinator).shownNames; } for (SimpleIdentifier name in names) { String nameStr = name.name; Element element = namespace.get(nameStr) ?? namespace.get("$nameStr="); if (element != null) { // Ensure that the name always resolves to a top-level variable // rather than a getter or setter if (element is PropertyAccessorElement) { name.staticElement = element.variable; } else { name.staticElement = element; } } } } } /** * Given a [node] that can have annotations associated with it, resolve the * annotations in the element model representing annotations to the node. */ void _resolveMetadataForParameter(NormalFormalParameter node) { _resolveAnnotations(node.metadata); } void _resolvePropertyAccess( Expression target, SimpleIdentifier propertyName, bool isCascaded) { DartType staticType = _getStaticType(target); // // If this property access is of the form 'E.m' where 'E' is an extension, // then look for the member in the extension. This does not apply to // conditional property accesses (i.e. 'C?.m'). // if (target is Identifier && target.staticElement is ExtensionElement) { ExtensionElement extension = target.staticElement; String memberName = propertyName.name; if (propertyName.inGetterContext()) { ExecutableElement element; element ??= extension.getGetter(memberName); element ??= extension.getMethod(memberName); if (element != null) { propertyName.staticElement = element; _checkForStaticAccessToInstanceMember(propertyName, element); } else { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_EXTENSION_GETTER, propertyName, [memberName, extension.name], ); } } if (propertyName.inSetterContext()) { var element = extension.getSetter(memberName); if (element != null) { propertyName.staticElement = element; _checkForStaticAccessToInstanceMember(propertyName, element); } else { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_EXTENSION_SETTER, propertyName, [memberName, extension.name], ); } } return; } // // If this property access is of the form 'C.m' where 'C' is a class, // then we don't call resolveProperty(...) which walks up the class // hierarchy, instead we just look for the member in the type only. This // does not apply to conditional property accesses (i.e. 'C?.m'). // ClassElement typeReference = getTypeReference(target); if (typeReference != null) { if (isCascaded) { typeReference = _typeType.element; } if (propertyName.inGetterContext()) { ExecutableElement element; if (element == null) { var getter = typeReference.getGetter(propertyName.name); if (getter != null && getter.isAccessibleIn(_definingLibrary)) { element = getter; } } if (element == null) { var method = typeReference.getMethod(propertyName.name); if (method != null && method.isAccessibleIn(_definingLibrary)) { element = method; } } if (element != null) { propertyName.staticElement = element; _checkForStaticAccessToInstanceMember(propertyName, element); } else { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_GETTER, propertyName, [propertyName.name, typeReference.name], ); } } if (propertyName.inSetterContext()) { ExecutableElement element; var setter = typeReference.getSetter(propertyName.name); if (setter != null && setter.isAccessibleIn(_definingLibrary)) { element = setter; } if (element != null) { propertyName.staticElement = element; _checkForStaticAccessToInstanceMember(propertyName, element); } else { var getter = typeReference.getGetter(propertyName.name); if (getter != null) { propertyName.staticElement = getter; // The error will be reported in ErrorVerifier. } else { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_SETTER, propertyName, [propertyName.name, typeReference.name], ); } } } return; } if (target is SuperExpression) { if (staticType is InterfaceTypeImpl) { if (propertyName.inGetterContext()) { var element = staticType.lookUpInheritedMember( propertyName.name, _definingLibrary, setter: false, concrete: true, forSuperInvocation: true); if (element != null) { propertyName.staticElement = element; } else { // We were not able to find the concrete dispatch target. // But we would like to give the user at least some resolution. // So, we retry without the "concrete" requirement. element = staticType.lookUpInheritedMember( propertyName.name, _definingLibrary, setter: false, concrete: false); if (element != null) { propertyName.staticElement = element; ClassElementImpl receiverSuperClass = AbstractClassElementImpl.getImpl( staticType.element.supertype.element, ); if (!receiverSuperClass.hasNoSuchMethod) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.ABSTRACT_SUPER_MEMBER_REFERENCE, propertyName, [element.kind.displayName, propertyName.name], ); } } else { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_SUPER_GETTER, propertyName, [propertyName.name, staticType.displayName], ); } } } if (propertyName.inSetterContext()) { var element = staticType.lookUpInheritedMember( propertyName.name, _definingLibrary, setter: true, concrete: true, forSuperInvocation: true); if (element != null) { propertyName.staticElement = element; } else { // We were not able to find the concrete dispatch target. // But we would like to give the user at least some resolution. // So, we retry without the "concrete" requirement. element = staticType.lookUpInheritedMember( propertyName.name, _definingLibrary, setter: true, concrete: false); if (element != null) { propertyName.staticElement = element; ClassElementImpl receiverSuperClass = AbstractClassElementImpl.getImpl( staticType.element.supertype.element, ); if (!receiverSuperClass.hasNoSuchMethod) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.ABSTRACT_SUPER_MEMBER_REFERENCE, propertyName, [element.kind.displayName, propertyName.name], ); } } else { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_SUPER_SETTER, propertyName, [propertyName.name, staticType.displayName], ); } } } } return; } if (staticType == null || staticType.isDynamic) { return; } if (staticType.isVoid) { _resolver.errorReporter.reportErrorForNode( StaticWarningCode.USE_OF_VOID_RESULT, propertyName, ); return; } var result = _newPropertyResolver() .resolve(target, staticType, propertyName.name, propertyName); if (propertyName.inGetterContext()) { var shouldReportUndefinedGetter = false; if (result.isSingle) { var getter = result.getter; if (getter != null) { propertyName.staticElement = getter; } else { shouldReportUndefinedGetter = true; } } else if (result.isNone) { if (staticType is FunctionType && propertyName.name == FunctionElement.CALL_METHOD_NAME) { // Referencing `.call` on a `Function` type is OK. } else if (staticType is InterfaceType && staticType.isDartCoreFunction && propertyName.name == FunctionElement.CALL_METHOD_NAME) { // Referencing `.call` on a `Function` type is OK. } else { shouldReportUndefinedGetter = true; } } if (shouldReportUndefinedGetter) { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_GETTER, propertyName, [propertyName.name, staticType.displayName], ); } } if (propertyName.inSetterContext()) { if (result.isSingle) { var setter = result.setter; if (setter != null) { propertyName.staticElement = setter; } else { var getter = result.getter; propertyName.staticElement = getter; // A more specific error will be reported in ErrorVerifier. } } else if (result.isNone) { _resolver.errorReporter.reportErrorForNode( StaticTypeWarningCode.UNDEFINED_SETTER, propertyName, [propertyName.name, staticType.displayName], ); } } } /** * Resolve the given simple [identifier] if possible. Return the element to * which it could be resolved, or `null` if it could not be resolved. This * does not record the results of the resolution. */ Element _resolveSimpleIdentifier(SimpleIdentifier identifier) { Element element = _resolver.nameScope.lookup(identifier, _definingLibrary); if (element is PropertyAccessorElement && identifier.inSetterContext()) { PropertyInducingElement variable = (element as PropertyAccessorElement).variable; if (variable != null) { PropertyAccessorElement setter = variable.setter; if (setter == null) { // // Check to see whether there might be a locally defined getter and // an inherited setter. // ClassElement enclosingClass = _resolver.enclosingClass; if (enclosingClass != null) { var propertyResolver = _newPropertyResolver(); propertyResolver.resolve( null, enclosingClass.thisType, identifier.name, identifier); setter = propertyResolver.result.setter; } } if (setter != null) { element = setter; } } } else if (element == null && (identifier.inSetterContext() || identifier.parent is CommentReference)) { Identifier setterId = new SyntheticIdentifier('${identifier.name}=', identifier); element = _resolver.nameScope.lookup(setterId, _definingLibrary); } if (element == null) { InterfaceType enclosingType; ClassElement enclosingClass = _resolver.enclosingClass; if (enclosingClass == null) { var enclosingExtension = _resolver.enclosingExtension; if (enclosingExtension == null) { return null; } DartType extendedType = _resolveTypeParameter(enclosingExtension.extendedType); if (extendedType is InterfaceType) { enclosingType = extendedType; } else if (extendedType is FunctionType) { enclosingType = _resolver.typeProvider.functionType; } else { return null; } } else { enclosingType = enclosingClass.thisType; } if (element == null && enclosingType != null) { var propertyResolver = _newPropertyResolver(); propertyResolver.resolve( null, enclosingType, identifier.name, identifier); if (identifier.inSetterContext() || identifier.parent is CommentReference) { element = propertyResolver.result.setter; } element ??= propertyResolver.result.getter; } } return element; } /** * If the given [type] is a type parameter, resolve it to the type that should * be used when looking up members. Otherwise, return the original type. */ DartType _resolveTypeParameter(DartType type) => type?.resolveToBound(_resolver.typeProvider.objectType); /** * Return `true` if we should report an error for a [member] lookup that found * no match on the given [type]. */ bool _shouldReportInvalidMember(DartType type, ResolutionResult result) => type != null && !type.isDynamic && result.isNone; /** * Checks whether the given [expression] is a reference to a class. If it is * then the element representing the class is returned, otherwise `null` is * returned. */ static ClassElement getTypeReference(Expression expression) { if (expression is Identifier) { Element staticElement = expression.staticElement; if (staticElement is ClassElement) { return staticElement; } } return null; } /** * Given a [node] that can have annotations associated with it, resolve the * annotations in the element model representing the annotations on the node. */ static void resolveMetadata(AnnotatedNode node) { _resolveAnnotations(node.metadata); if (node is VariableDeclaration) { AstNode parent = node.parent; if (parent is VariableDeclarationList) { _resolveAnnotations(parent.metadata); AstNode grandParent = parent.parent; if (grandParent is FieldDeclaration) { _resolveAnnotations(grandParent.metadata); } else if (grandParent is TopLevelVariableDeclaration) { _resolveAnnotations(grandParent.metadata); } } } } /** * Return `true` if the given [identifier] is the return type of a constructor * declaration. */ static bool _isConstructorReturnType(SimpleIdentifier identifier) { AstNode parent = identifier.parent; if (parent is ConstructorDeclaration) { return identical(parent.returnType, identifier); } return false; } /** * Return `true` if the given [identifier] is the return type of a factory * constructor. */ static bool _isFactoryConstructorReturnType(SimpleIdentifier identifier) { AstNode parent = identifier.parent; if (parent is ConstructorDeclaration) { return identical(parent.returnType, identifier) && parent.factoryKeyword != null; } return false; } /** * Resolve each of the annotations in the given list of [annotations]. */ static void _resolveAnnotations(NodeList<Annotation> annotations) { for (Annotation annotation in annotations) { ElementAnnotationImpl elementAnnotation = annotation.elementAnnotation; elementAnnotation.element = annotation.element; } } } /** * An identifier that can be used to look up names in the lexical scope when * there is no identifier in the AST structure. There is no identifier in the * AST when the parser could not distinguish between a method invocation and an * invocation of a top-level function imported with a prefix. */ class SyntheticIdentifier extends IdentifierImpl { /** * The name of the synthetic identifier. */ @override final String name; /** * The identifier to be highlighted in case of an error */ final Identifier targetIdentifier; /** * Initialize a newly created synthetic identifier to have the given [name] * and [targetIdentifier]. */ SyntheticIdentifier(this.name, this.targetIdentifier); @override Token get beginToken => null; @override Element get bestElement => null; @override Iterable<SyntacticEntity> get childEntities { // Should never be called, since a SyntheticIdentifier never appears in the // AST--it is just used for lookup. assert(false); return new ChildEntities(); } @override Token get endToken => null; @override int get length => targetIdentifier.length; @override int get offset => targetIdentifier.offset; @override Precedence get precedence => Precedence.primary; @deprecated @override Element get propagatedElement => null; @override Element get staticElement => null; @override E accept<E>(AstVisitor<E> visitor) => null; @override void visitChildren(AstVisitor visitor) {} } /// Helper for resolving properties (getters, setters, or methods). class _PropertyResolver { final TypeProvider _typeProvider; final InheritanceManager3 _inheritance; final LibraryElement _definingLibrary; final ExtensionMemberResolver _extensionResolver; ResolutionResult result = ResolutionResult.none; _PropertyResolver( this._typeProvider, this._inheritance, this._definingLibrary, this._extensionResolver, ); /// Look up the getter and the setter with the given [name] in the [type]. /// /// The [target] is optional, and used to identify `super`. /// /// The [errorNode] is used to report the ambiguous extension issue. ResolutionResult resolve( Expression target, DartType type, String name, Expression errorNode, ) { type = _resolveTypeParameter(type); ExecutableElement typeGetter; ExecutableElement typeSetter; void lookupIn(InterfaceType type) { var isSuper = target is SuperExpression; if (name == '[]') { typeGetter = type.lookUpInheritedMethod('[]', library: _definingLibrary, thisType: !isSuper); typeSetter = type.lookUpInheritedMethod('[]=', library: _definingLibrary, thisType: !isSuper); } else { typeGetter = type.lookUpInheritedGetter(name, library: _definingLibrary, thisType: !isSuper); typeGetter ??= type.lookUpInheritedMethod(name, library: _definingLibrary, thisType: !isSuper); typeSetter = type.lookUpInheritedSetter(name, library: _definingLibrary, thisType: !isSuper); } } if (type is InterfaceType) { lookupIn(type); } else if (type is FunctionType) { lookupIn(_typeProvider.functionType); } else { return ResolutionResult.none; } if (typeGetter != null || typeSetter != null) { result = ResolutionResult(getter: typeGetter, setter: typeSetter); } if (result.isNone) { result = _extensionResolver.findExtension(type, name, errorNode); } return result; } /// If the given [type] is a type parameter, replace it with its bound. /// Otherwise, return the original type. DartType _resolveTypeParameter(DartType type) { return type?.resolveToBound(_typeProvider.objectType); } }
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_dart.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' show AnnotatedNode, Comment; import 'package:analyzer/dart/ast/token.dart' show Token; import 'package:analyzer/src/dart/element/element.dart' show ElementImpl; export 'package:front_end/src/base/resolve_relative_uri.dart' show resolveRelativeUri; /** * If the given [node] has a documentation comment, remember its content * and range into the given [element]. */ void setElementDocumentationComment(ElementImpl element, AnnotatedNode node) { Comment comment = node.documentationComment; if (comment != null && comment.isDocumentation) { element.documentationComment = comment.tokens.map((Token t) => t.lexeme).join('\n'); } } /** * Check whether [uri1] starts with (or 'is prefixed by') [uri2] by checking * path segments. */ bool startsWith(Uri uri1, Uri uri2) { List<String> uri1Segments = uri1.pathSegments; List<String> uri2Segments = uri2.pathSegments.toList(); // Punt if empty (https://github.com/dart-lang/sdk/issues/24126) if (uri2Segments.isEmpty) { return false; } // Trim trailing empty segments ('/foo/' => ['foo', '']) if (uri2Segments.last == '') { uri2Segments.removeLast(); } if (uri2Segments.length > uri1Segments.length) { return false; } for (int i = 0; i < uri2Segments.length; ++i) { if (uri2Segments[i] != uri1Segments[i]) { return false; } } return true; } /** * The kind of a parameter. A parameter can be either positional or named, and * can be either required or optional. */ class ParameterKind implements Comparable<ParameterKind> { /// A positional required parameter. static const ParameterKind REQUIRED = const ParameterKind('REQUIRED', 0, false, false); /// A positional optional parameter. static const ParameterKind POSITIONAL = const ParameterKind('POSITIONAL', 1, false, true); /// A named required parameter. static const ParameterKind NAMED_REQUIRED = const ParameterKind('NAMED_REQUIRED', 2, true, false); /// A named optional parameter. static const ParameterKind NAMED = const ParameterKind('NAMED', 2, true, true); static const List<ParameterKind> values = const [ REQUIRED, POSITIONAL, NAMED_REQUIRED, NAMED ]; /** * The name of this parameter. */ final String name; /** * The ordinal value of the parameter. */ final int ordinal; /** * A flag indicating whether this is a named or positional parameter. */ final bool isNamed; /** * A flag indicating whether this is an optional or required parameter. */ final bool isOptional; /** * Initialize a newly created kind with the given state. */ const ParameterKind(this.name, this.ordinal, this.isNamed, this.isOptional); @override int get hashCode => ordinal; @override int compareTo(ParameterKind other) => ordinal - other.ordinal; @override String toString() => 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/generated/sdk_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. @deprecated library analyzer.src.generated.sdk_io; import 'dart:collection'; import 'package:analyzer/exception/exception.dart'; import 'package:analyzer/src/context/context.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/java_io.dart'; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source_io.dart'; import 'package:analyzer/src/summary/idl.dart' show PackageBundle; /** * An abstract implementation of a Dart SDK in which the available libraries are * stored in a library map. Subclasses are responsible for populating the * library map. */ @deprecated abstract class AbstractDartSdk implements DartSdk { /** * A mapping from Dart library URI's to the library represented by that URI. */ LibraryMap libraryMap = new LibraryMap(); /** * The [AnalysisOptions] to use to create the [context]. */ AnalysisOptions _analysisOptions; /** * The flag that specifies whether an SDK summary should be used. This is a * temporary flag until summaries are enabled by default. */ bool _useSummary = false; /** * The [AnalysisContext] which is used for all of the sources in this SDK. */ InternalAnalysisContext _analysisContext; /** * The mapping from Dart URI's to the corresponding sources. */ Map<String, Source> _uriToSourceMap = new HashMap<String, Source>(); /** * Set the [options] for this SDK analysis context. Throw [StateError] if the * context has been already created. */ void set analysisOptions(AnalysisOptions options) { if (_analysisContext != null) { throw new StateError( 'Analysis options cannot be changed after context creation.'); } _analysisOptions = options; } @override AnalysisContext get context { if (_analysisContext == null) { _analysisContext = new SdkAnalysisContext(_analysisOptions); SourceFactory factory = new SourceFactory([new DartUriResolver(this)]); _analysisContext.sourceFactory = factory; } return _analysisContext; } @override List<SdkLibrary> get sdkLibraries => libraryMap.sdkLibraries; @override List<String> get uris => libraryMap.uris; /** * Return `true` if the SDK summary will be used when available. */ bool get useSummary => _useSummary; /** * Specify whether SDK summary should be used. */ void set useSummary(bool use) { if (_analysisContext != null) { throw new StateError( 'The "useSummary" flag cannot be changed after context creation.'); } _useSummary = use; } /** * Add the extensions from one or more sdk extension files to this sdk. The * [extensions] should be a table mapping the names of extensions to the paths * where those extensions can be found. */ void addExtensions(Map<String, String> extensions) { extensions.forEach((String uri, String path) { String shortName = uri.substring(uri.indexOf(':') + 1); SdkLibraryImpl library = new SdkLibraryImpl(shortName); library.path = path; libraryMap.setLibrary(uri, library); }); } @override Source fromFileUri(Uri uri) { JavaFile file = new JavaFile.fromUri(uri); String path = _getPath(file); if (path == null) { return null; } try { return new FileBasedSource(file, Uri.parse(path)); } on FormatException catch (exception, stackTrace) { AnalysisEngine.instance.logger.logInformation( "Failed to create URI: $path", new CaughtException(exception, stackTrace)); } return null; } String getRelativePathFromFile(JavaFile file); @override SdkLibrary getSdkLibrary(String dartUri) => libraryMap.getLibrary(dartUri); /** * Return the [PackageBundle] for this SDK, if it exists, or `null` otherwise. * This method should not be used outside of `analyzer` and `analyzer_cli` * packages. */ @deprecated PackageBundle getSummarySdkBundle(bool _); FileBasedSource internalMapDartUri(String dartUri) { // TODO(brianwilkerson) Figure out how to unify the implementations in the // two subclasses. String libraryName; String relativePath; int index = dartUri.indexOf('/'); if (index >= 0) { libraryName = dartUri.substring(0, index); relativePath = dartUri.substring(index + 1); } else { libraryName = dartUri; relativePath = ""; } SdkLibrary library = getSdkLibrary(libraryName); if (library == null) { return null; } String srcPath; if (relativePath.isEmpty) { srcPath = library.path; } else { String libraryPath = library.path; int index = libraryPath.lastIndexOf(JavaFile.separator); if (index == -1) { index = libraryPath.lastIndexOf('/'); if (index == -1) { return null; } } String prefix = libraryPath.substring(0, index + 1); srcPath = '$prefix$relativePath'; } String filePath = srcPath.replaceAll('/', JavaFile.separator); try { JavaFile file = new JavaFile(filePath); return new FileBasedSource(file, Uri.parse(dartUri)); } on FormatException { return null; } } @override Source mapDartUri(String dartUri) { Source source = _uriToSourceMap[dartUri]; if (source == null) { source = internalMapDartUri(dartUri); _uriToSourceMap[dartUri] = source; } return source; } String _getPath(JavaFile file) { List<SdkLibrary> libraries = libraryMap.sdkLibraries; int length = libraries.length; List<String> paths = new List(length); String filePath = getRelativePathFromFile(file); if (filePath == null) { return null; } for (int i = 0; i < length; i++) { SdkLibrary library = libraries[i]; String libraryPath = library.path.replaceAll('/', JavaFile.separator); if (filePath == libraryPath) { return library.shortName; } paths[i] = libraryPath; } for (int i = 0; i < length; i++) { SdkLibrary library = libraries[i]; String libraryPath = paths[i]; int index = libraryPath.lastIndexOf(JavaFile.separator); if (index >= 0) { String prefix = libraryPath.substring(0, index + 1); if (filePath.startsWith(prefix)) { String relPath = filePath .substring(prefix.length) .replaceAll(JavaFile.separator, '/'); return '${library.shortName}/$relPath'; } } } return 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/type_system.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 'dart:math' as math; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart' show AstNode, ConstructorName; import 'package:analyzer/dart/ast/token.dart' show Keyword, TokenType; 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/type_system.dart' as public; import 'package:analyzer/error/listener.dart' show ErrorReporter; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/member.dart' show TypeParameterMember; 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 HintCode, StrongModeCode; import 'package:analyzer/src/generated/engine.dart' show AnalysisContext, AnalysisOptionsImpl; import 'package:analyzer/src/generated/resolver.dart' show TypeProvider; import 'package:analyzer/src/generated/utilities_dart.dart' show ParameterKind; import 'package:meta/meta.dart'; /** * `void`, `dynamic`, and `Object` are all equivalent. However, this makes * LUB/GLB indeterministic. Therefore, for the cases of LUB/GLB, we have some * types which are more top than others. * * So, `void` < `Object` < `dynamic` for the purposes of LUB and GLB. * * This is expressed by their topiness (higher = more toppy). */ int _getTopiness(DartType t) { // TODO(mfairhurst): switch legacy Top checks to true Top checks assert(_isLegacyTop(t, orTrueTop: true), 'only Top types have a topiness'); // Highest top if (t.isVoid) return 3; if (t.isDynamic) return 2; if (t.isObject) return 1; if (t.isDartAsyncFutureOr) return -3 + _getTopiness((t as InterfaceType).typeArguments[0]); // Lowest top assert(false, 'a Top type without a defined topiness'); // Try to ensure that if this happens, its less toppy than an actual Top type. return -100000; } bool _isBottom(DartType t) { return (t.isBottom && (t as TypeImpl).nullabilitySuffix != NullabilitySuffix.question) || identical(t, UnknownInferredType.instance); } /// Is [t] the bottom of the legacy type hierarchy. bool _isLegacyBottom(DartType t, {@required bool orTrueBottom}) { return (t.isBottom && (t as TypeImpl).nullabilitySuffix == NullabilitySuffix.question) || t.isDartCoreNull || (orTrueBottom ? _isBottom(t) : false); } /// Is [t] the top of the legacy type hierarch. bool _isLegacyTop(DartType t, {@required bool orTrueTop}) { if (t.isDartAsyncFutureOr) { return _isLegacyTop((t as InterfaceType).typeArguments[0], orTrueTop: orTrueTop); } if (t.isObject && (t as TypeImpl).nullabilitySuffix == NullabilitySuffix.none) { return true; } return orTrueTop ? _isTop(t) : false; } bool _isTop(DartType t) { if (t.isDartAsyncFutureOr) { return _isTop((t as InterfaceType).typeArguments[0]); } return t.isDynamic || (t.isObject && (t as TypeImpl).nullabilitySuffix != NullabilitySuffix.none) || t.isVoid || identical(t, UnknownInferredType.instance); } /** * A type system that implements the type semantics for Dart 2.0. */ class Dart2TypeSystem extends TypeSystem { /// Track types currently being compared via type parameter bounds so that we /// can detect recursion. static Set<TypeComparison> _typeParameterBoundsComparisons = new HashSet<TypeComparison>(); /** * False if implicit casts should always be disallowed, otherwise the * [FeatureSet] will be used. * * This affects the behavior of [isAssignableTo]. */ final bool implicitCasts; /// A flag indicating whether inference failures are allowed, off by default. /// /// This option is experimental and subject to change. final bool strictInference; final TypeProvider typeProvider; Dart2TypeSystem(this.typeProvider, {this.implicitCasts: true, this.strictInference: false}); /// Returns true iff the type [t] accepts function types, and requires an /// implicit coercion if interface types with a `call` method are passed in. /// /// This is true for: /// - all function types /// - the special type `Function` that is a supertype of all function types /// - `FutureOr<T>` where T is one of the two cases above. /// /// Note that this returns false if [t] is a top type such as Object. bool acceptsFunctionType(DartType t) { if (t == null) return false; if (t.isDartAsyncFutureOr) { return acceptsFunctionType((t as InterfaceType).typeArguments[0]); } return t is FunctionType || t.isDartCoreFunction; } bool anyParameterType(FunctionType ft, bool predicate(DartType t)) { return ft.parameters.any((p) => predicate(p.type)); } /// Given a type t, if t is an interface type with a call method /// defined, return the function type for the call method, otherwise /// return null. FunctionType getCallMethodType(DartType t) { if (t is InterfaceType) { return t.lookUpInheritedMethod("call")?.type; } return null; } /// Computes the greatest lower bound of [type1] and [type2]. DartType getGreatestLowerBound(DartType type1, DartType type2) { // The greatest lower bound relation is reflexive. if (identical(type1, type2)) { return type1; } // For any type T, GLB(?, T) == T. if (identical(type1, UnknownInferredType.instance)) { return type2; } if (identical(type2, UnknownInferredType.instance)) { return type1; } // For the purpose of GLB, we say some Tops are subtypes (less toppy) than // the others. Return the least toppy. // TODO(mfairhurst): switch legacy Top checks to true Top checks if (_isLegacyTop(type1, orTrueTop: true) && _isLegacyTop(type2, orTrueTop: true)) { return _getTopiness(type1) < _getTopiness(type2) ? type1 : type2; } // The GLB of top and any type is just that type. // Also GLB of bottom and any type is bottom. // TODO(mfairhurst): switch legacy Top checks to true Top checks // TODO(mfairhurst): switch legacy Bottom checks to true Bottom checks. if (_isLegacyTop(type1, orTrueTop: true) || _isLegacyBottom(type2, orTrueBottom: true)) { return type2; } // TODO(mfairhurst): switch legacy Bottom checks to true Bottom checks if (_isLegacyTop(type2, orTrueTop: true) || _isLegacyBottom(type1, orTrueBottom: true)) { return type1; } // Function types have structural GLB. if (type1 is FunctionType && type2 is FunctionType) { return _functionGreatestLowerBound(type1, type2); } // Otherwise, the GLB of two types is one of them it if it is a subtype of // the other. if (isSubtypeOf(type1, type2)) { return type1; } if (isSubtypeOf(type2, type1)) { return type2; } // No subtype relation, so no known GLB. // TODO(mfairhurst): implement fully NNBD GLB, and return Never (non-legacy) return BottomTypeImpl.instanceLegacy; } /** * Given a generic function type `F<T0, T1, ... Tn>` and a context type C, * infer an instantiation of F, such that `F<S0, S1, ..., Sn>` <: C. * * This is similar to [inferGenericFunctionOrType], but the return type is * also considered as part of the solution. * * If this function is called with a [contextType] that is also * uninstantiated, or a [fnType] that is already instantiated, it will have * no effect and return `null`. */ List<DartType> inferFunctionTypeInstantiation( FunctionType contextType, FunctionType fnType, {ErrorReporter errorReporter, AstNode errorNode}) { if (contextType.typeFormals.isNotEmpty || fnType.typeFormals.isEmpty) { return const <DartType>[]; } // Create a TypeSystem that will allow certain type parameters to be // inferred. It will optimistically assume these type parameters can be // subtypes (or supertypes) as necessary, and track the constraints that // are implied by this. var inferrer = new GenericInferrer(typeProvider, this, fnType.typeFormals); inferrer.constrainGenericFunctionInContext(fnType, contextType); // Infer and instantiate the resulting type. return inferrer.infer( fnType.typeFormals, errorReporter: errorReporter, errorNode: errorNode, ); } /// Infers type arguments for a generic type, function, method, or /// list/map literal, using the downward context type as well as the /// argument types if available. /// /// For example, given a function type with generic type parameters, this /// infers the type parameters from the actual argument types, and returns the /// instantiated function type. /// /// Concretely, given a function type with parameter types P0, P1, ... Pn, /// result type R, and generic type parameters T0, T1, ... Tm, use the /// argument types A0, A1, ... An to solve for the type parameters. /// /// For each parameter Pi, we want to ensure that Ai <: Pi. We can do this by /// running the subtype algorithm, and when we reach a type parameter Tj, /// recording the lower or upper bound it must satisfy. At the end, all /// constraints can be combined to determine the type. /// /// All constraints on each type parameter Tj are tracked, as well as where /// they originated, so we can issue an error message tracing back to the /// argument values, type parameter "extends" clause, or the return type /// context. List<DartType> inferGenericFunctionOrType({ ClassElement genericClass, @required List<TypeParameterElement> typeParameters, @required List<ParameterElement> parameters, @required DartType declaredReturnType, @required List<DartType> argumentTypes, @required DartType contextReturnType, ErrorReporter errorReporter, AstNode errorNode, bool downwards: false, bool isConst: false, }) { if (typeParameters.isEmpty) { return null; } // Create a TypeSystem that will allow certain type parameters to be // inferred. It will optimistically assume these type parameters can be // subtypes (or supertypes) as necessary, and track the constraints that // are implied by this. var inferrer = new GenericInferrer(typeProvider, this, typeParameters); if (contextReturnType != null) { if (isConst) { contextReturnType = _eliminateTypeVariables(contextReturnType); } inferrer.constrainReturnType(declaredReturnType, contextReturnType); } for (int i = 0; i < argumentTypes.length; i++) { // Try to pass each argument to each parameter, recording any type // parameter bounds that were implied by this assignment. inferrer.constrainArgument( argumentTypes[i], parameters[i].type, parameters[i].name, genericClass: genericClass, ); } return inferrer.infer( typeParameters, errorReporter: errorReporter, errorNode: errorNode, downwardsInferPhase: downwards, ); } /** * Given a [DartType] [type], if [type] is an uninstantiated * parameterized type then instantiate the parameters to their * bounds. See the issue for the algorithm description. * * https://github.com/dart-lang/sdk/issues/27526#issuecomment-260021397 * * TODO(scheglov) Move this method to elements for classes, typedefs, * and generic functions; compute lazily and cache. */ DartType instantiateToBounds(DartType type, {List<bool> hasError, Map<TypeParameterElement, DartType> knownTypes}) { List<TypeParameterElement> typeFormals = typeFormalsAsElements(type); List<DartType> arguments = instantiateTypeFormalsToBounds(typeFormals, hasError: hasError, knownTypes: knownTypes); if (arguments == null) { return type; } return instantiateType(type, arguments); } /** * Given uninstantiated [typeFormals], instantiate them to their bounds. * See the issue for the algorithm description. * * https://github.com/dart-lang/sdk/issues/27526#issuecomment-260021397 */ List<DartType> instantiateTypeFormalsToBounds( List<TypeParameterElement> typeFormals, {List<bool> hasError, Map<TypeParameterElement, DartType> knownTypes}) { int count = typeFormals.length; if (count == 0) { return const <DartType>[]; } Set<TypeParameterElement> all = new Set<TypeParameterElement>(); // all ground Map<TypeParameterElement, DartType> defaults = knownTypes ?? {}; // not ground Map<TypeParameterElement, DartType> partials = {}; for (TypeParameterElement typeParameter in typeFormals) { all.add(typeParameter); if (!defaults.containsKey(typeParameter)) { if (typeParameter.bound == null) { defaults[typeParameter] = DynamicTypeImpl.instance; } else { partials[typeParameter] = typeParameter.bound; } } } List<TypeParameterElement> getFreeParameters(DartType rootType) { List<TypeParameterElement> parameters; Set<DartType> visitedTypes = new HashSet<DartType>(); void appendParameters(DartType type) { if (type == null) { return; } if (visitedTypes.contains(type)) { return; } visitedTypes.add(type); if (type is TypeParameterType) { var element = type.element; if (all.contains(element)) { parameters ??= <TypeParameterElement>[]; parameters.add(element); } } else { if (type is FunctionType) { appendParameters(type.returnType); type.parameters.map((p) => p.type).forEach(appendParameters); } else if (type is InterfaceType) { type.typeArguments.forEach(appendParameters); } } } appendParameters(rootType); return parameters; } bool hasProgress = true; while (hasProgress) { hasProgress = false; for (TypeParameterElement parameter in partials.keys) { DartType value = partials[parameter]; List<TypeParameterElement> freeParameters = getFreeParameters(value); if (freeParameters == null) { defaults[parameter] = value; partials.remove(parameter); hasProgress = true; break; } else if (freeParameters.every(defaults.containsKey)) { defaults[parameter] = Substitution.fromMap(defaults).substituteType(value); partials.remove(parameter); hasProgress = true; break; } } } // If we stopped making progress, and not all types are ground, // then the whole type is malbounded and an error should be reported // if errors are requested, and a partially completed type should // be returned. if (partials.isNotEmpty) { if (hasError != null) { hasError[0] = true; } var domain = defaults.keys.toList(); var range = defaults.values.toList(); // Build a substitution Phi mapping each uncompleted type variable to // dynamic, and each completed type variable to its default. for (TypeParameterElement parameter in partials.keys) { domain.add(parameter); range.add(DynamicTypeImpl.instance); } // Set the default for an uncompleted type variable (T extends B) // to be Phi(B) for (TypeParameterElement parameter in partials.keys) { defaults[parameter] = Substitution.fromPairs(domain, range) .substituteType(partials[parameter]); } } List<DartType> orderedArguments = typeFormals.map((p) => defaults[p]).toList(); return orderedArguments; } /// Given the type defining [element], instantiate its type formals to /// their bounds. List<DartType> instantiateTypeFormalsToBounds2(Element element) { List<TypeParameterElement> typeParameters; if (element is ClassElement) { typeParameters = element.typeParameters; } else if (element is GenericTypeAliasElement) { typeParameters = element.typeParameters; } else { throw StateError('Unexpected: $element'); } if (typeParameters.isEmpty) { return const <DartType>[]; } return typeParameters .map((p) => (p as TypeParameterElementImpl).defaultType) .toList(); } @override bool isAssignableTo(DartType fromType, DartType toType, {FeatureSet featureSet}) { // An actual subtype if (isSubtypeOf(fromType, toType)) { return true; } // A call method tearoff if (fromType is InterfaceType && acceptsFunctionType(toType)) { var callMethodType = getCallMethodType(fromType); if (callMethodType != null && isAssignableTo(callMethodType, toType, featureSet: featureSet)) { return true; } } // First make sure --no-implicit-casts disables all downcasts, including // dynamic casts. if (!implicitCasts) { return false; } // Now handle NNBD default behavior, where we disable non-dynamic downcasts. if (featureSet != null && featureSet.isEnabled(Feature.non_nullable)) { return fromType.isDynamic; } // Don't allow implicit downcasts between function types // and call method objects, as these will almost always fail. if (fromType is FunctionType && getCallMethodType(toType) != null) { return false; } // Don't allow a non-generic function where a generic one is expected. The // former wouldn't know how to handle type arguments being passed to it. // TODO(rnystrom): This same check also exists in FunctionTypeImpl.relate() // but we don't always reliably go through that code path. This should be // cleaned up to avoid the redundancy. if (fromType is FunctionType && toType is FunctionType && fromType.typeFormals.isEmpty && toType.typeFormals.isNotEmpty) { return false; } // If the subtype relation goes the other way, allow the implicit downcast. if (isSubtypeOf(toType, fromType)) { // TODO(leafp,jmesserly): we emit warnings/hints for these in // src/task/strong/checker.dart, which is a bit inconsistent. That // code should be handled into places that use isAssignableTo, such as // ErrorVerifier. return true; } return false; } bool isGroundType(DartType t) { // TODO(leafp): Revisit this. if (t is TypeParameterType) { return false; } // TODO(mfairhurst): switch legacy Top checks to true Top checks if (_isLegacyTop(t, orTrueTop: true)) { return true; } if (t is FunctionType) { // TODO(mfairhurst): switch legacy Top checks to true Top checks // TODO(mfairhurst): switch legacy Bottom checks to true Bottom checks if (!_isLegacyTop(t.returnType, orTrueTop: true) || anyParameterType( t, (pt) => !_isLegacyBottom(pt, orTrueBottom: true))) { return false; } else { return true; } } if (t is InterfaceType) { List<DartType> typeArguments = t.typeArguments; for (DartType typeArgument in typeArguments) { // TODO(mfairhurst): switch legacy Top checks to true Top checks if (!_isLegacyTop(typeArgument, orTrueTop: true)) return false; } return true; } // We should not see any other type aside from malformed code. return false; } @override bool isMoreSpecificThan(DartType t1, DartType t2) => isSubtypeOf(t1, t2); @override bool isOverrideSubtypeOf(FunctionType f1, FunctionType f2) { return FunctionTypeImpl.relate(f1, f2, isSubtypeOf, parameterRelation: isOverrideSubtypeOfParameter, // Type parameter bounds are invariant. boundsRelation: (t1, t2, p1, p2) => isSubtypeOf(t1, t2) && isSubtypeOf(t2, t1)); } /// Check that parameter [p2] is a subtype of [p1], given that we are /// checking `f1 <: f2` where `p1` is a parameter of `f1` and `p2` is a /// parameter of `f2`. /// /// Parameters are contravariant, so we must check `p2 <: p1` to /// determine if `f1 <: f2`. This is used by [isOverrideSubtypeOf]. bool isOverrideSubtypeOfParameter(ParameterElement p1, ParameterElement p2) { return isSubtypeOf(p2.type, p1.type) || p1.isCovariant && isSubtypeOf(p1.type, p2.type); } /// Check if [_t1] is a subtype of [_t2]. /// /// Partially updated to reflect /// https://github.com/dart-lang/language/blob/da5adf7eb5f2d479069d8660ed7ca7b230098510/resources/type-system/subtyping.md /// /// However, it does not correlate 1:1 and does not specialize Null vs Never /// cases. It also is not guaranteed to be exactly accurate vs the "spec" /// because it has slightly different order of operations. These should be /// brought in line or proven equivalent. @override bool isSubtypeOf(DartType _t1, DartType _t2) { var t1 = _t1 as TypeImpl; var t2 = _t2 as TypeImpl; // Convert Null to Never? so that NullabilitySuffix can handle more cases. if (t1.isDartCoreNull) { t1 = BottomTypeImpl.instanceNullable; } if (t2.isDartCoreNull) { t2 = BottomTypeImpl.instanceNullable; } if (identical(t1, t2)) { return true; } // The types are void, dynamic, bottom, interface types, function types, // FutureOr<T> and type parameters. // // We proceed by eliminating these different classes from consideration. // `?` is treated as a top and a bottom type during inference. if (identical(t1, UnknownInferredType.instance) || identical(t2, UnknownInferredType.instance)) { return true; } // Trivial top case. if (_isTop(t2)) { return true; } // Legacy top case. Must be done now to find Object* <: Object. // TODO: handle false positives like FutureOr<Object?>* and T* extends int?. if (t1.nullabilitySuffix == NullabilitySuffix.star && _isLegacyTop(t2, orTrueTop: false)) { return true; } // Having excluded RHS top, this now must be false. if (_isTop(t1)) { return false; } // Handle T1? <: T2 if (t1.nullabilitySuffix == NullabilitySuffix.question) { if (t2.nullabilitySuffix == NullabilitySuffix.none) { // If T2 is not FutureOr<S2>, then subtype is false. if (!t2.isDartAsyncFutureOr) { return false; } // T1? <: FutureOr<S2> is true if S2 is nullable. final s2 = (t2 as InterfaceType).typeArguments[0]; if (!isNullable(s2)) { return false; } } } // Legacy bottom cases if (_isLegacyBottom(t1, orTrueBottom: true)) { return true; } if (_isLegacyBottom(t2, orTrueBottom: true)) { return false; } // Handle FutureOr<T> union type. if (t1 is InterfaceTypeImpl && t1.isDartAsyncFutureOr) { var t1TypeArg = t1.typeArguments[0]; if (t2 is InterfaceTypeImpl && t2.isDartAsyncFutureOr) { var t2TypeArg = t2.typeArguments[0]; // FutureOr<A> <: FutureOr<B> iff A <: B return isSubtypeOf(t1TypeArg, t2TypeArg); } // given t1 is Future<A> | A, then: // (Future<A> | A) <: t2 iff Future<A> <: t2 and A <: t2. var t1Future = typeProvider.futureType2(t1TypeArg); return isSubtypeOf(t1Future, t2) && isSubtypeOf(t1TypeArg, t2); } if (t2 is InterfaceTypeImpl && t2.isDartAsyncFutureOr) { // given t2 is Future<A> | A, then: // t1 <: (Future<A> | A) iff t1 <: Future<A> or t1 <: A var t2TypeArg = t2.typeArguments[0]; var t2Future = typeProvider.futureType2(t2TypeArg); return isSubtypeOf(t1, t2Future) || isSubtypeOf(t1, t2TypeArg); } // S <: T where S is a type variable // T is not dynamic or object (handled above) // True if T == S // Or true if bound of S is S' and S' <: T if (t1 is TypeParameterTypeImpl) { if (t2 is TypeParameterTypeImpl && t1.definition == t2.definition && _typeParameterBoundsSubtype(t1.bound, t2.bound, true)) { return true; } DartType bound = t1.element.bound; return bound == null ? false : _typeParameterBoundsSubtype(bound, t2, false); } if (t2 is TypeParameterType) { return false; } // We've eliminated void, dynamic, bottom, type parameters, FutureOr, // nullable, and legacy nullable types. The only cases are the combinations // of interface type and function type. // A function type can only subtype an interface type if // the interface type is Function if (t1 is FunctionType && t2 is InterfaceType) { return t2.isDartCoreFunction; } if (t1 is InterfaceType && t2 is FunctionType) return false; // Two interface types if (t1 is InterfaceTypeImpl && t2 is InterfaceTypeImpl) { return _isInterfaceSubtypeOf(t1, t2, null); } return _isFunctionSubtypeOf(t1 as FunctionType, t2 as FunctionType); } /// Given a [type] T that may have an unknown type `?`, returns a type /// R such that R <: T for any type substituted for `?`. /// /// In practice this will always replace `?` with either bottom or top /// (dynamic), depending on the position of `?`. /// /// This implements the operation the spec calls "least closure", or /// sometimes "least closure with respect to `?`". DartType lowerBoundForType(DartType type) { return _substituteForUnknownType(type, lowerBound: true); } @override DartType refineBinaryExpressionType(DartType leftType, TokenType operator, DartType rightType, DartType currentType, FeatureSet featureSet) { if (leftType is TypeParameterType && leftType.bound.isDartCoreNum) { if (rightType == leftType || rightType.isDartCoreInt) { if (operator == TokenType.PLUS || operator == TokenType.MINUS || operator == TokenType.STAR || operator == TokenType.PLUS_EQ || operator == TokenType.MINUS_EQ || operator == TokenType.STAR_EQ) { if (featureSet.isEnabled(Feature.non_nullable)) { return promoteToNonNull(leftType as TypeImpl); } return leftType; } } if (rightType.isDartCoreDouble) { if (operator == TokenType.PLUS || operator == TokenType.MINUS || operator == TokenType.STAR || operator == TokenType.SLASH) { InterfaceTypeImpl doubleType = typeProvider.doubleType; if (featureSet.isEnabled(Feature.non_nullable)) { return promoteToNonNull(doubleType); } return doubleType; } } return currentType; } return super.refineBinaryExpressionType( leftType, operator, rightType, currentType, featureSet); } @override DartType tryPromoteToType(DartType to, DartType from) { // Allow promoting to a subtype, for example: // // f(Base b) { // if (b is SubTypeOfBase) { // // promote `b` to SubTypeOfBase for this block // } // } // // This allows the variable to be used wherever the supertype (here `Base`) // is expected, while gaining a more precise type. if (isSubtypeOf(to, from)) { return to; } // For a type parameter `T extends U`, allow promoting the upper bound // `U` to `S` where `S <: U`, yielding a type parameter `T extends S`. if (from is TypeParameterTypeImpl) { if (isSubtypeOf(to, from.bound ?? DynamicTypeImpl.instance)) { var newElement = TypeParameterMember(from.element, null, to); return newElement.instantiate( nullabilitySuffix: from.nullabilitySuffix, ); } } return null; } /// Given a [type] T that may have an unknown type `?`, returns a type /// R such that T <: R for any type substituted for `?`. /// /// In practice this will always replace `?` with either bottom or top /// (dynamic), depending on the position of `?`. /// /// This implements the operation the spec calls "greatest closure", or /// sometimes "greatest closure with respect to `?`". DartType upperBoundForType(DartType type) { return _substituteForUnknownType(type); } /** * Eliminates type variables from the context [type], replacing them with * `Null` or `Object` as appropriate. * * For example in `List<T> list = const []`, the context type for inferring * the list should be changed from `List<T>` to `List<Null>` so the constant * doesn't depend on the type variables `T` (because it can't be canonicalized * at compile time, as `T` is unknown). * * Conceptually this is similar to the "least closure", except instead of * eliminating `?` ([UnknownInferredType]) it eliminates all type variables * ([TypeParameterType]). * * The equivalent CFE code can be found in the `TypeVariableEliminator` class. */ DartType _eliminateTypeVariables(DartType type) { return _substituteType(type, true, (type, lowerBound) { if (type is TypeParameterType) { return lowerBound ? typeProvider.nullType : typeProvider.objectType; } return type; }); } /** * Compute the greatest lower bound of function types [f] and [g]. * * The spec rules for GLB on function types, informally, are pretty simple: * * - If a parameter is required in both, it stays required. * * - If a positional parameter is optional or missing in one, it becomes * optional. * * - Named parameters are unioned together. * * - For any parameter that exists in both functions, use the LUB of them as * the resulting parameter type. * * - Use the GLB of their return types. */ DartType _functionGreatestLowerBound(FunctionType f, FunctionType g) { // Calculate the LUB of each corresponding pair of parameters. List<ParameterElement> parameters = []; bool hasPositional = false; bool hasNamed = false; addParameter( String name, DartType fType, DartType gType, ParameterKind kind) { DartType paramType; if (fType != null && gType != null) { // If both functions have this parameter, include both of their types. paramType = getLeastUpperBound(fType, gType); } else { paramType = fType ?? gType; } parameters.add(new ParameterElementImpl.synthetic(name, paramType, kind)); } // TODO(rnystrom): Right now, this assumes f and g do not have any type // parameters. Revisit that in the presence of generic methods. List<DartType> fRequired = f.normalParameterTypes; List<DartType> gRequired = g.normalParameterTypes; // We need some parameter names for in the synthesized function type. List<String> fRequiredNames = f.normalParameterNames; List<String> gRequiredNames = g.normalParameterNames; // Parameters that are required in both functions are required in the // result. int requiredCount = math.min(fRequired.length, gRequired.length); for (int i = 0; i < requiredCount; i++) { addParameter(fRequiredNames[i], fRequired[i], gRequired[i], ParameterKind.REQUIRED); } // Parameters that are optional or missing in either end up optional. List<DartType> fPositional = f.optionalParameterTypes; List<DartType> gPositional = g.optionalParameterTypes; List<String> fPositionalNames = f.optionalParameterNames; List<String> gPositionalNames = g.optionalParameterNames; int totalPositional = math.max(fRequired.length + fPositional.length, gRequired.length + gPositional.length); for (int i = requiredCount; i < totalPositional; i++) { // Find the corresponding positional parameters (required or optional) at // this index, if there is one. DartType fType; String fName; if (i < fRequired.length) { fType = fRequired[i]; fName = fRequiredNames[i]; } else if (i < fRequired.length + fPositional.length) { fType = fPositional[i - fRequired.length]; fName = fPositionalNames[i - fRequired.length]; } DartType gType; String gName; if (i < gRequired.length) { gType = gRequired[i]; gName = gRequiredNames[i]; } else if (i < gRequired.length + gPositional.length) { gType = gPositional[i - gRequired.length]; gName = gPositionalNames[i - gRequired.length]; } // The loop should not let us go past both f and g's positional params. assert(fType != null || gType != null); addParameter(fName ?? gName, fType, gType, ParameterKind.POSITIONAL); hasPositional = true; } // Union the named parameters together. // TODO(brianwilkerson) Handle the fact that named parameters can now be // required. Map<String, DartType> fNamed = f.namedParameterTypes; Map<String, DartType> gNamed = g.namedParameterTypes; for (String name in fNamed.keys.toSet()..addAll(gNamed.keys)) { addParameter(name, fNamed[name], gNamed[name], ParameterKind.NAMED); hasNamed = true; } // Edge case. Dart does not support functions with both optional positional // and named parameters. If we would synthesize that, give up. if (hasPositional && hasNamed) return typeProvider.bottomType; // Calculate the GLB of the return type. DartType returnType = getGreatestLowerBound(f.returnType, g.returnType); return new FunctionElementImpl.synthetic(parameters, returnType).type; } @override DartType _functionParameterBound(DartType f, DartType g) => getGreatestLowerBound(f, g); @override DartType _interfaceLeastUpperBound(InterfaceType type1, InterfaceType type2) { var helper = InterfaceLeastUpperBoundHelper(this); return helper.compute(type1, type2); } /// Check that [f1] is a subtype of [f2]. bool _isFunctionSubtypeOf(FunctionType f1, FunctionType f2) { return FunctionTypeImpl.relate(f1, f2, isSubtypeOf, parameterRelation: (p1, p2) => isSubtypeOf(p2.type, p1.type), // Type parameter bounds are invariant. boundsRelation: (t1, t2, p1, p2) => isSubtypeOf(t1, t2) && isSubtypeOf(t2, t1)); } bool _isInterfaceSubtypeOf( InterfaceType i1, InterfaceType i2, Set<ClassElement> visitedTypes) { // Note: we should never reach `_isInterfaceSubtypeOf` with `i2 == Object`, // because top types are eliminated before `isSubtypeOf` calls this. if (identical(i1, i2) || i2.isObject) { return true; } // Object cannot subtype anything but itself (handled above). if (i1.isObject) { return false; } ClassElement i1Element = i1.element; if (i1Element == i2.element) { List<DartType> tArgs1 = i1.typeArguments; List<DartType> tArgs2 = i2.typeArguments; assert(tArgs1.length == tArgs2.length); for (int i = 0; i < tArgs1.length; i++) { DartType t1 = tArgs1[i]; DartType t2 = tArgs2[i]; if (!isSubtypeOf(t1, t2)) { return false; } } return true; } // Classes types cannot subtype `Function` or vice versa. if (i1.isDartCoreFunction || i2.isDartCoreFunction) { return false; } // Guard against loops in the class hierarchy. // // Dart 2 does not allow multiple implementations of the same generic type // with different type arguments. So we can track just the class element // to find cycles, rather than tracking the full interface type. visitedTypes ??= new HashSet<ClassElement>(); if (!visitedTypes.add(i1Element)) return false; InterfaceType superclass = i1.superclass; if (superclass != null && _isInterfaceSubtypeOf(superclass, i2, visitedTypes)) { return true; } for (final parent in i1.interfaces) { if (_isInterfaceSubtypeOf(parent, i2, visitedTypes)) { return true; } } for (final parent in i1.mixins) { if (_isInterfaceSubtypeOf(parent, i2, visitedTypes)) { return true; } } if (i1Element.isMixin) { for (final parent in i1.superclassConstraints) { if (_isInterfaceSubtypeOf(parent, i2, visitedTypes)) { return true; } } } return false; } /** * Returns the greatest or least closure of [type], which replaces `?` * ([UnknownInferredType]) with `dynamic` or `Null` as appropriate. * * If [lowerBound] is true, this will return the "least closure", otherwise * it returns the "greatest closure". */ DartType _substituteForUnknownType(DartType type, {bool lowerBound: false}) { return _substituteType(type, lowerBound, (type, lowerBound) { if (identical(type, UnknownInferredType.instance)) { return lowerBound ? typeProvider.nullType : typeProvider.dynamicType; } return type; }); } /** * Apply the [visitType] substitution to [type], using the result value if * different, otherwise recursively apply the substitution. * * This method is used for substituting `?` ([UnknownInferredType]) with its * greatest/least closure, and for eliminating type parameters for inference * of `const` objects. * * See also [_eliminateTypeVariables] and [_substituteForUnknownType]. */ DartType _substituteType(DartType type, bool lowerBound, DartType Function(DartType, bool) visitType) { // Apply the substitution to this type, and return the result if different. var newType = visitType(type, lowerBound); if (!identical(newType, type)) { return newType; } if (type is InterfaceTypeImpl) { // Generic types are covariant, so keep the constraint direction. var newTypeArgs = _transformList( type.typeArguments, (t) => _substituteType(t, lowerBound, visitType)); if (identical(type.typeArguments, newTypeArgs)) return type; return new InterfaceTypeImpl(type.element, prunedTypedefs: type.prunedTypedefs, nullabilitySuffix: type.nullabilitySuffix) ..typeArguments = newTypeArgs; } if (type is FunctionType) { var parameters = type.parameters; var returnType = type.returnType; var newParameters = _transformList(parameters, (ParameterElement p) { // Parameters are contravariant, so flip the constraint direction. var newType = _substituteType(p.type, !lowerBound, visitType); return new ParameterElementImpl.synthetic( p.name, newType, // ignore: deprecated_member_use_from_same_package p.parameterKind); }); // Return type is covariant. var newReturnType = _substituteType(returnType, lowerBound, visitType); if (identical(parameters, newParameters) && identical(returnType, newReturnType)) { return type; } return new FunctionTypeImpl.synthetic( newReturnType, type.typeFormals, newParameters, nullabilitySuffix: (type as TypeImpl).nullabilitySuffix, ); } return type; } bool _typeParameterBoundsSubtype( DartType t1, DartType t2, bool recursionValue) { TypeComparison comparison = TypeComparison(t1, t2); if (_typeParameterBoundsComparisons.contains(comparison)) { return recursionValue; } _typeParameterBoundsComparisons.add(comparison); try { return isSubtypeOf(t1, t2); } finally { _typeParameterBoundsComparisons.remove(comparison); } } /** * This currently just implements a simple least upper bound to * handle some common cases. It also avoids some termination issues * with the naive spec algorithm. The least upper bound of two types * (at least one of which is a type parameter) is computed here as: * 1. If either type is a supertype of the other, return it. * 2. If the first type is a type parameter, replace it with its bound, * with recursive occurrences of itself replaced with Object. * The second part of this should ensure termination. Informally, * each type variable instantiation in one of the arguments to the * least upper bound algorithm now strictly reduces the number * of bound variables in scope in that argument position. * 3. If the second type is a type parameter, do the symmetric operation * to #2. * * It's not immediately obvious why this is symmetric in the case that both * of them are type parameters. For #1, symmetry holds since subtype * is antisymmetric. For #2, it's clearly not symmetric if upper bounds of * bottom are allowed. Ignoring this (for various reasons, not least * of which that there's no way to write it), there's an informal * argument (that might even be right) that you will always either * end up expanding both of them or else returning the same result no matter * which order you expand them in. A key observation is that * identical(expand(type1), type2) => subtype(type1, type2) * and hence the contra-positive. * * TODO(leafp): Think this through and figure out what's the right * definition. Be careful about termination. * * I suspect in general a reasonable algorithm is to expand the innermost * type variable first. Alternatively, you could probably choose to treat * it as just an instance of the interface type upper bound problem, with * the "inheritance" chain extended by the bounds placed on the variables. */ @override DartType _typeParameterLeastUpperBound(DartType type1, DartType type2) { if (isSubtypeOf(type1, type2)) { return type2; } if (isSubtypeOf(type2, type1)) { return type1; } if (type1 is TypeParameterType) { type1 = type1 .resolveToBound(typeProvider.objectType) .substitute2([typeProvider.objectType], [type1]); return getLeastUpperBound(type1, type2); } // We should only be called when at least one of the types is a // TypeParameterType type2 = type2 .resolveToBound(typeProvider.objectType) .substitute2([typeProvider.objectType], [type2]); return getLeastUpperBound(type1, type2); } static List<T> _transformList<T>(List<T> list, T f(T t)) { List<T> newList; for (var i = 0; i < list.length; i++) { var item = list[i]; var newItem = f(item); if (!identical(item, newItem)) { newList ??= new List.from(list); newList[i] = newItem; } } return newList ?? list; } } /// Tracks upper and lower type bounds for a set of type parameters. /// /// This class is used by calling [isSubtypeOf]. When it encounters one of /// the type parameters it is inferring, it will record the constraint, and /// optimistically assume the constraint will be satisfied. /// /// For example if we are inferring type parameter A, and we ask if /// `A <: num`, this will record that A must be a subytpe of `num`. It also /// handles cases when A appears as part of the structure of another type, for /// example `Iterable<A> <: Iterable<num>` would infer the same constraint /// (due to covariant generic types) as would `() -> A <: () -> num`. In /// contrast `(A) -> void <: (num) -> void`. /// /// Once the lower/upper bounds are determined, [infer] should be called to /// finish the inference. It will instantiate a generic function type with the /// inferred types for each type parameter. /// /// It can also optionally compute a partial solution, in case some of the type /// parameters could not be inferred (because the constraints cannot be /// satisfied), or bail on the inference when this happens. /// /// As currently designed, an instance of this class should only be used to /// infer a single call and discarded immediately afterwards. class GenericInferrer { final Dart2TypeSystem _typeSystem; final TypeProvider typeProvider; final Map<TypeParameterElement, List<_TypeConstraint>> constraints = {}; /// Buffer recording constraints recorded while performing a recursive call to /// [_matchSubtypeOf] that might fail, so that any constraints recorded during /// the failed match can be rewound. final _undoBuffer = <_TypeConstraint>[]; GenericInferrer(this.typeProvider, this._typeSystem, Iterable<TypeParameterElement> typeFormals) { for (var formal in typeFormals) { constraints[formal] = []; } } /// Apply an argument constraint, which asserts that the [argument] staticType /// is a subtype of the [parameterType]. void constrainArgument( DartType argumentType, DartType parameterType, String parameterName, {ClassElement genericClass}) { var origin = new _TypeConstraintFromArgument( argumentType, parameterType, parameterName, genericClass: genericClass); tryMatchSubtypeOf(argumentType, parameterType, origin, covariant: false); } /// Constrain a universal function type [fnType] used in a context /// [contextType]. void constrainGenericFunctionInContext( FunctionType fnType, DartType contextType) { var origin = new _TypeConstraintFromFunctionContext(fnType, contextType); // Since we're trying to infer the instantiation, we want to ignore type // formals as we check the parameters and return type. var inferFnType = fnType.instantiate(TypeParameterTypeImpl.getTypes(fnType.typeFormals)); tryMatchSubtypeOf(inferFnType, contextType, origin, covariant: true); } /// Apply a return type constraint, which asserts that the [declaredType] /// is a subtype of the [contextType]. void constrainReturnType(DartType declaredType, DartType contextType) { var origin = new _TypeConstraintFromReturnType(declaredType, contextType); tryMatchSubtypeOf(declaredType, contextType, origin, covariant: true); } /// Given the constraints that were given by calling [constrainArgument] and /// [constrainReturnType], find the type arguments for the [typeFormals] that /// satisfies these constraints. /// /// If [downwardsInferPhase] is set, we are in the first pass of inference, /// pushing context types down. At that point we are allowed to push down /// `?` to precisely represent an unknown type. If [downwardsInferPhase] is /// false, we are on our final inference pass, have all available information /// including argument types, and must not conclude `?` for any type formal. List<DartType> infer(List<TypeParameterElement> typeFormals, {bool considerExtendsClause: true, ErrorReporter errorReporter, AstNode errorNode, bool failAtError: false, bool downwardsInferPhase: false}) { // Initialize the inferred type array. // // In the downwards phase, they all start as `?` to offer reasonable // degradation for f-bounded type parameters. var inferredTypes = new List<DartType>.filled( typeFormals.length, UnknownInferredType.instance); var _inferTypeParameter = downwardsInferPhase ? _inferTypeParameterFromContext : _inferTypeParameterFromAll; for (int i = 0; i < typeFormals.length; i++) { TypeParameterElement typeParam = typeFormals[i]; _TypeConstraint extendsClause; if (considerExtendsClause && typeParam.bound != null) { extendsClause = new _TypeConstraint.fromExtends( typeParam, Substitution.fromPairs(typeFormals, inferredTypes) .substituteType(typeParam.bound)); } inferredTypes[i] = _inferTypeParameter(constraints[typeParam], extendsClause); } // If the downwards infer phase has failed, we'll catch this in the upwards // phase later on. if (downwardsInferPhase) { return inferredTypes; } // Check the inferred types against all of the constraints. var knownTypes = <TypeParameterElement, DartType>{}; for (int i = 0; i < typeFormals.length; i++) { TypeParameterElement typeParam = typeFormals[i]; var constraints = this.constraints[typeParam]; var typeParamBound = typeParam.bound != null ? Substitution.fromPairs(typeFormals, inferredTypes) .substituteType(typeParam.bound) : typeProvider.dynamicType; var inferred = inferredTypes[i]; bool success = constraints.every((c) => c.isSatisifedBy(_typeSystem, inferred)); if (success && !typeParamBound.isDynamic) { // If everything else succeeded, check the `extends` constraint. var extendsConstraint = new _TypeConstraint.fromExtends(typeParam, typeParamBound); constraints.add(extendsConstraint); success = extendsConstraint.isSatisifedBy(_typeSystem, inferred); } if (!success) { if (failAtError) return null; errorReporter?.reportErrorForNode( StrongModeCode.COULD_NOT_INFER, errorNode, [typeParam.name, _formatError(typeParam, inferred, constraints)]); // Heuristic: even if we failed, keep the erroneous type. // It should satisfy at least some of the constraints (e.g. the return // context). If we fall back to instantiateToBounds, we'll typically get // more errors (e.g. because `dynamic` is the most common bound). } if (inferred is FunctionType && inferred.typeFormals.isNotEmpty) { if (failAtError) return null; errorReporter ?.reportErrorForNode(StrongModeCode.COULD_NOT_INFER, errorNode, [ typeParam.name, ' Inferred candidate type $inferred has type parameters' ' ${(inferred as FunctionType).typeFormals}, but a function with' ' type parameters cannot be used as a type argument.' ]); // Heuristic: Using a generic function type as a bound makes subtyping // undecidable. Therefore, we cannot keep [inferred] unless we wish to // generate bogus subtyping errors. Instead generate plain [Function], // which is the most general function type. inferred = typeProvider.functionType; } if (UnknownInferredType.isKnown(inferred)) { knownTypes[typeParam] = inferred; } else if (_typeSystem.strictInference) { // [typeParam] could not be inferred. A result will still be returned // by [infer], with [typeParam] filled in as its bounds. This is // considered a failure of inference, under the "strict-inference" // mode. if (errorNode is ConstructorName) { String constructorName = '${errorNode.type}.${errorNode.name}'; errorReporter?.reportTypeErrorForNode( HintCode.INFERENCE_FAILURE_ON_INSTANCE_CREATION, errorNode, [constructorName]); } // TODO(srawlins): More inference failure cases, like functions, and // function expressions. } } // Use instantiate to bounds to finish things off. var hasError = new List<bool>.filled(typeFormals.length, false); var result = _typeSystem.instantiateTypeFormalsToBounds(typeFormals, hasError: hasError, knownTypes: knownTypes); // Report any errors from instantiateToBounds. for (int i = 0; i < hasError.length; i++) { if (hasError[i]) { if (failAtError) return null; TypeParameterElement typeParam = typeFormals[i]; var typeParamBound = Substitution.fromPairs(typeFormals, inferredTypes) .substituteType(typeParam.bound ?? typeProvider.objectType); // TODO(jmesserly): improve this error message. errorReporter ?.reportErrorForNode(StrongModeCode.COULD_NOT_INFER, errorNode, [ typeParam.name, "\nRecursive bound cannot be instantiated: '$typeParamBound'." "\nConsider passing explicit type argument(s) " "to the generic.\n\n'" ]); } } return result; } /// Tries to make [i1] a subtype of [i2] and accumulate constraints as needed. /// /// The return value indicates whether the match was successful. If it was /// unsuccessful, any constraints that were accumulated during the match /// attempt have been rewound (see [_rewindConstraints]). bool tryMatchSubtypeOf(DartType t1, DartType t2, _TypeConstraintOrigin origin, {bool covariant}) { int previousRewindBufferLength = _undoBuffer.length; bool success = _matchSubtypeOf(t1, t2, null, origin, covariant: covariant); if (!success) { _rewindConstraints(previousRewindBufferLength); } return success; } /// Choose the bound that was implied by the return type, if any. /// /// Which bound this is depends on what positions the type parameter /// appears in. If the type only appears only in a contravariant position, /// we will choose the lower bound instead. /// /// For example given: /// /// Func1<T, bool> makeComparer<T>(T x) => (T y) => x() == y; /// /// main() { /// Func1<num, bool> t = makeComparer/* infer <num> */(42); /// print(t(42.0)); /// false, no error. /// } /// /// The constraints we collect are: /// /// * `num <: T` /// * `int <: T` /// /// ... and no upper bound. Therefore the lower bound is the best choice. DartType _chooseTypeFromConstraints(Iterable<_TypeConstraint> constraints, {bool toKnownType: false}) { DartType lower = UnknownInferredType.instance; DartType upper = UnknownInferredType.instance; for (var constraint in constraints) { // Given constraints: // // L1 <: T <: U1 // L2 <: T <: U2 // // These can be combined to produce: // // LUB(L1, L2) <: T <: GLB(U1, U2). // // This can then be done for all constraints in sequence. // // This resulting constraint may be unsatisfiable; in that case inference // will fail. upper = _getGreatestLowerBound(upper, constraint.upperBound); lower = _typeSystem.getLeastUpperBound(lower, constraint.lowerBound); } // Prefer the known bound, if any. // Otherwise take whatever bound has partial information, e.g. `Iterable<?>` // // For both of those, prefer the lower bound (arbitrary heuristic). if (UnknownInferredType.isKnown(lower)) { return lower; } if (UnknownInferredType.isKnown(upper)) { return upper; } if (!identical(UnknownInferredType.instance, lower)) { return toKnownType ? _typeSystem.lowerBoundForType(lower) : lower; } if (!identical(UnknownInferredType.instance, upper)) { return toKnownType ? _typeSystem.upperBoundForType(upper) : upper; } return lower; } String _formatError(TypeParameterElement typeParam, DartType inferred, Iterable<_TypeConstraint> constraints) { var intro = "Tried to infer '$inferred' for '${typeParam.name}'" " which doesn't work:"; var constraintsByOrigin = <_TypeConstraintOrigin, List<_TypeConstraint>>{}; for (var c in constraints) { constraintsByOrigin.putIfAbsent(c.origin, () => []).add(c); } // Only report unique constraint origins. Iterable<_TypeConstraint> isSatisified(bool expected) => constraintsByOrigin .values .where((l) => l.every((c) => c.isSatisifedBy(_typeSystem, inferred)) == expected) .expand((i) => i); String unsatisified = _formatConstraints(isSatisified(false)); String satisified = _formatConstraints(isSatisified(true)); assert(unsatisified.isNotEmpty); if (satisified.isNotEmpty) { satisified = "\nThe type '$inferred' was inferred from:\n$satisified"; } return '\n\n$intro\n$unsatisified$satisified\n\n' 'Consider passing explicit type argument(s) to the generic.\n\n'; } /// This is first calls strong mode's GLB, but if it fails to find anything /// (i.e. returns the bottom type), we kick in a few additional rules: /// /// - `GLB(FutureOr<A>, B)` is defined as: /// - `GLB(FutureOr<A>, FutureOr<B>) == FutureOr<GLB(A, B)>` /// - `GLB(FutureOr<A>, Future<B>) == Future<GLB(A, B)>` /// - else `GLB(FutureOr<A>, B) == GLB(A, B)` /// - `GLB(A, FutureOr<B>) == GLB(FutureOr<B>, A)` (defined above), /// - else `GLB(A, B) == Null` DartType _getGreatestLowerBound(DartType t1, DartType t2) { var result = _typeSystem.getGreatestLowerBound(t1, t2); if (result.isBottom) { // See if we can do better by considering FutureOr rules. if (t1 is InterfaceType && t1.isDartAsyncFutureOr) { var t1TypeArg = t1.typeArguments[0]; if (t2 is InterfaceType) { // GLB(FutureOr<A>, FutureOr<B>) == FutureOr<GLB(A, B)> if (t2.isDartAsyncFutureOr) { var t2TypeArg = t2.typeArguments[0]; return typeProvider .futureOrType2(_getGreatestLowerBound(t1TypeArg, t2TypeArg)); } // GLB(FutureOr<A>, Future<B>) == Future<GLB(A, B)> if (t2.isDartAsyncFuture) { var t2TypeArg = t2.typeArguments[0]; return typeProvider .futureType2(_getGreatestLowerBound(t1TypeArg, t2TypeArg)); } } // GLB(FutureOr<A>, B) == GLB(A, B) return _getGreatestLowerBound(t1TypeArg, t2); } if (t2 is InterfaceType && t2.isDartAsyncFutureOr) { // GLB(A, FutureOr<B>) == GLB(FutureOr<B>, A) return _getGreatestLowerBound(t2, t1); } return typeProvider.nullType; } return result; } DartType _inferTypeParameterFromAll( List<_TypeConstraint> constraints, _TypeConstraint extendsClause) { // See if we already fixed this type from downwards inference. // If so, then we aren't allowed to change it based on argument types. DartType t = _inferTypeParameterFromContext( constraints.where((c) => c.isDownwards), extendsClause); if (UnknownInferredType.isKnown(t)) { // Remove constraints that aren't downward ones; we'll ignore these for // error reporting, because inference already succeeded. constraints.removeWhere((c) => !c.isDownwards); return t; } if (extendsClause != null) { constraints = constraints.toList()..add(extendsClause); } var choice = _chooseTypeFromConstraints(constraints, toKnownType: true); return choice; } DartType _inferTypeParameterFromContext( Iterable<_TypeConstraint> constraints, _TypeConstraint extendsClause) { DartType t = _chooseTypeFromConstraints(constraints); if (UnknownInferredType.isUnknown(t)) { return t; } // If we're about to make our final choice, apply the extends clause. // This gives us a chance to refine the choice, in case it would violate // the `extends` clause. For example: // // Object obj = math.min/*<infer Object, error>*/(1, 2); // // If we consider the `T extends num` we conclude `<num>`, which works. if (extendsClause != null) { constraints = constraints.toList()..add(extendsClause); return _chooseTypeFromConstraints(constraints); } return t; } /// Tries to make [i1] a subtype of [i2] and accumulate constraints as needed. /// /// The return value indicates whether the match was successful. If it was /// unsuccessful, the caller is responsible for ignoring any constraints that /// were accumulated (see [_rewindConstraints]). bool _matchInterfaceSubtypeOf(InterfaceType i1, InterfaceType i2, Set<Element> visited, _TypeConstraintOrigin origin, {bool covariant}) { if (identical(i1, i2)) { return true; } if (i1.element == i2.element) { List<DartType> tArgs1 = i1.typeArguments; List<DartType> tArgs2 = i2.typeArguments; assert(tArgs1.length == tArgs2.length); for (int i = 0; i < tArgs1.length; i++) { if (!_matchSubtypeOf( tArgs1[i], tArgs2[i], new HashSet<Element>(), origin, covariant: covariant)) { return false; } } return true; } if (i1.isObject) { return false; } // Guard against loops in the class hierarchy bool guardedInterfaceSubtype(InterfaceType t1) { visited ??= new HashSet<Element>(); if (visited.add(t1.element)) { bool matched = _matchInterfaceSubtypeOf(t1, i2, visited, origin, covariant: covariant); visited.remove(t1.element); return matched; } else { // In the case of a recursive type parameter, consider the subtype // match to have failed. return false; } } // We don't need to search the entire class hierarchy, since a given // subclass can't appear multiple times with different generic parameters. // So shortcut to the first match found. // // We don't need undo logic here because if the classes don't match, nothing // is added to the constraint set. var superclass = i1.superclass; if (superclass != null && guardedInterfaceSubtype(superclass)) return true; for (final parent in i1.interfaces) { if (guardedInterfaceSubtype(parent)) return true; } for (final parent in i1.mixins) { if (guardedInterfaceSubtype(parent)) return true; } for (final parent in i1.superclassConstraints) { if (guardedInterfaceSubtype(parent)) return true; } return false; } /// Assert that [t1] will be a subtype of [t2], and returns if the constraint /// can be satisfied. /// /// [covariant] must be true if [t1] is a declared type of the generic /// function and [t2] is the context type, or false if the reverse. For /// example [covariant] is used when [t1] is the declared return type /// and [t2] is the context type. Contravariant would be used if [t1] is the /// argument type (i.e. passed in to the generic function) and [t2] is the /// declared parameter type. /// /// [origin] indicates where the constraint came from, for example an argument /// or return type. bool _matchSubtypeOf(DartType t1, DartType t2, Set<Element> visited, _TypeConstraintOrigin origin, {bool covariant}) { if (covariant && t1 is TypeParameterType) { var constraints = this.constraints[t1.element]; if (constraints != null) { if (!identical(t2, UnknownInferredType.instance)) { var constraint = new _TypeConstraint(origin, t1.element, upper: t2); constraints.add(constraint); _undoBuffer.add(constraint); } return true; } } if (!covariant && t2 is TypeParameterType) { var constraints = this.constraints[t2.element]; if (constraints != null) { if (!identical(t1, UnknownInferredType.instance)) { var constraint = new _TypeConstraint(origin, t2.element, lower: t1); constraints.add(constraint); _undoBuffer.add(constraint); } return true; } } if (identical(t1, t2)) { return true; } // TODO(jmesserly): this logic is taken from subtype. bool matchSubtype(DartType t1, DartType t2) { return _matchSubtypeOf(t1, t2, null, origin, covariant: covariant); } // Handle FutureOr<T> union type. if (t1 is InterfaceType && t1.isDartAsyncFutureOr) { var t1TypeArg = t1.typeArguments[0]; if (t2 is InterfaceType && t2.isDartAsyncFutureOr) { var t2TypeArg = t2.typeArguments[0]; // FutureOr<A> <: FutureOr<B> iff A <: B return matchSubtype(t1TypeArg, t2TypeArg); } // given t1 is Future<A> | A, then: // (Future<A> | A) <: t2 iff Future<A> <: t2 and A <: t2. var t1Future = typeProvider.futureType2(t1TypeArg); return matchSubtype(t1Future, t2) && matchSubtype(t1TypeArg, t2); } if (t2 is InterfaceType && t2.isDartAsyncFutureOr) { // given t2 is Future<A> | A, then: // t1 <: (Future<A> | A) iff t1 <: Future<A> or t1 <: A var t2TypeArg = t2.typeArguments[0]; var t2Future = typeProvider.futureType2(t2TypeArg); // First we try matching `t1 <: Future<A>`. If that succeeds *and* // records at least one constraint, then we proceed using that constraint. var previousRewindBufferLength = _undoBuffer.length; var success = tryMatchSubtypeOf(t1, t2Future, origin, covariant: covariant); if (_undoBuffer.length != previousRewindBufferLength) { // Trying to match `t1 <: Future<A>` succeeded and recorded constraints, // so those are the constraints we want. return true; } else { // Either `t1 <: Future<A>` failed to match, or it matched trivially // without recording any constraints (e.g. because t1 is `Null`). We // want constraints, because they let us do more precise inference, so // go ahead and try matching `t1 <: A` to see if it records any // constraints. if (tryMatchSubtypeOf(t1, t2TypeArg, origin, covariant: covariant)) { // Trying to match `t1 <: A` succeeded. If it recorded constraints, // those are the constraints we want. If it didn't, then there's no // way we're going to get any constraints. So either way, we want to // return `true` since the match suceeded and the constraints we want // (if any) have been recorded. return true; } else { // Trying to match `t1 <: A` failed. So there's no way we are going // to get any constraints. Just return `success` to indicate whether // the match succeeded. return success; } } } // S <: T where S is a type variable // T is not dynamic or object (handled above) // True if T == S // Or true if bound of S is S' and S' <: T if (t1 is TypeParameterType) { // Guard against recursive type parameters // // TODO(jmesserly): this function isn't guarding against anything (it's // not passsing down `visitedSet`, so adding the element has no effect). bool guardedSubtype(DartType t1, DartType t2) { var visitedSet = visited ?? new HashSet<Element>(); if (visitedSet.add(t1.element)) { bool matched = matchSubtype(t1, t2); visitedSet.remove(t1.element); return matched; } else { // In the case of a recursive type parameter, consider the subtype // match to have failed. return false; } } if (t2 is TypeParameterType && t1.definition == t2.definition) { return guardedSubtype(t1.bound, t2.bound); } return guardedSubtype(t1.bound, t2); } if (t2 is TypeParameterType) { return false; } // TODO(mfairhurst): switch legacy Bottom checks to true Bottom checks // TODO(mfairhurst): switch legacy Top checks to true Top checks if (_isLegacyBottom(t1, orTrueBottom: true) || _isLegacyTop(t2, orTrueTop: true)) return true; if (t1 is InterfaceType && t2 is InterfaceType) { return _matchInterfaceSubtypeOf(t1, t2, visited, origin, covariant: covariant); } if (t1 is FunctionType && t2 is FunctionType) { return FunctionTypeImpl.relate(t1, t2, matchSubtype, parameterRelation: (p1, p2) { return _matchSubtypeOf(p2.type, p1.type, null, origin, covariant: !covariant); }, // Type parameter bounds are invariant. boundsRelation: (t1, t2, p1, p2) => matchSubtype(t1, t2) && matchSubtype(t2, t1)); } if (t1 is FunctionType && t2 == typeProvider.functionType) { return true; } return false; } /// Un-does constraints that were gathered by a failed match attempt, until /// [_undoBuffer] has length [previousRewindBufferLength]. /// /// The intended usage is that the caller should record the length of /// [_undoBuffer] before attempting to make a match. Then, if the match /// fails, pass the recorded length to this method to erase any constraints /// that were recorded during the failed match. void _rewindConstraints(int previousRewindBufferLength) { while (_undoBuffer.length > previousRewindBufferLength) { var constraint = _undoBuffer.removeLast(); var element = constraint.typeParameter; assert(identical(constraints[element].last, constraint)); constraints[element].removeLast(); } } static String _formatConstraints(Iterable<_TypeConstraint> constraints) { List<List<String>> lineParts = new Set<_TypeConstraintOrigin>.from(constraints.map((c) => c.origin)) .map((o) => o.formatError()) .toList(); int prefixMax = lineParts.map((p) => p[0].length).fold(0, math.max); // Use a set to prevent identical message lines. // (It's not uncommon for the same constraint to show up in a few places.) var messageLines = new Set<String>.from(lineParts.map((parts) { var prefix = parts[0]; var middle = parts[1]; var prefixPad = ' ' * (prefixMax - prefix.length); var middlePad = ' ' * (prefixMax); var end = ""; if (parts.length > 2) { end = '\n $middlePad ${parts[2]}'; } return ' $prefix$prefixPad $middle$end'; })); return messageLines.join('\n'); } } /// The instantiation of a [ClassElement] with type arguments. /// /// It is not a [DartType] itself, because it does not have nullability. /// But it should be used where nullability does not make sense - to specify /// superclasses, mixins, and implemented interfaces. class InstantiatedClass { final ClassElement element; final List<DartType> arguments; final Substitution _substitution; InstantiatedClass(this.element, this.arguments) : _substitution = Substitution.fromPairs( element.typeParameters, arguments, ); /// Return the [InstantiatedClass] that corresponds to the [type] - with the /// same element and type arguments, ignoring its nullability suffix. factory InstantiatedClass.of(InterfaceType type) { return InstantiatedClass(type.element, type.typeArguments); } @override int get hashCode { var hash = 0x3fffffff & element.hashCode; for (var i = 0; i < arguments.length; i++) { hash = 0x3fffffff & (hash * 31 + (hash ^ arguments[i].hashCode)); } return hash; } /// Return the interfaces that are directly implemented by this class. List<InstantiatedClass> get interfaces { var interfaces = element.interfaces; var result = List<InstantiatedClass>(interfaces.length); for (var i = 0; i < interfaces.length; i++) { var interface = interfaces[i]; var substituted = _substitution.substituteType(interface); result[i] = InstantiatedClass.of(substituted); } return result; } /// Return `true` if this type represents the type 'Function' defined in the /// dart:core library. bool get isDartCoreFunction { return element.name == 'Function' && element.library.isDartCore; } /// Return the superclass of this type, or `null` if this type represents /// the class 'Object'. InstantiatedClass get superclass { var supertype = element.supertype; if (supertype == null) return null; supertype = _substitution.substituteType(supertype); return InstantiatedClass.of(supertype); } /// Return a list containing all of the superclass constraints defined for /// this class. The list will be empty if this class does not represent a /// mixin declaration. If this class _does_ represent a mixin declaration but /// the declaration does not have an `on` clause, then the list will contain /// the type for the class `Object`. List<InstantiatedClass> get superclassConstraints { var constraints = element.superclassConstraints; var result = List<InstantiatedClass>(constraints.length); for (var i = 0; i < constraints.length; i++) { var constraint = constraints[i]; var substituted = _substitution.substituteType(constraint); result[i] = InstantiatedClass.of(substituted); } return result; } @visibleForTesting InterfaceType get withNullabilitySuffixNone { return withNullability(NullabilitySuffix.none); } @override bool operator ==(Object other) { if (identical(this, other)) return true; if (other is InstantiatedClass) { if (element != other.element) return false; if (arguments.length != other.arguments.length) return false; for (var i = 0; i < arguments.length; i++) { if (arguments[i] != other.arguments[i]) return false; } return true; } return false; } @override String toString() { var buffer = StringBuffer(); buffer.write(element.name); if (arguments.isNotEmpty) { buffer.write('<'); buffer.write(arguments.join(', ')); buffer.write('>'); } return buffer.toString(); } InterfaceType withNullability(NullabilitySuffix nullability) { return InterfaceTypeImpl.explicit( element, arguments, nullabilitySuffix: nullability, ); } } class InterfaceLeastUpperBoundHelper { final TypeSystem typeSystem; InterfaceLeastUpperBoundHelper(this.typeSystem); /// This currently does not implement a very complete least upper bound /// algorithm, but handles a couple of the very common cases that are /// causing pain in real code. The current algorithm is: /// 1. If either of the types is a supertype of the other, return it. /// This is in fact the best result in this case. /// 2. If the two types have the same class element, then take the /// pointwise least upper bound of the type arguments. This is again /// the best result, except that the recursive calls may not return /// the true least upper bounds. The result is guaranteed to be a /// well-formed type under the assumption that the input types were /// well-formed (and assuming that the recursive calls return /// well-formed types). /// 3. Otherwise return the spec-defined least upper bound. This will /// be an upper bound, might (or might not) be least, and might /// (or might not) be a well-formed type. /// /// TODO(leafp): Use matchTypes or something similar here to handle the /// case where one of the types is a superclass (but not supertype) of /// the other, e.g. LUB(Iterable<double>, List<int>) = Iterable<num> /// TODO(leafp): Figure out the right final algorithm and implement it. InterfaceTypeImpl compute(InterfaceTypeImpl type1, InterfaceTypeImpl type2) { var nullability = _chooseNullability(type1, type2); // Strip off nullability. type1 = type1.withNullability(NullabilitySuffix.none); type2 = type2.withNullability(NullabilitySuffix.none); if (typeSystem.isSubtypeOf(type1, type2)) { return type2.withNullability(nullability); } if (typeSystem.isSubtypeOf(type2, type1)) { return type1.withNullability(nullability); } if (type1.element == type2.element) { var args1 = type1.typeArguments; var args2 = type2.typeArguments; assert(args1.length == args2.length); var args = List<DartType>(args1.length); for (int i = 0; i < args1.length; i++) { args[i] = typeSystem.getLeastUpperBound(args1[i], args2[i]); } return new InterfaceTypeImpl.explicit( type1.element, args, nullabilitySuffix: nullability, ); } var result = _computeLeastUpperBound( InstantiatedClass.of(type1), InstantiatedClass.of(type2), ); return result.withNullability(nullability); } /// Compute the least upper bound of types [i] and [j], both of which are /// known to be interface types. /// /// In the event that the algorithm fails (which might occur due to a bug in /// the analyzer), `null` is returned. InstantiatedClass _computeLeastUpperBound( InstantiatedClass i, InstantiatedClass j, ) { // compute set of supertypes var si = computeSuperinterfaceSet(i); var sj = computeSuperinterfaceSet(j); // union si with i and sj with j si.add(i); sj.add(j); // compute intersection, reference as set 's' var s = _intersection(si, sj); return _computeTypeAtMaxUniqueDepth(s); } /** * Return the length of the longest inheritance path from the [element] to * Object. */ @visibleForTesting static int computeLongestInheritancePathToObject(ClassElement element) { return _computeLongestInheritancePathToObject( element, 0, Set<ClassElement>(), ); } /// Return all of the superinterfaces of the given [type]. @visibleForTesting static Set<InstantiatedClass> computeSuperinterfaceSet( InstantiatedClass type) { var result = Set<InstantiatedClass>(); _addSuperinterfaces(result, type); return result; } /// Add all of the superinterfaces of the given [type] to the given [set]. static void _addSuperinterfaces( Set<InstantiatedClass> set, InstantiatedClass type) { for (var interface in type.interfaces) { if (!interface.isDartCoreFunction) { if (set.add(interface)) { _addSuperinterfaces(set, interface); } } } for (var constraint in type.superclassConstraints) { if (!constraint.isDartCoreFunction) { if (set.add(constraint)) { _addSuperinterfaces(set, constraint); } } } var supertype = type.superclass; if (supertype != null && !supertype.isDartCoreFunction) { if (set.add(supertype)) { _addSuperinterfaces(set, supertype); } } } static NullabilitySuffix _chooseNullability( InterfaceTypeImpl type1, InterfaceTypeImpl type2, ) { var nullability1 = type1.nullabilitySuffix; var nullability2 = type2.nullabilitySuffix; if (nullability1 == NullabilitySuffix.question || nullability2 == NullabilitySuffix.question) { return NullabilitySuffix.question; } else if (nullability1 == NullabilitySuffix.star || nullability2 == NullabilitySuffix.star) { return NullabilitySuffix.star; } return NullabilitySuffix.none; } /// Return the length of the longest inheritance path from a subtype of the /// given [element] to Object, where the given [depth] is the length of the /// longest path from the subtype to this type. The set of [visitedElements] /// is used to prevent infinite recursion in the case of a cyclic type /// structure. static int _computeLongestInheritancePathToObject( ClassElement element, int depth, Set<ClassElement> visitedElements) { // Object case if (element.isDartCoreObject || visitedElements.contains(element)) { return depth; } int longestPath = 1; try { visitedElements.add(element); int pathLength; // loop through each of the superinterfaces recursively calling this // method and keeping track of the longest path to return for (InterfaceType interface in element.superclassConstraints) { pathLength = _computeLongestInheritancePathToObject( interface.element, depth + 1, visitedElements); if (pathLength > longestPath) { longestPath = pathLength; } } // loop through each of the superinterfaces recursively calling this // method and keeping track of the longest path to return for (InterfaceType interface in element.interfaces) { pathLength = _computeLongestInheritancePathToObject( interface.element, depth + 1, visitedElements); if (pathLength > longestPath) { longestPath = pathLength; } } // finally, perform this same check on the super type // TODO(brianwilkerson) Does this also need to add in the number of mixin // classes? InterfaceType supertype = element.supertype; if (supertype != null) { pathLength = _computeLongestInheritancePathToObject( supertype.element, depth + 1, visitedElements); if (pathLength > longestPath) { longestPath = pathLength; } } } finally { visitedElements.remove(element); } return longestPath; } /// Return the type from the [types] list that has the longest inheritance /// path to Object of unique length. static InstantiatedClass _computeTypeAtMaxUniqueDepth( List<InstantiatedClass> types, ) { // for each element in Set s, compute the largest inheritance path to Object List<int> depths = new List<int>.filled(types.length, 0); int maxDepth = 0; for (int i = 0; i < types.length; i++) { depths[i] = computeLongestInheritancePathToObject(types[i].element); if (depths[i] > maxDepth) { maxDepth = depths[i]; } } // ensure that the currently computed maxDepth is unique, // otherwise, decrement and test for uniqueness again for (; maxDepth >= 0; maxDepth--) { int indexOfLeastUpperBound = -1; int numberOfTypesAtMaxDepth = 0; for (int m = 0; m < depths.length; m++) { if (depths[m] == maxDepth) { numberOfTypesAtMaxDepth++; indexOfLeastUpperBound = m; } } if (numberOfTypesAtMaxDepth == 1) { return types[indexOfLeastUpperBound]; } } // Should be impossible--there should always be exactly one type with the // maximum depth. assert(false); return null; } /** * Return the intersection of the [first] and [second] sets of types, where * intersection is based on the equality of the types themselves. */ static List<InstantiatedClass> _intersection( Set<InstantiatedClass> first, Set<InstantiatedClass> second, ) { var result = first.toSet(); result.retainAll(second); return result.toList(); } } /// Used to check for infinite loops, if we repeat the same type comparison. class TypeComparison { final DartType lhs; final DartType rhs; TypeComparison(this.lhs, this.rhs); @override int get hashCode => lhs.hashCode * 11 + rhs.hashCode; @override bool operator ==(Object other) { if (other is TypeComparison) { return lhs == other.lhs && rhs == other.rhs; } return false; } @override String toString() => "$lhs vs $rhs"; } /** * The interface `TypeSystem` defines the behavior of an object representing * the type system. This provides a common location to put methods that act on * types but may need access to more global data structures, and it paves the * way for a possible future where we may wish to make the type system * pluggable. */ // TODO(brianwilkerson) Rename this class to TypeSystemImpl. abstract class TypeSystem implements public.TypeSystem { /** * The provider of types for the system */ TypeProvider get typeProvider; @override DartType flatten(DartType type) { if (type is InterfaceType) { // Implement the cases: // - "If T = FutureOr<S> then flatten(T) = S." // - "If T = Future<S> then flatten(T) = S." if (type.isDartAsyncFutureOr || type.isDartAsyncFuture) { return type.typeArguments.isNotEmpty ? type.typeArguments[0] : DynamicTypeImpl.instance; } // Implement the case: "Otherwise if T <: Future then let S be a type // such that T << Future<S> and for all R, if T << Future<R> then S << R. // Then flatten(T) = S." // // In other words, given the set of all types R such that T << Future<R>, // let S be the most specific of those types, if any such S exists. // // Since we only care about the most specific type, it is sufficient to // look at the types appearing as a parameter to Future in the type // hierarchy of T. We don't need to consider the supertypes of those // types, since they are by definition less specific. List<DartType> candidateTypes = _searchTypeHierarchyForFutureTypeParameters(type); DartType flattenResult = InterfaceTypeImpl.findMostSpecificType(candidateTypes, this); if (flattenResult != null) { return flattenResult; } } // Implement the case: "In any other circumstance, flatten(T) = T." return type; } List<InterfaceType> gatherMixinSupertypeConstraintsForInference( ClassElement mixinElement) { List<InterfaceType> candidates; if (mixinElement.isMixin) { candidates = mixinElement.superclassConstraints; } else { candidates = [mixinElement.supertype]; candidates.addAll(mixinElement.mixins); if (mixinElement.isMixinApplication) { candidates.removeLast(); } } return candidates .where((type) => type.element.typeParameters.isNotEmpty) .toList(); } /** * Compute the least upper bound of two types. */ DartType getLeastUpperBound(DartType type1, DartType type2) { // The least upper bound relation is reflexive. if (identical(type1, type2)) { return type1; } // For any type T, LUB(?, T) == T. if (identical(type1, UnknownInferredType.instance)) { return type2; } if (identical(type2, UnknownInferredType.instance)) { return type1; } // For the purpose of LUB, we say some Tops are subtypes (less toppy) than // the others. Return the most toppy. // TODO(mfairhurst): switch legacy Top checks to true Top checks if (_isLegacyTop(type1, orTrueTop: true) && _isLegacyTop(type2, orTrueTop: true)) { return _getTopiness(type1) > _getTopiness(type2) ? type1 : type2; } // The least upper bound of top and any type T is top. // The least upper bound of bottom and any type T is T. // TODO(mfairhurst): switch legacy Top checks to true Top checks // TODO(mfairhurst): switch legacy Bottom checks to true Bottom checks if (_isLegacyTop(type1, orTrueTop: true) || _isLegacyBottom(type2, orTrueBottom: true)) { return type1; } // TODO(mfairhurst): switch legacy Top checks to true Top checks // TODO(mfairhurst): switch legacy Bottom checks to true Bottom checks if (_isLegacyTop(type2, orTrueTop: true) || _isLegacyBottom(type1, orTrueBottom: true)) { return type2; } if (type1 is TypeParameterType || type2 is TypeParameterType) { return _typeParameterLeastUpperBound(type1, type2); } // In Dart 1, the least upper bound of a function type and an interface type // T is the least upper bound of Function and T. // // In Dart 2, the result is `Function` iff T is `Function`, otherwise the // result is `Object`. if (type1 is FunctionType && type2 is InterfaceType) { return type2.isDartCoreFunction ? type2 : typeProvider.objectType; } if (type2 is FunctionType && type1 is InterfaceType) { return type1.isDartCoreFunction ? type1 : typeProvider.objectType; } // At this point type1 and type2 should both either be interface types or // function types. if (type1 is InterfaceType && type2 is InterfaceType) { return _interfaceLeastUpperBound(type1, type2); } if (type1 is FunctionType && type2 is FunctionType) { return _functionLeastUpperBound(type1, type2); } // Should never happen. As a defensive measure, return the dynamic type. assert(false); return typeProvider.dynamicType; } /** * Given a [DartType] [type], instantiate it with its bounds. * * The behavior of this method depends on the type system, for example, in * classic Dart `dynamic` will be used for all type arguments, whereas * strong mode prefers the actual bound type if it was specified. */ DartType instantiateToBounds(DartType type, {List<bool> hasError}); /** * Given a [DartType] [type] and a list of types * [typeArguments], instantiate the type formals with the * provided actuals. If [type] is not a parameterized type, * no instantiation is done. */ DartType instantiateType(DartType type, List<DartType> typeArguments) { if (type is ParameterizedType) { return type.instantiate(typeArguments); } else { return type; } } /** * Given uninstantiated [typeFormals], instantiate them to their bounds. */ List<DartType> instantiateTypeFormalsToBounds( List<TypeParameterElement> typeFormals, {List<bool> hasError}); /** * Return `true` if the [leftType] is assignable to the [rightType] (that is, * if leftType <==> rightType). Accepts a [FeatureSet] to correctly handle * NNBD implicit downcasts. */ bool isAssignableTo(DartType leftType, DartType rightType, {FeatureSet featureSet}); /** * Return `true` if the [leftType] is more specific than the [rightType] * (that is, if leftType << rightType), as defined in the Dart language spec. * * In strong mode, this is equivalent to [isSubtypeOf]. */ @Deprecated('Use isSubtypeOf() instead.') bool isMoreSpecificThan(DartType leftType, DartType rightType); @override bool isNonNullable(DartType type) { if (type.isDynamic || type.isVoid || type.isDartCoreNull) { return false; } else if ((type as TypeImpl).nullabilitySuffix == NullabilitySuffix.question) { return false; } else if (type.isDartAsyncFutureOr) { return isNonNullable((type as InterfaceType).typeArguments[0]); } else if (type is TypeParameterType) { return isNonNullable(type.bound); } return true; } @override bool isNullable(DartType type) { if (type.isDynamic || type.isVoid || type.isDartCoreNull) { return true; } else if ((type as TypeImpl).nullabilitySuffix == NullabilitySuffix.question) { return true; } else if (type.isDartAsyncFutureOr) { return isNullable((type as InterfaceType).typeArguments[0]); } return false; } /// Check that [f1] is a subtype of [f2] for a member override. /// /// This is different from the normal function subtyping in two ways: /// - we know the function types are strict arrows, /// - it allows opt-in covariant parameters. bool isOverrideSubtypeOf(FunctionType f1, FunctionType f2); @override bool isPotentiallyNonNullable(DartType type) => !isNullable(type); @override bool isPotentiallyNullable(DartType type) => !isNonNullable(type); /** * Return `true` if the [leftType] is a subtype of the [rightType] (that is, * if leftType <: rightType). */ bool isSubtypeOf(DartType leftType, DartType rightType); @override DartType leastUpperBound(DartType leftType, DartType rightType) { return getLeastUpperBound(leftType, rightType); } /// Returns a nullable version of [type]. The result would be equivalent to /// the union `type | Null` (if we supported union types). DartType makeNullable(TypeImpl type) { // TODO(paulberry): handle type parameter types return type.withNullability(NullabilitySuffix.question); } /// Attempts to find the appropriate substitution for the [mixinElement] /// type parameters that can be applied to [srcTypes] to make it equal to /// [destTypes]. If no such substitution can be found, `null` is returned. List<DartType> matchSupertypeConstraints( ClassElement mixinElement, List<DartType> srcTypes, List<DartType> destTypes, ) { var typeParameters = mixinElement.typeParameters; var inferrer = new GenericInferrer(typeProvider, this, typeParameters); for (int i = 0; i < srcTypes.length; i++) { inferrer.constrainReturnType(srcTypes[i], destTypes[i]); inferrer.constrainReturnType(destTypes[i], srcTypes[i]); } var inferredTypes = inferrer.infer( typeParameters, considerExtendsClause: false, ); var substitution = Substitution.fromPairs(typeParameters, inferredTypes); for (int i = 0; i < srcTypes.length; i++) { if (substitution.substituteType(srcTypes[i]) != destTypes[i]) { // Failed to find an appropriate substitution return null; } } return inferredTypes; } /** * Searches the superinterfaces of [type] for implementations of [genericType] * and returns the most specific type argument used for that generic type. * * For a more general/robust solution, use [InterfaceTypeImpl.asInstanceOf]. * * For example, given [type] `List<int>` and [genericType] `Iterable<T>`, * returns [int]. * * Returns `null` if [type] does not implement [genericType]. */ DartType mostSpecificTypeArgument(DartType type, DartType genericType) { if (type is! InterfaceType) return null; if (genericType is! InterfaceType) return null; var asInstanceOf = (type as InterfaceTypeImpl) .asInstanceOf((genericType as InterfaceType).element); if (asInstanceOf != null) { return asInstanceOf.typeArguments[0]; } return null; } /// Returns a non-nullable version of [type]. This is equivalent to the /// operation `NonNull` defined in the spec. DartType promoteToNonNull(covariant TypeImpl type) { if (type.isDartCoreNull) return BottomTypeImpl.instance; if (type is TypeParameterTypeImpl) { var promotedElement = TypeParameterElementImpl.synthetic( type.element.name, ); var bound = type.element.bound ?? typeProvider.objectType; promotedElement.bound = promoteToNonNull(bound); return TypeParameterTypeImpl( promotedElement, nullabilitySuffix: NullabilitySuffix.none, ); } return type.withNullability(NullabilitySuffix.none); } /** * Determine the type of a binary expression with the given [operator] whose * left operand has the type [leftType] and whose right operand has the type * [rightType], given that resolution has so far produced the [currentType]. * The [featureSet] is used to determine whether any features that effect the * computation have been enabled. */ DartType refineBinaryExpressionType(DartType leftType, TokenType operator, DartType rightType, DartType currentType, FeatureSet featureSet) { // bool if (operator == TokenType.AMPERSAND_AMPERSAND || operator == TokenType.BAR_BAR || operator == TokenType.EQ_EQ || operator == TokenType.BANG_EQ) { if (featureSet.isEnabled(Feature.non_nullable)) { return promoteToNonNull(typeProvider.boolType as TypeImpl); } return typeProvider.boolType; } if (leftType.isDartCoreInt) { // int op double if (operator == TokenType.MINUS || operator == TokenType.PERCENT || operator == TokenType.PLUS || operator == TokenType.STAR || operator == TokenType.MINUS_EQ || operator == TokenType.PERCENT_EQ || operator == TokenType.PLUS_EQ || operator == TokenType.STAR_EQ) { if (rightType.isDartCoreDouble) { InterfaceTypeImpl doubleType = typeProvider.doubleType; if (featureSet.isEnabled(Feature.non_nullable)) { return promoteToNonNull(doubleType); } return doubleType; } } // int op int if (operator == TokenType.MINUS || operator == TokenType.PERCENT || operator == TokenType.PLUS || operator == TokenType.STAR || operator == TokenType.TILDE_SLASH || operator == TokenType.MINUS_EQ || operator == TokenType.PERCENT_EQ || operator == TokenType.PLUS_EQ || operator == TokenType.STAR_EQ || operator == TokenType.TILDE_SLASH_EQ) { if (rightType.isDartCoreInt) { InterfaceTypeImpl intType = typeProvider.intType; if (featureSet.isEnabled(Feature.non_nullable)) { return promoteToNonNull(intType); } return intType; } } } // default return currentType; } @override DartType resolveToBound(DartType type) { if (type is TypeParameterTypeImpl) { var element = type.element; var bound = element.bound as TypeImpl; if (bound == null) { return typeProvider.objectType; } NullabilitySuffix nullabilitySuffix = type.nullabilitySuffix; NullabilitySuffix newNullabilitySuffix; if (nullabilitySuffix == NullabilitySuffix.question || bound.nullabilitySuffix == NullabilitySuffix.question) { newNullabilitySuffix = NullabilitySuffix.question; } else if (nullabilitySuffix == NullabilitySuffix.star || bound.nullabilitySuffix == NullabilitySuffix.star) { newNullabilitySuffix = NullabilitySuffix.star; } else { newNullabilitySuffix = NullabilitySuffix.none; } var resolved = resolveToBound(bound) as TypeImpl; return resolved.withNullability(newNullabilitySuffix); } return type; } /** * Tries to promote from the first type from the second type, and returns the * promoted type if it succeeds, otherwise null. */ DartType tryPromoteToType(DartType to, DartType from); /** * Given a [DartType] type, return the [TypeParameterElement]s corresponding * to its formal type parameters (if any). * * @param type the type whose type arguments are to be returned * @return the type arguments associated with the given type */ List<TypeParameterElement> typeFormalsAsElements(DartType type) { if (type is FunctionType) { return type.typeFormals; } else if (type is InterfaceType) { return type.typeParameters; } else { return const <TypeParameterElement>[]; } } /** * Given a [DartType] type, return the [DartType]s corresponding * to its formal type parameters (if any). * * @param type the type whose type arguments are to be returned * @return the type arguments associated with the given type */ List<DartType> typeFormalsAsTypes(DartType type) => TypeParameterTypeImpl.getTypes(typeFormalsAsElements(type)); /** * Compute the least upper bound of function types [f] and [g]. * * The spec rules for LUB on function types, informally, are pretty simple * (though unsound): * * - If the functions don't have the same number of required parameters, * always return `Function`. * * - Discard any optional named or positional parameters the two types do not * have in common. * * - Compute the LUB of each corresponding pair of parameter and return types. * Return a function type with those types. */ DartType _functionLeastUpperBound(FunctionType f, FunctionType g) { var fTypeFormals = f.typeFormals; var gTypeFormals = g.typeFormals; // If F and G differ in their number of type parameters, then the // least upper bound of F and G is Function. if (fTypeFormals.length != gTypeFormals.length) { return typeProvider.functionType; } // If F and G differ in bounds of their of type parameters, then the // least upper bound of F and G is Function. var freshTypeFormalTypes = FunctionTypeImpl.relateTypeFormals(f, g, (t, s, _, __) => t == s); if (freshTypeFormalTypes == null) { return typeProvider.functionType; } var typeFormals = freshTypeFormalTypes .map<TypeParameterElement>((t) => t.element) .toList(); f = f.instantiate(freshTypeFormalTypes); g = g.instantiate(freshTypeFormalTypes); List<DartType> fRequired = f.normalParameterTypes; List<DartType> gRequired = g.normalParameterTypes; // We need some parameter names for in the synthesized function type, so // arbitrarily use f's. List<String> fRequiredNames = f.normalParameterNames; List<String> fPositionalNames = f.optionalParameterNames; // If F and G differ in their number of required parameters, then the // least upper bound of F and G is Function. if (fRequired.length != gRequired.length) { return typeProvider.functionType; } // Calculate the LUB of each corresponding pair of parameters. List<ParameterElement> parameters = []; for (int i = 0; i < fRequired.length; i++) { parameters.add(new ParameterElementImpl.synthetic( fRequiredNames[i], _functionParameterBound(fRequired[i], gRequired[i]), ParameterKind.REQUIRED)); } List<DartType> fPositional = f.optionalParameterTypes; List<DartType> gPositional = g.optionalParameterTypes; // Ignore any extra optional positional parameters if one has more than the // other. int length = math.min(fPositional.length, gPositional.length); for (int i = 0; i < length; i++) { parameters.add(new ParameterElementImpl.synthetic( fPositionalNames[i], _functionParameterBound(fPositional[i], gPositional[i]), ParameterKind.POSITIONAL)); } // TODO(brianwilkerson) Handle the fact that named parameters can now be // required. Map<String, DartType> fNamed = f.namedParameterTypes; Map<String, DartType> gNamed = g.namedParameterTypes; for (String name in fNamed.keys.toSet()..retainAll(gNamed.keys)) { parameters.add(new ParameterElementImpl.synthetic( name, _functionParameterBound(fNamed[name], gNamed[name]), ParameterKind.NAMED)); } // Calculate the LUB of the return type. DartType returnType = getLeastUpperBound(f.returnType, g.returnType); return FunctionTypeImpl.synthetic(returnType, typeFormals, parameters); } /** * Calculates the appropriate upper or lower bound of a pair of parameters * for two function types whose least upper bound is being calculated. * * In spec mode, this uses least upper bound, which... doesn't really make * much sense. Strong mode overrides this to use greatest lower bound. */ DartType _functionParameterBound(DartType f, DartType g) => getLeastUpperBound(f, g); /** * Given two [InterfaceType]s [type1] and [type2] return their least upper * bound in a type system specific manner. */ DartType _interfaceLeastUpperBound(InterfaceType type1, InterfaceType type2); /** * Starting from the given [type], search its class hierarchy for types of the * form Future<R>, and return a list of the resulting R's. */ List<DartType> _searchTypeHierarchyForFutureTypeParameters(DartType type) { List<DartType> result = <DartType>[]; HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>(); void recurse(InterfaceTypeImpl type) { if (type.isDartAsyncFuture && type.typeArguments.isNotEmpty) { result.add(type.typeArguments[0]); } if (visitedClasses.add(type.element)) { if (type.superclass != null) { recurse(type.superclass); } for (InterfaceType interface in type.interfaces) { recurse(interface); } visitedClasses.remove(type.element); } } recurse(type); return result; } /** * Given two [DartType]s [type1] and [type2] at least one of which is a * [TypeParameterType], return their least upper bound in a type system * specific manner. */ DartType _typeParameterLeastUpperBound(DartType type1, DartType type2); /** * Create either a strong mode or regular type system based on context. */ static TypeSystem create(AnalysisContext context) { var options = context.analysisOptions as AnalysisOptionsImpl; return new Dart2TypeSystem(context.typeProvider, implicitCasts: options.implicitCasts, strictInference: options.strictInference); } } /// A type that is being inferred but is not currently known. /// /// This type will only appear in a downward inference context for type /// parameters that we do not know yet. Notationally it is written `?`, for /// example `List<?>`. This is distinct from `List<dynamic>`. These types will /// never appear in the final resolved AST. class UnknownInferredType extends TypeImpl { static final UnknownInferredType instance = new UnknownInferredType._(); UnknownInferredType._() : super(UnknownInferredTypeElement.instance, Keyword.DYNAMIC.lexeme); @override int get hashCode => 1; @override bool get isDynamic => true; @override NullabilitySuffix get nullabilitySuffix => NullabilitySuffix.star; @override bool operator ==(Object object) => identical(object, this); @override void appendTo(StringBuffer buffer, Set<TypeImpl> types, {bool withNullability = false}) { buffer.write('?'); } @override bool isMoreSpecificThan(DartType type, [bool withDynamic = false, Set<Element> visitedElements]) { // T is S if (identical(this, type)) { return true; } // else return withDynamic; } @override bool isSubtypeOf(DartType type) => true; @override bool isSupertypeOf(DartType type) => true; @override TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this; @override DartType replaceTopAndBottom(TypeProvider typeProvider, {bool isCovariant = true}) { // In theory this should never happen, since we only need to do this // replacement when checking super-boundedness of explicitly-specified // types, or types produced by mixin inference or instantiate-to-bounds, and // the unknown type can't occur in any of those cases. assert( false, 'Attempted to check super-boundedness of a type including "?"'); // But just in case it does, behave similar to `dynamic`. if (isCovariant) { return typeProvider.nullType; } else { return this; } } @override DartType substitute2( List<DartType> argumentTypes, List<DartType> parameterTypes, [List<FunctionTypeAliasElement> prune]) { int length = parameterTypes.length; for (int i = 0; i < length; i++) { if (parameterTypes[i] == this) { return argumentTypes[i]; } } return this; } @override TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) => this; /// Given a [type] T, return true if it does not have an unknown type `?`. static bool isKnown(DartType type) => !isUnknown(type); /// Given a [type] T, return true if it has an unknown type `?`. static bool isUnknown(DartType type) { if (identical(type, UnknownInferredType.instance)) { return true; } if (type is InterfaceTypeImpl) { return type.typeArguments.any(isUnknown); } if (type is FunctionType) { return isUnknown(type.returnType) || type.parameters.any((p) => isUnknown(p.type)); } return false; } } /// The synthetic element for [UnknownInferredType]. class UnknownInferredTypeElement extends ElementImpl implements TypeDefiningElement { static final UnknownInferredTypeElement instance = new UnknownInferredTypeElement._(); UnknownInferredTypeElement._() : super(Keyword.DYNAMIC.lexeme, -1) { setModifier(Modifier.SYNTHETIC, true); } @override ElementKind get kind => ElementKind.DYNAMIC; @override UnknownInferredType get type => UnknownInferredType.instance; @override T accept<T>(ElementVisitor visitor) => null; } /// A constraint on a type parameter that we're inferring. class _TypeConstraint extends _TypeRange { /// The type parameter that is constrained by [lowerBound] or [upperBound]. final TypeParameterElement typeParameter; /// Where this constraint comes from, used for error messages. /// /// See [toString]. final _TypeConstraintOrigin origin; _TypeConstraint(this.origin, this.typeParameter, {DartType upper, DartType lower}) : super(upper: upper, lower: lower); _TypeConstraint.fromExtends( TypeParameterElement element, DartType extendsType) : this( new _TypeConstraintFromExtendsClause(element, extendsType), element, upper: extendsType); bool get isDownwards => origin is! _TypeConstraintFromArgument; bool isSatisifedBy(TypeSystem ts, DartType type) => ts.isSubtypeOf(lowerBound, type) && ts.isSubtypeOf(type, upperBound); /// Converts this constraint to a message suitable for a type inference error. @override String toString() => !identical(upperBound, UnknownInferredType.instance) ? "'$typeParameter' must extend '$upperBound'" : "'$lowerBound' must extend '$typeParameter'"; } class _TypeConstraintFromArgument extends _TypeConstraintOrigin { final DartType argumentType; final DartType parameterType; final String parameterName; final ClassElement genericClass; _TypeConstraintFromArgument( this.argumentType, this.parameterType, this.parameterName, {this.genericClass}); @override formatError() { // TODO(jmesserly): we should highlight the span. That would be more useful. // However in summary code it doesn't look like the AST node with span is // available. String prefix; if (genericClass != null && (genericClass.name == "List" || genericClass.name == "Map") && genericClass.library.isDartCore == true) { // This will become: // "List element" // "Map key" // "Map value" prefix = "${genericClass.name} $parameterName"; } else { prefix = "Parameter '$parameterName'"; } return [ prefix, "declared as '$parameterType'", "but argument is '$argumentType'." ]; } } class _TypeConstraintFromExtendsClause extends _TypeConstraintOrigin { final TypeParameterElement typeParam; final DartType extendsType; _TypeConstraintFromExtendsClause(this.typeParam, this.extendsType); @override formatError() { return [ "Type parameter '${typeParam.name}'", "declared to extend '$extendsType'." ]; } } class _TypeConstraintFromFunctionContext extends _TypeConstraintOrigin { final DartType contextType; final DartType functionType; _TypeConstraintFromFunctionContext(this.functionType, this.contextType); @override formatError() { return [ "Function type", "declared as '$functionType'", "used where '$contextType' is required." ]; } } class _TypeConstraintFromReturnType extends _TypeConstraintOrigin { final DartType contextType; final DartType declaredType; _TypeConstraintFromReturnType(this.declaredType, this.contextType); @override formatError() { return [ "Return type", "declared as '$declaredType'", "used where '$contextType' is required." ]; } } /// The origin of a type constraint, for the purposes of producing a human /// readable error message during type inference as well as determining whether /// the constraint was used to fix the type parameter or not. abstract class _TypeConstraintOrigin { List<String> formatError(); } class _TypeRange { /// The upper bound of the type parameter. In other words, T <: upperBound. /// /// In Dart this can be written as `<T extends UpperBoundType>`. /// /// In inference, this can happen as a result of parameters of function type. /// For example, consider a signature like: /// /// T reduce<T>(List<T> values, T f(T x, T y)); /// /// and a call to it like: /// /// reduce(values, (num x, num y) => ...); /// /// From the function expression's parameters, we conclude `T <: num`. We may /// still be able to conclude a different [lower] based on `values` or /// the type of the elided `=> ...` body. For example: /// /// reduce(['x'], (num x, num y) => 'hi'); /// /// Here the [lower] will be `String` and the upper bound will be `num`, /// which cannot be satisfied, so this is ill typed. final DartType upperBound; /// The lower bound of the type parameter. In other words, lowerBound <: T. /// /// This kind of constraint cannot be expressed in Dart, but it applies when /// we're doing inference. For example, consider a signature like: /// /// T pickAtRandom<T>(T x, T y); /// /// and a call to it like: /// /// pickAtRandom(1, 2.0) /// /// when we see the first parameter is an `int`, we know that `int <: T`. /// When we see `double` this implies `double <: T`. /// Combining these constraints results in a lower bound of `num`. /// /// In general, we choose the lower bound as our inferred type, so we can /// offer the most constrained (strongest) result type. final DartType lowerBound; _TypeRange({DartType lower, DartType upper}) : lowerBound = lower ?? UnknownInferredType.instance, upperBound = upper ?? UnknownInferredType.instance; /// Formats the typeRange as a string suitable for unit testing. /// /// For example, if [typeName] is 'T' and the range has bounds int and Object /// respectively, the returned string will be 'int <: T <: Object'. @visibleForTesting String format(String typeName) { var lowerString = identical(lowerBound, UnknownInferredType.instance) ? '' : '$lowerBound <: '; var upperString = identical(upperBound, UnknownInferredType.instance) ? '' : ' <: $upperBound'; return '$lowerString$typeName$upperString'; } @override String toString() => format('(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/element.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. /** * This library is deprecated. Please convert all references to this library to * reference one of the following public libraries: * * package:analyzer/dart/element/element.dart * * package:analyzer/dart/element/type.dart * * package:analyzer/dart/element/visitor.dart * * If your code is using APIs not available in these public libraries, please * contact the analyzer team to either find an alternate API or have the API you * depend on added to the public API. */ @deprecated library analyzer.src.generated.element; export 'package:analyzer/dart/element/element.dart'; export 'package:analyzer/dart/element/type.dart'; export 'package:analyzer/dart/element/visitor.dart'; export 'package:analyzer/src/dart/element/element.dart'; export 'package:analyzer/src/dart/element/member.dart'; export 'package:analyzer/src/dart/element/type.dart';
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_collection.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/src/generated/java_core.dart'; /** * Returns `true` if a and b contain equal elements in the same order. */ bool listsEqual(List a, List b) { // TODO(rnystrom): package:collection also implements this, and analyzer // already transitively depends on that package. Consider using it instead. if (identical(a, b)) { return true; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } /** * Methods for operating on integers as if they were arrays of booleans. These * arrays can be indexed by either integers or by enumeration constants. */ class BooleanArray { /** * Return the value of the element of the given [array] at the given [index]. */ static bool get(int array, int index) { _checkIndex(index); return (array & (1 << index)) > 0; } /** * Return the value of the element at the given index. */ @deprecated static bool getEnum<E extends Enum<E>>(int array, Enum<E> index) => get(array, index.ordinal); /** * Set the value of the element of the given [array] at the given [index] to * the given [value]. */ static int set(int array, int index, bool value) { _checkIndex(index); if (value) { return array | (1 << index); } else { return array & ~(1 << index); } } /** * Set the value of the element at the given index to the given value. */ @deprecated static int setEnum<E extends Enum<E>>(int array, Enum<E> index, bool value) => set(array, index.ordinal, value); /** * Throw an exception if the index is not within the bounds allowed for an * integer-encoded array of boolean values. */ static void _checkIndex(int index) { if (index < 0 || index > 30) { throw new RangeError("Index not between 0 and 30: $index"); } } }
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/parser.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. library analyzer.parser; import 'dart:collection'; import "dart:math" as math; 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/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/token.dart'; import 'package:analyzer/src/dart/error/syntactic_errors.dart'; import 'package:analyzer/src/dart/scanner/reader.dart'; import 'package:analyzer/src/dart/scanner/scanner.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/fasta/ast_builder.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine; import 'package:analyzer/src/generated/java_core.dart'; import 'package:analyzer/src/generated/java_engine.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:front_end/src/fasta/parser/identifier_context.dart' as fasta; import 'package:front_end/src/fasta/parser/member_kind.dart' as fasta; import 'package:front_end/src/fasta/parser/parser.dart' as fasta; import 'package:front_end/src/fasta/parser/type_info.dart' as fasta; import 'package:front_end/src/fasta/scanner.dart' as fasta; import 'package:meta/meta.dart'; export 'package:analyzer/src/dart/ast/utilities.dart' show ResolutionCopier; export 'package:analyzer/src/dart/error/syntactic_errors.dart'; part 'parser_fasta.dart'; /// A simple data-holder for a method that needs to return multiple values. class CommentAndMetadata { /// The documentation comment that was parsed, or `null` if none was given. final Comment comment; /// The metadata that was parsed, or `null` if none was given. final List<Annotation> metadata; /// Initialize a newly created holder with the given [comment] and [metadata]. CommentAndMetadata(this.comment, this.metadata); /// Return `true` if some metadata was parsed. bool get hasMetadata => metadata != null && metadata.isNotEmpty; } /// A simple data-holder for a method that needs to return multiple values. class FinalConstVarOrType { /// The 'final', 'const' or 'var' keyword, or `null` if none was given. final Token keyword; /// The type, or `null` if no type was specified. final TypeAnnotation type; /// Initialize a newly created holder with the given [keyword] and [type]. FinalConstVarOrType(this.keyword, this.type); } /// A simple data-holder for a method that needs to return multiple values. class Modifiers { /// The token representing the keyword 'abstract', or `null` if the keyword /// was not found. Token abstractKeyword; /// The token representing the keyword 'const', or `null` if the keyword was /// not found. Token constKeyword; /// The token representing the keyword 'covariant', or `null` if the keyword /// was not found. Token covariantKeyword; /// The token representing the keyword 'external', or `null` if the keyword /// was not found. Token externalKeyword; /// The token representing the keyword 'factory', or `null` if the keyword was /// not found. Token factoryKeyword; /// The token representing the keyword 'final', or `null` if the keyword was /// not found. Token finalKeyword; /// The token representing the keyword 'static', or `null` if the keyword was /// not found. Token staticKeyword; /// The token representing the keyword 'var', or `null` if the keyword was not /// found. Token varKeyword; @override String toString() { StringBuffer buffer = new StringBuffer(); bool needsSpace = _appendKeyword(buffer, false, abstractKeyword); needsSpace = _appendKeyword(buffer, needsSpace, constKeyword); needsSpace = _appendKeyword(buffer, needsSpace, externalKeyword); needsSpace = _appendKeyword(buffer, needsSpace, factoryKeyword); needsSpace = _appendKeyword(buffer, needsSpace, finalKeyword); needsSpace = _appendKeyword(buffer, needsSpace, staticKeyword); _appendKeyword(buffer, needsSpace, varKeyword); return buffer.toString(); } /// If the given [keyword] is not `null`, append it to the given [builder], /// prefixing it with a space if [needsSpace] is `true`. Return `true` if /// subsequent keywords need to be prefixed with a space. bool _appendKeyword(StringBuffer buffer, bool needsSpace, Token keyword) { if (keyword != null) { if (needsSpace) { buffer.writeCharCode(0x20); } buffer.write(keyword.lexeme); return true; } return needsSpace; } } /// A parser used to parse tokens into an AST structure. class Parser { static String ASYNC = Keyword.ASYNC.lexeme; static String _AWAIT = Keyword.AWAIT.lexeme; static String _HIDE = Keyword.HIDE.lexeme; static String _SHOW = Keyword.SHOW.lexeme; static String SYNC = Keyword.SYNC.lexeme; static String _YIELD = Keyword.YIELD.lexeme; static const int _MAX_TREE_DEPTH = 300; /// A flag indicating whether the analyzer [Parser] factory method /// will return a fasta based parser or an analyzer based parser. static const bool useFasta = const bool.fromEnvironment("useFastaParser", defaultValue: true); /// The source being parsed. final Source _source; /// The error listener that will be informed of any errors that are found /// during the parse. final AnalysisErrorListener _errorListener; /// An [_errorListener] lock, if more than `0`, then errors are not reported. int _errorListenerLock = 0; /// A flag indicating whether the parser should parse instance creation /// expressions that lack either the `new` or `const` keyword. bool _enableOptionalNewAndConst = true; /// A flag indicating whether parser is to parse function bodies. bool _parseFunctionBodies = true; /// The next token to be parsed. Token _currentToken; /// The depth of the current AST. When this depth is too high, so we're at the /// risk of overflowing the stack, we stop parsing and report an error. int _treeDepth = 0; /// A flag indicating whether the parser is currently in a function body /// marked as being 'async'. bool _inAsync = false; /// A flag indicating whether the parser is currently in a function body /// marked(by a star) as being a generator. bool _inGenerator = false; /// A flag indicating whether the parser is currently in the body of a loop. bool _inLoop = false; /// A flag indicating whether the parser is currently in a switch statement. bool _inSwitch = false; /// A flag indicating whether the parser is currently in a constructor field /// initializer, with no intervening parentheses, braces, or brackets. bool _inInitializer = false; /// A flag indicating whether the parser is to parse generic method syntax. @deprecated bool parseGenericMethods = false; bool allowNativeClause; FeatureSet _featureSet; /// Initialize a newly created parser to parse tokens in the given [_source] /// and to report any errors that are found to the given [_errorListener]. factory Parser(Source source, AnalysisErrorListener errorListener, {bool useFasta, @required FeatureSet featureSet}) { featureSet ??= FeatureSet.fromEnableFlags([]); if (useFasta ?? Parser.useFasta) { return new _Parser2(source, errorListener, featureSet, allowNativeClause: true); } else { return new Parser.withoutFasta(source, errorListener, featureSet: featureSet); } } /// Creates a parser using the old (legacy) analyzer parsing logic. /// /// In a future major version release of the analyzer, the [featureSet] /// argument will be required. Parser.withoutFasta(this._source, this._errorListener, {FeatureSet featureSet}) { if (featureSet != null) { _configureFeatures(featureSet); } } /// Return the current token. Token get currentToken => _currentToken; /// Set the token with which the parse is to begin to the given [token]. void set currentToken(Token token) { this._currentToken = token; } /// Return `true` if the parser is to parse asserts in the initializer list of /// a constructor. @deprecated bool get enableAssertInitializer => true; /// Set whether the parser is to parse asserts in the initializer list of a /// constructor to match the given [enable] flag. @deprecated void set enableAssertInitializer(bool enable) {} /// Return `true` if the parser should parse instance creation expressions /// that lack either the `new` or `const` keyword. bool get enableOptionalNewAndConst => _enableOptionalNewAndConst; /// Set whether the parser should parse instance creation expressions that /// lack either the `new` or `const` keyword. void set enableOptionalNewAndConst(bool enable) { _enableOptionalNewAndConst = enable; } /// Enables or disables parsing of set literals. void set enableSetLiterals(bool value) { // TODO(danrubel): Remove this method once the reference to this flag // has been removed from dartfmt. } /// Return `true` if the parser is to allow URI's in part-of directives. @deprecated bool get enableUriInPartOf => true; /// Set whether the parser is to allow URI's in part-of directives to the /// given [enable] flag. @deprecated void set enableUriInPartOf(bool enable) {} /// Return `true` if the current token is the first token of a return type /// that is followed by an identifier, possibly followed by a list of type /// parameters, followed by a left-parenthesis. This is used by /// [parseTypeAlias] to determine whether or not to parse a return type. bool get hasReturnTypeInTypeAlias { // TODO(brianwilkerson) This is too expensive as implemented and needs to be // re-implemented or removed. Token next = skipTypeAnnotation(_currentToken); if (next == null) { return false; } return _tokenMatchesIdentifier(next); } /// Set whether the parser is to parse the async support. /// /// Support for removing the 'async' library has been removed. @deprecated void set parseAsync(bool parseAsync) {} @deprecated bool get parseConditionalDirectives => true; @deprecated void set parseConditionalDirectives(bool value) {} /// Set whether parser is to parse function bodies. void set parseFunctionBodies(bool parseFunctionBodies) { this._parseFunctionBodies = parseFunctionBodies; } /// Return the content of a string with the given literal representation. The /// [lexeme] is the literal representation of the string. The flag [isFirst] /// is `true` if this is the first token in a string literal. The flag /// [isLast] is `true` if this is the last token in a string literal. String computeStringValue(String lexeme, bool isFirst, bool isLast) { StringLexemeHelper helper = new StringLexemeHelper(lexeme, isFirst, isLast); int start = helper.start; int end = helper.end; bool stringEndsAfterStart = end >= start; assert(stringEndsAfterStart); if (!stringEndsAfterStart) { AnalysisEngine.instance.logger.logError( "Internal error: computeStringValue($lexeme, $isFirst, $isLast)"); return ""; } if (helper.isRaw) { return lexeme.substring(start, end); } StringBuffer buffer = new StringBuffer(); int index = start; while (index < end) { index = _translateCharacter(buffer, lexeme, index); } return buffer.toString(); } /// Return a synthetic identifier. SimpleIdentifier createSyntheticIdentifier({bool isDeclaration: false}) { Token syntheticToken; if (_currentToken.type.isKeyword) { // Consider current keyword token as an identifier. // It is not always true, e.g. "^is T" where "^" is place the place for // synthetic identifier. By creating SyntheticStringToken we can // distinguish a real identifier from synthetic. In the code completion // behavior will depend on a cursor position - before or on "is". syntheticToken = _injectToken(new SyntheticStringToken( TokenType.IDENTIFIER, _currentToken.lexeme, _currentToken.offset)); } else { syntheticToken = _createSyntheticToken(TokenType.IDENTIFIER); } return astFactory.simpleIdentifier(syntheticToken, isDeclaration: isDeclaration); } /// Return a synthetic string literal. SimpleStringLiteral createSyntheticStringLiteral() => astFactory .simpleStringLiteral(_createSyntheticToken(TokenType.STRING), ""); /// Advance to the next token in the token stream, making it the new current /// token and return the token that was current before this method was /// invoked. Token getAndAdvance() { Token token = _currentToken; _currentToken = _currentToken.next; return token; } /// Return `true` if the current token appears to be the beginning of a /// function declaration. bool isFunctionDeclaration() { Keyword keyword = _currentToken.keyword; Token afterReturnType = skipTypeWithoutFunction(_currentToken); if (afterReturnType != null && _tokenMatchesKeyword(afterReturnType, Keyword.FUNCTION)) { afterReturnType = skipGenericFunctionTypeAfterReturnType(afterReturnType); } if (afterReturnType == null) { // There was no return type, but it is optional, so go back to where we // started. afterReturnType = _currentToken; } Token afterIdentifier = skipSimpleIdentifier(afterReturnType); if (afterIdentifier == null) { // It's possible that we parsed the function name as if it were a type // name, so see whether it makes sense if we assume that there is no type. afterIdentifier = skipSimpleIdentifier(_currentToken); } if (afterIdentifier == null) { return false; } if (isFunctionExpression(afterIdentifier)) { return true; } // It's possible that we have found a getter. While this isn't valid at this // point we test for it in order to recover better. if (keyword == Keyword.GET) { Token afterName = skipSimpleIdentifier(_currentToken.next); if (afterName == null) { return false; } TokenType type = afterName.type; return type == TokenType.FUNCTION || type == TokenType.OPEN_CURLY_BRACKET; } else if (_tokenMatchesKeyword(afterReturnType, Keyword.GET)) { Token afterName = skipSimpleIdentifier(afterReturnType.next); if (afterName == null) { return false; } TokenType type = afterName.type; return type == TokenType.FUNCTION || type == TokenType.OPEN_CURLY_BRACKET; } return false; } /// Return `true` if the given [token] appears to be the beginning of a /// function expression. bool isFunctionExpression(Token token) { // Function expressions aren't allowed in initializer lists. if (_inInitializer) { return false; } Token afterTypeParameters = _skipTypeParameterList(token); if (afterTypeParameters == null) { afterTypeParameters = token; } Token afterParameters = _skipFormalParameterList(afterTypeParameters); if (afterParameters == null) { return false; } if (afterParameters.matchesAny( const <TokenType>[TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION])) { return true; } String lexeme = afterParameters.lexeme; return lexeme == ASYNC || lexeme == SYNC; } /// Return `true` if the current token is the first token in an initialized /// variable declaration rather than an expression. This method assumes that /// we have already skipped past any metadata that might be associated with /// the declaration. /// /// initializedVariableDeclaration ::= /// declaredIdentifier ('=' expression)? (',' initializedIdentifier)* /// /// declaredIdentifier ::= /// metadata finalConstVarOrType identifier /// /// finalConstVarOrType ::= /// 'final' type? /// | 'const' type? /// | 'var' /// | type /// /// type ::= /// qualified typeArguments? /// /// initializedIdentifier ::= /// identifier ('=' expression)? bool isInitializedVariableDeclaration() { Keyword keyword = _currentToken.keyword; if (keyword == Keyword.FINAL || keyword == Keyword.VAR || keyword == Keyword.VOID) { // An expression cannot start with a keyword other than 'const', // 'rethrow', or 'throw'. return true; } if (keyword == Keyword.CONST) { // Look to see whether we might be at the start of a list or map literal, // otherwise this should be the start of a variable declaration. return !_peek().matchesAny(const <TokenType>[ TokenType.LT, TokenType.OPEN_CURLY_BRACKET, TokenType.OPEN_SQUARE_BRACKET, TokenType.INDEX ]); } bool allowAdditionalTokens = true; // We know that we have an identifier, and need to see whether it might be // a type name. if (_currentToken.type != TokenType.IDENTIFIER) { allowAdditionalTokens = false; } Token token = skipTypeName(_currentToken); if (token == null) { // There was no type name, so this can't be a declaration. return false; } while (_atGenericFunctionTypeAfterReturnType(token)) { token = skipGenericFunctionTypeAfterReturnType(token); if (token == null) { // There was no type name, so this can't be a declaration. return false; } } if (token.type != TokenType.IDENTIFIER) { allowAdditionalTokens = false; } token = skipSimpleIdentifier(token); if (token == null) { return false; } TokenType type = token.type; // Usual cases in valid code: // String v = ''; // String v, v2; // String v; // for (String item in items) {} if (type == TokenType.EQ || type == TokenType.COMMA || type == TokenType.SEMICOLON || token.keyword == Keyword.IN) { return true; } // It is OK to parse as a variable declaration in these cases: // String v } // String v if (true) print('OK'); // String v { print(42); } // ...but not in these cases: // get getterName { // String get getterName if (allowAdditionalTokens) { if (type == TokenType.CLOSE_CURLY_BRACKET || type.isKeyword || type == TokenType.IDENTIFIER || type == TokenType.OPEN_CURLY_BRACKET) { return true; } } return false; } /// Return `true` if the current token appears to be the beginning of a switch /// member. bool isSwitchMember() { Token token = _currentToken; while (_tokenMatches(token, TokenType.IDENTIFIER) && _tokenMatches(token.next, TokenType.COLON)) { token = token.next.next; } Keyword keyword = token.keyword; return keyword == Keyword.CASE || keyword == Keyword.DEFAULT; } /// Parse an additive expression. Return the additive expression that was /// parsed. /// /// additiveExpression ::= /// multiplicativeExpression (additiveOperator multiplicativeExpression)* /// | 'super' (additiveOperator multiplicativeExpression)+ Expression parseAdditiveExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type.isAdditiveOperator) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseMultiplicativeExpression(); } while (_currentToken.type.isAdditiveOperator) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseMultiplicativeExpression()); } return expression; } /// Parse an annotation. Return the annotation that was parsed. /// /// This method assumes that the current token matches [TokenType.AT]. /// /// annotation ::= /// '@' qualified ('.' identifier)? arguments? Annotation parseAnnotation() { Token atSign = getAndAdvance(); Identifier name = parsePrefixedIdentifier(); Token period; SimpleIdentifier constructorName; if (_matches(TokenType.PERIOD)) { period = getAndAdvance(); constructorName = parseSimpleIdentifier(); } ArgumentList arguments; if (_matches(TokenType.OPEN_PAREN)) { arguments = parseArgumentList(); } return astFactory.annotation( atSign, name, period, constructorName, arguments); } /// Parse an argument. Return the argument that was parsed. /// /// argument ::= /// namedArgument /// | expression /// /// namedArgument ::= /// label expression Expression parseArgument() { // TODO(brianwilkerson) Consider returning a wrapper indicating whether the // expression is a named expression in order to remove the 'is' check in // 'parseArgumentList'. // // Both namedArgument and expression can start with an identifier, but only // namedArgument can have an identifier followed by a colon. // if (_matchesIdentifier() && _tokenMatches(_peek(), TokenType.COLON)) { return astFactory.namedExpression(parseLabel(), parseExpression2()); } else { return parseExpression2(); } } /// Parse a list of arguments. Return the argument list that was parsed. /// /// This method assumes that the current token matches [TokenType.OPEN_PAREN]. /// /// arguments ::= /// '(' argumentList? ')' /// /// argumentList ::= /// namedArgument (',' namedArgument)* /// | expressionList (',' namedArgument)* ArgumentList parseArgumentList() { Token leftParenthesis = getAndAdvance(); if (_matches(TokenType.CLOSE_PAREN)) { return astFactory.argumentList(leftParenthesis, null, getAndAdvance()); } /// Return `true` if the parser appears to be at the beginning of an /// argument even though there was no comma. This is a special case of the /// more general recovery technique described below. bool isLikelyMissingComma() { if (_matchesIdentifier() && _tokenMatches(_currentToken.next, TokenType.COLON) && leftParenthesis is BeginToken && leftParenthesis.endToken != null) { _reportErrorForToken( ParserErrorCode.EXPECTED_TOKEN, _currentToken.previous, [',']); return true; } return false; } // // Even though unnamed arguments must all appear before any named arguments, // we allow them to appear in any order so that we can recover faster. // bool wasInInitializer = _inInitializer; _inInitializer = false; try { Token previousStartOfArgument = _currentToken; Expression argument = parseArgument(); List<Expression> arguments = <Expression>[argument]; bool foundNamedArgument = argument is NamedExpression; bool generatedError = false; while (_optional(TokenType.COMMA) || (isLikelyMissingComma() && previousStartOfArgument != _currentToken)) { if (_matches(TokenType.CLOSE_PAREN)) { break; } previousStartOfArgument = _currentToken; argument = parseArgument(); arguments.add(argument); if (argument is NamedExpression) { foundNamedArgument = true; } else if (foundNamedArgument) { if (!generatedError) { if (!argument.isSynthetic) { // Report the error, once, but allow the arguments to be in any // order in the AST. _reportErrorForCurrentToken( ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT); generatedError = true; } } } } // Recovery: If the next token is not a right parenthesis, look at the // left parenthesis to see whether there is a matching right parenthesis. // If there is, then we're more likely missing a comma and should go back // to parsing arguments. Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); return astFactory.argumentList( leftParenthesis, arguments, rightParenthesis); } finally { _inInitializer = wasInInitializer; } } /// Parse an assert statement. Return the assert statement. /// /// This method assumes that the current token matches `Keyword.ASSERT`. /// /// assertStatement ::= /// 'assert' '(' expression [',' expression] ')' ';' AssertStatement parseAssertStatement() { Token keyword = getAndAdvance(); Token leftParen = _expect(TokenType.OPEN_PAREN); Expression expression = parseExpression2(); Token comma; Expression message; if (_matches(TokenType.COMMA)) { comma = getAndAdvance(); if (_matches(TokenType.CLOSE_PAREN)) { comma; } else { message = parseExpression2(); if (_matches(TokenType.COMMA)) { getAndAdvance(); } } } Token rightParen = _expect(TokenType.CLOSE_PAREN); Token semicolon = _expect(TokenType.SEMICOLON); // TODO(brianwilkerson) We should capture the trailing comma in the AST, but // that would be a breaking change, so we drop it for now. return astFactory.assertStatement( keyword, leftParen, expression, comma, message, rightParen, semicolon); } /// Parse an assignable expression. The [primaryAllowed] is `true` if the /// expression is allowed to be a primary without any assignable selector. /// Return the assignable expression that was parsed. /// /// assignableExpression ::= /// primary (arguments* assignableSelector)+ /// | 'super' unconditionalAssignableSelector /// | identifier Expression parseAssignableExpression(bool primaryAllowed) { // // A primary expression can start with an identifier. We resolve the // ambiguity by determining whether the primary consists of anything other // than an identifier and/or is followed by an assignableSelector. // Expression expression = parsePrimaryExpression(); bool isOptional = primaryAllowed || _isValidAssignableExpression(expression); while (true) { while (_isLikelyArgumentList()) { TypeArgumentList typeArguments = _parseOptionalTypeArguments(); ArgumentList argumentList = parseArgumentList(); Expression currentExpression = expression; if (currentExpression is SimpleIdentifier) { expression = astFactory.methodInvocation( null, null, currentExpression, typeArguments, argumentList); } else if (currentExpression is PrefixedIdentifier) { expression = astFactory.methodInvocation( currentExpression.prefix, currentExpression.period, currentExpression.identifier, typeArguments, argumentList); } else if (currentExpression is PropertyAccess) { expression = astFactory.methodInvocation( currentExpression.target, currentExpression.operator, currentExpression.propertyName, typeArguments, argumentList); } else { expression = astFactory.functionExpressionInvocation( expression, typeArguments, argumentList); } if (!primaryAllowed) { isOptional = false; } } Expression selectorExpression = parseAssignableSelector( expression, isOptional || (expression is PrefixedIdentifier)); if (identical(selectorExpression, expression)) { return expression; } expression = selectorExpression; isOptional = true; } } /// Parse an assignable selector. The [prefix] is the expression preceding the /// selector. The [optional] is `true` if the selector is optional. Return the /// assignable selector that was parsed, or the original prefix if there was /// no assignable selector. If [allowConditional] is false, then the '?.' /// operator will still be parsed, but a parse error will be generated. /// /// unconditionalAssignableSelector ::= /// '[' expression ']' /// | '.' identifier /// /// assignableSelector ::= /// unconditionalAssignableSelector /// | '?.' identifier Expression parseAssignableSelector(Expression prefix, bool optional, {bool allowConditional: true}) { TokenType type = _currentToken.type; if (type == TokenType.OPEN_SQUARE_BRACKET) { Token leftBracket = getAndAdvance(); bool wasInInitializer = _inInitializer; _inInitializer = false; try { Expression index = parseExpression2(); Token rightBracket = _expect(TokenType.CLOSE_SQUARE_BRACKET); return astFactory.indexExpressionForTarget( prefix, leftBracket, index, rightBracket); } finally { _inInitializer = wasInInitializer; } } else { bool isQuestionPeriod = type == TokenType.QUESTION_PERIOD; if (type == TokenType.PERIOD || isQuestionPeriod) { if (isQuestionPeriod && !allowConditional) { _reportErrorForCurrentToken( ParserErrorCode.INVALID_OPERATOR_FOR_SUPER, [_currentToken.lexeme]); } Token operator = getAndAdvance(); return astFactory.propertyAccess( prefix, operator, parseSimpleIdentifier()); } else if (type == TokenType.INDEX) { _splitIndex(); Token leftBracket = getAndAdvance(); Expression index = parseSimpleIdentifier(); Token rightBracket = getAndAdvance(); return astFactory.indexExpressionForTarget( prefix, leftBracket, index, rightBracket); } else { if (!optional) { // Report the missing selector. _reportErrorForCurrentToken( ParserErrorCode.MISSING_ASSIGNABLE_SELECTOR); } return prefix; } } } /// Parse a await expression. Return the await expression that was parsed. /// /// This method assumes that the current token matches `_AWAIT`. /// /// awaitExpression ::= /// 'await' unaryExpression AwaitExpression parseAwaitExpression() { Token awaitToken = getAndAdvance(); Expression expression = parseUnaryExpression(); return astFactory.awaitExpression(awaitToken, expression); } /// Parse a bitwise and expression. Return the bitwise and expression that was /// parsed. /// /// bitwiseAndExpression ::= /// shiftExpression ('&' shiftExpression)* /// | 'super' ('&' shiftExpression)+ Expression parseBitwiseAndExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type == TokenType.AMPERSAND) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseShiftExpression(); } while (_currentToken.type == TokenType.AMPERSAND) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseShiftExpression()); } return expression; } /// Parse a bitwise or expression. Return the bitwise or expression that was /// parsed. /// /// bitwiseOrExpression ::= /// bitwiseXorExpression ('|' bitwiseXorExpression)* /// | 'super' ('|' bitwiseXorExpression)+ Expression parseBitwiseOrExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type == TokenType.BAR) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseBitwiseXorExpression(); } while (_currentToken.type == TokenType.BAR) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseBitwiseXorExpression()); } return expression; } /// Parse a bitwise exclusive-or expression. Return the bitwise exclusive-or /// expression that was parsed. /// /// bitwiseXorExpression ::= /// bitwiseAndExpression ('^' bitwiseAndExpression)* /// | 'super' ('^' bitwiseAndExpression)+ Expression parseBitwiseXorExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type == TokenType.CARET) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseBitwiseAndExpression(); } while (_currentToken.type == TokenType.CARET) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseBitwiseAndExpression()); } return expression; } /// Parse a block. Return the block that was parsed. /// /// This method assumes that the current token matches /// [TokenType.OPEN_CURLY_BRACKET]. /// /// block ::= /// '{' statements '}' Block parseBlock() { bool isEndOfBlock() { TokenType type = _currentToken.type; return type == TokenType.EOF || type == TokenType.CLOSE_CURLY_BRACKET; } Token leftBracket = getAndAdvance(); List<Statement> statements = <Statement>[]; Token statementStart = _currentToken; while (!isEndOfBlock()) { Statement statement = parseStatement2(); if (identical(_currentToken, statementStart)) { // Ensure that we are making progress and report an error if we're not. _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); } else if (statement != null) { statements.add(statement); } statementStart = _currentToken; } // Recovery: If the next token is not a right curly bracket, look at the // left curly bracket to see whether there is a matching right bracket. If // there is, then we're more likely missing a semi-colon and should go back // to parsing statements. Token rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET); return astFactory.block(leftBracket, statements, rightBracket); } /// Parse a break statement. Return the break statement that was parsed. /// /// This method assumes that the current token matches `Keyword.BREAK`. /// /// breakStatement ::= /// 'break' identifier? ';' Statement parseBreakStatement() { Token breakKeyword = getAndAdvance(); SimpleIdentifier label; if (_matchesIdentifier()) { label = _parseSimpleIdentifierUnchecked(); } if (!_inLoop && !_inSwitch && label == null) { _reportErrorForToken(ParserErrorCode.BREAK_OUTSIDE_OF_LOOP, breakKeyword); } Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.breakStatement(breakKeyword, label, semicolon); } /// Parse a cascade section. Return the expression representing the cascaded /// method invocation. /// /// This method assumes that the current token matches /// `TokenType.PERIOD_PERIOD`. /// /// cascadeSection ::= /// '..' (cascadeSelector typeArguments? arguments*) /// (assignableSelector typeArguments? arguments*)* cascadeAssignment? /// /// cascadeSelector ::= /// '[' expression ']' /// | identifier /// /// cascadeAssignment ::= /// assignmentOperator expressionWithoutCascade Expression parseCascadeSection() { Token period = getAndAdvance(); Expression expression; SimpleIdentifier functionName; if (_matchesIdentifier()) { functionName = _parseSimpleIdentifierUnchecked(); } else if (_currentToken.type == TokenType.OPEN_SQUARE_BRACKET) { Token leftBracket = getAndAdvance(); bool wasInInitializer = _inInitializer; _inInitializer = false; try { Expression index = parseExpression2(); Token rightBracket = _expect(TokenType.CLOSE_SQUARE_BRACKET); expression = astFactory.indexExpressionForCascade( period, leftBracket, index, rightBracket); period; } finally { _inInitializer = wasInInitializer; } } else { _reportErrorForToken(ParserErrorCode.MISSING_IDENTIFIER, _currentToken, [_currentToken.lexeme]); functionName = createSyntheticIdentifier(); } assert((expression == null && functionName != null) || (expression != null && functionName == null)); if (_isLikelyArgumentList()) { do { TypeArgumentList typeArguments = _parseOptionalTypeArguments(); if (functionName != null) { expression = astFactory.methodInvocation(expression, period, functionName, typeArguments, parseArgumentList()); period; functionName; } else if (expression == null) { // It should not be possible to get here. expression = astFactory.methodInvocation(expression, period, createSyntheticIdentifier(), typeArguments, parseArgumentList()); } else { expression = astFactory.functionExpressionInvocation( expression, typeArguments, parseArgumentList()); } } while (_isLikelyArgumentList()); } else if (functionName != null) { expression = astFactory.propertyAccess(expression, period, functionName); period; } assert(expression != null); bool progress = true; while (progress) { progress = false; Expression selector = parseAssignableSelector(expression, true); if (!identical(selector, expression)) { expression = selector; progress = true; while (_isLikelyArgumentList()) { TypeArgumentList typeArguments = _parseOptionalTypeArguments(); Expression currentExpression = expression; if (currentExpression is PropertyAccess) { expression = astFactory.methodInvocation( currentExpression.target, currentExpression.operator, currentExpression.propertyName, typeArguments, parseArgumentList()); } else { expression = astFactory.functionExpressionInvocation( expression, typeArguments, parseArgumentList()); } } } } if (_currentToken.type.isAssignmentOperator) { Token operator = getAndAdvance(); _ensureAssignable(expression); expression = astFactory.assignmentExpression( expression, operator, parseExpressionWithoutCascade()); } return expression; } /// Parse a class declaration. The [commentAndMetadata] is the metadata to be /// associated with the member. The [abstractKeyword] is the token for the /// keyword 'abstract', or `null` if the keyword was not given. Return the /// class declaration that was parsed. /// /// This method assumes that the current token matches `Keyword.CLASS`. /// /// classDeclaration ::= /// metadata 'abstract'? 'class' name typeParameterList? (extendsClause withClause?)? implementsClause? '{' classMembers '}' | /// metadata 'abstract'? 'class' mixinApplicationClass CompilationUnitMember parseClassDeclaration( CommentAndMetadata commentAndMetadata, Token abstractKeyword) { // // Parse the name and type parameters. // Token keyword = getAndAdvance(); SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); String className = name.name; TypeParameterList typeParameters; TokenType type = _currentToken.type; if (type == TokenType.LT) { typeParameters = parseTypeParameterList(); type = _currentToken.type; } // // Check to see whether this might be a class type alias rather than a class // declaration. // if (type == TokenType.EQ) { return _parseClassTypeAliasAfterName( commentAndMetadata, abstractKeyword, keyword, name, typeParameters); } // // Parse the clauses. The parser accepts clauses in any order, but will // generate errors if they are not in the order required by the // specification. // ExtendsClause extendsClause; WithClause withClause; ImplementsClause implementsClause; bool foundClause = true; while (foundClause) { Keyword keyword = _currentToken.keyword; if (keyword == Keyword.EXTENDS) { if (extendsClause == null) { extendsClause = parseExtendsClause(); if (withClause != null) { _reportErrorForToken( ParserErrorCode.WITH_BEFORE_EXTENDS, withClause.withKeyword); } else if (implementsClause != null) { _reportErrorForToken(ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS, implementsClause.implementsKeyword); } } else { _reportErrorForToken(ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES, extendsClause.extendsKeyword); parseExtendsClause(); } } else if (keyword == Keyword.WITH) { if (withClause == null) { withClause = parseWithClause(); if (implementsClause != null) { _reportErrorForToken(ParserErrorCode.IMPLEMENTS_BEFORE_WITH, implementsClause.implementsKeyword); } } else { _reportErrorForToken( ParserErrorCode.MULTIPLE_WITH_CLAUSES, withClause.withKeyword); parseWithClause(); // TODO(brianwilkerson) Should we merge the list of applied mixins // into a single list? } } else if (keyword == Keyword.IMPLEMENTS) { if (implementsClause == null) { implementsClause = parseImplementsClause(); } else { _reportErrorForToken(ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES, implementsClause.implementsKeyword); parseImplementsClause(); // TODO(brianwilkerson) Should we merge the list of implemented // classes into a single list? } } else { foundClause = false; } } // // Look for and skip over the extra-lingual 'native' specification. // NativeClause nativeClause; if (_matchesKeyword(Keyword.NATIVE) && _tokenMatches(_peek(), TokenType.STRING)) { nativeClause = _parseNativeClause(); } // // Parse the body of the class. // Token leftBracket; List<ClassMember> members; Token rightBracket; if (_matches(TokenType.OPEN_CURLY_BRACKET)) { leftBracket = getAndAdvance(); members = _parseClassMembers(className, _getEndToken(leftBracket)); rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET); } else { // Recovery: Check for an unmatched closing curly bracket and parse // members until it is reached. leftBracket = _createSyntheticToken(TokenType.OPEN_CURLY_BRACKET); rightBracket = _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET); _reportErrorForCurrentToken(ParserErrorCode.MISSING_CLASS_BODY); } ClassDeclaration classDeclaration = astFactory.classDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, abstractKeyword, keyword, name, typeParameters, extendsClause, withClause, implementsClause, leftBracket, members, rightBracket); classDeclaration.nativeClause = nativeClause; return classDeclaration; } /// Parse a class member. The [className] is the name of the class containing /// the member being parsed. Return the class member that was parsed, or /// `null` if what was found was not a valid class member. /// /// classMemberDefinition ::= /// declaration ';' /// | methodSignature functionBody ClassMember parseClassMember(String className) { CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); Modifiers modifiers = parseModifiers(); Keyword keyword = _currentToken.keyword; if (keyword == Keyword.VOID || _atGenericFunctionTypeAfterReturnType(_currentToken)) { TypeAnnotation returnType; if (keyword == Keyword.VOID) { if (_atGenericFunctionTypeAfterReturnType(_peek())) { returnType = parseTypeAnnotation(false); } else { returnType = astFactory.typeName( astFactory.simpleIdentifier(getAndAdvance()), null); } } else { returnType = parseTypeAnnotation(false); } keyword = _currentToken.keyword; Token next = _peek(); bool isFollowedByIdentifier = _tokenMatchesIdentifier(next); if (keyword == Keyword.GET && isFollowedByIdentifier) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return parseGetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, returnType); } else if (keyword == Keyword.SET && isFollowedByIdentifier) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return parseSetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, returnType); } else if (keyword == Keyword.OPERATOR && (_isOperator(next) || next.type == TokenType.EQ_EQ_EQ)) { _validateModifiersForOperator(modifiers); return _parseOperatorAfterKeyword(commentAndMetadata, modifiers.externalKeyword, returnType, getAndAdvance()); } else if (_matchesIdentifier() && _peek().matchesAny(const <TokenType>[ TokenType.OPEN_PAREN, TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION, TokenType.LT ])) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return _parseMethodDeclarationAfterReturnType(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, returnType); } else if (_matchesIdentifier() && _peek().matchesAny(const <TokenType>[ TokenType.EQ, TokenType.COMMA, TokenType.SEMICOLON ])) { return parseInitializedIdentifierList( commentAndMetadata, modifiers.staticKeyword, modifiers.covariantKeyword, _validateModifiersForField(modifiers), returnType); } else { // // We have found an error of some kind. Try to recover. // if (_isOperator(_currentToken)) { // // We appear to have found an operator declaration without the // 'operator' keyword. // _validateModifiersForOperator(modifiers); return parseOperator( commentAndMetadata, modifiers.externalKeyword, returnType); } _reportErrorForToken( ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken); return null; } } Token next = _peek(); bool isFollowedByIdentifier = _tokenMatchesIdentifier(next); if (keyword == Keyword.GET && isFollowedByIdentifier) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return parseGetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, null); } else if (keyword == Keyword.SET && isFollowedByIdentifier) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return parseSetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, null); } else if (keyword == Keyword.OPERATOR && _isOperator(next)) { _validateModifiersForOperator(modifiers); return _parseOperatorAfterKeyword( commentAndMetadata, modifiers.externalKeyword, null, getAndAdvance()); } else if (!_matchesIdentifier()) { // // Recover from an error. // if (_matchesKeyword(Keyword.CLASS)) { _reportErrorForCurrentToken(ParserErrorCode.CLASS_IN_CLASS); // TODO(brianwilkerson) We don't currently have any way to capture the // class that was parsed. parseClassDeclaration(commentAndMetadata, null); return null; } else if (_matchesKeyword(Keyword.ABSTRACT) && _tokenMatchesKeyword(_peek(), Keyword.CLASS)) { _reportErrorForToken(ParserErrorCode.CLASS_IN_CLASS, _peek()); // TODO(brianwilkerson) We don't currently have any way to capture the // class that was parsed. parseClassDeclaration(commentAndMetadata, getAndAdvance()); return null; } else if (_matchesKeyword(Keyword.ENUM)) { _reportErrorForToken(ParserErrorCode.ENUM_IN_CLASS, _peek()); // TODO(brianwilkerson) We don't currently have any way to capture the // enum that was parsed. parseEnumDeclaration(commentAndMetadata); return null; } else if (_isOperator(_currentToken)) { // // We appear to have found an operator declaration without the // 'operator' keyword. // _validateModifiersForOperator(modifiers); return parseOperator( commentAndMetadata, modifiers.externalKeyword, null); } Token keyword = modifiers.varKeyword ?? modifiers.finalKeyword ?? modifiers.constKeyword; if (keyword != null) { // // We appear to have found an incomplete field declaration. // _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); VariableDeclaration variable = astFactory.variableDeclaration( createSyntheticIdentifier(), null, null); List<VariableDeclaration> variables = <VariableDeclaration>[variable]; return astFactory.fieldDeclaration2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: modifiers.covariantKeyword, fieldList: astFactory.variableDeclarationList( null, null, keyword, null, variables), semicolon: _expect(TokenType.SEMICOLON)); } _reportErrorForToken( ParserErrorCode.EXPECTED_CLASS_MEMBER, _currentToken); if (commentAndMetadata.comment != null || commentAndMetadata.hasMetadata) { // // We appear to have found an incomplete declaration at the end of the // class. At this point it consists of a metadata, which we don't want // to loose, so we'll treat it as a method declaration with a missing // name, parameters and empty body. // return astFactory.methodDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, null, null, null, null, null, createSyntheticIdentifier(isDeclaration: true), null, astFactory.formalParameterList( _createSyntheticToken(TokenType.OPEN_PAREN), <FormalParameter>[], null, null, _createSyntheticToken(TokenType.CLOSE_PAREN)), astFactory .emptyFunctionBody(_createSyntheticToken(TokenType.SEMICOLON))); } return null; } else if (_tokenMatches(next, TokenType.PERIOD) && _tokenMatchesIdentifierOrKeyword(_peekAt(2)) && _tokenMatches(_peekAt(3), TokenType.OPEN_PAREN)) { if (!_tokenMatchesIdentifier(_peekAt(2))) { _reportErrorForToken(ParserErrorCode.INVALID_CONSTRUCTOR_NAME, _peekAt(2), [_peekAt(2).lexeme]); } return _parseConstructor( commentAndMetadata, modifiers.externalKeyword, _validateModifiersForConstructor(modifiers), modifiers.factoryKeyword, parseSimpleIdentifier(), getAndAdvance(), parseSimpleIdentifier(allowKeyword: true, isDeclaration: true), parseFormalParameterList()); } else if (_tokenMatches(next, TokenType.OPEN_PAREN)) { TypeName returnType; SimpleIdentifier methodName = parseSimpleIdentifier(isDeclaration: true); TypeParameterList typeParameters; FormalParameterList parameters = parseFormalParameterList(); if (_matches(TokenType.COLON) || modifiers.factoryKeyword != null || methodName.name == className) { return _parseConstructor( commentAndMetadata, modifiers.externalKeyword, _validateModifiersForConstructor(modifiers), modifiers.factoryKeyword, astFactory.simpleIdentifier(methodName.token, isDeclaration: false), null, null, parameters); } _validateModifiersForGetterOrSetterOrMethod(modifiers); _validateFormalParameterList(parameters); return _parseMethodDeclarationAfterParameters( commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, returnType, methodName, typeParameters, parameters); } else if (next.matchesAny(const <TokenType>[ TokenType.EQ, TokenType.COMMA, TokenType.SEMICOLON ])) { if (modifiers.constKeyword == null && modifiers.finalKeyword == null && modifiers.varKeyword == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE); } return parseInitializedIdentifierList( commentAndMetadata, modifiers.staticKeyword, modifiers.covariantKeyword, _validateModifiersForField(modifiers), null); } else if (keyword == Keyword.TYPEDEF) { _reportErrorForCurrentToken(ParserErrorCode.TYPEDEF_IN_CLASS); // TODO(brianwilkerson) We don't currently have any way to capture the // function type alias that was parsed. _parseFunctionTypeAlias(commentAndMetadata, getAndAdvance()); return null; } else { Token token = _skipTypeParameterList(_peek()); if (token != null && _tokenMatches(token, TokenType.OPEN_PAREN)) { return _parseMethodDeclarationAfterReturnType(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, null); } } TypeAnnotation type = _parseTypeAnnotationAfterIdentifier(); keyword = _currentToken.keyword; next = _peek(); isFollowedByIdentifier = _tokenMatchesIdentifier(next); if (keyword == Keyword.GET && isFollowedByIdentifier) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return parseGetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, type); } else if (keyword == Keyword.SET && isFollowedByIdentifier) { _validateModifiersForGetterOrSetterOrMethod(modifiers); return parseSetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, type); } else if (keyword == Keyword.OPERATOR && _isOperator(next)) { _validateModifiersForOperator(modifiers); return _parseOperatorAfterKeyword( commentAndMetadata, modifiers.externalKeyword, type, getAndAdvance()); } else if (!_matchesIdentifier()) { if (_matches(TokenType.CLOSE_CURLY_BRACKET)) { // // We appear to have found an incomplete declaration at the end of the // class. At this point it consists of a type name, so we'll treat it as // a field declaration with a missing field name and semicolon. // return parseInitializedIdentifierList( commentAndMetadata, modifiers.staticKeyword, modifiers.covariantKeyword, _validateModifiersForField(modifiers), type); } if (_isOperator(_currentToken)) { // // We appear to have found an operator declaration without the // 'operator' keyword. // _validateModifiersForOperator(modifiers); return parseOperator( commentAndMetadata, modifiers.externalKeyword, type); } // // We appear to have found an incomplete declaration before another // declaration. At this point it consists of a type name, so we'll treat // it as a field declaration with a missing field name and semicolon. // _reportErrorForToken( ParserErrorCode.EXPECTED_CLASS_MEMBER, _currentToken); try { _lockErrorListener(); return parseInitializedIdentifierList( commentAndMetadata, modifiers.staticKeyword, modifiers.covariantKeyword, _validateModifiersForField(modifiers), type); } finally { _unlockErrorListener(); } } else if (_tokenMatches(next, TokenType.OPEN_PAREN)) { SimpleIdentifier methodName = _parseSimpleIdentifierUnchecked(isDeclaration: true); TypeParameterList typeParameters; FormalParameterList parameters = parseFormalParameterList(); if (methodName.name == className) { _reportErrorForNode(ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE, type); return _parseConstructor( commentAndMetadata, modifiers.externalKeyword, _validateModifiersForConstructor(modifiers), modifiers.factoryKeyword, astFactory.simpleIdentifier(methodName.token, isDeclaration: true), null, null, parameters); } _validateModifiersForGetterOrSetterOrMethod(modifiers); _validateFormalParameterList(parameters); return _parseMethodDeclarationAfterParameters( commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, type, methodName, typeParameters, parameters); } else if (_tokenMatches(next, TokenType.LT)) { return _parseMethodDeclarationAfterReturnType(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, type); } else if (_tokenMatches(next, TokenType.OPEN_CURLY_BRACKET)) { // We have found "TypeName identifier {", and are guessing that this is a // getter without the keyword 'get'. _validateModifiersForGetterOrSetterOrMethod(modifiers); _reportErrorForCurrentToken(ParserErrorCode.MISSING_GET); _currentToken = _injectToken( new SyntheticKeywordToken(Keyword.GET, _currentToken.offset)); return parseGetter(commentAndMetadata, modifiers.externalKeyword, modifiers.staticKeyword, type); } return parseInitializedIdentifierList( commentAndMetadata, modifiers.staticKeyword, modifiers.covariantKeyword, _validateModifiersForField(modifiers), type); } /// Parse a single combinator. Return the combinator that was parsed, or /// `null` if no combinator is found. /// /// combinator ::= /// 'show' identifier (',' identifier)* /// | 'hide' identifier (',' identifier)* Combinator parseCombinator() { if (_matchesKeyword(Keyword.SHOW)) { return astFactory.showCombinator(getAndAdvance(), parseIdentifierList()); } else if (_matchesKeyword(Keyword.HIDE)) { return astFactory.hideCombinator(getAndAdvance(), parseIdentifierList()); } return null; } /// Parse a list of combinators in a directive. Return the combinators that /// were parsed, or `null` if there are no combinators. /// /// combinator ::= /// 'show' identifier (',' identifier)* /// | 'hide' identifier (',' identifier)* List<Combinator> parseCombinators() { List<Combinator> combinators; while (true) { Combinator combinator = parseCombinator(); if (combinator == null) { break; } combinators ??= <Combinator>[]; combinators.add(combinator); } return combinators; } /// Parse the documentation comment and metadata preceding a declaration. This /// method allows any number of documentation comments to occur before, after /// or between the metadata, but only returns the last (right-most) /// documentation comment that is found. Return the documentation comment and /// metadata that were parsed. /// /// metadata ::= /// annotation* CommentAndMetadata parseCommentAndMetadata() { // TODO(brianwilkerson) Consider making the creation of documentation // comments be lazy. List<DocumentationCommentToken> tokens = parseDocumentationCommentTokens(); List<Annotation> metadata; while (_matches(TokenType.AT)) { metadata ??= <Annotation>[]; metadata.add(parseAnnotation()); List<DocumentationCommentToken> optionalTokens = parseDocumentationCommentTokens(); if (optionalTokens != null) { tokens = optionalTokens; } } return new CommentAndMetadata(parseDocumentationComment(tokens), metadata); } /// Parse a comment reference from the source between square brackets. The /// [referenceSource] is the source occurring between the square brackets /// within a documentation comment. The [sourceOffset] is the offset of the /// first character of the reference source. Return the comment reference that /// was parsed, or `null` if no reference could be found. /// /// commentReference ::= /// 'new'? prefixedIdentifier CommentReference parseCommentReference( String referenceSource, int sourceOffset) { // TODO(brianwilkerson) The errors are not getting the right offset/length // and are being duplicated. try { BooleanErrorListener listener = new BooleanErrorListener(); Scanner scanner = new Scanner( null, new SubSequenceReader(referenceSource, sourceOffset), listener) ..configureFeatures(_featureSet); scanner.setSourceStart(1, 1); Token firstToken = scanner.tokenize(); if (listener.errorReported) { return null; } if (firstToken.type == TokenType.EOF) { Token syntheticToken = new SyntheticStringToken(TokenType.IDENTIFIER, "", sourceOffset); syntheticToken.setNext(firstToken); return astFactory.commentReference( null, astFactory.simpleIdentifier(syntheticToken)); } Token newKeyword; if (_tokenMatchesKeyword(firstToken, Keyword.NEW)) { newKeyword = firstToken; firstToken = firstToken.next; } if (firstToken.isUserDefinableOperator) { if (firstToken.next.type != TokenType.EOF) { return null; } Identifier identifier = astFactory.simpleIdentifier(firstToken); return astFactory.commentReference(null, identifier); } else if (_tokenMatchesKeyword(firstToken, Keyword.OPERATOR)) { Token secondToken = firstToken.next; if (secondToken.isUserDefinableOperator) { if (secondToken.next.type != TokenType.EOF) { return null; } Identifier identifier = astFactory.simpleIdentifier(secondToken); return astFactory.commentReference(null, identifier); } return null; } else if (_tokenMatchesIdentifier(firstToken)) { Token secondToken = firstToken.next; Token thirdToken = secondToken.next; Token nextToken; Identifier identifier; if (_tokenMatches(secondToken, TokenType.PERIOD)) { if (thirdToken.isUserDefinableOperator) { identifier = astFactory.prefixedIdentifier( astFactory.simpleIdentifier(firstToken), secondToken, astFactory.simpleIdentifier(thirdToken)); nextToken = thirdToken.next; } else if (_tokenMatchesKeyword(thirdToken, Keyword.OPERATOR)) { Token fourthToken = thirdToken.next; if (fourthToken.isUserDefinableOperator) { identifier = astFactory.prefixedIdentifier( astFactory.simpleIdentifier(firstToken), secondToken, astFactory.simpleIdentifier(fourthToken)); nextToken = fourthToken.next; } else { return null; } } else if (_tokenMatchesIdentifier(thirdToken)) { identifier = astFactory.prefixedIdentifier( astFactory.simpleIdentifier(firstToken), secondToken, astFactory.simpleIdentifier(thirdToken)); nextToken = thirdToken.next; } } else { identifier = astFactory.simpleIdentifier(firstToken); nextToken = firstToken.next; } if (nextToken.type != TokenType.EOF) { return null; } return astFactory.commentReference(newKeyword, identifier); } else { Keyword keyword = firstToken.keyword; if (keyword == Keyword.THIS || keyword == Keyword.NULL || keyword == Keyword.TRUE || keyword == Keyword.FALSE) { // TODO(brianwilkerson) If we want to support this we will need to // extend the definition of CommentReference to take an expression // rather than an identifier. For now we just ignore it to reduce the // number of errors produced, but that's probably not a valid long term // approach. return null; } } } catch (exception) { // Ignored because we assume that it wasn't a real comment reference. } return null; } /// Parse all of the comment references occurring in the given array of /// documentation comments. The [tokens] are the comment tokens representing /// the documentation comments to be parsed. Return the comment references /// that were parsed. /// /// commentReference ::= /// '[' 'new'? qualified ']' libraryReference? /// /// libraryReference ::= /// '(' stringLiteral ')' List<CommentReference> parseCommentReferences( List<DocumentationCommentToken> tokens) { List<CommentReference> references = <CommentReference>[]; bool isInGitHubCodeBlock = false; for (DocumentationCommentToken token in tokens) { String comment = token.lexeme; // Skip GitHub code blocks. // https://help.github.com/articles/creating-and-highlighting-code-blocks/ if (tokens.length != 1) { if (comment.contains('```')) { isInGitHubCodeBlock = !isInGitHubCodeBlock; } if (isInGitHubCodeBlock) { continue; } } // Remove GitHub include code. comment = _removeGitHubInlineCode(comment); // Find references. int length = comment.length; List<List<int>> codeBlockRanges = _getCodeBlockRanges(comment); int leftIndex = comment.indexOf('['); while (leftIndex >= 0 && leftIndex + 1 < length) { List<int> range = _findRange(codeBlockRanges, leftIndex); if (range == null) { int nameOffset = token.offset + leftIndex + 1; int rightIndex = comment.indexOf(']', leftIndex); if (rightIndex >= 0) { int firstChar = comment.codeUnitAt(leftIndex + 1); if (firstChar != 0x27 && firstChar != 0x22) { if (_isLinkText(comment, rightIndex)) { // TODO(brianwilkerson) Handle the case where there's a library // URI in the link text. } else { CommentReference reference = parseCommentReference( comment.substring(leftIndex + 1, rightIndex), nameOffset); if (reference != null) { references.add(reference); } } } } else { // terminating ']' is not typed yet int charAfterLeft = comment.codeUnitAt(leftIndex + 1); Token nameToken; if (Character.isLetterOrDigit(charAfterLeft)) { int nameEnd = StringUtilities.indexOfFirstNotLetterDigit( comment, leftIndex + 1); String name = comment.substring(leftIndex + 1, nameEnd); nameToken = new StringToken(TokenType.IDENTIFIER, name, nameOffset); } else { nameToken = new SyntheticStringToken( TokenType.IDENTIFIER, '', nameOffset); } nameToken.setNext(new Token.eof(nameToken.end)); references.add(astFactory.commentReference( null, astFactory.simpleIdentifier(nameToken))); // next character rightIndex = leftIndex + 1; } leftIndex = comment.indexOf('[', rightIndex); } else { leftIndex = comment.indexOf('[', range[1]); } } } return references; } /// Parse a compilation unit, starting with the given [token]. Return the /// compilation unit that was parsed. CompilationUnit parseCompilationUnit(Token token) { _currentToken = token; return parseCompilationUnit2(); } /// Parse a compilation unit. Return the compilation unit that was parsed. /// /// Specified: /// /// compilationUnit ::= /// scriptTag? directive* topLevelDeclaration* /// /// Actual: /// /// compilationUnit ::= /// scriptTag? topLevelElement* /// /// topLevelElement ::= /// directive /// | topLevelDeclaration CompilationUnit parseCompilationUnit2() { Token firstToken = _currentToken; ScriptTag scriptTag; if (_matches(TokenType.SCRIPT_TAG)) { scriptTag = astFactory.scriptTag(getAndAdvance()); } // // Even though all directives must appear before declarations and must occur // in a given order, we allow directives and declarations to occur in any // order so that we can recover better. // bool libraryDirectiveFound = false; bool partOfDirectiveFound = false; bool partDirectiveFound = false; bool directiveFoundAfterDeclaration = false; List<Directive> directives = <Directive>[]; List<CompilationUnitMember> declarations = <CompilationUnitMember>[]; Token memberStart = _currentToken; TokenType type = _currentToken.type; while (type != TokenType.EOF) { CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); Keyword keyword = _currentToken.keyword; TokenType nextType = _currentToken.next.type; if ((keyword == Keyword.IMPORT || keyword == Keyword.EXPORT || keyword == Keyword.LIBRARY || keyword == Keyword.PART) && nextType != TokenType.PERIOD && nextType != TokenType.LT && nextType != TokenType.OPEN_PAREN) { Directive parseDirective() { if (keyword == Keyword.IMPORT) { if (partDirectiveFound) { _reportErrorForCurrentToken( ParserErrorCode.IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE); } return parseImportDirective(commentAndMetadata); } else if (keyword == Keyword.EXPORT) { if (partDirectiveFound) { _reportErrorForCurrentToken( ParserErrorCode.EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE); } return parseExportDirective(commentAndMetadata); } else if (keyword == Keyword.LIBRARY) { if (libraryDirectiveFound) { _reportErrorForCurrentToken( ParserErrorCode.MULTIPLE_LIBRARY_DIRECTIVES); } else { if (directives.isNotEmpty) { _reportErrorForCurrentToken( ParserErrorCode.LIBRARY_DIRECTIVE_NOT_FIRST); } libraryDirectiveFound = true; } return parseLibraryDirective(commentAndMetadata); } else if (keyword == Keyword.PART) { if (_tokenMatchesKeyword(_peek(), Keyword.OF)) { partOfDirectiveFound = true; return _parsePartOfDirective(commentAndMetadata); } else { partDirectiveFound = true; return _parsePartDirective(commentAndMetadata); } } else { // Internal error: this method should not have been invoked if the // current token was something other than one of the above. throw new StateError( "parseDirective invoked in an invalid state (currentToken = $_currentToken)"); } } Directive directive = parseDirective(); if (declarations.isNotEmpty && !directiveFoundAfterDeclaration) { _reportErrorForToken(ParserErrorCode.DIRECTIVE_AFTER_DECLARATION, directive.beginToken); directiveFoundAfterDeclaration = true; } directives.add(directive); } else if (type == TokenType.SEMICOLON) { // TODO(brianwilkerson) Consider moving this error detection into // _parseCompilationUnitMember (in the places where EXPECTED_EXECUTABLE // is being generated). _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); } else { CompilationUnitMember member; try { member = parseCompilationUnitMember(commentAndMetadata); } on _TooDeepTreeError { _reportErrorForToken(ParserErrorCode.STACK_OVERFLOW, _currentToken); Token eof = new Token.eof(0); return astFactory.compilationUnit( beginToken: eof, endToken: eof, featureSet: _featureSet); } if (member != null) { declarations.add(member); } } if (identical(_currentToken, memberStart)) { _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); while (!_matches(TokenType.EOF) && !_couldBeStartOfCompilationUnitMember()) { _advance(); } } memberStart = _currentToken; type = _currentToken.type; } if (partOfDirectiveFound && directives.length > 1) { // TODO(brianwilkerson) Improve error reporting when both a library and // part-of directive are found. // if (libraryDirectiveFound) { // int directiveCount = directives.length; // for (int i = 0; i < directiveCount; i++) { // Directive directive = directives[i]; // if (directive is PartOfDirective) { // _reportErrorForToken( // ParserErrorCode.PART_OF_IN_LIBRARY, directive.partKeyword); // } // } // } else { bool firstPartOf = true; int directiveCount = directives.length; for (int i = 0; i < directiveCount; i++) { Directive directive = directives[i]; if (directive is PartOfDirective) { if (firstPartOf) { firstPartOf = false; } else { _reportErrorForToken(ParserErrorCode.MULTIPLE_PART_OF_DIRECTIVES, directive.partKeyword); } } else { _reportErrorForToken(ParserErrorCode.NON_PART_OF_DIRECTIVE_IN_PART, directives[i].keyword); } // } } } return astFactory.compilationUnit( beginToken: firstToken, scriptTag: scriptTag, directives: directives, declarations: declarations, endToken: _currentToken, featureSet: _featureSet); } /// Parse a compilation unit member. The [commentAndMetadata] is the metadata /// to be associated with the member. Return the compilation unit member that /// was parsed, or `null` if what was parsed could not be represented as a /// compilation unit member. /// /// compilationUnitMember ::= /// classDefinition /// | functionTypeAlias /// | external functionSignature /// | external getterSignature /// | external setterSignature /// | functionSignature functionBody /// | returnType? getOrSet identifier formalParameterList functionBody /// | (final | const) type? staticFinalDeclarationList ';' /// | variableDeclaration ';' CompilationUnitMember parseCompilationUnitMember( CommentAndMetadata commentAndMetadata) { Modifiers modifiers = parseModifiers(); Keyword keyword = _currentToken.keyword; if (keyword == Keyword.CLASS) { return parseClassDeclaration( commentAndMetadata, _validateModifiersForClass(modifiers)); } Token next = _peek(); TokenType nextType = next.type; if (keyword == Keyword.TYPEDEF && nextType != TokenType.PERIOD && nextType != TokenType.LT && nextType != TokenType.OPEN_PAREN) { _validateModifiersForTypedef(modifiers); return parseTypeAlias(commentAndMetadata); } else if (keyword == Keyword.ENUM) { _validateModifiersForEnum(modifiers); return parseEnumDeclaration(commentAndMetadata); } else if (keyword == Keyword.VOID || _atGenericFunctionTypeAfterReturnType(_currentToken)) { TypeAnnotation returnType; if (keyword == Keyword.VOID) { if (_atGenericFunctionTypeAfterReturnType(next)) { returnType = parseTypeAnnotation(false); } else { returnType = astFactory.typeName( astFactory.simpleIdentifier(getAndAdvance()), null); } } else { returnType = parseTypeAnnotation(false); } keyword = _currentToken.keyword; next = _peek(); if ((keyword == Keyword.GET || keyword == Keyword.SET) && _tokenMatchesIdentifier(next)) { _validateModifiersForTopLevelFunction(modifiers); return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, returnType); } else if (keyword == Keyword.OPERATOR && _isOperator(next)) { _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken); return _convertToFunctionDeclaration(_parseOperatorAfterKeyword( commentAndMetadata, modifiers.externalKeyword, returnType, getAndAdvance())); } else if (_matchesIdentifier() && next.matchesAny(const <TokenType>[ TokenType.OPEN_PAREN, TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION, TokenType.LT ])) { _validateModifiersForTopLevelFunction(modifiers); return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, returnType); } else if (_matchesIdentifier() && next.matchesAny(const <TokenType>[ TokenType.EQ, TokenType.COMMA, TokenType.SEMICOLON ])) { return astFactory.topLevelVariableDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, parseVariableDeclarationListAfterType(null, _validateModifiersForTopLevelVariable(modifiers), returnType), _expect(TokenType.SEMICOLON)); } else { // // We have found an error of some kind. Try to recover. // _reportErrorForToken( ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken); return null; } } else if ((keyword == Keyword.GET || keyword == Keyword.SET) && _tokenMatchesIdentifier(next)) { _validateModifiersForTopLevelFunction(modifiers); return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, null); } else if (keyword == Keyword.OPERATOR && _isOperator(next)) { _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken); return _convertToFunctionDeclaration(_parseOperatorAfterKeyword( commentAndMetadata, modifiers.externalKeyword, null, getAndAdvance())); } else if (!_matchesIdentifier()) { Token keyword = modifiers.varKeyword; if (keyword == null) { keyword = modifiers.finalKeyword; } if (keyword == null) { keyword = modifiers.constKeyword; } if (keyword != null) { // // We appear to have found an incomplete top-level variable declaration. // _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); VariableDeclaration variable = astFactory.variableDeclaration( createSyntheticIdentifier(), null, null); List<VariableDeclaration> variables = <VariableDeclaration>[variable]; return astFactory.topLevelVariableDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, astFactory.variableDeclarationList( null, null, keyword, null, variables), _expect(TokenType.SEMICOLON)); } _reportErrorForToken(ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken); return null; } else if (_isPeekGenericTypeParametersAndOpenParen()) { return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, null); } else if (_tokenMatches(next, TokenType.OPEN_PAREN)) { TypeName returnType; _validateModifiersForTopLevelFunction(modifiers); return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, returnType); } else if (next.matchesAny(const <TokenType>[ TokenType.EQ, TokenType.COMMA, TokenType.SEMICOLON ])) { if (modifiers.constKeyword == null && modifiers.finalKeyword == null && modifiers.varKeyword == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE); } return astFactory.topLevelVariableDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, parseVariableDeclarationListAfterType( null, _validateModifiersForTopLevelVariable(modifiers), null), _expect(TokenType.SEMICOLON)); } TypeAnnotation returnType = parseTypeAnnotation(false); keyword = _currentToken.keyword; next = _peek(); if ((keyword == Keyword.GET || keyword == Keyword.SET) && _tokenMatchesIdentifier(next)) { _validateModifiersForTopLevelFunction(modifiers); return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, returnType); } else if (keyword == Keyword.OPERATOR && _isOperator(next)) { _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken); return _convertToFunctionDeclaration(_parseOperatorAfterKeyword( commentAndMetadata, modifiers.externalKeyword, returnType, getAndAdvance())); } else if (_matches(TokenType.AT)) { return astFactory.topLevelVariableDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, parseVariableDeclarationListAfterType(null, _validateModifiersForTopLevelVariable(modifiers), returnType), _expect(TokenType.SEMICOLON)); } else if (!_matchesIdentifier()) { // TODO(brianwilkerson) Generalize this error. We could also be parsing a // top-level variable at this point. _reportErrorForToken(ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken); Token semicolon; if (_matches(TokenType.SEMICOLON)) { semicolon = getAndAdvance(); } else { semicolon = _createSyntheticToken(TokenType.SEMICOLON); } VariableDeclaration variable = astFactory.variableDeclaration( createSyntheticIdentifier(), null, null); List<VariableDeclaration> variables = <VariableDeclaration>[variable]; return astFactory.topLevelVariableDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, astFactory.variableDeclarationList( null, null, null, returnType, variables), semicolon); } else if (next.matchesAny(const <TokenType>[ TokenType.OPEN_PAREN, TokenType.FUNCTION, TokenType.OPEN_CURLY_BRACKET, TokenType.LT ])) { _validateModifiersForTopLevelFunction(modifiers); return parseFunctionDeclaration( commentAndMetadata, modifiers.externalKeyword, returnType); } return astFactory.topLevelVariableDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, parseVariableDeclarationListAfterType( null, _validateModifiersForTopLevelVariable(modifiers), returnType), _expect(TokenType.SEMICOLON)); } /// Parse a conditional expression. Return the conditional expression that was /// parsed. /// /// conditionalExpression ::= /// ifNullExpression ('?' expressionWithoutCascade ':' expressionWithoutCascade)? Expression parseConditionalExpression() { Expression condition = parseIfNullExpression(); if (_currentToken.type != TokenType.QUESTION) { return condition; } Token question = getAndAdvance(); Expression thenExpression = parseExpressionWithoutCascade(); Token colon = _expect(TokenType.COLON); Expression elseExpression = parseExpressionWithoutCascade(); return astFactory.conditionalExpression( condition, question, thenExpression, colon, elseExpression); } /// Parse a configuration in either an import or export directive. /// /// This method assumes that the current token matches `Keyword.IF`. /// /// configuration ::= /// 'if' '(' test ')' uri /// /// test ::= /// dottedName ('==' stringLiteral)? /// /// dottedName ::= /// identifier ('.' identifier)* Configuration parseConfiguration() { Token ifKeyword = getAndAdvance(); Token leftParenthesis = _expect(TokenType.OPEN_PAREN); DottedName name = parseDottedName(); Token equalToken; StringLiteral value; if (_matches(TokenType.EQ_EQ)) { equalToken = getAndAdvance(); value = parseStringLiteral(); if (value is StringInterpolation) { _reportErrorForNode( ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION, value); } } Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); StringLiteral libraryUri = _parseUri(); return astFactory.configuration(ifKeyword, leftParenthesis, name, equalToken, value, rightParenthesis, libraryUri); } /// Parse a const expression. Return the const expression that was parsed. /// /// This method assumes that the current token matches `Keyword.CONST`. /// /// constExpression ::= /// instanceCreationExpression /// | listLiteral /// | mapLiteral Expression parseConstExpression() { Token keyword = getAndAdvance(); TokenType type = _currentToken.type; if (type == TokenType.LT) { return parseListOrMapLiteral(keyword); } else if (type == TokenType.OPEN_SQUARE_BRACKET || type == TokenType.INDEX) { return parseListLiteral(keyword, null); } else if (type == TokenType.OPEN_CURLY_BRACKET) { return parseMapLiteral(keyword, null); } return parseInstanceCreationExpression(keyword); } /// Parse a field initializer within a constructor. The flag [hasThis] should /// be true if the current token is `this`. Return the field initializer that /// was parsed. /// /// fieldInitializer: /// ('this' '.')? identifier '=' conditionalExpression cascadeSection* ConstructorFieldInitializer parseConstructorFieldInitializer(bool hasThis) { Token keywordToken; Token period; if (hasThis) { keywordToken = getAndAdvance(); period = _expect(TokenType.PERIOD); } SimpleIdentifier fieldName = parseSimpleIdentifier(); Token equals; TokenType type = _currentToken.type; if (type == TokenType.EQ) { equals = getAndAdvance(); } else { _reportErrorForCurrentToken( ParserErrorCode.MISSING_ASSIGNMENT_IN_INITIALIZER); Keyword keyword = _currentToken.keyword; if (keyword != Keyword.THIS && keyword != Keyword.SUPER && type != TokenType.OPEN_CURLY_BRACKET && type != TokenType.FUNCTION) { equals = _createSyntheticToken(TokenType.EQ); } else { return astFactory.constructorFieldInitializer( keywordToken, period, fieldName, _createSyntheticToken(TokenType.EQ), createSyntheticIdentifier()); } } bool wasInInitializer = _inInitializer; _inInitializer = true; try { Expression expression = parseConditionalExpression(); if (_matches(TokenType.PERIOD_PERIOD)) { List<Expression> cascadeSections = <Expression>[]; do { Expression section = parseCascadeSection(); if (section != null) { cascadeSections.add(section); } } while (_matches(TokenType.PERIOD_PERIOD)); expression = astFactory.cascadeExpression(expression, cascadeSections); } return astFactory.constructorFieldInitializer( keywordToken, period, fieldName, equals, expression); } finally { _inInitializer = wasInInitializer; } } /// Parse the name of a constructor. Return the constructor name that was /// parsed. /// /// constructorName: /// type ('.' identifier)? ConstructorName parseConstructorName() { TypeName type = parseTypeName(false); Token period; SimpleIdentifier name; if (_matches(TokenType.PERIOD)) { period = getAndAdvance(); name = parseSimpleIdentifier(); } return astFactory.constructorName(type, period, name); } /// Parse a continue statement. Return the continue statement that was parsed. /// /// This method assumes that the current token matches `Keyword.CONTINUE`. /// /// continueStatement ::= /// 'continue' identifier? ';' Statement parseContinueStatement() { Token continueKeyword = getAndAdvance(); if (!_inLoop && !_inSwitch) { _reportErrorForToken( ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP, continueKeyword); } SimpleIdentifier label; if (_matchesIdentifier()) { label = _parseSimpleIdentifierUnchecked(); } if (_inSwitch && !_inLoop && label == null) { _reportErrorForToken( ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE, continueKeyword); } Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.continueStatement(continueKeyword, label, semicolon); } /// Parse a directive. The [commentAndMetadata] is the metadata to be /// associated with the directive. Return the directive that was parsed. /// /// directive ::= /// exportDirective /// | libraryDirective /// | importDirective /// | partDirective Directive parseDirective(CommentAndMetadata commentAndMetadata) { if (_matchesKeyword(Keyword.IMPORT)) { return parseImportDirective(commentAndMetadata); } else if (_matchesKeyword(Keyword.EXPORT)) { return parseExportDirective(commentAndMetadata); } else if (_matchesKeyword(Keyword.LIBRARY)) { return parseLibraryDirective(commentAndMetadata); } else if (_matchesKeyword(Keyword.PART)) { return parsePartOrPartOfDirective(commentAndMetadata); } else { // Internal error: this method should not have been invoked if the current // token was something other than one of the above. throw new StateError( "parseDirective invoked in an invalid state; currentToken = $_currentToken"); } } /// Parse the script tag and directives in a compilation unit, starting with /// the given [token], until the first non-directive is encountered. The /// remainder of the compilation unit will not be parsed. Specifically, if /// there are directives later in the file, they will not be parsed. Return /// the compilation unit that was parsed. CompilationUnit parseDirectives(Token token) { _currentToken = token; return parseDirectives2(); } /// Parse the script tag and directives in a compilation unit until the first /// non-directive is encountered. Return the compilation unit that was parsed. /// /// compilationUnit ::= /// scriptTag? directive* CompilationUnit parseDirectives2() { Token firstToken = _currentToken; ScriptTag scriptTag; if (_matches(TokenType.SCRIPT_TAG)) { scriptTag = astFactory.scriptTag(getAndAdvance()); } List<Directive> directives = <Directive>[]; while (!_matches(TokenType.EOF)) { CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); Keyword keyword = _currentToken.keyword; TokenType type = _peek().type; if ((keyword == Keyword.IMPORT || keyword == Keyword.EXPORT || keyword == Keyword.LIBRARY || keyword == Keyword.PART) && type != TokenType.PERIOD && type != TokenType.LT && type != TokenType.OPEN_PAREN) { directives.add(parseDirective(commentAndMetadata)); } else if (_matches(TokenType.SEMICOLON)) { _advance(); } else { while (!_matches(TokenType.EOF)) { _advance(); } return astFactory.compilationUnit( beginToken: firstToken, scriptTag: scriptTag, directives: directives, endToken: _currentToken, featureSet: _featureSet); } } return astFactory.compilationUnit( beginToken: firstToken, scriptTag: scriptTag, directives: directives, endToken: _currentToken, featureSet: _featureSet); } /// Parse a documentation comment based on the given list of documentation /// comment tokens. Return the documentation comment that was parsed, or /// `null` if there was no comment. /// /// documentationComment ::= /// multiLineComment? /// | singleLineComment* Comment parseDocumentationComment(List<DocumentationCommentToken> tokens) { if (tokens == null) { return null; } List<CommentReference> references = parseCommentReferences(tokens); return astFactory.documentationComment(tokens, references); } /// Parse a documentation comment. Return the documentation comment that was /// parsed, or `null` if there was no comment. /// /// documentationComment ::= /// multiLineComment? /// | singleLineComment* List<DocumentationCommentToken> parseDocumentationCommentTokens() { List<DocumentationCommentToken> tokens = <DocumentationCommentToken>[]; CommentToken commentToken = _currentToken.precedingComments; while (commentToken != null) { if (commentToken is DocumentationCommentToken) { if (tokens.isNotEmpty) { if (commentToken.type == TokenType.SINGLE_LINE_COMMENT) { if (tokens[0].type != TokenType.SINGLE_LINE_COMMENT) { tokens.clear(); } } else { tokens.clear(); } } tokens.add(commentToken); } commentToken = commentToken.next; } return tokens.isEmpty ? null : tokens; } /// Parse a do statement. Return the do statement that was parsed. /// /// This method assumes that the current token matches `Keyword.DO`. /// /// doStatement ::= /// 'do' statement 'while' '(' expression ')' ';' Statement parseDoStatement() { bool wasInLoop = _inLoop; _inLoop = true; try { Token doKeyword = getAndAdvance(); Statement body = parseStatement2(); Token whileKeyword = _expectKeyword(Keyword.WHILE); Token leftParenthesis = _expect(TokenType.OPEN_PAREN); Expression condition = parseExpression2(); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.doStatement(doKeyword, body, whileKeyword, leftParenthesis, condition, rightParenthesis, semicolon); } finally { _inLoop = wasInLoop; } } /// Parse a dotted name. Return the dotted name that was parsed. /// /// dottedName ::= /// identifier ('.' identifier)* DottedName parseDottedName() { List<SimpleIdentifier> components = <SimpleIdentifier>[ parseSimpleIdentifier() ]; while (_optional(TokenType.PERIOD)) { components.add(parseSimpleIdentifier()); } return astFactory.dottedName(components); } /// Parse an empty statement. Return the empty statement that was parsed. /// /// This method assumes that the current token matches `TokenType.SEMICOLON`. /// /// emptyStatement ::= /// ';' Statement parseEmptyStatement() => astFactory.emptyStatement(getAndAdvance()); /// Parse an enum declaration. The [commentAndMetadata] is the metadata to be /// associated with the member. Return the enum declaration that was parsed. /// /// This method assumes that the current token matches `Keyword.ENUM`. /// /// enumType ::= /// metadata 'enum' id '{' id (',' id)* (',')? '}' EnumDeclaration parseEnumDeclaration(CommentAndMetadata commentAndMetadata) { Token keyword = getAndAdvance(); SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); Token leftBracket; List<EnumConstantDeclaration> constants = <EnumConstantDeclaration>[]; Token rightBracket; if (_matches(TokenType.OPEN_CURLY_BRACKET)) { leftBracket = getAndAdvance(); if (_matchesIdentifier() || _matches(TokenType.AT)) { constants.add(_parseEnumConstantDeclaration()); } else if (_matches(TokenType.COMMA) && _tokenMatchesIdentifier(_peek())) { constants.add(_parseEnumConstantDeclaration()); _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); } else { constants.add(_parseEnumConstantDeclaration()); _reportErrorForCurrentToken(ParserErrorCode.EMPTY_ENUM_BODY); } while (_optional(TokenType.COMMA)) { if (_matches(TokenType.CLOSE_CURLY_BRACKET)) { break; } constants.add(_parseEnumConstantDeclaration()); } rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET); } else { leftBracket = _createSyntheticToken(TokenType.OPEN_CURLY_BRACKET); rightBracket = _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET); _reportErrorForCurrentToken(ParserErrorCode.MISSING_ENUM_BODY); } return astFactory.enumDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, name, leftBracket, constants, rightBracket); } /// Parse an equality expression. Return the equality expression that was /// parsed. /// /// equalityExpression ::= /// relationalExpression (equalityOperator relationalExpression)? /// | 'super' equalityOperator relationalExpression Expression parseEqualityExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type.isEqualityOperator) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseRelationalExpression(); } bool leftEqualityExpression = false; while (_currentToken.type.isEqualityOperator) { if (leftEqualityExpression) { _reportErrorForNode( ParserErrorCode.EQUALITY_CANNOT_BE_EQUALITY_OPERAND, expression); } expression = astFactory.binaryExpression( expression, getAndAdvance(), parseRelationalExpression()); leftEqualityExpression = true; } return expression; } /// Parse an export directive. The [commentAndMetadata] is the metadata to be /// associated with the directive. Return the export directive that was /// parsed. /// /// This method assumes that the current token matches `Keyword.EXPORT`. /// /// exportDirective ::= /// metadata 'export' stringLiteral configuration* combinator*';' ExportDirective parseExportDirective(CommentAndMetadata commentAndMetadata) { Token exportKeyword = getAndAdvance(); StringLiteral libraryUri = _parseUri(); List<Configuration> configurations = _parseConfigurations(); List<Combinator> combinators = parseCombinators(); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.exportDirective( commentAndMetadata.comment, commentAndMetadata.metadata, exportKeyword, libraryUri, configurations, combinators, semicolon); } /// Parse an expression, starting with the given [token]. Return the /// expression that was parsed, or `null` if the tokens do not represent a /// recognizable expression. Expression parseExpression(Token token) { _currentToken = token; return parseExpression2(); } /// Parse an expression that might contain a cascade. Return the expression /// that was parsed. /// /// expression ::= /// assignableExpression assignmentOperator expression /// | conditionalExpression cascadeSection* /// | throwExpression Expression parseExpression2() { if (_treeDepth > _MAX_TREE_DEPTH) { throw new _TooDeepTreeError(); } _treeDepth++; try { Keyword keyword = _currentToken.keyword; if (keyword == Keyword.THROW) { return parseThrowExpression(); } else if (keyword == Keyword.RETHROW) { // TODO(brianwilkerson) Rethrow is a statement again. return parseRethrowExpression(); } // // assignableExpression is a subset of conditionalExpression, so we can // parse a conditional expression and then determine whether it is followed // by an assignmentOperator, checking for conformance to the restricted // grammar after making that determination. // Expression expression = parseConditionalExpression(); TokenType type = _currentToken.type; if (type == TokenType.PERIOD_PERIOD) { List<Expression> cascadeSections = <Expression>[]; do { Expression section = parseCascadeSection(); if (section != null) { cascadeSections.add(section); } } while (_currentToken.type == TokenType.PERIOD_PERIOD); return astFactory.cascadeExpression(expression, cascadeSections); } else if (type.isAssignmentOperator) { Token operator = getAndAdvance(); _ensureAssignable(expression); return astFactory.assignmentExpression( expression, operator, parseExpression2()); } return expression; } finally { _treeDepth--; } } /// Parse a list of expressions. Return the expression that was parsed. /// /// expressionList ::= /// expression (',' expression)* List<Expression> parseExpressionList() { List<Expression> expressions = <Expression>[parseExpression2()]; while (_optional(TokenType.COMMA)) { expressions.add(parseExpression2()); } return expressions; } /// Parse an expression that does not contain any cascades. Return the /// expression that was parsed. /// /// expressionWithoutCascade ::= /// assignableExpression assignmentOperator expressionWithoutCascade /// | conditionalExpression /// | throwExpressionWithoutCascade Expression parseExpressionWithoutCascade() { if (_matchesKeyword(Keyword.THROW)) { return parseThrowExpressionWithoutCascade(); } else if (_matchesKeyword(Keyword.RETHROW)) { return parseRethrowExpression(); } // // assignableExpression is a subset of conditionalExpression, so we can // parse a conditional expression and then determine whether it is followed // by an assignmentOperator, checking for conformance to the restricted // grammar after making that determination. // Expression expression = parseConditionalExpression(); if (_currentToken.type.isAssignmentOperator) { Token operator = getAndAdvance(); _ensureAssignable(expression); expression = astFactory.assignmentExpression( expression, operator, parseExpressionWithoutCascade()); } return expression; } /// Parse a class extends clause. Return the class extends clause that was /// parsed. /// /// This method assumes that the current token matches `Keyword.EXTENDS`. /// /// classExtendsClause ::= /// 'extends' type ExtendsClause parseExtendsClause() { Token keyword = getAndAdvance(); TypeName superclass = parseTypeName(false); return astFactory.extendsClause(keyword, superclass); } /// Parse the 'final', 'const', 'var' or type preceding a variable /// declaration. The [optional] is `true` if the keyword and type are /// optional. Return the 'final', 'const', 'var' or type that was parsed. /// /// finalConstVarOrType ::= /// 'final' type? /// | 'const' type? /// | 'var' /// | type FinalConstVarOrType parseFinalConstVarOrType(bool optional, {bool inFunctionType: false}) { Token keywordToken; TypeAnnotation type; Keyword keyword = _currentToken.keyword; if (keyword == Keyword.FINAL || keyword == Keyword.CONST) { keywordToken = getAndAdvance(); if (_isTypedIdentifier(_currentToken)) { type = parseTypeAnnotation(false); } } else if (keyword == Keyword.VAR) { keywordToken = getAndAdvance(); } else if (_isTypedIdentifier(_currentToken)) { type = parseTypeAnnotation(false); } else if (inFunctionType && _matchesIdentifier()) { type = parseTypeAnnotation(false); } else if (!optional) { // If there is a valid type immediately following an unexpected token, // then report and skip the unexpected token. Token next = _peek(); Keyword nextKeyword = next.keyword; if (nextKeyword == Keyword.FINAL || nextKeyword == Keyword.CONST || nextKeyword == Keyword.VAR || _isTypedIdentifier(next) || inFunctionType && _tokenMatchesIdentifier(next)) { _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]); _advance(); return parseFinalConstVarOrType(optional, inFunctionType: inFunctionType); } _reportErrorForCurrentToken( ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE); } else { // Support parameters such as `(/*=K*/ key, /*=V*/ value)` // This is not supported if the type is required. type; } return new FinalConstVarOrType(keywordToken, type); } /// Parse a formal parameter. At most one of `isOptional` and `isNamed` can be /// `true`. The [kind] is the kind of parameter being expected based on the /// presence or absence of group delimiters. Return the formal parameter that /// was parsed. /// /// defaultFormalParameter ::= /// normalFormalParameter ('=' expression)? /// /// defaultNamedParameter ::= /// normalFormalParameter ('=' expression)? /// normalFormalParameter (':' expression)? FormalParameter parseFormalParameter(ParameterKind kind, {bool inFunctionType: false}) { NormalFormalParameter parameter = parseNormalFormalParameter(inFunctionType: inFunctionType); TokenType type = _currentToken.type; if (type == TokenType.EQ) { if (inFunctionType) { _reportErrorForCurrentToken( ParserErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE); } Token separator = getAndAdvance(); Expression defaultValue = parseExpression2(); if (kind == ParameterKind.REQUIRED) { _reportErrorForNode( ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP, parameter); kind = ParameterKind.POSITIONAL; } else if (kind == ParameterKind.NAMED && inFunctionType && parameter.identifier == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_NAME_FOR_NAMED_PARAMETER); parameter.identifier = createSyntheticIdentifier(isDeclaration: true); } return astFactory.defaultFormalParameter( parameter, kind, separator, defaultValue); } else if (type == TokenType.COLON) { if (inFunctionType) { _reportErrorForCurrentToken( ParserErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE); } Token separator = getAndAdvance(); Expression defaultValue = parseExpression2(); if (kind == ParameterKind.REQUIRED) { _reportErrorForNode( ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP, parameter); kind = ParameterKind.NAMED; } else if (kind == ParameterKind.POSITIONAL) { _reportErrorForToken( ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER, separator); } else if (kind == ParameterKind.NAMED && inFunctionType && parameter.identifier == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_NAME_FOR_NAMED_PARAMETER); parameter.identifier = createSyntheticIdentifier(isDeclaration: true); } return astFactory.defaultFormalParameter( parameter, kind, separator, defaultValue); } else if (kind != ParameterKind.REQUIRED) { if (kind == ParameterKind.NAMED && inFunctionType && parameter.identifier == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_NAME_FOR_NAMED_PARAMETER); parameter.identifier = createSyntheticIdentifier(isDeclaration: true); } return astFactory.defaultFormalParameter(parameter, kind, null, null); } return parameter; } /// Parse a list of formal parameters. Return the formal parameters that were /// parsed. /// /// formalParameterList ::= /// '(' ')' /// | '(' normalFormalParameters (',' optionalFormalParameters)? ')' /// | '(' optionalFormalParameters ')' /// /// normalFormalParameters ::= /// normalFormalParameter (',' normalFormalParameter)* /// /// optionalFormalParameters ::= /// optionalPositionalFormalParameters /// | namedFormalParameters /// /// optionalPositionalFormalParameters ::= /// '[' defaultFormalParameter (',' defaultFormalParameter)* ']' /// /// namedFormalParameters ::= /// '{' defaultNamedParameter (',' defaultNamedParameter)* '}' FormalParameterList parseFormalParameterList({bool inFunctionType: false}) { if (_matches(TokenType.OPEN_PAREN)) { return _parseFormalParameterListUnchecked(inFunctionType: inFunctionType); } // TODO(brianwilkerson) Improve the error message. _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [TokenType.OPEN_PAREN.lexeme]); // Recovery: Check for an unmatched closing paren and parse parameters until // it is reached. return _parseFormalParameterListAfterParen( _createSyntheticToken(TokenType.OPEN_PAREN)); } /// Parse a for statement. Return the for statement that was parsed. /// /// forStatement ::= /// 'for' '(' forLoopParts ')' statement /// /// forLoopParts ::= /// forInitializerStatement expression? ';' expressionList? /// | declaredIdentifier 'in' expression /// | identifier 'in' expression /// /// forInitializerStatement ::= /// localVariableDeclaration ';' /// | expression? ';' Statement parseForStatement() { bool wasInLoop = _inLoop; _inLoop = true; try { Token awaitKeyword; if (_matchesKeyword(Keyword.AWAIT)) { awaitKeyword = getAndAdvance(); } Token forKeyword = _expectKeyword(Keyword.FOR); Token leftParenthesis = _expect(TokenType.OPEN_PAREN); VariableDeclarationList variableList; Expression initialization; if (!_matches(TokenType.SEMICOLON)) { CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); if (_matchesIdentifier() && (_tokenMatchesKeyword(_peek(), Keyword.IN) || _tokenMatches(_peek(), TokenType.COLON))) { SimpleIdentifier variableName = _parseSimpleIdentifierUnchecked(); variableList = astFactory.variableDeclarationList( commentAndMetadata.comment, commentAndMetadata.metadata, null, null, <VariableDeclaration>[ astFactory.variableDeclaration(variableName, null, null) ]); } else if (isInitializedVariableDeclaration()) { variableList = parseVariableDeclarationListAfterMetadata(commentAndMetadata); } else { initialization = parseExpression2(); } TokenType type = _currentToken.type; if (_matchesKeyword(Keyword.IN) || type == TokenType.COLON) { if (type == TokenType.COLON) { _reportErrorForCurrentToken(ParserErrorCode.COLON_IN_PLACE_OF_IN); } DeclaredIdentifier loopVariable; SimpleIdentifier identifier; if (variableList == null) { // We found: <expression> 'in' _reportErrorForCurrentToken( ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH); } else { NodeList<VariableDeclaration> variables = variableList.variables; if (variables.length > 1) { _reportErrorForCurrentToken( ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH, [variables.length.toString()]); } VariableDeclaration variable = variables[0]; if (variable.initializer != null) { _reportErrorForCurrentToken( ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH); } Token keyword = variableList.keyword; TypeAnnotation type = variableList.type; if (keyword != null || type != null) { loopVariable = astFactory.declaredIdentifier( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, type, astFactory.simpleIdentifier(variable.name.token, isDeclaration: true)); } else { if (commentAndMetadata.hasMetadata) { // TODO(jwren) metadata isn't allowed before the identifier in // "identifier in expression", add warning if commentAndMetadata // has content } identifier = variable.name; } } Token inKeyword = getAndAdvance(); Expression iterator = parseExpression2(); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); Statement body = parseStatement2(); ForLoopParts forLoopParts; if (loopVariable == null) { forLoopParts = astFactory.forEachPartsWithIdentifier( identifier: identifier, inKeyword: inKeyword, iterable: iterator); } else { forLoopParts = astFactory.forEachPartsWithDeclaration( loopVariable: loopVariable, inKeyword: inKeyword, iterable: iterator); } return astFactory.forStatement( forKeyword: forKeyword, leftParenthesis: leftParenthesis, forLoopParts: forLoopParts, rightParenthesis: rightParenthesis, body: body); } } if (awaitKeyword != null) { _reportErrorForToken( ParserErrorCode.INVALID_AWAIT_IN_FOR, awaitKeyword); } Token leftSeparator = _expect(TokenType.SEMICOLON); Expression condition; if (!_matches(TokenType.SEMICOLON)) { condition = parseExpression2(); } Token rightSeparator = _expect(TokenType.SEMICOLON); List<Expression> updaters; if (!_matches(TokenType.CLOSE_PAREN)) { updaters = parseExpressionList(); } ForLoopParts forLoopParts; if (variableList != null) { forLoopParts = astFactory.forPartsWithDeclarations( variables: variableList, leftSeparator: leftSeparator, condition: condition, rightSeparator: rightSeparator, updaters: updaters); } else { forLoopParts = astFactory.forPartsWithExpression( initialization: initialization, leftSeparator: leftSeparator, condition: condition, rightSeparator: rightSeparator, updaters: updaters); } Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); Statement body = parseStatement2(); return astFactory.forStatement( forKeyword: forKeyword, leftParenthesis: leftParenthesis, forLoopParts: forLoopParts, rightParenthesis: rightParenthesis, body: body); } finally { _inLoop = wasInLoop; } } /// Parse a function body. The [mayBeEmpty] is `true` if the function body is /// allowed to be empty. The [emptyErrorCode] is the error code to report if /// function body expected, but not found. The [inExpression] is `true` if the /// function body is being parsed as part of an expression and therefore does /// not have a terminating semicolon. Return the function body that was /// parsed. /// /// functionBody ::= /// '=>' expression ';' /// | block /// /// functionExpressionBody ::= /// '=>' expression /// | block FunctionBody parseFunctionBody( bool mayBeEmpty, ParserErrorCode emptyErrorCode, bool inExpression) { bool wasInAsync = _inAsync; bool wasInGenerator = _inGenerator; bool wasInLoop = _inLoop; bool wasInSwitch = _inSwitch; _inAsync = false; _inGenerator = false; _inLoop = false; _inSwitch = false; try { TokenType type = _currentToken.type; if (type == TokenType.SEMICOLON) { if (!mayBeEmpty) { _reportErrorForCurrentToken(emptyErrorCode); } return astFactory.emptyFunctionBody(getAndAdvance()); } Token keyword; Token star; bool foundAsync = false; bool foundSync = false; if (type.isKeyword) { String lexeme = _currentToken.lexeme; if (lexeme == ASYNC) { foundAsync = true; keyword = getAndAdvance(); if (_matches(TokenType.STAR)) { star = getAndAdvance(); _inGenerator = true; } type = _currentToken.type; _inAsync = true; } else if (lexeme == SYNC) { foundSync = true; keyword = getAndAdvance(); if (_matches(TokenType.STAR)) { star = getAndAdvance(); _inGenerator = true; } type = _currentToken.type; } } if (type == TokenType.FUNCTION) { if (keyword != null) { if (!foundAsync) { _reportErrorForToken(ParserErrorCode.INVALID_SYNC, keyword); keyword; } else if (star != null) { _reportErrorForToken( ParserErrorCode.INVALID_STAR_AFTER_ASYNC, star); } } Token functionDefinition = getAndAdvance(); if (_matchesKeyword(Keyword.RETURN)) { _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); } Expression expression = parseExpression2(); Token semicolon; if (!inExpression) { semicolon = _expect(TokenType.SEMICOLON); } if (!_parseFunctionBodies) { return astFactory .emptyFunctionBody(_createSyntheticToken(TokenType.SEMICOLON)); } return astFactory.expressionFunctionBody( keyword, functionDefinition, expression, semicolon); } else if (type == TokenType.OPEN_CURLY_BRACKET) { if (keyword != null) { if (foundSync && star == null) { _reportErrorForToken( ParserErrorCode.MISSING_STAR_AFTER_SYNC, keyword); } } if (!_parseFunctionBodies) { _skipBlock(); return astFactory .emptyFunctionBody(_createSyntheticToken(TokenType.SEMICOLON)); } return astFactory.blockFunctionBody(keyword, star, parseBlock()); } else if (_matchesKeyword(Keyword.NATIVE)) { Token nativeToken = getAndAdvance(); StringLiteral stringLiteral; if (_matches(TokenType.STRING)) { stringLiteral = _parseStringLiteralUnchecked(); } return astFactory.nativeFunctionBody( nativeToken, stringLiteral, _expect(TokenType.SEMICOLON)); } else { // Invalid function body _reportErrorForCurrentToken(emptyErrorCode); return astFactory .emptyFunctionBody(_createSyntheticToken(TokenType.SEMICOLON)); } } finally { _inAsync = wasInAsync; _inGenerator = wasInGenerator; _inLoop = wasInLoop; _inSwitch = wasInSwitch; } } /// Parse a function declaration. The [commentAndMetadata] is the /// documentation comment and metadata to be associated with the declaration. /// The [externalKeyword] is the 'external' keyword, or `null` if the /// function is not external. The [returnType] is the return type, or `null` /// if there is no return type. The [isStatement] is `true` if the function /// declaration is being parsed as a statement. Return the function /// declaration that was parsed. /// /// functionDeclaration ::= /// functionSignature functionBody /// | returnType? getOrSet identifier formalParameterList functionBody FunctionDeclaration parseFunctionDeclaration( CommentAndMetadata commentAndMetadata, Token externalKeyword, TypeAnnotation returnType) { Token keywordToken; bool isGetter = false; Keyword keyword = _currentToken.keyword; SimpleIdentifier name; if (keyword == Keyword.GET) { keywordToken = getAndAdvance(); isGetter = true; } else if (keyword == Keyword.SET) { keywordToken = getAndAdvance(); } if (keywordToken != null && _matches(TokenType.OPEN_PAREN)) { name = astFactory.simpleIdentifier(keywordToken, isDeclaration: true); keywordToken; isGetter = false; } else { name = parseSimpleIdentifier(isDeclaration: true); } TypeParameterList typeParameters = _parseGenericMethodTypeParameters(); FormalParameterList parameters; if (!isGetter) { if (_matches(TokenType.OPEN_PAREN)) { parameters = _parseFormalParameterListUnchecked(); _validateFormalParameterList(parameters); } else { _reportErrorForCurrentToken( ParserErrorCode.MISSING_FUNCTION_PARAMETERS); parameters = astFactory.formalParameterList( _createSyntheticToken(TokenType.OPEN_PAREN), null, null, null, _createSyntheticToken(TokenType.CLOSE_PAREN)); } } else if (_matches(TokenType.OPEN_PAREN)) { _reportErrorForCurrentToken(ParserErrorCode.GETTER_WITH_PARAMETERS); _parseFormalParameterListUnchecked(); } FunctionBody body; if (externalKeyword == null) { body = parseFunctionBody( false, ParserErrorCode.MISSING_FUNCTION_BODY, false); } else { body = astFactory.emptyFunctionBody(_expect(TokenType.SEMICOLON)); } // if (!isStatement && matches(TokenType.SEMICOLON)) { // // TODO(brianwilkerson) Improve this error message. // reportError(ParserErrorCode.UNEXPECTED_TOKEN, currentToken.getLexeme()); // advance(); // } return astFactory.functionDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, externalKeyword, returnType, keywordToken, name, astFactory.functionExpression(typeParameters, parameters, body)); } /// Parse a function declaration statement. Return the function declaration /// statement that was parsed. /// /// functionDeclarationStatement ::= /// functionSignature functionBody Statement parseFunctionDeclarationStatement() { Modifiers modifiers = parseModifiers(); _validateModifiersForFunctionDeclarationStatement(modifiers); return _parseFunctionDeclarationStatementAfterReturnType( parseCommentAndMetadata(), _parseOptionalReturnType()); } /// Parse a function expression. Return the function expression that was /// parsed. /// /// functionExpression ::= /// typeParameters? formalParameterList functionExpressionBody FunctionExpression parseFunctionExpression() { TypeParameterList typeParameters = _parseGenericMethodTypeParameters(); FormalParameterList parameters = parseFormalParameterList(); _validateFormalParameterList(parameters); FunctionBody body = parseFunctionBody(false, ParserErrorCode.MISSING_FUNCTION_BODY, true); return astFactory.functionExpression(typeParameters, parameters, body); } /// Parse the portion of a generic function type following the [returnType]. /// /// functionType ::= /// returnType? 'Function' typeParameters? parameterTypeList /// parameterTypeList ::= /// '(' ')' | /// | '(' normalParameterTypes ','? ')' | /// | '(' normalParameterTypes ',' optionalParameterTypes ')' | /// | '(' optionalParameterTypes ')' /// normalParameterTypes ::= /// normalParameterType (',' normalParameterType)* /// normalParameterType ::= /// type | typedIdentifier /// optionalParameterTypes ::= /// optionalPositionalParameterTypes | namedParameterTypes /// optionalPositionalParameterTypes ::= /// '[' normalParameterTypes ','? ']' /// namedParameterTypes ::= /// '{' typedIdentifier (',' typedIdentifier)* ','? '}' /// typedIdentifier ::= /// type identifier GenericFunctionType parseGenericFunctionTypeAfterReturnType( TypeAnnotation returnType) { Token functionKeyword; if (_matchesKeyword(Keyword.FUNCTION)) { functionKeyword = getAndAdvance(); } else if (_matchesIdentifier()) { _reportErrorForCurrentToken(ParserErrorCode.NAMED_FUNCTION_TYPE); } else { _reportErrorForCurrentToken(ParserErrorCode.MISSING_FUNCTION_KEYWORD); } TypeParameterList typeParameters; if (_matches(TokenType.LT)) { typeParameters = parseTypeParameterList(); } FormalParameterList parameters = parseFormalParameterList(inFunctionType: true); return astFactory.genericFunctionType( returnType, functionKeyword, typeParameters, parameters); } /// Parse a generic function type alias. /// /// This method assumes that the current token is an identifier. /// /// genericTypeAlias ::= /// 'typedef' identifier typeParameterList? '=' functionType ';' GenericTypeAlias parseGenericTypeAlias( CommentAndMetadata commentAndMetadata, Token keyword) { Identifier name = _parseSimpleIdentifierUnchecked(isDeclaration: true); TypeParameterList typeParameters; if (_matches(TokenType.LT)) { typeParameters = parseTypeParameterList(); } Token equals = _expect(TokenType.EQ); TypeAnnotation functionType = parseTypeAnnotation(false); Token semicolon = _expect(TokenType.SEMICOLON); if (functionType is! GenericFunctionType) { // TODO(brianwilkerson) Generate a better error. _reportErrorForToken( ParserErrorCode.INVALID_GENERIC_FUNCTION_TYPE, semicolon); // TODO(brianwilkerson) Recover better than this. return astFactory.genericTypeAlias( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, name, typeParameters, equals, null, semicolon); } return astFactory.genericTypeAlias( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, name, typeParameters, equals, functionType, semicolon); } /// Parse a getter. The [commentAndMetadata] is the documentation comment and /// metadata to be associated with the declaration. The externalKeyword] is /// the 'external' token. The staticKeyword] is the static keyword, or `null` /// if the getter is not static. The [returnType] the return type that has /// already been parsed, or `null` if there was no return type. Return the /// getter that was parsed. /// /// This method assumes that the current token matches `Keyword.GET`. /// /// getter ::= /// getterSignature functionBody? /// /// getterSignature ::= /// 'external'? 'static'? returnType? 'get' identifier MethodDeclaration parseGetter(CommentAndMetadata commentAndMetadata, Token externalKeyword, Token staticKeyword, TypeAnnotation returnType) { Token propertyKeyword = getAndAdvance(); SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); if (_matches(TokenType.OPEN_PAREN) && _tokenMatches(_peek(), TokenType.CLOSE_PAREN)) { _reportErrorForCurrentToken(ParserErrorCode.GETTER_WITH_PARAMETERS); _advance(); _advance(); } FunctionBody body = parseFunctionBody( externalKeyword != null || staticKeyword == null, ParserErrorCode.STATIC_GETTER_WITHOUT_BODY, false); if (externalKeyword != null && body is! EmptyFunctionBody) { _reportErrorForCurrentToken(ParserErrorCode.EXTERNAL_GETTER_WITH_BODY); } return astFactory.methodDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, externalKeyword, staticKeyword, returnType, propertyKeyword, null, name, null, null, body); } /// Parse a list of identifiers. Return the list of identifiers that were /// parsed. /// /// identifierList ::= /// identifier (',' identifier)* List<SimpleIdentifier> parseIdentifierList() { List<SimpleIdentifier> identifiers = <SimpleIdentifier>[ parseSimpleIdentifier() ]; while (_optional(TokenType.COMMA)) { identifiers.add(parseSimpleIdentifier()); } return identifiers; } /// Parse an if-null expression. Return the if-null expression that was /// parsed. /// /// ifNullExpression ::= logicalOrExpression ('??' logicalOrExpression)* Expression parseIfNullExpression() { Expression expression = parseLogicalOrExpression(); while (_currentToken.type == TokenType.QUESTION_QUESTION) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseLogicalOrExpression()); } return expression; } /// Parse an if statement. Return the if statement that was parsed. /// /// This method assumes that the current token matches `Keyword.IF`. /// /// ifStatement ::= /// 'if' '(' expression ')' statement ('else' statement)? Statement parseIfStatement() { Token ifKeyword = getAndAdvance(); Token leftParenthesis = _expect(TokenType.OPEN_PAREN); Expression condition = parseExpression2(); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); Statement thenStatement = parseStatement2(); Token elseKeyword; Statement elseStatement; if (_matchesKeyword(Keyword.ELSE)) { elseKeyword = getAndAdvance(); elseStatement = parseStatement2(); } return astFactory.ifStatement(ifKeyword, leftParenthesis, condition, rightParenthesis, thenStatement, elseKeyword, elseStatement); } /// Parse an implements clause. Return the implements clause that was parsed. /// /// This method assumes that the current token matches `Keyword.IMPLEMENTS`. /// /// implementsClause ::= /// 'implements' type (',' type)* ImplementsClause parseImplementsClause() { Token keyword = getAndAdvance(); List<TypeName> interfaces = <TypeName>[]; do { TypeName typeName = parseTypeName(false); interfaces.add(typeName); } while (_optional(TokenType.COMMA)); return astFactory.implementsClause(keyword, interfaces); } /// Parse an import directive. The [commentAndMetadata] is the metadata to be /// associated with the directive. Return the import directive that was /// parsed. /// /// This method assumes that the current token matches `Keyword.IMPORT`. /// /// importDirective ::= /// metadata 'import' stringLiteral configuration* (deferred)? ('as' identifier)? combinator*';' ImportDirective parseImportDirective(CommentAndMetadata commentAndMetadata) { Token importKeyword = getAndAdvance(); StringLiteral libraryUri = _parseUri(); List<Configuration> configurations = _parseConfigurations(); Token deferredToken; Token asToken; SimpleIdentifier prefix; if (_matchesKeyword(Keyword.DEFERRED)) { deferredToken = getAndAdvance(); } if (_matchesKeyword(Keyword.AS)) { asToken = getAndAdvance(); prefix = parseSimpleIdentifier(isDeclaration: true); } else if (deferredToken != null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_PREFIX_IN_DEFERRED_IMPORT); } else if (!_matches(TokenType.SEMICOLON) && !_matchesKeyword(Keyword.SHOW) && !_matchesKeyword(Keyword.HIDE)) { Token nextToken = _peek(); if (_tokenMatchesKeyword(nextToken, Keyword.AS) || _tokenMatchesKeyword(nextToken, Keyword.SHOW) || _tokenMatchesKeyword(nextToken, Keyword.HIDE)) { _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken]); _advance(); if (_matchesKeyword(Keyword.AS)) { asToken = getAndAdvance(); prefix = parseSimpleIdentifier(isDeclaration: true); } } } List<Combinator> combinators = parseCombinators(); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.importDirective( commentAndMetadata.comment, commentAndMetadata.metadata, importKeyword, libraryUri, configurations, deferredToken, asToken, prefix, combinators, semicolon); } /// Parse a list of initialized identifiers. The [commentAndMetadata] is the /// documentation comment and metadata to be associated with the declaration. /// The [staticKeyword] is the static keyword, or `null` if the getter is not /// static. The [keyword] is the token representing the 'final', 'const' or /// 'var' keyword, or `null` if there is no keyword. The [type] is the type /// that has already been parsed, or `null` if 'var' was provided. Return the /// getter that was parsed. /// /// declaration ::= /// ('static' | 'covariant')? ('var' | type) initializedIdentifierList ';' /// | 'final' type? initializedIdentifierList ';' /// /// initializedIdentifierList ::= /// initializedIdentifier (',' initializedIdentifier)* /// /// initializedIdentifier ::= /// identifier ('=' expression)? FieldDeclaration parseInitializedIdentifierList( CommentAndMetadata commentAndMetadata, Token staticKeyword, Token covariantKeyword, Token keyword, TypeAnnotation type) { VariableDeclarationList fieldList = parseVariableDeclarationListAfterType(null, keyword, type); return astFactory.fieldDeclaration2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: covariantKeyword, staticKeyword: staticKeyword, fieldList: fieldList, semicolon: _expect(TokenType.SEMICOLON)); } /// Parse an instance creation expression. The [keyword] is the 'new' or /// 'const' keyword that introduces the expression. Return the instance /// creation expression that was parsed. /// /// instanceCreationExpression ::= /// ('new' | 'const') type ('.' identifier)? argumentList InstanceCreationExpression parseInstanceCreationExpression(Token keyword) { ConstructorName constructorName = parseConstructorName(); ArgumentList argumentList = _parseArgumentListChecked(); return astFactory.instanceCreationExpression( keyword, constructorName, argumentList); } /// Parse a label. Return the label that was parsed. /// /// This method assumes that the current token matches an identifier and that /// the following token matches `TokenType.COLON`. /// /// label ::= /// identifier ':' Label parseLabel({bool isDeclaration: false}) { SimpleIdentifier label = _parseSimpleIdentifierUnchecked(isDeclaration: isDeclaration); Token colon = getAndAdvance(); return astFactory.label(label, colon); } /// Parse a library directive. The [commentAndMetadata] is the metadata to be /// associated with the directive. Return the library directive that was /// parsed. /// /// This method assumes that the current token matches `Keyword.LIBRARY`. /// /// libraryDirective ::= /// metadata 'library' identifier ';' LibraryDirective parseLibraryDirective( CommentAndMetadata commentAndMetadata) { Token keyword = getAndAdvance(); LibraryIdentifier libraryName = _parseLibraryName( ParserErrorCode.MISSING_NAME_IN_LIBRARY_DIRECTIVE, keyword); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.libraryDirective(commentAndMetadata.comment, commentAndMetadata.metadata, keyword, libraryName, semicolon); } /// Parse a library identifier. Return the library identifier that was parsed. /// /// libraryIdentifier ::= /// identifier ('.' identifier)* LibraryIdentifier parseLibraryIdentifier() { List<SimpleIdentifier> components = <SimpleIdentifier>[]; components.add(parseSimpleIdentifier()); while (_optional(TokenType.PERIOD)) { components.add(parseSimpleIdentifier()); } return astFactory.libraryIdentifier(components); } /// Parse a list literal. The [modifier] is the 'const' modifier appearing /// before the literal, or `null` if there is no modifier. The [typeArguments] /// is the type arguments appearing before the literal, or `null` if there are /// no type arguments. Return the list literal that was parsed. /// /// This method assumes that the current token matches either /// `TokenType.OPEN_SQUARE_BRACKET` or `TokenType.INDEX`. /// /// listLiteral ::= /// 'const'? typeArguments? '[' (expressionList ','?)? ']' ListLiteral parseListLiteral(Token modifier, TypeArgumentList typeArguments) { if (_matches(TokenType.INDEX)) { _splitIndex(); return astFactory.listLiteral( modifier, typeArguments, getAndAdvance(), null, getAndAdvance()); } Token leftBracket = getAndAdvance(); if (_matches(TokenType.CLOSE_SQUARE_BRACKET)) { return astFactory.listLiteral( modifier, typeArguments, leftBracket, null, getAndAdvance()); } bool wasInInitializer = _inInitializer; _inInitializer = false; try { List<Expression> elements = <Expression>[parseExpression2()]; while (_optional(TokenType.COMMA)) { if (_matches(TokenType.CLOSE_SQUARE_BRACKET)) { return astFactory.listLiteral( modifier, typeArguments, leftBracket, elements, getAndAdvance()); } elements.add(parseExpression2()); } Token rightBracket = _expect(TokenType.CLOSE_SQUARE_BRACKET); return astFactory.listLiteral( modifier, typeArguments, leftBracket, elements, rightBracket); } finally { _inInitializer = wasInInitializer; } } /// Parse a list or map literal. The [modifier] is the 'const' modifier /// appearing before the literal, or `null` if there is no modifier. Return /// the list or map literal that was parsed. /// /// listOrMapLiteral ::= /// listLiteral /// | mapLiteral TypedLiteral parseListOrMapLiteral(Token modifier) { TypeArgumentList typeArguments = _parseOptionalTypeArguments(); if (_matches(TokenType.OPEN_CURLY_BRACKET)) { return parseMapLiteral(modifier, typeArguments); } else if (_matches(TokenType.OPEN_SQUARE_BRACKET) || _matches(TokenType.INDEX)) { return parseListLiteral(modifier, typeArguments); } _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL); return astFactory.listLiteral( modifier, typeArguments, _createSyntheticToken(TokenType.OPEN_SQUARE_BRACKET), null, _createSyntheticToken(TokenType.CLOSE_SQUARE_BRACKET)); } /// Parse a logical and expression. Return the logical and expression that was /// parsed. /// /// logicalAndExpression ::= /// equalityExpression ('&&' equalityExpression)* Expression parseLogicalAndExpression() { Expression expression = parseEqualityExpression(); while (_currentToken.type == TokenType.AMPERSAND_AMPERSAND) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseEqualityExpression()); } return expression; } /// Parse a logical or expression. Return the logical or expression that was /// parsed. /// /// logicalOrExpression ::= /// logicalAndExpression ('||' logicalAndExpression)* Expression parseLogicalOrExpression() { Expression expression = parseLogicalAndExpression(); while (_currentToken.type == TokenType.BAR_BAR) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseLogicalAndExpression()); } return expression; } /// Parse a map literal. The [modifier] is the 'const' modifier appearing /// before the literal, or `null` if there is no modifier. The [typeArguments] /// is the type arguments that were declared, or `null` if there are no type /// arguments. Return the map literal that was parsed. /// /// This method assumes that the current token matches /// `TokenType.OPEN_CURLY_BRACKET`. /// /// mapLiteral ::= /// 'const'? typeArguments? '{' (mapLiteralEntry (',' mapLiteralEntry)* ','?)? '}' SetOrMapLiteral parseMapLiteral( Token modifier, TypeArgumentList typeArguments) { Token leftBracket = getAndAdvance(); if (_matches(TokenType.CLOSE_CURLY_BRACKET)) { return astFactory.setOrMapLiteral( constKeyword: modifier, typeArguments: typeArguments, leftBracket: leftBracket, rightBracket: getAndAdvance()); } bool wasInInitializer = _inInitializer; _inInitializer = false; try { List<MapLiteralEntry> entries = <MapLiteralEntry>[parseMapLiteralEntry()]; while (_optional(TokenType.COMMA)) { if (_matches(TokenType.CLOSE_CURLY_BRACKET)) { return astFactory.setOrMapLiteral( constKeyword: modifier, typeArguments: typeArguments, leftBracket: leftBracket, elements: entries, rightBracket: getAndAdvance()); } entries.add(parseMapLiteralEntry()); } Token rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET); return astFactory.setOrMapLiteral( constKeyword: modifier, typeArguments: typeArguments, leftBracket: leftBracket, elements: entries, rightBracket: rightBracket); } finally { _inInitializer = wasInInitializer; } } /// Parse a map literal entry. Return the map literal entry that was parsed. /// /// mapLiteralEntry ::= /// expression ':' expression MapLiteralEntry parseMapLiteralEntry() { Expression key = parseExpression2(); Token separator = _expect(TokenType.COLON); Expression value = parseExpression2(); return astFactory.mapLiteralEntry(key, separator, value); } /// Parse the modifiers preceding a declaration. This method allows the /// modifiers to appear in any order but does generate errors for duplicated /// modifiers. Checks for other problems, such as having the modifiers appear /// in the wrong order or specifying both 'const' and 'final', are reported in /// one of the methods whose name is prefixed with `validateModifiersFor`. /// Return the modifiers that were parsed. /// /// modifiers ::= /// ('abstract' | 'const' | 'external' | 'factory' | 'final' | 'static' | 'var')* Modifiers parseModifiers() { Modifiers modifiers = new Modifiers(); bool progress = true; while (progress) { TokenType nextType = _peek().type; if (nextType == TokenType.PERIOD || nextType == TokenType.LT || nextType == TokenType.OPEN_PAREN) { return modifiers; } Keyword keyword = _currentToken.keyword; if (keyword == Keyword.ABSTRACT) { if (modifiers.abstractKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.abstractKeyword = getAndAdvance(); } } else if (keyword == Keyword.CONST) { if (modifiers.constKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.constKeyword = getAndAdvance(); } } else if (keyword == Keyword.COVARIANT) { if (modifiers.covariantKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.covariantKeyword = getAndAdvance(); } } else if (keyword == Keyword.EXTERNAL) { if (modifiers.externalKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.externalKeyword = getAndAdvance(); } } else if (keyword == Keyword.FACTORY) { if (modifiers.factoryKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.factoryKeyword = getAndAdvance(); } } else if (keyword == Keyword.FINAL) { if (modifiers.finalKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.finalKeyword = getAndAdvance(); } } else if (keyword == Keyword.STATIC) { if (modifiers.staticKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.staticKeyword = getAndAdvance(); } } else if (keyword == Keyword.VAR) { if (modifiers.varKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.DUPLICATED_MODIFIER, [_currentToken.lexeme]); _advance(); } else { modifiers.varKeyword = getAndAdvance(); } } else { progress = false; } } return modifiers; } /// Parse a multiplicative expression. Return the multiplicative expression /// that was parsed. /// /// multiplicativeExpression ::= /// unaryExpression (multiplicativeOperator unaryExpression)* /// | 'super' (multiplicativeOperator unaryExpression)+ Expression parseMultiplicativeExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type.isMultiplicativeOperator) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseUnaryExpression(); } while (_currentToken.type.isMultiplicativeOperator) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseUnaryExpression()); } return expression; } /// Parse a new expression. Return the new expression that was parsed. /// /// This method assumes that the current token matches `Keyword.NEW`. /// /// newExpression ::= /// instanceCreationExpression InstanceCreationExpression parseNewExpression() => parseInstanceCreationExpression(getAndAdvance()); /// Parse a non-labeled statement. Return the non-labeled statement that was /// parsed. /// /// nonLabeledStatement ::= /// block /// | assertStatement /// | breakStatement /// | continueStatement /// | doStatement /// | forStatement /// | ifStatement /// | returnStatement /// | switchStatement /// | tryStatement /// | whileStatement /// | variableDeclarationList ';' /// | expressionStatement /// | functionSignature functionBody Statement parseNonLabeledStatement() { // TODO(brianwilkerson) Pass the comment and metadata on where appropriate. CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); TokenType type = _currentToken.type; if (type == TokenType.OPEN_CURLY_BRACKET) { if (_tokenMatches(_peek(), TokenType.STRING)) { Token afterString = skipStringLiteral(_currentToken.next); if (afterString != null && afterString.type == TokenType.COLON) { return astFactory.expressionStatement( parseExpression2(), _expect(TokenType.SEMICOLON)); } } return parseBlock(); } else if (type.isKeyword && !_currentToken.keyword.isBuiltInOrPseudo) { Keyword keyword = _currentToken.keyword; // TODO(jwren) compute some metrics to figure out a better order for this // if-then sequence to optimize performance if (keyword == Keyword.ASSERT) { return parseAssertStatement(); } else if (keyword == Keyword.BREAK) { return parseBreakStatement(); } else if (keyword == Keyword.CONTINUE) { return parseContinueStatement(); } else if (keyword == Keyword.DO) { return parseDoStatement(); } else if (keyword == Keyword.FOR) { return parseForStatement(); } else if (keyword == Keyword.IF) { return parseIfStatement(); } else if (keyword == Keyword.RETHROW) { return astFactory.expressionStatement( parseRethrowExpression(), _expect(TokenType.SEMICOLON)); } else if (keyword == Keyword.RETURN) { return parseReturnStatement(); } else if (keyword == Keyword.SWITCH) { return parseSwitchStatement(); } else if (keyword == Keyword.THROW) { return astFactory.expressionStatement( parseThrowExpression(), _expect(TokenType.SEMICOLON)); } else if (keyword == Keyword.TRY) { return parseTryStatement(); } else if (keyword == Keyword.WHILE) { return parseWhileStatement(); } else if (keyword == Keyword.VAR || keyword == Keyword.FINAL) { return parseVariableDeclarationStatementAfterMetadata( commentAndMetadata); } else if (keyword == Keyword.VOID) { TypeAnnotation returnType; if (_atGenericFunctionTypeAfterReturnType(_peek())) { returnType = parseTypeAnnotation(false); } else { returnType = astFactory.typeName( astFactory.simpleIdentifier(getAndAdvance()), null); } Token next = _currentToken.next; if (_matchesIdentifier() && next.matchesAny(const <TokenType>[ TokenType.OPEN_PAREN, TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION, TokenType.LT ])) { return _parseFunctionDeclarationStatementAfterReturnType( commentAndMetadata, returnType); } else if (_matchesIdentifier() && next.matchesAny(const <TokenType>[ TokenType.EQ, TokenType.COMMA, TokenType.SEMICOLON ])) { return _parseVariableDeclarationStatementAfterType( commentAndMetadata, null, returnType); } else { // // We have found an error of some kind. Try to recover. // if (_matches(TokenType.CLOSE_CURLY_BRACKET)) { // // We appear to have found an incomplete statement at the end of a // block. Parse it as a variable declaration. // return _parseVariableDeclarationStatementAfterType( commentAndMetadata, null, returnType); } _reportErrorForCurrentToken(ParserErrorCode.MISSING_STATEMENT); // TODO(brianwilkerson) Recover from this error. return astFactory .emptyStatement(_createSyntheticToken(TokenType.SEMICOLON)); } } else if (keyword == Keyword.CONST) { Token next = _currentToken.next; if (next.matchesAny(const <TokenType>[ TokenType.LT, TokenType.OPEN_CURLY_BRACKET, TokenType.OPEN_SQUARE_BRACKET, TokenType.INDEX ])) { return astFactory.expressionStatement( parseExpression2(), _expect(TokenType.SEMICOLON)); } else if (_tokenMatches(next, TokenType.IDENTIFIER)) { Token afterType = skipTypeName(next); if (afterType != null) { if (_tokenMatches(afterType, TokenType.OPEN_PAREN) || (_tokenMatches(afterType, TokenType.PERIOD) && _tokenMatches(afterType.next, TokenType.IDENTIFIER) && _tokenMatches(afterType.next.next, TokenType.OPEN_PAREN))) { return astFactory.expressionStatement( parseExpression2(), _expect(TokenType.SEMICOLON)); } } } return parseVariableDeclarationStatementAfterMetadata( commentAndMetadata); } else if (keyword == Keyword.NEW || keyword == Keyword.TRUE || keyword == Keyword.FALSE || keyword == Keyword.NULL || keyword == Keyword.SUPER || keyword == Keyword.THIS) { return astFactory.expressionStatement( parseExpression2(), _expect(TokenType.SEMICOLON)); } else { // // We have found an error of some kind. Try to recover. // _reportErrorForCurrentToken(ParserErrorCode.MISSING_STATEMENT); return astFactory .emptyStatement(_createSyntheticToken(TokenType.SEMICOLON)); } } else if (_atGenericFunctionTypeAfterReturnType(_currentToken)) { TypeAnnotation returnType = parseTypeAnnotation(false); Token next = _currentToken.next; if (_matchesIdentifier() && next.matchesAny(const <TokenType>[ TokenType.OPEN_PAREN, TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION, TokenType.LT ])) { return _parseFunctionDeclarationStatementAfterReturnType( commentAndMetadata, returnType); } else if (_matchesIdentifier() && next.matchesAny(const <TokenType>[ TokenType.EQ, TokenType.COMMA, TokenType.SEMICOLON ])) { return _parseVariableDeclarationStatementAfterType( commentAndMetadata, null, returnType); } else { // // We have found an error of some kind. Try to recover. // if (_matches(TokenType.CLOSE_CURLY_BRACKET)) { // // We appear to have found an incomplete statement at the end of a // block. Parse it as a variable declaration. // return _parseVariableDeclarationStatementAfterType( commentAndMetadata, null, returnType); } _reportErrorForCurrentToken(ParserErrorCode.MISSING_STATEMENT); // TODO(brianwilkerson) Recover from this error. return astFactory .emptyStatement(_createSyntheticToken(TokenType.SEMICOLON)); } } else if (_inGenerator && _matchesKeyword(Keyword.YIELD)) { return parseYieldStatement(); } else if (_inAsync && _matchesKeyword(Keyword.AWAIT)) { if (_tokenMatchesKeyword(_peek(), Keyword.FOR)) { return parseForStatement(); } return astFactory.expressionStatement( parseExpression2(), _expect(TokenType.SEMICOLON)); } else if (_matchesKeyword(Keyword.AWAIT) && _tokenMatchesKeyword(_peek(), Keyword.FOR)) { Token awaitToken = _currentToken; Statement statement = parseForStatement(); if (!(statement is ForStatement && statement.forLoopParts is ForParts)) { _reportErrorForToken( CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT, awaitToken); } return statement; } else if (type == TokenType.SEMICOLON) { return parseEmptyStatement(); } else if (isInitializedVariableDeclaration()) { return parseVariableDeclarationStatementAfterMetadata(commentAndMetadata); } else if (isFunctionDeclaration()) { return parseFunctionDeclarationStatement(); } else if (type == TokenType.CLOSE_CURLY_BRACKET) { _reportErrorForCurrentToken(ParserErrorCode.MISSING_STATEMENT); return astFactory .emptyStatement(_createSyntheticToken(TokenType.SEMICOLON)); } else { return astFactory.expressionStatement( parseExpression2(), _expect(TokenType.SEMICOLON)); } } /// Parse a normal formal parameter. Return the normal formal parameter that /// was parsed. /// /// normalFormalParameter ::= /// functionSignature /// | fieldFormalParameter /// | simpleFormalParameter /// /// functionSignature: /// metadata returnType? identifier typeParameters? formalParameterList /// /// fieldFormalParameter ::= /// metadata finalConstVarOrType? 'this' '.' identifier /// /// simpleFormalParameter ::= /// declaredIdentifier /// | metadata identifier NormalFormalParameter parseNormalFormalParameter( {bool inFunctionType: false}) { Token covariantKeyword; CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); if (_matchesKeyword(Keyword.COVARIANT)) { // Check to ensure that 'covariant' isn't being used as the parameter name. Token next = _peek(); if (_tokenMatchesKeyword(next, Keyword.FINAL) || _tokenMatchesKeyword(next, Keyword.CONST) || _tokenMatchesKeyword(next, Keyword.VAR) || _tokenMatchesKeyword(next, Keyword.THIS) || _tokenMatchesKeyword(next, Keyword.VOID) || _tokenMatchesIdentifier(next)) { covariantKeyword = getAndAdvance(); } } FinalConstVarOrType holder = parseFinalConstVarOrType(!inFunctionType, inFunctionType: inFunctionType); Token thisKeyword; Token period; if (_matchesKeyword(Keyword.THIS)) { thisKeyword = getAndAdvance(); period = _expect(TokenType.PERIOD); } if (!_matchesIdentifier() && inFunctionType) { return astFactory.simpleFormalParameter2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: covariantKeyword, keyword: holder.keyword, type: holder.type, identifier: null); } SimpleIdentifier identifier = parseSimpleIdentifier(); TypeParameterList typeParameters = _parseGenericMethodTypeParameters(); if (_matches(TokenType.OPEN_PAREN)) { FormalParameterList parameters = _parseFormalParameterListUnchecked(); if (thisKeyword == null) { if (holder.keyword != null) { _reportErrorForToken( ParserErrorCode.FUNCTION_TYPED_PARAMETER_VAR, holder.keyword); } return astFactory.functionTypedFormalParameter2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: covariantKeyword, returnType: holder.type, identifier: astFactory.simpleIdentifier(identifier.token, isDeclaration: true), typeParameters: typeParameters, parameters: parameters); } else { return astFactory.fieldFormalParameter2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: covariantKeyword, keyword: holder.keyword, type: holder.type, thisKeyword: thisKeyword, period: period, identifier: identifier, typeParameters: typeParameters, parameters: parameters); } } else if (typeParameters != null) { // TODO(brianwilkerson) Report an error. It looks like a function-typed // parameter with no parameter list. //_reportErrorForToken(ParserErrorCode.MISSING_PARAMETERS, typeParameters.endToken); } TypeAnnotation type = holder.type; if (type != null && holder.keyword != null && _tokenMatchesKeyword(holder.keyword, Keyword.VAR)) { _reportErrorForToken(ParserErrorCode.VAR_AND_TYPE, holder.keyword); } if (thisKeyword != null) { // TODO(brianwilkerson) If there are type parameters but no parameters, // should we create a synthetic empty parameter list here so we can // capture the type parameters? return astFactory.fieldFormalParameter2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: covariantKeyword, keyword: holder.keyword, type: type, thisKeyword: thisKeyword, period: period, identifier: identifier); } return astFactory.simpleFormalParameter2( comment: commentAndMetadata.comment, metadata: commentAndMetadata.metadata, covariantKeyword: covariantKeyword, keyword: holder.keyword, type: type, identifier: astFactory.simpleIdentifier(identifier.token, isDeclaration: true)); } /// Parse an operator declaration. The [commentAndMetadata] is the /// documentation comment and metadata to be associated with the declaration. /// The [externalKeyword] is the 'external' token. The [returnType] is the /// return type that has already been parsed, or `null` if there was no return /// type. Return the operator declaration that was parsed. /// /// operatorDeclaration ::= /// operatorSignature (';' | functionBody) /// /// operatorSignature ::= /// 'external'? returnType? 'operator' operator formalParameterList MethodDeclaration parseOperator(CommentAndMetadata commentAndMetadata, Token externalKeyword, TypeName returnType) { Token operatorKeyword; if (_matchesKeyword(Keyword.OPERATOR)) { operatorKeyword = getAndAdvance(); } else { _reportErrorForToken( ParserErrorCode.MISSING_KEYWORD_OPERATOR, _currentToken); operatorKeyword = _createSyntheticKeyword(Keyword.OPERATOR); } return _parseOperatorAfterKeyword( commentAndMetadata, externalKeyword, returnType, operatorKeyword); } /// Parse a part or part-of directive. The [commentAndMetadata] is the /// metadata to be associated with the directive. Return the part or part-of /// directive that was parsed. /// /// This method assumes that the current token matches `Keyword.PART`. /// /// partDirective ::= /// metadata 'part' stringLiteral ';' /// /// partOfDirective ::= /// metadata 'part' 'of' identifier ';' Directive parsePartOrPartOfDirective(CommentAndMetadata commentAndMetadata) { if (_tokenMatchesKeyword(_peek(), Keyword.OF)) { return _parsePartOfDirective(commentAndMetadata); } return _parsePartDirective(commentAndMetadata); } /// Parse a postfix expression. Return the postfix expression that was parsed. /// /// postfixExpression ::= /// assignableExpression postfixOperator /// | primary selector* /// /// selector ::= /// assignableSelector /// | argumentPart Expression parsePostfixExpression() { Expression operand = parseAssignableExpression(true); TokenType type = _currentToken.type; if (type == TokenType.OPEN_SQUARE_BRACKET || type == TokenType.PERIOD || type == TokenType.QUESTION_PERIOD || type == TokenType.OPEN_PAREN || type == TokenType.LT || type == TokenType.INDEX) { do { if (_isLikelyArgumentList()) { TypeArgumentList typeArguments = _parseOptionalTypeArguments(); ArgumentList argumentList = parseArgumentList(); Expression currentOperand = operand; if (currentOperand is PropertyAccess) { operand = astFactory.methodInvocation( currentOperand.target, currentOperand.operator, currentOperand.propertyName, typeArguments, argumentList); } else { operand = astFactory.functionExpressionInvocation( operand, typeArguments, argumentList); } } else if (enableOptionalNewAndConst && operand is Identifier && _isLikelyNamedInstanceCreation()) { TypeArgumentList typeArguments = _parseOptionalTypeArguments(); Token period = _expect(TokenType.PERIOD); SimpleIdentifier name = parseSimpleIdentifier(); ArgumentList argumentList = parseArgumentList(); TypeName typeName = astFactory.typeName(operand, typeArguments); operand = astFactory.instanceCreationExpression(null, astFactory.constructorName(typeName, period, name), argumentList); } else { operand = parseAssignableSelector(operand, true); } type = _currentToken.type; } while (type == TokenType.OPEN_SQUARE_BRACKET || type == TokenType.PERIOD || type == TokenType.QUESTION_PERIOD || type == TokenType.OPEN_PAREN || type == TokenType.INDEX); return operand; } if (!_currentToken.type.isIncrementOperator) { return operand; } _ensureAssignable(operand); Token operator = getAndAdvance(); return astFactory.postfixExpression(operand, operator); } /// Parse a prefixed identifier. Return the prefixed identifier that was /// parsed. /// /// prefixedIdentifier ::= /// identifier ('.' identifier)? Identifier parsePrefixedIdentifier() { return _parsePrefixedIdentifierAfterIdentifier(parseSimpleIdentifier()); } /// Parse a primary expression. Return the primary expression that was parsed. /// /// primary ::= /// thisExpression /// | 'super' unconditionalAssignableSelector /// | functionExpression /// | literal /// | identifier /// | newExpression /// | constObjectExpression /// | '(' expression ')' /// | argumentDefinitionTest /// /// literal ::= /// nullLiteral /// | booleanLiteral /// | numericLiteral /// | stringLiteral /// | symbolLiteral /// | mapLiteral /// | listLiteral Expression parsePrimaryExpression() { if (_matchesIdentifier()) { // TODO(brianwilkerson) The code below was an attempt to recover from an // error case, but it needs to be applied as a recovery only after we // know that parsing it as an identifier doesn't work. Leaving the code as // a reminder of how to recover. // if (isFunctionExpression(_peek())) { // // // // Function expressions were allowed to have names at one point, but this is now illegal. // // // reportError(ParserErrorCode.NAMED_FUNCTION_EXPRESSION, getAndAdvance()); // return parseFunctionExpression(); // } return _parsePrefixedIdentifierUnchecked(); } TokenType type = _currentToken.type; if (type == TokenType.STRING) { return parseStringLiteral(); } else if (type == TokenType.INT) { Token token = getAndAdvance(); int value; try { value = int.parse(token.lexeme); } on FormatException { // The invalid format should have been reported by the scanner. } return astFactory.integerLiteral(token, value); } Keyword keyword = _currentToken.keyword; if (keyword == Keyword.NULL) { return astFactory.nullLiteral(getAndAdvance()); } else if (keyword == Keyword.NEW) { return parseNewExpression(); } else if (keyword == Keyword.THIS) { return astFactory.thisExpression(getAndAdvance()); } else if (keyword == Keyword.SUPER) { return parseAssignableSelector( astFactory.superExpression(getAndAdvance()), false, allowConditional: false); } else if (keyword == Keyword.FALSE) { return astFactory.booleanLiteral(getAndAdvance(), false); } else if (keyword == Keyword.TRUE) { return astFactory.booleanLiteral(getAndAdvance(), true); } if (type == TokenType.DOUBLE) { Token token = getAndAdvance(); double value = 0.0; try { value = double.parse(token.lexeme); } on FormatException { // The invalid format should have been reported by the scanner. } return astFactory.doubleLiteral(token, value); } else if (type == TokenType.HEXADECIMAL) { Token token = getAndAdvance(); int value; try { value = int.parse(token.lexeme); } on FormatException { // The invalid format should have been reported by the scanner. } return astFactory.integerLiteral(token, value); } else if (keyword == Keyword.CONST) { return parseConstExpression(); } else if (type == TokenType.OPEN_PAREN) { if (isFunctionExpression(_currentToken)) { return parseFunctionExpression(); } Token leftParenthesis = getAndAdvance(); bool wasInInitializer = _inInitializer; _inInitializer = false; try { Expression expression = parseExpression2(); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); return astFactory.parenthesizedExpression( leftParenthesis, expression, rightParenthesis); } finally { _inInitializer = wasInInitializer; } } else if (type == TokenType.LT) { if (isFunctionExpression(currentToken)) { return parseFunctionExpression(); } return parseListOrMapLiteral(null); } else if (type == TokenType.OPEN_CURLY_BRACKET) { return parseMapLiteral(null, null); } else if (type == TokenType.OPEN_SQUARE_BRACKET || type == TokenType.INDEX) { return parseListLiteral(null, null); } else if (type == TokenType.QUESTION && _tokenMatches(_peek(), TokenType.IDENTIFIER)) { _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]); _advance(); return parsePrimaryExpression(); } else if (keyword == Keyword.VOID) { // // Recover from having a return type of "void" where a return type is not // expected. // // TODO(brianwilkerson) Improve this error message. _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]); _advance(); return parsePrimaryExpression(); } else if (type == TokenType.HASH) { return parseSymbolLiteral(); } else { _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); return createSyntheticIdentifier(); } } /// Parse a redirecting constructor invocation. The flag [hasPeriod] should be /// `true` if the `this` is followed by a period. Return the redirecting /// constructor invocation that was parsed. /// /// This method assumes that the current token matches `Keyword.THIS`. /// /// redirectingConstructorInvocation ::= /// 'this' ('.' identifier)? arguments RedirectingConstructorInvocation parseRedirectingConstructorInvocation( bool hasPeriod) { Token keyword = getAndAdvance(); Token period; SimpleIdentifier constructorName; if (hasPeriod) { period = getAndAdvance(); if (_matchesIdentifier()) { constructorName = _parseSimpleIdentifierUnchecked(isDeclaration: false); } else { _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); constructorName = createSyntheticIdentifier(isDeclaration: false); _advance(); } } ArgumentList argumentList = _parseArgumentListChecked(); return astFactory.redirectingConstructorInvocation( keyword, period, constructorName, argumentList); } /// Parse a relational expression. Return the relational expression that was /// parsed. /// /// relationalExpression ::= /// bitwiseOrExpression ('is' '!'? type | 'as' type | relationalOperator bitwiseOrExpression)? /// | 'super' relationalOperator bitwiseOrExpression Expression parseRelationalExpression() { if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type.isRelationalOperator) { Expression expression = astFactory.superExpression(getAndAdvance()); Token operator = getAndAdvance(); return astFactory.binaryExpression( expression, operator, parseBitwiseOrExpression()); } Expression expression = parseBitwiseOrExpression(); Keyword keyword = _currentToken.keyword; if (keyword == Keyword.AS) { Token asOperator = getAndAdvance(); return astFactory.asExpression( expression, asOperator, parseTypeNotVoid(true)); } else if (keyword == Keyword.IS) { Token isOperator = getAndAdvance(); Token notOperator; if (_matches(TokenType.BANG)) { notOperator = getAndAdvance(); } TypeAnnotation type = parseTypeNotVoid(true); return astFactory.isExpression(expression, isOperator, notOperator, type); } else if (_currentToken.type.isRelationalOperator) { Token operator = getAndAdvance(); return astFactory.binaryExpression( expression, operator, parseBitwiseOrExpression()); } return expression; } /// Parse a rethrow expression. Return the rethrow expression that was parsed. /// /// This method assumes that the current token matches `Keyword.RETHROW`. /// /// rethrowExpression ::= /// 'rethrow' Expression parseRethrowExpression() => astFactory.rethrowExpression(getAndAdvance()); /// Parse a return statement. Return the return statement that was parsed. /// /// This method assumes that the current token matches `Keyword.RETURN`. /// /// returnStatement ::= /// 'return' expression? ';' Statement parseReturnStatement() { Token returnKeyword = getAndAdvance(); if (_matches(TokenType.SEMICOLON)) { return astFactory.returnStatement(returnKeyword, null, getAndAdvance()); } Expression expression = parseExpression2(); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.returnStatement(returnKeyword, expression, semicolon); } /// Parse a setter. The [commentAndMetadata] is the documentation comment and /// metadata to be associated with the declaration. The [externalKeyword] is /// the 'external' token. The [staticKeyword] is the static keyword, or `null` /// if the setter is not static. The [returnType] is the return type that has /// already been parsed, or `null` if there was no return type. Return the /// setter that was parsed. /// /// This method assumes that the current token matches `Keyword.SET`. /// /// setter ::= /// setterSignature functionBody? /// /// setterSignature ::= /// 'external'? 'static'? returnType? 'set' identifier formalParameterList MethodDeclaration parseSetter(CommentAndMetadata commentAndMetadata, Token externalKeyword, Token staticKeyword, TypeAnnotation returnType) { Token propertyKeyword = getAndAdvance(); SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); FormalParameterList parameters = parseFormalParameterList(); _validateFormalParameterList(parameters); FunctionBody body = parseFunctionBody( externalKeyword != null || staticKeyword == null, ParserErrorCode.STATIC_SETTER_WITHOUT_BODY, false); if (externalKeyword != null && body is! EmptyFunctionBody) { _reportErrorForCurrentToken(ParserErrorCode.EXTERNAL_SETTER_WITH_BODY); } return astFactory.methodDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, externalKeyword, staticKeyword, returnType, propertyKeyword, null, name, null, parameters, body); } /// Parse a shift expression. Return the shift expression that was parsed. /// /// shiftExpression ::= /// additiveExpression (shiftOperator additiveExpression)* /// | 'super' (shiftOperator additiveExpression)+ Expression parseShiftExpression() { Expression expression; if (_currentToken.keyword == Keyword.SUPER && _currentToken.next.type.isShiftOperator) { expression = astFactory.superExpression(getAndAdvance()); } else { expression = parseAdditiveExpression(); } while (_currentToken.type.isShiftOperator) { expression = astFactory.binaryExpression( expression, getAndAdvance(), parseAdditiveExpression()); } return expression; } /// Parse a simple identifier. Return the simple identifier that was parsed. /// /// identifier ::= /// IDENTIFIER SimpleIdentifier parseSimpleIdentifier( {bool allowKeyword: false, bool isDeclaration: false}) { if (_matchesIdentifier() || (allowKeyword && _tokenMatchesIdentifierOrKeyword(_currentToken))) { return _parseSimpleIdentifierUnchecked(isDeclaration: isDeclaration); } _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); return createSyntheticIdentifier(isDeclaration: isDeclaration); } /// Parse a statement, starting with the given [token]. Return the statement /// that was parsed, or `null` if the tokens do not represent a recognizable /// statement. Statement parseStatement(Token token) { _currentToken = token; return parseStatement2(); } /// Parse a statement. Return the statement that was parsed. /// /// statement ::= /// label* nonLabeledStatement Statement parseStatement2() { if (_treeDepth > _MAX_TREE_DEPTH) { throw new _TooDeepTreeError(); } _treeDepth++; try { List<Label> labels; while ( _matchesIdentifier() && _currentToken.next.type == TokenType.COLON) { Label label = parseLabel(isDeclaration: true); if (labels == null) { labels = <Label>[label]; } else { labels.add(label); } } Statement statement = parseNonLabeledStatement(); if (labels == null) { return statement; } return astFactory.labeledStatement(labels, statement); } finally { _treeDepth--; } } /// Parse a sequence of statements, starting with the given [token]. Return /// the statements that were parsed, or `null` if the tokens do not represent /// a recognizable sequence of statements. List<Statement> parseStatements(Token token) { _currentToken = token; return _parseStatementList(); } /// Parse a string literal. Return the string literal that was parsed. /// /// stringLiteral ::= /// MULTI_LINE_STRING+ /// | SINGLE_LINE_STRING+ StringLiteral parseStringLiteral() { if (_matches(TokenType.STRING)) { return _parseStringLiteralUnchecked(); } _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_STRING_LITERAL); return createSyntheticStringLiteral(); } /// Parse a super constructor invocation. Return the super constructor /// invocation that was parsed. /// /// This method assumes that the current token matches [Keyword.SUPER]. /// /// superConstructorInvocation ::= /// 'super' ('.' identifier)? arguments SuperConstructorInvocation parseSuperConstructorInvocation() { Token keyword = getAndAdvance(); Token period; SimpleIdentifier constructorName; if (_matches(TokenType.PERIOD)) { period = getAndAdvance(); constructorName = parseSimpleIdentifier(); } ArgumentList argumentList = _parseArgumentListChecked(); return astFactory.superConstructorInvocation( keyword, period, constructorName, argumentList); } /// Parse a switch statement. Return the switch statement that was parsed. /// /// switchStatement ::= /// 'switch' '(' expression ')' '{' switchCase* defaultCase? '}' /// /// switchCase ::= /// label* ('case' expression ':') statements /// /// defaultCase ::= /// label* 'default' ':' statements SwitchStatement parseSwitchStatement() { bool wasInSwitch = _inSwitch; _inSwitch = true; try { HashSet<String> definedLabels = new HashSet<String>(); Token keyword = _expectKeyword(Keyword.SWITCH); Token leftParenthesis = _expect(TokenType.OPEN_PAREN); Expression expression = parseExpression2(); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); Token leftBracket = _expect(TokenType.OPEN_CURLY_BRACKET); Token defaultKeyword; List<SwitchMember> members = <SwitchMember>[]; TokenType type = _currentToken.type; while (type != TokenType.EOF && type != TokenType.CLOSE_CURLY_BRACKET) { List<Label> labels = <Label>[]; while ( _matchesIdentifier() && _tokenMatches(_peek(), TokenType.COLON)) { SimpleIdentifier identifier = _parseSimpleIdentifierUnchecked(isDeclaration: true); String label = identifier.token.lexeme; if (definedLabels.contains(label)) { _reportErrorForToken( ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT, identifier.token, [label]); } else { definedLabels.add(label); } Token colon = getAndAdvance(); labels.add(astFactory.label(identifier, colon)); } Keyword keyword = _currentToken.keyword; if (keyword == Keyword.CASE) { Token caseKeyword = getAndAdvance(); Expression caseExpression = parseExpression2(); Token colon = _expect(TokenType.COLON); members.add(astFactory.switchCase(labels, caseKeyword, caseExpression, colon, _parseStatementList())); if (defaultKeyword != null) { _reportErrorForToken( ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE, caseKeyword); } } else if (keyword == Keyword.DEFAULT) { if (defaultKeyword != null) { _reportErrorForToken( ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES, _peek()); } defaultKeyword = getAndAdvance(); Token colon = _expect(TokenType.COLON); members.add(astFactory.switchDefault( labels, defaultKeyword, colon, _parseStatementList())); } else { // We need to advance, otherwise we could end up in an infinite loop, // but this could be a lot smarter about recovering from the error. _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_CASE_OR_DEFAULT); bool atEndOrNextMember() { TokenType type = _currentToken.type; if (type == TokenType.EOF || type == TokenType.CLOSE_CURLY_BRACKET) { return true; } Keyword keyword = _currentToken.keyword; return keyword == Keyword.CASE || keyword == Keyword.DEFAULT; } while (!atEndOrNextMember()) { _advance(); } } type = _currentToken.type; } Token rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET); return astFactory.switchStatement(keyword, leftParenthesis, expression, rightParenthesis, leftBracket, members, rightBracket); } finally { _inSwitch = wasInSwitch; } } /// Parse a symbol literal. Return the symbol literal that was parsed. /// /// This method assumes that the current token matches [TokenType.HASH]. /// /// symbolLiteral ::= /// '#' identifier ('.' identifier)* SymbolLiteral parseSymbolLiteral() { Token poundSign = getAndAdvance(); List<Token> components = <Token>[]; if (_matchesIdentifier()) { components.add(getAndAdvance()); while (_optional(TokenType.PERIOD)) { if (_matchesIdentifier()) { components.add(getAndAdvance()); } else { _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); components.add(_createSyntheticToken(TokenType.IDENTIFIER)); break; } } } else if (_currentToken.isOperator) { components.add(getAndAdvance()); } else if (_matchesKeyword(Keyword.VOID)) { components.add(getAndAdvance()); } else { _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); components.add(_createSyntheticToken(TokenType.IDENTIFIER)); } return astFactory.symbolLiteral(poundSign, components); } /// Parse a throw expression. Return the throw expression that was parsed. /// /// This method assumes that the current token matches [Keyword.THROW]. /// /// throwExpression ::= /// 'throw' expression Expression parseThrowExpression() { Token keyword = getAndAdvance(); TokenType type = _currentToken.type; if (type == TokenType.SEMICOLON || type == TokenType.CLOSE_PAREN) { _reportErrorForToken( ParserErrorCode.MISSING_EXPRESSION_IN_THROW, _currentToken); return astFactory.throwExpression(keyword, createSyntheticIdentifier()); } Expression expression = parseExpression2(); return astFactory.throwExpression(keyword, expression); } /// Parse a throw expression. Return the throw expression that was parsed. /// /// This method assumes that the current token matches [Keyword.THROW]. /// /// throwExpressionWithoutCascade ::= /// 'throw' expressionWithoutCascade Expression parseThrowExpressionWithoutCascade() { Token keyword = getAndAdvance(); TokenType type = _currentToken.type; if (type == TokenType.SEMICOLON || type == TokenType.CLOSE_PAREN) { _reportErrorForToken( ParserErrorCode.MISSING_EXPRESSION_IN_THROW, _currentToken); return astFactory.throwExpression(keyword, createSyntheticIdentifier()); } Expression expression = parseExpressionWithoutCascade(); return astFactory.throwExpression(keyword, expression); } /// Parse a try statement. Return the try statement that was parsed. /// /// This method assumes that the current token matches [Keyword.TRY]. /// /// tryStatement ::= /// 'try' block (onPart+ finallyPart? | finallyPart) /// /// onPart ::= /// catchPart block /// | 'on' type catchPart? block /// /// catchPart ::= /// 'catch' '(' identifier (',' identifier)? ')' /// /// finallyPart ::= /// 'finally' block Statement parseTryStatement() { Token tryKeyword = getAndAdvance(); Block body = _parseBlockChecked(); List<CatchClause> catchClauses = <CatchClause>[]; Block finallyClause; while (_matchesKeyword(Keyword.ON) || _matchesKeyword(Keyword.CATCH)) { Token onKeyword; TypeName exceptionType; if (_matchesKeyword(Keyword.ON)) { onKeyword = getAndAdvance(); exceptionType = parseTypeNotVoid(false); } Token catchKeyword; Token leftParenthesis; SimpleIdentifier exceptionParameter; Token comma; SimpleIdentifier stackTraceParameter; Token rightParenthesis; if (_matchesKeyword(Keyword.CATCH)) { catchKeyword = getAndAdvance(); leftParenthesis = _expect(TokenType.OPEN_PAREN); exceptionParameter = parseSimpleIdentifier(isDeclaration: true); if (_matches(TokenType.COMMA)) { comma = getAndAdvance(); stackTraceParameter = parseSimpleIdentifier(isDeclaration: true); } rightParenthesis = _expect(TokenType.CLOSE_PAREN); } Block catchBody = _parseBlockChecked(); catchClauses.add(astFactory.catchClause( onKeyword, exceptionType, catchKeyword, leftParenthesis, exceptionParameter, comma, stackTraceParameter, rightParenthesis, catchBody)); } Token finallyKeyword; if (_matchesKeyword(Keyword.FINALLY)) { finallyKeyword = getAndAdvance(); finallyClause = _parseBlockChecked(); } else if (catchClauses.isEmpty) { _reportErrorForCurrentToken(ParserErrorCode.MISSING_CATCH_OR_FINALLY); } return astFactory.tryStatement( tryKeyword, body, catchClauses, finallyKeyword, finallyClause); } /// Parse a type alias. The [commentAndMetadata] is the metadata to be /// associated with the member. Return the type alias that was parsed. /// /// This method assumes that the current token matches [Keyword.TYPEDEF]. /// /// typeAlias ::= /// 'typedef' typeAliasBody /// | genericTypeAlias /// /// typeAliasBody ::= /// functionTypeAlias /// /// functionTypeAlias ::= /// functionPrefix typeParameterList? formalParameterList ';' /// /// functionPrefix ::= /// returnType? name TypeAlias parseTypeAlias(CommentAndMetadata commentAndMetadata) { Token keyword = getAndAdvance(); if (_matchesIdentifier()) { Token next = _peek(); if (_tokenMatches(next, TokenType.LT)) { next = _skipTypeParameterList(next); if (next != null && _tokenMatches(next, TokenType.EQ)) { TypeAlias typeAlias = parseGenericTypeAlias(commentAndMetadata, keyword); return typeAlias; } } else if (_tokenMatches(next, TokenType.EQ)) { TypeAlias typeAlias = parseGenericTypeAlias(commentAndMetadata, keyword); return typeAlias; } } return _parseFunctionTypeAlias(commentAndMetadata, keyword); } /// Parse a type. /// /// type ::= /// typeWithoutFunction /// | functionType TypeAnnotation parseTypeAnnotation(bool inExpression) { TypeAnnotation type; if (_atGenericFunctionTypeAfterReturnType(_currentToken)) { // Generic function type with no return type. type = parseGenericFunctionTypeAfterReturnType(null); } else { type = parseTypeWithoutFunction(inExpression); } while (_atGenericFunctionTypeAfterReturnType(_currentToken)) { type = parseGenericFunctionTypeAfterReturnType(type); } return type; } /// Parse a list of type arguments. Return the type argument list that was /// parsed. /// /// This method assumes that the current token matches `TokenType.LT`. /// /// typeArguments ::= /// '<' typeList '>' /// /// typeList ::= /// type (',' type)* TypeArgumentList parseTypeArgumentList() { Token leftBracket = getAndAdvance(); List<TypeAnnotation> arguments = <TypeAnnotation>[ parseTypeAnnotation(false) ]; while (_optional(TokenType.COMMA)) { arguments.add(parseTypeAnnotation(false)); } Token rightBracket = _expectGt(); return astFactory.typeArgumentList(leftBracket, arguments, rightBracket); } /// Parse a type which is not void and is not a function type. Return the type /// that was parsed. /// /// typeNotVoidWithoutFunction ::= /// qualified typeArguments? // TODO(eernst): Rename this to `parseTypeNotVoidWithoutFunction`? // Apparently, it was named `parseTypeName` before type arguments existed. TypeName parseTypeName(bool inExpression) { return _parseTypeName(inExpression); } /// Parse a type which is not `void`. /// /// typeNotVoid ::= /// functionType /// | typeNotVoidWithoutFunction TypeAnnotation parseTypeNotVoid(bool inExpression) { TypeAnnotation type; if (_atGenericFunctionTypeAfterReturnType(_currentToken)) { // Generic function type with no return type. type = parseGenericFunctionTypeAfterReturnType(null); } else if (_currentToken.keyword == Keyword.VOID && _atGenericFunctionTypeAfterReturnType(_currentToken.next)) { type = astFactory.typeName( astFactory.simpleIdentifier(getAndAdvance()), null); } else { type = parseTypeName(inExpression); } while (_atGenericFunctionTypeAfterReturnType(_currentToken)) { type = parseGenericFunctionTypeAfterReturnType(type); } return type; } /// Parse a type parameter. Return the type parameter that was parsed. /// /// typeParameter ::= /// metadata name ('extends' bound)? TypeParameter parseTypeParameter() { CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); if (_matchesKeyword(Keyword.EXTENDS)) { Token keyword = getAndAdvance(); TypeAnnotation bound = parseTypeNotVoid(false); return astFactory.typeParameter(commentAndMetadata.comment, commentAndMetadata.metadata, name, keyword, bound); } return astFactory.typeParameter(commentAndMetadata.comment, commentAndMetadata.metadata, name, null, null); } /// Parse a list of type parameters. Return the list of type parameters that /// were parsed. /// /// This method assumes that the current token matches `TokenType.LT`. /// /// typeParameterList ::= /// '<' typeParameter (',' typeParameter)* '>' TypeParameterList parseTypeParameterList() { Token leftBracket = getAndAdvance(); List<TypeParameter> typeParameters = <TypeParameter>[parseTypeParameter()]; while (_optional(TokenType.COMMA)) { typeParameters.add(parseTypeParameter()); } Token rightBracket = _expectGt(); return astFactory.typeParameterList( leftBracket, typeParameters, rightBracket); } /// Parse a type which is not a function type. /// /// typeWithoutFunction ::= /// `void` /// | typeNotVoidWithoutFunction TypeAnnotation parseTypeWithoutFunction(bool inExpression) { if (_currentToken.keyword == Keyword.VOID) { return astFactory.typeName( astFactory.simpleIdentifier(getAndAdvance()), null); } else { return parseTypeName(inExpression); } } /// Parse a unary expression. Return the unary expression that was parsed. /// /// unaryExpression ::= /// prefixOperator unaryExpression /// | awaitExpression /// | postfixExpression /// | unaryOperator 'super' /// | '-' 'super' /// | incrementOperator assignableExpression Expression parseUnaryExpression() { TokenType type = _currentToken.type; if (type == TokenType.MINUS || type == TokenType.BANG || type == TokenType.TILDE) { Token operator = getAndAdvance(); if (_matchesKeyword(Keyword.SUPER)) { TokenType nextType = _peek().type; if (nextType == TokenType.OPEN_SQUARE_BRACKET || nextType == TokenType.PERIOD) { // "prefixOperator unaryExpression" // --> "prefixOperator postfixExpression" // --> "prefixOperator primary selector*" // --> "prefixOperator 'super' assignableSelector selector*" return astFactory.prefixExpression(operator, parseUnaryExpression()); } return astFactory.prefixExpression( operator, astFactory.superExpression(getAndAdvance())); } return astFactory.prefixExpression(operator, parseUnaryExpression()); } else if (_currentToken.type.isIncrementOperator) { Token operator = getAndAdvance(); if (_matchesKeyword(Keyword.SUPER)) { TokenType nextType = _peek().type; if (nextType == TokenType.OPEN_SQUARE_BRACKET || nextType == TokenType.PERIOD) { // --> "prefixOperator 'super' assignableSelector selector*" return astFactory.prefixExpression(operator, parseUnaryExpression()); } // // Even though it is not valid to use an incrementing operator // ('++' or '--') before 'super', we can (and therefore must) interpret // "--super" as semantically equivalent to "-(-super)". Unfortunately, // we cannot do the same for "++super" because "+super" is also not // valid. // if (type == TokenType.MINUS_MINUS) { Token firstOperator = _createToken(operator, TokenType.MINUS); Token secondOperator = new Token(TokenType.MINUS, operator.offset + 1); secondOperator.setNext(_currentToken); firstOperator.setNext(secondOperator); operator.previous.setNext(firstOperator); return astFactory.prefixExpression( firstOperator, astFactory.prefixExpression( secondOperator, astFactory.superExpression(getAndAdvance()))); } // Invalid operator before 'super' _reportErrorForCurrentToken( ParserErrorCode.INVALID_OPERATOR_FOR_SUPER, [operator.lexeme]); return astFactory.prefixExpression( operator, astFactory.superExpression(getAndAdvance())); } return astFactory.prefixExpression( operator, parseAssignableExpression(false)); } else if (type == TokenType.PLUS) { _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER); return createSyntheticIdentifier(); } else if (_inAsync && _matchesKeyword(Keyword.AWAIT)) { return parseAwaitExpression(); } return parsePostfixExpression(); } /// Parse a variable declaration. Return the variable declaration that was /// parsed. /// /// variableDeclaration ::= /// identifier ('=' expression)? VariableDeclaration parseVariableDeclaration() { // TODO(paulberry): prior to the fix for bug 23204, we permitted // annotations before variable declarations (e.g. "String @deprecated s;"). // Although such constructions are prohibited by the spec, we may want to // consider handling them anyway to allow for better parser recovery in the // event that the user erroneously tries to use them. However, as a // counterargument, this would likely degrade parser recovery in the event // of a construct like "class C { int @deprecated foo() {} }" (i.e. the // user is in the middle of inserting "int bar;" prior to // "@deprecated foo() {}"). SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); Token equals; Expression initializer; if (_matches(TokenType.EQ)) { equals = getAndAdvance(); initializer = parseExpression2(); } return astFactory.variableDeclaration(name, equals, initializer); } /// Parse a variable declaration list. The [commentAndMetadata] is the /// metadata to be associated with the variable declaration list. Return the /// variable declaration list that was parsed. /// /// variableDeclarationList ::= /// finalConstVarOrType variableDeclaration (',' variableDeclaration)* VariableDeclarationList parseVariableDeclarationListAfterMetadata( CommentAndMetadata commentAndMetadata) { FinalConstVarOrType holder = parseFinalConstVarOrType(false); return parseVariableDeclarationListAfterType( commentAndMetadata, holder.keyword, holder.type); } /// Parse a variable declaration list. The [commentAndMetadata] is the /// metadata to be associated with the variable declaration list, or `null` /// if there is no attempt at parsing the comment and metadata. The [keyword] /// is the token representing the 'final', 'const' or 'var' keyword, or /// `null` if there is no keyword. The [type] is the type of the variables in /// the list. Return the variable declaration list that was parsed. /// /// variableDeclarationList ::= /// finalConstVarOrType variableDeclaration (',' variableDeclaration)* VariableDeclarationList parseVariableDeclarationListAfterType( CommentAndMetadata commentAndMetadata, Token keyword, TypeAnnotation type) { if (type != null && keyword != null && _tokenMatchesKeyword(keyword, Keyword.VAR)) { _reportErrorForToken(ParserErrorCode.VAR_AND_TYPE, keyword); } List<VariableDeclaration> variables = <VariableDeclaration>[ parseVariableDeclaration() ]; while (_optional(TokenType.COMMA)) { variables.add(parseVariableDeclaration()); } return astFactory.variableDeclarationList(commentAndMetadata?.comment, commentAndMetadata?.metadata, keyword, type, variables); } /// Parse a variable declaration statement. The [commentAndMetadata] is the /// metadata to be associated with the variable declaration statement, or /// `null` if there is no attempt at parsing the comment and metadata. Return /// the variable declaration statement that was parsed. /// /// variableDeclarationStatement ::= /// variableDeclarationList ';' VariableDeclarationStatement parseVariableDeclarationStatementAfterMetadata( CommentAndMetadata commentAndMetadata) { // Token startToken = currentToken; VariableDeclarationList variableList = parseVariableDeclarationListAfterMetadata(commentAndMetadata); // if (!matches(TokenType.SEMICOLON)) { // if (matches(startToken, Keyword.VAR) && isTypedIdentifier(startToken.getNext())) { // // TODO(brianwilkerson) This appears to be of the form "var type variable". We should do // // a better job of recovering in this case. // } // } Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.variableDeclarationStatement(variableList, semicolon); } /// Parse a while statement. Return the while statement that was parsed. /// /// This method assumes that the current token matches [Keyword.WHILE]. /// /// whileStatement ::= /// 'while' '(' expression ')' statement Statement parseWhileStatement() { bool wasInLoop = _inLoop; _inLoop = true; try { Token keyword = getAndAdvance(); Token leftParenthesis = _expect(TokenType.OPEN_PAREN); Expression condition = parseExpression2(); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); Statement body = parseStatement2(); return astFactory.whileStatement( keyword, leftParenthesis, condition, rightParenthesis, body); } finally { _inLoop = wasInLoop; } } /// Parse a with clause. Return the with clause that was parsed. /// /// This method assumes that the current token matches `Keyword.WITH`. /// /// withClause ::= /// 'with' typeName (',' typeName)* WithClause parseWithClause() { Token withKeyword = getAndAdvance(); List<TypeName> types = <TypeName>[]; do { TypeName typeName = parseTypeName(false); types.add(typeName); } while (_optional(TokenType.COMMA)); return astFactory.withClause(withKeyword, types); } /// Parse a yield statement. Return the yield statement that was parsed. /// /// This method assumes that the current token matches [Keyword.YIELD]. /// /// yieldStatement ::= /// 'yield' '*'? expression ';' YieldStatement parseYieldStatement() { Token yieldToken = getAndAdvance(); Token star; if (_matches(TokenType.STAR)) { star = getAndAdvance(); } Expression expression = parseExpression2(); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.yieldStatement(yieldToken, star, expression, semicolon); } /// Parse a formal parameter list, starting at the [startToken], without /// actually creating a formal parameter list or changing the current token. /// Return the token following the parameter list that was parsed, or `null` /// if the given token is not the first token in a valid parameter list. /// /// This method must be kept in sync with [parseFormalParameterList]. Token skipFormalParameterList(Token startToken) { if (!_tokenMatches(startToken, TokenType.OPEN_PAREN)) { return null; } return (startToken as BeginToken).endToken?.next; } /// Parse the portion of a generic function type after the return type, /// starting at the [startToken], without actually creating a generic function /// type or changing the current token. Return the token following the generic /// function type that was parsed, or `null` if the given token is not the /// first token in a valid generic function type. /// /// This method must be kept in sync with /// [parseGenericFunctionTypeAfterReturnType]. Token skipGenericFunctionTypeAfterReturnType(Token startToken) { Token next = startToken.next; // Skip 'Function' if (_tokenMatches(next, TokenType.LT)) { next = skipTypeParameterList(next); if (next == null) { return null; } } return skipFormalParameterList(next); } /// Parse a prefixed identifier, starting at the [startToken], without /// actually creating a prefixed identifier or changing the current token. /// Return the token following the prefixed identifier that was parsed, or /// `null` if the given token is not the first token in a valid prefixed /// identifier. /// /// This method must be kept in sync with [parsePrefixedIdentifier]. /// /// prefixedIdentifier ::= /// identifier ('.' identifier)? Token skipPrefixedIdentifier(Token startToken) { Token token = skipSimpleIdentifier(startToken); if (token == null) { return null; } else if (!_tokenMatches(token, TokenType.PERIOD)) { return token; } token = token.next; Token nextToken = skipSimpleIdentifier(token); if (nextToken != null) { return nextToken; } else if (_tokenMatches(token, TokenType.CLOSE_PAREN) || _tokenMatches(token, TokenType.COMMA)) { // If the `id.` is followed by something that cannot produce a valid // structure then assume this is a prefixed identifier but missing the // trailing identifier return token; } return null; } /// Parse a simple identifier, starting at the [startToken], without actually /// creating a simple identifier or changing the current token. Return the /// token following the simple identifier that was parsed, or `null` if the /// given token is not the first token in a valid simple identifier. /// /// This method must be kept in sync with [parseSimpleIdentifier]. /// /// identifier ::= /// IDENTIFIER Token skipSimpleIdentifier(Token startToken) { if (_tokenMatches(startToken, TokenType.IDENTIFIER) || _tokenMatchesPseudoKeyword(startToken)) { return startToken.next; } return null; } /// Parse a string literal, starting at the [startToken], without actually /// creating a string literal or changing the current token. Return the token /// following the string literal that was parsed, or `null` if the given token /// is not the first token in a valid string literal. /// /// This method must be kept in sync with [parseStringLiteral]. /// /// stringLiteral ::= /// MULTI_LINE_STRING+ /// | SINGLE_LINE_STRING+ Token skipStringLiteral(Token startToken) { Token token = startToken; while (token != null && _tokenMatches(token, TokenType.STRING)) { token = token.next; TokenType type = token.type; if (type == TokenType.STRING_INTERPOLATION_EXPRESSION || type == TokenType.STRING_INTERPOLATION_IDENTIFIER) { token = _skipStringInterpolation(token); } } if (identical(token, startToken)) { return null; } return token; } /// Parse a type annotation, starting at the [startToken], without actually /// creating a type annotation or changing the current token. Return the token /// following the type annotation that was parsed, or `null` if the given /// token is not the first token in a valid type annotation. /// /// This method must be kept in sync with [parseTypeAnnotation]. Token skipTypeAnnotation(Token startToken) { Token next; if (_atGenericFunctionTypeAfterReturnType(startToken)) { // Generic function type with no return type. next = skipGenericFunctionTypeAfterReturnType(startToken); } else { next = skipTypeWithoutFunction(startToken); } while (next != null && _atGenericFunctionTypeAfterReturnType(next)) { next = skipGenericFunctionTypeAfterReturnType(next); } return next; } /// Parse a list of type arguments, starting at the [startToken], without /// actually creating a type argument list or changing the current token. /// Return the token following the type argument list that was parsed, or /// `null` if the given token is not the first token in a valid type argument /// list. /// /// This method must be kept in sync with [parseTypeArgumentList]. /// /// typeArguments ::= /// '<' typeList '>' /// /// typeList ::= /// type (',' type)* Token skipTypeArgumentList(Token startToken) { Token token = startToken; if (!_tokenMatches(token, TokenType.LT)) { return null; } token = skipTypeAnnotation(token.next); if (token == null) { // If the start token '<' is followed by '>' // then assume this should be type argument list but is missing a type token = startToken.next; if (_tokenMatches(token, TokenType.GT)) { return token.next; } return null; } while (_tokenMatches(token, TokenType.COMMA)) { token = skipTypeAnnotation(token.next); if (token == null) { return null; } } if (token.type == TokenType.GT) { return token.next; } else if (token.type == TokenType.GT_GT) { Token second = new Token(TokenType.GT, token.offset + 1); second.setNextWithoutSettingPrevious(token.next); return second; } return null; } /// Parse a type name, starting at the [startToken], without actually creating /// a type name or changing the current token. Return the token following the /// type name that was parsed, or `null` if the given token is not the first /// token in a valid type name. /// /// This method must be kept in sync with [parseTypeName]. /// /// type ::= /// qualified typeArguments? Token skipTypeName(Token startToken) { Token token = skipPrefixedIdentifier(startToken); if (token == null) { return null; } if (_tokenMatches(token, TokenType.LT)) { token = skipTypeArgumentList(token); } return token; } /// Parse a type parameter list, starting at the [startToken], without /// actually creating a type parameter list or changing the current token. /// Return the token following the type parameter list that was parsed, or /// `null` if the given token is not the first token in a valid type parameter /// list. /// /// This method must be kept in sync with [parseTypeParameterList]. Token skipTypeParameterList(Token startToken) { if (!_tokenMatches(startToken, TokenType.LT)) { return null; } int depth = 1; Token previous = startToken; Token next = startToken.next; while (next != previous) { if (_tokenMatches(next, TokenType.LT)) { depth++; } else if (_tokenMatches(next, TokenType.GT)) { depth--; if (depth == 0) { return next.next; } } previous = next; next = next.next; } return null; } /// Parse a typeWithoutFunction, starting at the [startToken], without /// actually creating a TypeAnnotation or changing the current token. Return /// the token following the typeWithoutFunction that was parsed, or `null` if /// the given token is not the first token in a valid typeWithoutFunction. /// /// This method must be kept in sync with [parseTypeWithoutFunction]. Token skipTypeWithoutFunction(Token startToken) { if (startToken.keyword == Keyword.VOID) { return startToken.next; } else { return skipTypeName(startToken); } } /// Advance to the next token in the token stream. void _advance() { _currentToken = _currentToken.next; } /// Append the character equivalent of the given [codePoint] to the given /// [builder]. Use the [startIndex] and [endIndex] to report an error, and /// don't append anything to the builder, if the code point is invalid. The /// [escapeSequence] is the escape sequence that was parsed to produce the /// code point (used for error reporting). void _appendCodePoint(StringBuffer buffer, String source, int codePoint, int startIndex, int endIndex) { if (codePoint < 0 || codePoint > Character.MAX_CODE_POINT) { String escapeSequence = source.substring(startIndex, endIndex + 1); _reportErrorForCurrentToken( ParserErrorCode.INVALID_CODE_POINT, [escapeSequence]); return; } if (codePoint < Character.MAX_VALUE) { buffer.writeCharCode(codePoint); } else { buffer.write(Character.toChars(codePoint)); } } /// Return `true` if we are positioned at the keyword 'Function' in a generic /// function type alias. bool _atGenericFunctionTypeAfterReturnType(Token startToken) { if (_tokenMatchesKeyword(startToken, Keyword.FUNCTION)) { Token next = startToken.next; if (next != null && (_tokenMatches(next, TokenType.OPEN_PAREN) || _tokenMatches(next, TokenType.LT))) { return true; } } return false; } void _configureFeatures(FeatureSet featureSet) { if (featureSet.isEnabled(Feature.control_flow_collections)) { throw new UnimplementedError('control_flow_collections experiment' ' not supported by analyzer parser'); } if (featureSet.isEnabled(Feature.non_nullable)) { throw new UnimplementedError( 'non-nullable experiment not supported by analyzer parser'); } if (featureSet.isEnabled(Feature.spread_collections)) { throw new UnimplementedError( 'spread_collections experiment not supported by analyzer parser'); } if (featureSet.isEnabled(Feature.triple_shift)) { throw new UnimplementedError('triple_shift experiment' ' not supported by analyzer parser'); } _featureSet = featureSet; } /// Convert the given [method] declaration into the nearest valid top-level /// function declaration (that is, the function declaration that most closely /// captures the components of the given method declaration). FunctionDeclaration _convertToFunctionDeclaration(MethodDeclaration method) => astFactory.functionDeclaration( method.documentationComment, method.metadata, method.externalKeyword, method.returnType, method.propertyKeyword, method.name, astFactory.functionExpression( method.typeParameters, method.parameters, method.body)); /// Return `true` if the current token could be the start of a compilation /// unit member. This method is used for recovery purposes to decide when to /// stop skipping tokens after finding an error while parsing a compilation /// unit member. bool _couldBeStartOfCompilationUnitMember() { Keyword keyword = _currentToken.keyword; Token next = _currentToken.next; TokenType nextType = next.type; if ((keyword == Keyword.IMPORT || keyword == Keyword.EXPORT || keyword == Keyword.LIBRARY || keyword == Keyword.PART) && nextType != TokenType.PERIOD && nextType != TokenType.LT) { // This looks like the start of a directive return true; } else if (keyword == Keyword.CLASS) { // This looks like the start of a class definition return true; } else if (keyword == Keyword.TYPEDEF && nextType != TokenType.PERIOD && nextType != TokenType.LT) { // This looks like the start of a typedef return true; } else if (keyword == Keyword.VOID || ((keyword == Keyword.GET || keyword == Keyword.SET) && _tokenMatchesIdentifier(next)) || (keyword == Keyword.OPERATOR && _isOperator(next))) { // This looks like the start of a function return true; } else if (_matchesIdentifier()) { if (nextType == TokenType.OPEN_PAREN) { // This looks like the start of a function return true; } Token token = skipTypeAnnotation(_currentToken); if (token == null) { return false; } // TODO(brianwilkerson) This looks wrong; should we be checking 'token'? if (keyword == Keyword.GET || keyword == Keyword.SET || (keyword == Keyword.OPERATOR && _isOperator(next)) || _matchesIdentifier()) { return true; } } return false; } /// Return a synthetic token representing the given [keyword]. Token _createSyntheticKeyword(Keyword keyword) => _injectToken(new SyntheticKeywordToken(keyword, _currentToken.offset)); /// Return a synthetic token with the given [type]. Token _createSyntheticToken(TokenType type) => _injectToken(new StringToken(type, "", _currentToken.offset)); /// Create and return a new token with the given [type]. The token will /// replace the first portion of the given [token], so it will have the same /// offset and will have any comments that might have preceded the token. Token _createToken(Token token, TokenType type, {bool isBegin: false}) { CommentToken comments = token.precedingComments; if (comments == null) { if (isBegin) { return new BeginToken(type, token.offset); } return new Token(type, token.offset); } else if (isBegin) { return new BeginToken(type, token.offset, comments); } return new Token(type, token.offset, comments); } /// Check that the given [expression] is assignable and report an error if it /// isn't. /// /// assignableExpression ::= /// primary (arguments* assignableSelector)+ /// | 'super' unconditionalAssignableSelector /// | identifier /// /// unconditionalAssignableSelector ::= /// '[' expression ']' /// | '.' identifier /// /// assignableSelector ::= /// unconditionalAssignableSelector /// | '?.' identifier void _ensureAssignable(Expression expression) { if (expression != null && !expression.isAssignable) { _reportErrorForCurrentToken( ParserErrorCode.ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE); } } /// If the current token has the expected type, return it after advancing to /// the next token. Otherwise report an error and return the current token /// without advancing. /// /// Note that the method [_expectGt] should be used if the argument to this /// method would be [TokenType.GT]. /// /// The [type] is the type of token that is expected. Token _expect(TokenType type) { if (_matches(type)) { return getAndAdvance(); } // Remove uses of this method in favor of matches? // Pass in the error code to use to report the error? if (type == TokenType.SEMICOLON) { if (_tokenMatches(_currentToken.next, TokenType.SEMICOLON)) { _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]); _advance(); return getAndAdvance(); } _reportErrorForToken(ParserErrorCode.EXPECTED_TOKEN, _currentToken.previous, [type.lexeme]); return _createSyntheticToken(TokenType.SEMICOLON); } _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_TOKEN, [type.lexeme]); return _createSyntheticToken(type); } /// If the current token has the type [TokenType.GT], return it after /// advancing to the next token. Otherwise report an error and create a /// synthetic token. Token _expectGt() { if (_matchesGt()) { return getAndAdvance(); } _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [TokenType.GT.lexeme]); return _createSyntheticToken(TokenType.GT); } /// If the current token is a keyword matching the given [keyword], return it /// after advancing to the next token. Otherwise report an error and return /// the current token without advancing. Token _expectKeyword(Keyword keyword) { if (_matchesKeyword(keyword)) { return getAndAdvance(); } // Remove uses of this method in favor of matches? // Pass in the error code to use to report the error? _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [keyword.lexeme]); return _currentToken; } /// Search the given list of [ranges] for a range that contains the given /// [index]. Return the range that was found, or `null` if none of the ranges /// contain the index. List<int> _findRange(List<List<int>> ranges, int index) { int rangeCount = ranges.length; for (int i = 0; i < rangeCount; i++) { List<int> range = ranges[i]; if (range[0] <= index && index <= range[1]) { return range; } else if (index < range[0]) { return null; } } return null; } /// Return a list of the ranges of characters in the given [comment] that /// should be treated as code blocks. List<List<int>> _getCodeBlockRanges(String comment) { List<List<int>> ranges = <List<int>>[]; int length = comment.length; if (length < 3) { return ranges; } int index = 0; int firstChar = comment.codeUnitAt(0); if (firstChar == 0x2F) { int secondChar = comment.codeUnitAt(1); int thirdChar = comment.codeUnitAt(2); if ((secondChar == 0x2A && thirdChar == 0x2A) || (secondChar == 0x2F && thirdChar == 0x2F)) { index = 3; } } if (StringUtilities.startsWith4(comment, index, 0x20, 0x20, 0x20, 0x20)) { int end = index + 4; while (end < length && comment.codeUnitAt(end) != 0xD && comment.codeUnitAt(end) != 0xA) { end = end + 1; } ranges.add(<int>[index, end]); index = end; } while (index < length) { int currentChar = comment.codeUnitAt(index); if (currentChar == 0xD || currentChar == 0xA) { index = index + 1; while (index < length && Character.isWhitespace(comment.codeUnitAt(index))) { index = index + 1; } if (StringUtilities.startsWith6( comment, index, 0x2A, 0x20, 0x20, 0x20, 0x20, 0x20)) { int end = index + 6; while (end < length && comment.codeUnitAt(end) != 0xD && comment.codeUnitAt(end) != 0xA) { end = end + 1; } ranges.add(<int>[index, end]); index = end; } } else if (index + 1 < length && currentChar == 0x5B && comment.codeUnitAt(index + 1) == 0x3A) { int end = StringUtilities.indexOf2(comment, index + 2, 0x3A, 0x5D); if (end < 0) { end = length; } ranges.add(<int>[index, end]); index = end + 1; } else { index = index + 1; } } return ranges; } /// Return the end token associated with the given [beginToken], or `null` if /// either the given token is not a begin token or it does not have an end /// token associated with it. Token _getEndToken(Token beginToken) { if (beginToken is BeginToken) { return beginToken.endToken; } return null; } /// Inject the given [token] into the token stream immediately before the /// current token. Token _injectToken(Token token) { Token previous = _currentToken.previous; token.setNext(_currentToken); previous.setNext(token); return token; } /// Return `true` if the given [character] is a valid hexadecimal digit. bool _isHexDigit(int character) => (0x30 <= character && character <= 0x39) || (0x41 <= character && character <= 0x46) || (0x61 <= character && character <= 0x66); bool _isLikelyArgumentList() { // Try to reduce the amount of lookahead required here before enabling // generic methods. if (_matches(TokenType.OPEN_PAREN)) { return true; } Token token = skipTypeArgumentList(_currentToken); return token != null && _tokenMatches(token, TokenType.OPEN_PAREN); } /// Return `true` if it looks like we have found the invocation of a named /// constructor following the name of the type: /// ``` /// typeArguments? '.' identifier '(' /// ``` bool _isLikelyNamedInstanceCreation() { Token token = skipTypeArgumentList(_currentToken); if (token != null && _tokenMatches(token, TokenType.PERIOD)) { token = skipSimpleIdentifier(token.next); if (token != null && _tokenMatches(token, TokenType.OPEN_PAREN)) { return true; } } return false; } /// Given that we have just found bracketed text within the given [comment], /// look to see whether that text is (a) followed by a parenthesized link /// address, (b) followed by a colon, or (c) followed by optional whitespace /// and another square bracket. The [rightIndex] is the index of the right /// bracket. Return `true` if the bracketed text is followed by a link /// address. /// /// This method uses the syntax described by the /// <a href="http://daringfireball.net/projects/markdown/syntax">markdown</a> /// project. bool _isLinkText(String comment, int rightIndex) { int length = comment.length; int index = rightIndex + 1; if (index >= length) { return false; } int nextChar = comment.codeUnitAt(index); if (nextChar == 0x28 || nextChar == 0x3A) { return true; } while (Character.isWhitespace(nextChar)) { index = index + 1; if (index >= length) { return false; } nextChar = comment.codeUnitAt(index); } return nextChar == 0x5B; } /// Return `true` if the given [startToken] appears to be the beginning of an /// operator declaration. bool _isOperator(Token startToken) { // Accept any operator here, even if it is not user definable. if (!startToken.isOperator) { return false; } // Token "=" means that it is actually a field initializer. if (startToken.type == TokenType.EQ) { return false; } // Consume all operator tokens. Token token = startToken.next; while (token.isOperator) { token = token.next; } // Formal parameter list is expect now. return _tokenMatches(token, TokenType.OPEN_PAREN); } bool _isPeekGenericTypeParametersAndOpenParen() { Token token = _skipTypeParameterList(_peek()); return token != null && _tokenMatches(token, TokenType.OPEN_PAREN); } /// Return `true` if the [startToken] appears to be the first token of a type /// name that is followed by a variable or field formal parameter. bool _isTypedIdentifier(Token startToken) { Token token = skipTypeAnnotation(startToken); if (token == null) { return false; } else if (_tokenMatchesIdentifier(token)) { return true; } else if (_tokenMatchesKeyword(token, Keyword.THIS) && _tokenMatches(token.next, TokenType.PERIOD) && _tokenMatchesIdentifier(token.next.next)) { return true; } else if (startToken.next != token && !_tokenMatches(token, TokenType.OPEN_PAREN)) { // The type is more than a simple identifier, so it should be assumed to // be a type name. return true; } return false; } /// Return `true` if the given [expression] is a primary expression that is /// allowed to be an assignable expression without any assignable selector. bool _isValidAssignableExpression(Expression expression) { if (expression is SimpleIdentifier) { return true; } else if (expression is PropertyAccess) { return expression.target is SuperExpression; } else if (expression is IndexExpression) { return expression.target is SuperExpression; } return false; } /// Increments the error reporting lock level. If level is more than `0`, then /// [reportError] wont report any error. void _lockErrorListener() { _errorListenerLock++; } /// Return `true` if the current token has the given [type]. Note that the /// method [_matchesGt] should be used if the argument to this method would be /// [TokenType.GT]. bool _matches(TokenType type) => _currentToken.type == type; /// Return `true` if the current token has a type of [TokenType.GT]. Note that /// this method, unlike other variants, will modify the token stream if /// possible to match desired type. In particular, if the next token is either /// a '>>' or '>>>', the token stream will be re-written and `true` will be /// returned. bool _matchesGt() { TokenType currentType = _currentToken.type; if (currentType == TokenType.GT) { return true; } else if (currentType == TokenType.GT_GT) { Token first = _createToken(_currentToken, TokenType.GT); Token second = new Token(TokenType.GT, _currentToken.offset + 1); second.setNext(_currentToken.next); first.setNext(second); _currentToken.previous.setNext(first); _currentToken = first; return true; } else if (currentType == TokenType.GT_EQ) { Token first = _createToken(_currentToken, TokenType.GT); Token second = new Token(TokenType.EQ, _currentToken.offset + 1); second.setNext(_currentToken.next); first.setNext(second); _currentToken.previous.setNext(first); _currentToken = first; return true; } else if (currentType == TokenType.GT_GT_EQ) { int offset = _currentToken.offset; Token first = _createToken(_currentToken, TokenType.GT); Token second = new Token(TokenType.GT, offset + 1); Token third = new Token(TokenType.EQ, offset + 2); third.setNext(_currentToken.next); second.setNext(third); first.setNext(second); _currentToken.previous.setNext(first); _currentToken = first; return true; } return false; } /// Return `true` if the current token is a valid identifier. Valid /// identifiers include built-in identifiers (pseudo-keywords). bool _matchesIdentifier() => _tokenMatchesIdentifier(_currentToken); /// Return `true` if the current token matches the given [keyword]. bool _matchesKeyword(Keyword keyword) => _tokenMatchesKeyword(_currentToken, keyword); /// If the current token has the given [type], then advance to the next token /// and return `true`. Otherwise, return `false` without advancing. This /// method should not be invoked with an argument value of [TokenType.GT]. bool _optional(TokenType type) { if (_currentToken.type == type) { _advance(); return true; } return false; } /// Parse an argument list when we need to check for an open paren and recover /// when there isn't one. Return the argument list that was parsed. ArgumentList _parseArgumentListChecked() { if (_matches(TokenType.OPEN_PAREN)) { return parseArgumentList(); } _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [TokenType.OPEN_PAREN.lexeme]); // Recovery: Look to see whether there is a close paren that isn't matched // to an open paren and if so parse the list of arguments as normal. return astFactory.argumentList(_createSyntheticToken(TokenType.OPEN_PAREN), null, _createSyntheticToken(TokenType.CLOSE_PAREN)); } /// Parse an assert within a constructor's initializer list. Return the /// assert. /// /// This method assumes that the current token matches `Keyword.ASSERT`. /// /// assertInitializer ::= /// 'assert' '(' expression [',' expression] ')' AssertInitializer _parseAssertInitializer() { Token keyword = getAndAdvance(); Token leftParen = _expect(TokenType.OPEN_PAREN); Expression expression = parseExpression2(); Token comma; Expression message; if (_matches(TokenType.COMMA)) { comma = getAndAdvance(); if (_matches(TokenType.CLOSE_PAREN)) { comma; } else { message = parseExpression2(); if (_matches(TokenType.COMMA)) { getAndAdvance(); } } } Token rightParen = _expect(TokenType.CLOSE_PAREN); return astFactory.assertInitializer( keyword, leftParen, expression, comma, message, rightParen); } /// Parse a block when we need to check for an open curly brace and recover /// when there isn't one. Return the block that was parsed. /// /// block ::= /// '{' statements '}' Block _parseBlockChecked() { if (_matches(TokenType.OPEN_CURLY_BRACKET)) { return parseBlock(); } // TODO(brianwilkerson) Improve the error message. _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [TokenType.OPEN_CURLY_BRACKET.lexeme]); // Recovery: Check for an unmatched closing curly bracket and parse // statements until it is reached. return astFactory.block(_createSyntheticToken(TokenType.OPEN_CURLY_BRACKET), null, _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET)); } /// Parse a list of class members. The [className] is the name of the class /// whose members are being parsed. The [closingBracket] is the closing /// bracket for the class, or `null` if the closing bracket is missing. /// Return the list of class members that were parsed. /// /// classMembers ::= /// (metadata memberDefinition)* List<ClassMember> _parseClassMembers(String className, Token closingBracket) { List<ClassMember> members = <ClassMember>[]; Token memberStart = _currentToken; TokenType type = _currentToken.type; Keyword keyword = _currentToken.keyword; while (type != TokenType.EOF && type != TokenType.CLOSE_CURLY_BRACKET && (closingBracket != null || (keyword != Keyword.CLASS && keyword != Keyword.TYPEDEF))) { if (type == TokenType.SEMICOLON) { _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); } else { ClassMember member = parseClassMember(className); if (member != null) { members.add(member); } } if (identical(_currentToken, memberStart)) { _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); } memberStart = _currentToken; type = _currentToken.type; keyword = _currentToken.keyword; } return members; } /// Parse a class type alias. The [commentAndMetadata] is the metadata to be /// associated with the member. The [abstractKeyword] is the token /// representing the 'abstract' keyword. The [classKeyword] is the token /// representing the 'class' keyword. The [className] is the name of the /// alias, and the [typeParameters] are the type parameters following the /// name. Return the class type alias that was parsed. /// /// classTypeAlias ::= /// identifier typeParameters? '=' 'abstract'? mixinApplication /// /// mixinApplication ::= /// type withClause implementsClause? ';' ClassTypeAlias _parseClassTypeAliasAfterName( CommentAndMetadata commentAndMetadata, Token abstractKeyword, Token classKeyword, SimpleIdentifier className, TypeParameterList typeParameters) { Token equals = _expect(TokenType.EQ); TypeName superclass = parseTypeName(false); WithClause withClause; if (_matchesKeyword(Keyword.WITH)) { withClause = parseWithClause(); } else { _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [Keyword.WITH.lexeme]); } ImplementsClause implementsClause; if (_matchesKeyword(Keyword.IMPLEMENTS)) { implementsClause = parseImplementsClause(); } Token semicolon; if (_matches(TokenType.SEMICOLON)) { semicolon = getAndAdvance(); } else { if (_matches(TokenType.OPEN_CURLY_BRACKET)) { _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [TokenType.SEMICOLON.lexeme]); Token leftBracket = getAndAdvance(); _parseClassMembers(className.name, _getEndToken(leftBracket)); _expect(TokenType.CLOSE_CURLY_BRACKET); } else { _reportErrorForToken(ParserErrorCode.EXPECTED_TOKEN, _currentToken.previous, [TokenType.SEMICOLON.lexeme]); } semicolon = _createSyntheticToken(TokenType.SEMICOLON); } return astFactory.classTypeAlias( commentAndMetadata.comment, commentAndMetadata.metadata, classKeyword, className, typeParameters, equals, abstractKeyword, superclass, withClause, implementsClause, semicolon); } /// Parse a list of configurations. Return the configurations that were /// parsed, or `null` if there are no configurations. List<Configuration> _parseConfigurations() { List<Configuration> configurations; while (_matchesKeyword(Keyword.IF)) { configurations ??= <Configuration>[]; configurations.add(parseConfiguration()); } return configurations; } ConstructorDeclaration _parseConstructor( CommentAndMetadata commentAndMetadata, Token externalKeyword, Token constKeyword, Token factoryKeyword, SimpleIdentifier returnType, Token period, SimpleIdentifier name, FormalParameterList parameters) { bool bodyAllowed = externalKeyword == null; Token separator; List<ConstructorInitializer> initializers; if (_matches(TokenType.COLON)) { separator = getAndAdvance(); initializers = <ConstructorInitializer>[]; do { Keyword keyword = _currentToken.keyword; if (keyword == Keyword.THIS) { TokenType nextType = _peek().type; if (nextType == TokenType.OPEN_PAREN) { bodyAllowed = false; initializers.add(parseRedirectingConstructorInvocation(false)); } else if (nextType == TokenType.PERIOD && _tokenMatches(_peekAt(3), TokenType.OPEN_PAREN)) { bodyAllowed = false; initializers.add(parseRedirectingConstructorInvocation(true)); } else { initializers.add(parseConstructorFieldInitializer(true)); } } else if (keyword == Keyword.SUPER) { initializers.add(parseSuperConstructorInvocation()); } else if (_matches(TokenType.OPEN_CURLY_BRACKET) || _matches(TokenType.FUNCTION)) { _reportErrorForCurrentToken(ParserErrorCode.MISSING_INITIALIZER); } else if (_matchesKeyword(Keyword.ASSERT)) { initializers.add(_parseAssertInitializer()); } else { initializers.add(parseConstructorFieldInitializer(false)); } } while (_optional(TokenType.COMMA)); if (factoryKeyword != null) { _reportErrorForToken( ParserErrorCode.FACTORY_WITH_INITIALIZERS, factoryKeyword); } } ConstructorName redirectedConstructor; FunctionBody body; if (_matches(TokenType.EQ)) { separator = getAndAdvance(); redirectedConstructor = parseConstructorName(); body = astFactory.emptyFunctionBody(_expect(TokenType.SEMICOLON)); if (factoryKeyword == null) { _reportErrorForNode( ParserErrorCode.REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR, redirectedConstructor); } } else { body = parseFunctionBody(true, ParserErrorCode.MISSING_FUNCTION_BODY, false); if (constKeyword != null && factoryKeyword != null && externalKeyword == null && body is! NativeFunctionBody) { _reportErrorForToken(ParserErrorCode.CONST_FACTORY, factoryKeyword); } else if (body is EmptyFunctionBody) { if (factoryKeyword != null && externalKeyword == null && _parseFunctionBodies) { _reportErrorForToken( ParserErrorCode.FACTORY_WITHOUT_BODY, factoryKeyword); } } else { if (constKeyword != null && body is! NativeFunctionBody) { _reportErrorForNode( ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY, body); } else if (externalKeyword != null) { _reportErrorForNode( ParserErrorCode.EXTERNAL_CONSTRUCTOR_WITH_BODY, body); } else if (!bodyAllowed) { _reportErrorForNode( ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY, body); } } } return astFactory.constructorDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, externalKeyword, constKeyword, factoryKeyword, returnType, period, name, parameters, separator, initializers, redirectedConstructor, body); } /// Parse an enum constant declaration. Return the enum constant declaration /// that was parsed. /// /// Specified: /// /// enumConstant ::= /// id /// /// Actual: /// /// enumConstant ::= /// metadata id EnumConstantDeclaration _parseEnumConstantDeclaration() { CommentAndMetadata commentAndMetadata = parseCommentAndMetadata(); SimpleIdentifier name; if (_matchesIdentifier()) { name = _parseSimpleIdentifierUnchecked(isDeclaration: true); } else { name = createSyntheticIdentifier(); } return astFactory.enumConstantDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, name); } /// Parse a list of formal parameters given that the list starts with the /// given [leftParenthesis]. Return the formal parameters that were parsed. FormalParameterList _parseFormalParameterListAfterParen(Token leftParenthesis, {bool inFunctionType: false}) { if (_matches(TokenType.CLOSE_PAREN)) { return astFactory.formalParameterList( leftParenthesis, null, null, null, getAndAdvance()); } // // Even though it is invalid to have default parameters outside of brackets, // required parameters inside of brackets, or multiple groups of default and // named parameters, we allow all of these cases so that we can recover // better. // List<FormalParameter> parameters = <FormalParameter>[]; Token leftSquareBracket; Token rightSquareBracket; Token leftCurlyBracket; Token rightCurlyBracket; ParameterKind kind = ParameterKind.REQUIRED; bool firstParameter = true; bool reportedMultiplePositionalGroups = false; bool reportedMultipleNamedGroups = false; bool reportedMixedGroups = false; bool wasOptionalParameter = false; Token initialToken; do { if (firstParameter) { firstParameter = false; } else if (!_optional(TokenType.COMMA)) { // TODO(brianwilkerson) The token is wrong, we need to recover from this // case. if (_getEndToken(leftParenthesis) != null) { _reportErrorForCurrentToken( ParserErrorCode.EXPECTED_TOKEN, [TokenType.COMMA.lexeme]); } else { _reportErrorForToken(ParserErrorCode.MISSING_CLOSING_PARENTHESIS, _currentToken.previous); break; } } initialToken = _currentToken; // // Handle the beginning of parameter groups. // TokenType type = _currentToken.type; if (type == TokenType.OPEN_SQUARE_BRACKET) { wasOptionalParameter = true; if (leftSquareBracket != null && !reportedMultiplePositionalGroups) { _reportErrorForCurrentToken( ParserErrorCode.MULTIPLE_POSITIONAL_PARAMETER_GROUPS); reportedMultiplePositionalGroups = true; } if (leftCurlyBracket != null && !reportedMixedGroups) { _reportErrorForCurrentToken(ParserErrorCode.MIXED_PARAMETER_GROUPS); reportedMixedGroups = true; } leftSquareBracket = getAndAdvance(); kind = ParameterKind.POSITIONAL; } else if (type == TokenType.OPEN_CURLY_BRACKET) { wasOptionalParameter = true; if (leftCurlyBracket != null && !reportedMultipleNamedGroups) { _reportErrorForCurrentToken( ParserErrorCode.MULTIPLE_NAMED_PARAMETER_GROUPS); reportedMultipleNamedGroups = true; } if (leftSquareBracket != null && !reportedMixedGroups) { _reportErrorForCurrentToken(ParserErrorCode.MIXED_PARAMETER_GROUPS); reportedMixedGroups = true; } leftCurlyBracket = getAndAdvance(); kind = ParameterKind.NAMED; } // // Parse and record the parameter. // FormalParameter parameter = parseFormalParameter(kind, inFunctionType: inFunctionType); parameters.add(parameter); if (kind == ParameterKind.REQUIRED && wasOptionalParameter) { _reportErrorForNode( ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS, parameter); } // // Handle the end of parameter groups. // // TODO(brianwilkerson) Improve the detection and reporting of missing and // mismatched delimiters. type = _currentToken.type; // Advance past trailing commas as appropriate. if (type == TokenType.COMMA) { // Only parse commas trailing normal (non-positional/named) params. if (rightSquareBracket == null && rightCurlyBracket == null) { Token next = _peek(); if (next.type == TokenType.CLOSE_PAREN || next.type == TokenType.CLOSE_CURLY_BRACKET || next.type == TokenType.CLOSE_SQUARE_BRACKET) { _advance(); type = _currentToken.type; } } } if (type == TokenType.CLOSE_SQUARE_BRACKET) { rightSquareBracket = getAndAdvance(); if (leftSquareBracket == null) { if (leftCurlyBracket != null) { _reportErrorForCurrentToken( ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP, ['}', ']']); rightCurlyBracket = rightSquareBracket; rightSquareBracket; // Skip over synthetic closer inserted by fasta // since we've already reported an error if (_currentToken.type == TokenType.CLOSE_CURLY_BRACKET && _currentToken.isSynthetic) { _advance(); } } else { _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP, ["["]); } } kind = ParameterKind.REQUIRED; } else if (type == TokenType.CLOSE_CURLY_BRACKET) { rightCurlyBracket = getAndAdvance(); if (leftCurlyBracket == null) { if (leftSquareBracket != null) { _reportErrorForCurrentToken( ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP, [']', '}']); rightSquareBracket = rightCurlyBracket; rightCurlyBracket; // Skip over synthetic closer inserted by fasta // since we've already reported an error if (_currentToken.type == TokenType.CLOSE_SQUARE_BRACKET && _currentToken.isSynthetic) { _advance(); } } else { _reportErrorForCurrentToken( ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP, ["{"]); } } kind = ParameterKind.REQUIRED; } } while (!_matches(TokenType.CLOSE_PAREN) && !identical(initialToken, _currentToken)); Token rightParenthesis = _expect(TokenType.CLOSE_PAREN); // // Check that the groups were closed correctly. // if (leftSquareBracket != null && rightSquareBracket == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP, ["]"]); } if (leftCurlyBracket != null && rightCurlyBracket == null) { _reportErrorForCurrentToken( ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP, ["}"]); } // // Build the parameter list. // leftSquareBracket ??= leftCurlyBracket; rightSquareBracket ??= rightCurlyBracket; return astFactory.formalParameterList(leftParenthesis, parameters, leftSquareBracket, rightSquareBracket, rightParenthesis); } /// Parse a list of formal parameters. Return the formal parameters that were /// parsed. /// /// This method assumes that the current token matches `TokenType.OPEN_PAREN`. FormalParameterList _parseFormalParameterListUnchecked( {bool inFunctionType: false}) { return _parseFormalParameterListAfterParen(getAndAdvance(), inFunctionType: inFunctionType); } /// Parse a function declaration statement. The [commentAndMetadata] is the /// documentation comment and metadata to be associated with the declaration. /// The [returnType] is the return type, or `null` if there is no return type. /// Return the function declaration statement that was parsed. /// /// functionDeclarationStatement ::= /// functionSignature functionBody Statement _parseFunctionDeclarationStatementAfterReturnType( CommentAndMetadata commentAndMetadata, TypeAnnotation returnType) { FunctionDeclaration declaration = parseFunctionDeclaration(commentAndMetadata, null, returnType); Token propertyKeyword = declaration.propertyKeyword; if (propertyKeyword != null) { if (propertyKeyword.keyword == Keyword.GET) { _reportErrorForToken( ParserErrorCode.GETTER_IN_FUNCTION, propertyKeyword); } else { _reportErrorForToken( ParserErrorCode.SETTER_IN_FUNCTION, propertyKeyword); } } return astFactory.functionDeclarationStatement(declaration); } /// Parse a function type alias. The [commentAndMetadata] is the metadata to /// be associated with the member. The [keyword] is the token representing the /// 'typedef' keyword. Return the function type alias that was parsed. /// /// functionTypeAlias ::= /// functionPrefix typeParameterList? formalParameterList ';' /// /// functionPrefix ::= /// returnType? name FunctionTypeAlias _parseFunctionTypeAlias( CommentAndMetadata commentAndMetadata, Token keyword) { TypeAnnotation returnType; if (hasReturnTypeInTypeAlias) { returnType = parseTypeAnnotation(false); } SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true); TypeParameterList typeParameters; if (_matches(TokenType.LT)) { typeParameters = parseTypeParameterList(); } TokenType type = _currentToken.type; if (type == TokenType.SEMICOLON || type == TokenType.EOF) { _reportErrorForCurrentToken(ParserErrorCode.MISSING_TYPEDEF_PARAMETERS); FormalParameterList parameters = astFactory.formalParameterList( _createSyntheticToken(TokenType.OPEN_PAREN), null, null, null, _createSyntheticToken(TokenType.CLOSE_PAREN)); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.functionTypeAlias( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, returnType, name, typeParameters, parameters, semicolon); } else if (type == TokenType.OPEN_PAREN) { FormalParameterList parameters = _parseFormalParameterListUnchecked(); _validateFormalParameterList(parameters); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.functionTypeAlias( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, returnType, name, typeParameters, parameters, semicolon); } else { _reportErrorForCurrentToken(ParserErrorCode.MISSING_TYPEDEF_PARAMETERS); // Recovery: At the very least we should skip to the start of the next // valid compilation unit member, allowing for the possibility of finding // the typedef parameters before that point. return astFactory.functionTypeAlias( commentAndMetadata.comment, commentAndMetadata.metadata, keyword, returnType, name, typeParameters, astFactory.formalParameterList( _createSyntheticToken(TokenType.OPEN_PAREN), null, null, null, _createSyntheticToken(TokenType.CLOSE_PAREN)), _createSyntheticToken(TokenType.SEMICOLON)); } } /// Parse the generic method or function's type parameters. /// /// For backwards compatibility this can optionally use comments. /// See [parseGenericMethodComments]. TypeParameterList _parseGenericMethodTypeParameters() { if (_matches(TokenType.LT)) { return parseTypeParameterList(); } return null; } /// Parse a library name. The [missingNameError] is the error code to be used /// if the library name is missing. The [missingNameToken] is the token /// associated with the error produced if the library name is missing. Return /// the library name that was parsed. /// /// libraryName ::= /// libraryIdentifier LibraryIdentifier _parseLibraryName( ParserErrorCode missingNameError, Token missingNameToken) { if (_matchesIdentifier()) { return parseLibraryIdentifier(); } else if (_matches(TokenType.STRING)) { // Recovery: This should be extended to handle arbitrary tokens until we // can find a token that can start a compilation unit member. StringLiteral string = parseStringLiteral(); _reportErrorForNode(ParserErrorCode.NON_IDENTIFIER_LIBRARY_NAME, string); } else { _reportErrorForToken(missingNameError, missingNameToken); } return astFactory .libraryIdentifier(<SimpleIdentifier>[createSyntheticIdentifier()]); } /// Parse a method declaration. The [commentAndMetadata] is the documentation /// comment and metadata to be associated with the declaration. The /// [externalKeyword] is the 'external' token. The [staticKeyword] is the /// static keyword, or `null` if the getter is not static. The [returnType] is /// the return type of the method. The [name] is the name of the method. The /// [parameters] is the parameters to the method. Return the method /// declaration that was parsed. /// /// functionDeclaration ::= /// ('external' 'static'?)? functionSignature functionBody /// | 'external'? functionSignature ';' MethodDeclaration _parseMethodDeclarationAfterParameters( CommentAndMetadata commentAndMetadata, Token externalKeyword, Token staticKeyword, TypeAnnotation returnType, SimpleIdentifier name, TypeParameterList typeParameters, FormalParameterList parameters) { FunctionBody body = parseFunctionBody( externalKeyword != null || staticKeyword == null, ParserErrorCode.MISSING_FUNCTION_BODY, false); if (externalKeyword != null) { if (body is! EmptyFunctionBody) { _reportErrorForNode(ParserErrorCode.EXTERNAL_METHOD_WITH_BODY, body); } } else if (staticKeyword != null) { if (body is EmptyFunctionBody && _parseFunctionBodies) { _reportErrorForNode(ParserErrorCode.ABSTRACT_STATIC_METHOD, body); } } return astFactory.methodDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, externalKeyword, staticKeyword, returnType, null, null, name, typeParameters, parameters, body); } /// Parse a method declaration. The [commentAndMetadata] is the documentation /// comment and metadata to be associated with the declaration. The /// [externalKeyword] is the 'external' token. The [staticKeyword] is the /// static keyword, or `null` if the getter is not static. The [returnType] is /// the return type of the method. Return the method declaration that was /// parsed. /// /// functionDeclaration ::= /// 'external'? 'static'? functionSignature functionBody /// | 'external'? functionSignature ';' MethodDeclaration _parseMethodDeclarationAfterReturnType( CommentAndMetadata commentAndMetadata, Token externalKeyword, Token staticKeyword, TypeAnnotation returnType) { SimpleIdentifier methodName = parseSimpleIdentifier(isDeclaration: true); TypeParameterList typeParameters = _parseGenericMethodTypeParameters(); FormalParameterList parameters; TokenType type = _currentToken.type; // TODO(brianwilkerson) Figure out why we care what the current token is if // it isn't a paren. if (type != TokenType.OPEN_PAREN && (type == TokenType.OPEN_CURLY_BRACKET || type == TokenType.FUNCTION)) { _reportErrorForToken( ParserErrorCode.MISSING_METHOD_PARAMETERS, _currentToken.previous); parameters = astFactory.formalParameterList( _createSyntheticToken(TokenType.OPEN_PAREN), null, null, null, _createSyntheticToken(TokenType.CLOSE_PAREN)); } else { parameters = parseFormalParameterList(); } _validateFormalParameterList(parameters); return _parseMethodDeclarationAfterParameters( commentAndMetadata, externalKeyword, staticKeyword, returnType, methodName, typeParameters, parameters); } /// Parse a class native clause. Return the native clause that was parsed. /// /// This method assumes that the current token matches `_NATIVE`. /// /// classNativeClause ::= /// 'native' name NativeClause _parseNativeClause() { Token keyword = getAndAdvance(); StringLiteral name = parseStringLiteral(); return astFactory.nativeClause(keyword, name); } /// Parse an operator declaration starting after the 'operator' keyword. The /// [commentAndMetadata] is the documentation comment and metadata to be /// associated with the declaration. The [externalKeyword] is the 'external' /// token. The [returnType] is the return type that has already been parsed, /// or `null` if there was no return type. The [operatorKeyword] is the /// 'operator' keyword. Return the operator declaration that was parsed. /// /// operatorDeclaration ::= /// operatorSignature (';' | functionBody) /// /// operatorSignature ::= /// 'external'? returnType? 'operator' operator formalParameterList MethodDeclaration _parseOperatorAfterKeyword( CommentAndMetadata commentAndMetadata, Token externalKeyword, TypeAnnotation returnType, Token operatorKeyword) { if (!_currentToken.isUserDefinableOperator) { _reportErrorForCurrentToken( _currentToken.type == TokenType.EQ_EQ_EQ ? ParserErrorCode.INVALID_OPERATOR : ParserErrorCode.NON_USER_DEFINABLE_OPERATOR, [_currentToken.lexeme]); } SimpleIdentifier name = astFactory.simpleIdentifier(getAndAdvance(), isDeclaration: true); if (_matches(TokenType.EQ)) { Token previous = _currentToken.previous; if ((_tokenMatches(previous, TokenType.EQ_EQ) || _tokenMatches(previous, TokenType.BANG_EQ)) && _currentToken.offset == previous.offset + 2) { _reportErrorForCurrentToken(ParserErrorCode.INVALID_OPERATOR, ["${previous.lexeme}${_currentToken.lexeme}"]); _advance(); } } FormalParameterList parameters = parseFormalParameterList(); _validateFormalParameterList(parameters); FunctionBody body = parseFunctionBody(true, ParserErrorCode.MISSING_FUNCTION_BODY, false); if (externalKeyword != null && body is! EmptyFunctionBody) { _reportErrorForCurrentToken(ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY); } return astFactory.methodDeclaration( commentAndMetadata.comment, commentAndMetadata.metadata, externalKeyword, null, returnType, null, operatorKeyword, name, null, parameters, body); } /// Parse a return type if one is given, otherwise return `null` without /// advancing. Return the return type that was parsed. TypeAnnotation _parseOptionalReturnType() { Keyword keyword = _currentToken.keyword; if (keyword == Keyword.VOID) { if (_atGenericFunctionTypeAfterReturnType(_peek())) { return parseTypeAnnotation(false); } return astFactory.typeName( astFactory.simpleIdentifier(getAndAdvance()), null); } else if (_matchesIdentifier()) { Token next = _peek(); if (keyword != Keyword.GET && keyword != Keyword.SET && keyword != Keyword.OPERATOR && (_tokenMatchesIdentifier(next) || _tokenMatches(next, TokenType.LT))) { Token afterTypeParameters = _skipTypeParameterList(next); if (afterTypeParameters != null && _tokenMatches(afterTypeParameters, TokenType.OPEN_PAREN)) { // If the identifier is followed by type parameters and a parenthesis, // then the identifier is the name of a generic method, not a return // type. return null; } return parseTypeAnnotation(false); } Token next2 = next.next; Token next3 = next2.next; if (_tokenMatches(next, TokenType.PERIOD) && _tokenMatchesIdentifier(next2) && (_tokenMatchesIdentifier(next3) || _tokenMatches(next3, TokenType.LT))) { return parseTypeAnnotation(false); } } return null; } /// Parse a [TypeArgumentList] if present, otherwise return null. /// This also supports the comment form, if enabled: `/*<T>*/` TypeArgumentList _parseOptionalTypeArguments() { if (_matches(TokenType.LT)) { return parseTypeArgumentList(); } return null; } /// Parse a part directive. The [commentAndMetadata] is the metadata to be /// associated with the directive. Return the part or part-of directive that /// was parsed. /// /// This method assumes that the current token matches `Keyword.PART`. /// /// partDirective ::= /// metadata 'part' stringLiteral ';' Directive _parsePartDirective(CommentAndMetadata commentAndMetadata) { Token partKeyword = getAndAdvance(); StringLiteral partUri = _parseUri(); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.partDirective(commentAndMetadata.comment, commentAndMetadata.metadata, partKeyword, partUri, semicolon); } /// Parse a part-of directive. The [commentAndMetadata] is the metadata to be /// associated with the directive. Return the part or part-of directive that /// was parsed. /// /// This method assumes that the current token matches [Keyword.PART] and that /// the following token matches the identifier 'of'. /// /// partOfDirective ::= /// metadata 'part' 'of' identifier ';' Directive _parsePartOfDirective(CommentAndMetadata commentAndMetadata) { Token partKeyword = getAndAdvance(); Token ofKeyword = getAndAdvance(); if (_matches(TokenType.STRING)) { StringLiteral libraryUri = _parseUri(); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.partOfDirective( commentAndMetadata.comment, commentAndMetadata.metadata, partKeyword, ofKeyword, libraryUri, null, semicolon); } LibraryIdentifier libraryName = _parseLibraryName( ParserErrorCode.MISSING_NAME_IN_PART_OF_DIRECTIVE, ofKeyword); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.partOfDirective( commentAndMetadata.comment, commentAndMetadata.metadata, partKeyword, ofKeyword, null, libraryName, semicolon); } /// Parse a prefixed identifier given that the given [qualifier] was already /// parsed. Return the prefixed identifier that was parsed. /// /// prefixedIdentifier ::= /// identifier ('.' identifier)? Identifier _parsePrefixedIdentifierAfterIdentifier( SimpleIdentifier qualifier) { if (!_matches(TokenType.PERIOD)) { return qualifier; } Token period = getAndAdvance(); SimpleIdentifier qualified = parseSimpleIdentifier(); return astFactory.prefixedIdentifier(qualifier, period, qualified); } /// Parse a prefixed identifier. Return the prefixed identifier that was /// parsed. /// /// This method assumes that the current token matches an identifier. /// /// prefixedIdentifier ::= /// identifier ('.' identifier)? Identifier _parsePrefixedIdentifierUnchecked() { return _parsePrefixedIdentifierAfterIdentifier( _parseSimpleIdentifierUnchecked()); } /// Parse a simple identifier. Return the simple identifier that was parsed. /// /// This method assumes that the current token matches an identifier. /// /// identifier ::= /// IDENTIFIER SimpleIdentifier _parseSimpleIdentifierUnchecked( {bool isDeclaration: false}) { String lexeme = _currentToken.lexeme; if ((_inAsync || _inGenerator) && (lexeme == _AWAIT || lexeme == _YIELD)) { _reportErrorForCurrentToken( ParserErrorCode.ASYNC_KEYWORD_USED_AS_IDENTIFIER); } return astFactory.simpleIdentifier(getAndAdvance(), isDeclaration: isDeclaration); } /// Parse a list of statements within a switch statement. Return the /// statements that were parsed. /// /// statements ::= /// statement* List<Statement> _parseStatementList() { List<Statement> statements = <Statement>[]; Token statementStart = _currentToken; TokenType type = _currentToken.type; while (type != TokenType.EOF && type != TokenType.CLOSE_CURLY_BRACKET && !isSwitchMember()) { statements.add(parseStatement2()); if (identical(_currentToken, statementStart)) { _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken, [_currentToken.lexeme]); _advance(); } statementStart = _currentToken; type = _currentToken.type; } return statements; } /// Parse a string literal that contains interpolations. Return the string /// literal that was parsed. /// /// This method assumes that the current token matches either /// [TokenType.STRING_INTERPOLATION_EXPRESSION] or /// [TokenType.STRING_INTERPOLATION_IDENTIFIER]. StringInterpolation _parseStringInterpolation(Token string) { List<InterpolationElement> elements = <InterpolationElement>[ astFactory.interpolationString( string, computeStringValue(string.lexeme, true, false)) ]; bool hasMore = true; bool isExpression = _matches(TokenType.STRING_INTERPOLATION_EXPRESSION); while (hasMore) { if (isExpression) { Token openToken = getAndAdvance(); bool wasInInitializer = _inInitializer; _inInitializer = false; try { Expression expression = parseExpression2(); Token rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET); elements.add(astFactory.interpolationExpression( openToken, expression, rightBracket)); } finally { _inInitializer = wasInInitializer; } } else { Token openToken = getAndAdvance(); Expression expression; if (_matchesKeyword(Keyword.THIS)) { expression = astFactory.thisExpression(getAndAdvance()); } else { expression = parseSimpleIdentifier(); } elements.add( astFactory.interpolationExpression(openToken, expression, null)); } if (_matches(TokenType.STRING)) { string = getAndAdvance(); isExpression = _matches(TokenType.STRING_INTERPOLATION_EXPRESSION); hasMore = isExpression || _matches(TokenType.STRING_INTERPOLATION_IDENTIFIER); elements.add(astFactory.interpolationString( string, computeStringValue(string.lexeme, false, !hasMore))); } else { hasMore = false; } } return astFactory.stringInterpolation(elements); } /// Parse a string literal. Return the string literal that was parsed. /// /// This method assumes that the current token matches `TokenType.STRING`. /// /// stringLiteral ::= /// MULTI_LINE_STRING+ /// | SINGLE_LINE_STRING+ StringLiteral _parseStringLiteralUnchecked() { List<StringLiteral> strings = <StringLiteral>[]; do { Token string = getAndAdvance(); if (_matches(TokenType.STRING_INTERPOLATION_EXPRESSION) || _matches(TokenType.STRING_INTERPOLATION_IDENTIFIER)) { strings.add(_parseStringInterpolation(string)); } else { strings.add(astFactory.simpleStringLiteral( string, computeStringValue(string.lexeme, true, true))); } } while (_matches(TokenType.STRING)); return strings.length == 1 ? strings[0] : astFactory.adjacentStrings(strings); } /// Parse a type annotation, possibly superseded by a type name in a comment. /// Return the type name that was parsed. /// /// This method assumes that the current token is an identifier. /// /// type ::= /// qualified typeArguments? TypeAnnotation _parseTypeAnnotationAfterIdentifier() { return parseTypeAnnotation(false); } TypeName _parseTypeName(bool inExpression) { Identifier typeName; if (_matchesIdentifier()) { typeName = _parsePrefixedIdentifierUnchecked(); } else if (_matchesKeyword(Keyword.VAR)) { _reportErrorForCurrentToken(ParserErrorCode.VAR_AS_TYPE_NAME); typeName = astFactory.simpleIdentifier(getAndAdvance()); } else { typeName = createSyntheticIdentifier(); _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_TYPE_NAME); } TypeArgumentList typeArguments = _parseOptionalTypeArguments(); return astFactory.typeName(typeName, typeArguments); } /// Parse a string literal representing a URI. Return the string literal that /// was parsed. StringLiteral _parseUri() { // TODO(brianwilkerson) Should this function also return true for valid // top-level keywords? bool isKeywordAfterUri(Token token) => token.lexeme == Keyword.AS.lexeme || token.lexeme == _HIDE || token.lexeme == _SHOW; TokenType type = _currentToken.type; if (type != TokenType.STRING && type != TokenType.SEMICOLON && !isKeywordAfterUri(_currentToken)) { // Attempt to recover in the case where the URI was not enclosed in // quotes. Token token = _currentToken; bool isValidInUri(Token token) { TokenType type = token.type; return type == TokenType.COLON || type == TokenType.SLASH || type == TokenType.PERIOD || type == TokenType.PERIOD_PERIOD || type == TokenType.PERIOD_PERIOD_PERIOD || type == TokenType.INT || type == TokenType.DOUBLE; } while ((_tokenMatchesIdentifier(token) && !isKeywordAfterUri(token)) || isValidInUri(token)) { token = token.next; } if (_tokenMatches(token, TokenType.SEMICOLON) || isKeywordAfterUri(token)) { Token endToken = token.previous; token = _currentToken; int endOffset = token.end; StringBuffer buffer = new StringBuffer(); buffer.write(token.lexeme); while (token != endToken) { token = token.next; if (token.offset != endOffset || token.precedingComments != null) { return parseStringLiteral(); } buffer.write(token.lexeme); endOffset = token.end; } String value = buffer.toString(); Token newToken = new StringToken(TokenType.STRING, "'$value'", _currentToken.offset); _reportErrorForToken( ParserErrorCode.NON_STRING_LITERAL_AS_URI, newToken); _currentToken = endToken.next; return astFactory.simpleStringLiteral(newToken, value); } } return parseStringLiteral(); } /// Parse a variable declaration statement. The [commentAndMetadata] is the /// metadata to be associated with the variable declaration statement, or /// `null` if there is no attempt at parsing the comment and metadata. The /// [keyword] is the token representing the 'final', 'const' or 'var' keyword, /// or `null` if there is no keyword. The [type] is the type of the variables /// in the list. Return the variable declaration statement that was parsed. /// /// variableDeclarationStatement ::= /// variableDeclarationList ';' VariableDeclarationStatement _parseVariableDeclarationStatementAfterType( CommentAndMetadata commentAndMetadata, Token keyword, TypeAnnotation type) { VariableDeclarationList variableList = parseVariableDeclarationListAfterType( commentAndMetadata, keyword, type); Token semicolon = _expect(TokenType.SEMICOLON); return astFactory.variableDeclarationStatement(variableList, semicolon); } /// Return the token that is immediately after the current token. This is /// equivalent to [_peekAt](1). Token _peek() => _currentToken.next; /// Return the token that is the given [distance] after the current token, /// where the distance is the number of tokens to look ahead. A distance of /// `0` is the current token, `1` is the next token, etc. Token _peekAt(int distance) { Token token = _currentToken; for (int i = 0; i < distance; i++) { token = token.next; } return token; } String _removeGitHubInlineCode(String comment) { int index = 0; while (true) { int beginIndex = comment.indexOf('`', index); if (beginIndex == -1) { break; } int endIndex = comment.indexOf('`', beginIndex + 1); if (endIndex == -1) { break; } comment = comment.substring(0, beginIndex + 1) + ' ' * (endIndex - beginIndex - 1) + comment.substring(endIndex); index = endIndex + 1; } return comment; } /// Report the given [error]. void _reportError(AnalysisError error) { if (_errorListenerLock != 0) { return; } _errorListener.onError(error); } /// Report an error with the given [errorCode] and [arguments] associated with /// the current token. void _reportErrorForCurrentToken(ParserErrorCode errorCode, [List<Object> arguments]) { _reportErrorForToken(errorCode, _currentToken, arguments); } /// Report an error with the given [errorCode] and [arguments] associated with /// the given [node]. void _reportErrorForNode(ParserErrorCode errorCode, AstNode node, [List<Object> arguments]) { _reportError(new AnalysisError( _source, node.offset, node.length, errorCode, arguments)); } /// Report an error with the given [errorCode] and [arguments] associated with /// the given [token]. void _reportErrorForToken(ErrorCode errorCode, Token token, [List<Object> arguments]) { if (token.type == TokenType.EOF) { token = token.previous; } _reportError(new AnalysisError(_source, token.offset, math.max(token.length, 1), errorCode, arguments)); } /// Skips a block with all containing blocks. void _skipBlock() { Token endToken = (_currentToken as BeginToken).endToken; if (endToken == null) { endToken = _currentToken.next; while (!identical(endToken, _currentToken)) { _currentToken = endToken; endToken = _currentToken.next; } _reportErrorForToken( ParserErrorCode.EXPECTED_TOKEN, _currentToken.previous, ["}"]); } else { _currentToken = endToken.next; } } /// Parse the 'final', 'const', 'var' or type preceding a variable /// declaration, starting at the given token, without actually creating a /// type or changing the current token. Return the token following the type /// that was parsed, or `null` if the given token is not the first token in a /// valid type. The [startToken] is the token at which parsing is to begin. /// Return the token following the type that was parsed. /// /// finalConstVarOrType ::= /// | 'final' type? /// | 'const' type? /// | 'var' /// | type Token _skipFinalConstVarOrType(Token startToken) { Keyword keyword = startToken.keyword; if (keyword == Keyword.FINAL || keyword == Keyword.CONST) { Token next = startToken.next; if (_tokenMatchesIdentifier(next)) { Token next2 = next.next; // "Type parameter" or "Type<" or "prefix.Type" if (_tokenMatchesIdentifier(next2) || _tokenMatches(next2, TokenType.LT) || _tokenMatches(next2, TokenType.PERIOD)) { return skipTypeName(next); } // "parameter" return next; } } else if (keyword == Keyword.VAR) { return startToken.next; } else if (_tokenMatchesIdentifier(startToken)) { Token next = startToken.next; if (_tokenMatchesIdentifier(next) || _tokenMatches(next, TokenType.LT) || _tokenMatchesKeyword(next, Keyword.THIS) || (_tokenMatches(next, TokenType.PERIOD) && _tokenMatchesIdentifier(next.next) && (_tokenMatchesIdentifier(next.next.next) || _tokenMatches(next.next.next, TokenType.LT) || _tokenMatchesKeyword(next.next.next, Keyword.THIS)))) { return skipTypeAnnotation(startToken); } } return null; } /// Parse a list of formal parameters, starting at the [startToken], without /// actually creating a formal parameter list or changing the current token. /// Return the token following the formal parameter list that was parsed, or /// `null` if the given token is not the first token in a valid list of formal /// parameter. /// /// Note that unlike other skip methods, this method uses a heuristic. In the /// worst case, the parameters could be prefixed by metadata, which would /// require us to be able to skip arbitrary expressions. Rather than duplicate /// the logic of most of the parse methods we simply look for something that /// is likely to be a list of parameters and then skip to returning the token /// after the closing parenthesis. /// /// This method must be kept in sync with [parseFormalParameterList]. /// /// formalParameterList ::= /// '(' ')' /// | '(' normalFormalParameters (',' optionalFormalParameters)? ')' /// | '(' optionalFormalParameters ')' /// /// normalFormalParameters ::= /// normalFormalParameter (',' normalFormalParameter)* /// /// optionalFormalParameters ::= /// optionalPositionalFormalParameters /// | namedFormalParameters /// /// optionalPositionalFormalParameters ::= /// '[' defaultFormalParameter (',' defaultFormalParameter)* ']' /// /// namedFormalParameters ::= /// '{' defaultNamedParameter (',' defaultNamedParameter)* '}' Token _skipFormalParameterList(Token startToken) { if (!_tokenMatches(startToken, TokenType.OPEN_PAREN)) { return null; } Token next = startToken.next; if (_tokenMatches(next, TokenType.CLOSE_PAREN)) { return next.next; } // // Look to see whether the token after the open parenthesis is something // that should only occur at the beginning of a parameter list. // if (next.matchesAny(const <TokenType>[ TokenType.AT, TokenType.OPEN_SQUARE_BRACKET, TokenType.OPEN_CURLY_BRACKET ]) || _tokenMatchesKeyword(next, Keyword.VOID) || (_tokenMatchesIdentifier(next) && (next.next.matchesAny( const <TokenType>[TokenType.COMMA, TokenType.CLOSE_PAREN])))) { return _skipPastMatchingToken(startToken); } // // Look to see whether the first parameter is a function typed parameter // without a return type. // if (_tokenMatchesIdentifier(next) && _tokenMatches(next.next, TokenType.OPEN_PAREN)) { Token afterParameters = _skipFormalParameterList(next.next); if (afterParameters != null && afterParameters.matchesAny( const <TokenType>[TokenType.COMMA, TokenType.CLOSE_PAREN])) { return _skipPastMatchingToken(startToken); } } // // Look to see whether the first parameter has a type or is a function typed // parameter with a return type. // Token afterType = _skipFinalConstVarOrType(next); if (afterType == null) { return null; } if (skipSimpleIdentifier(afterType) == null) { return null; } return _skipPastMatchingToken(startToken); } /// If the [startToken] is a begin token with an associated end token, then /// return the token following the end token. Otherwise, return `null`. Token _skipPastMatchingToken(Token startToken) { if (startToken is! BeginToken) { return null; } Token closeParen = (startToken as BeginToken).endToken; if (closeParen == null) { return null; } return closeParen.next; } /// Parse a string literal that contains interpolations, starting at the /// [startToken], without actually creating a string literal or changing the /// current token. Return the token following the string literal that was /// parsed, or `null` if the given token is not the first token in a valid /// string literal. /// /// This method must be kept in sync with [parseStringInterpolation]. Token _skipStringInterpolation(Token startToken) { Token token = startToken; TokenType type = token.type; while (type == TokenType.STRING_INTERPOLATION_EXPRESSION || type == TokenType.STRING_INTERPOLATION_IDENTIFIER) { if (type == TokenType.STRING_INTERPOLATION_EXPRESSION) { token = token.next; type = token.type; // // Rather than verify that the following tokens represent a valid // expression, we simply skip tokens until we reach the end of the // interpolation, being careful to handle nested string literals. // int bracketNestingLevel = 1; while (bracketNestingLevel > 0) { if (type == TokenType.EOF) { return null; } else if (type == TokenType.OPEN_CURLY_BRACKET) { bracketNestingLevel++; token = token.next; } else if (type == TokenType.CLOSE_CURLY_BRACKET) { bracketNestingLevel--; token = token.next; } else if (type == TokenType.STRING) { token = skipStringLiteral(token); if (token == null) { return null; } } else { token = token.next; } type = token.type; } token = token.next; type = token.type; } else { token = token.next; if (token.type != TokenType.IDENTIFIER) { return null; } token = token.next; } type = token.type; if (type == TokenType.STRING) { token = token.next; type = token.type; } } return token; } /// Parse a list of type parameters, starting at the [startToken], without /// actually creating a type parameter list or changing the current token. /// Return the token following the type parameter list that was parsed, or /// `null` if the given token is not the first token in a valid type parameter /// list. /// /// This method must be kept in sync with [parseTypeParameterList]. /// /// typeParameterList ::= /// '<' typeParameter (',' typeParameter)* '>' Token _skipTypeParameterList(Token startToken) { if (!_tokenMatches(startToken, TokenType.LT)) { return null; } // // We can't skip a type parameter because it can be preceded by metadata, // so we just assume that everything before the matching end token is valid. // int depth = 1; Token next = startToken.next; while (depth > 0) { if (_tokenMatches(next, TokenType.EOF)) { return null; } else if (_tokenMatches(next, TokenType.LT)) { depth++; } else if (_tokenMatches(next, TokenType.GT)) { depth--; } else if (_tokenMatches(next, TokenType.GT_EQ)) { if (depth == 1) { Token fakeEquals = new Token(TokenType.EQ, next.offset + 2); fakeEquals.setNextWithoutSettingPrevious(next.next); return fakeEquals; } depth--; } else if (_tokenMatches(next, TokenType.GT_GT)) { depth -= 2; } else if (_tokenMatches(next, TokenType.GT_GT_EQ)) { if (depth < 2) { return null; } else if (depth == 2) { Token fakeEquals = new Token(TokenType.EQ, next.offset + 2); fakeEquals.setNextWithoutSettingPrevious(next.next); return fakeEquals; } depth -= 2; } next = next.next; } return next; } /// Assuming that the current token is an index token ('[]'), split it into /// two tokens ('[' and ']'), leaving the left bracket as the current token. void _splitIndex() { // Split the token into two separate tokens. BeginToken leftBracket = _createToken( _currentToken, TokenType.OPEN_SQUARE_BRACKET, isBegin: true); Token rightBracket = new Token(TokenType.CLOSE_SQUARE_BRACKET, _currentToken.offset + 1); leftBracket.endToken = rightBracket; rightBracket.setNext(_currentToken.next); leftBracket.setNext(rightBracket); _currentToken.previous.setNext(leftBracket); _currentToken = leftBracket; } /// Return `true` if the given [token] has the given [type]. bool _tokenMatches(Token token, TokenType type) => token.type == type; /// Return `true` if the given [token] is a valid identifier. Valid /// identifiers include built-in identifiers (pseudo-keywords). bool _tokenMatchesIdentifier(Token token) => _tokenMatches(token, TokenType.IDENTIFIER) || _tokenMatchesPseudoKeyword(token); /// Return `true` if the given [token] is either an identifier or a keyword. bool _tokenMatchesIdentifierOrKeyword(Token token) => _tokenMatches(token, TokenType.IDENTIFIER) || token.type.isKeyword; /// Return `true` if the given [token] matches the given [keyword]. bool _tokenMatchesKeyword(Token token, Keyword keyword) => token.keyword == keyword; /// Return `true` if the given [token] matches a pseudo keyword. bool _tokenMatchesPseudoKeyword(Token token) => token.keyword?.isBuiltInOrPseudo ?? false; /// Translate the characters at the given [index] in the given [lexeme], /// appending the translated character to the given [buffer]. The index is /// assumed to be valid. int _translateCharacter(StringBuffer buffer, String lexeme, int index) { int currentChar = lexeme.codeUnitAt(index); if (currentChar != 0x5C) { buffer.writeCharCode(currentChar); return index + 1; } // // We have found an escape sequence, so we parse the string to determine // what kind of escape sequence and what character to add to the builder. // int length = lexeme.length; int currentIndex = index + 1; if (currentIndex >= length) { // Illegal escape sequence: no char after escape. // This cannot actually happen because it would require the escape // character to be the last character in the string, but if it were it // would escape the closing quote, leaving the string unclosed. // reportError(ParserErrorCode.MISSING_CHAR_IN_ESCAPE_SEQUENCE); return length; } currentChar = lexeme.codeUnitAt(currentIndex); if (currentChar == 0x6E) { buffer.writeCharCode(0xA); // newline } else if (currentChar == 0x72) { buffer.writeCharCode(0xD); // carriage return } else if (currentChar == 0x66) { buffer.writeCharCode(0xC); // form feed } else if (currentChar == 0x62) { buffer.writeCharCode(0x8); // backspace } else if (currentChar == 0x74) { buffer.writeCharCode(0x9); // tab } else if (currentChar == 0x76) { buffer.writeCharCode(0xB); // vertical tab } else if (currentChar == 0x78) { if (currentIndex + 2 >= length) { // Illegal escape sequence: not enough hex digits _reportErrorForCurrentToken(ParserErrorCode.INVALID_HEX_ESCAPE); return length; } int firstDigit = lexeme.codeUnitAt(currentIndex + 1); int secondDigit = lexeme.codeUnitAt(currentIndex + 2); if (!_isHexDigit(firstDigit) || !_isHexDigit(secondDigit)) { // Illegal escape sequence: invalid hex digit _reportErrorForCurrentToken(ParserErrorCode.INVALID_HEX_ESCAPE); } else { int charCode = (Character.digit(firstDigit, 16) << 4) + Character.digit(secondDigit, 16); buffer.writeCharCode(charCode); } return currentIndex + 3; } else if (currentChar == 0x75) { currentIndex++; if (currentIndex >= length) { // Illegal escape sequence: not enough hex digits _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); return length; } currentChar = lexeme.codeUnitAt(currentIndex); if (currentChar == 0x7B) { currentIndex++; if (currentIndex >= length) { // Illegal escape sequence: incomplete escape _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); return length; } currentChar = lexeme.codeUnitAt(currentIndex); int digitCount = 0; int value = 0; while (currentChar != 0x7D) { if (!_isHexDigit(currentChar)) { // Illegal escape sequence: invalid hex digit _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); currentIndex++; while (currentIndex < length && lexeme.codeUnitAt(currentIndex) != 0x7D) { currentIndex++; } return currentIndex + 1; } digitCount++; value = (value << 4) + Character.digit(currentChar, 16); currentIndex++; if (currentIndex >= length) { // Illegal escape sequence: incomplete escape _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); return length; } currentChar = lexeme.codeUnitAt(currentIndex); } if (digitCount < 1 || digitCount > 6) { // Illegal escape sequence: not enough or too many hex digits _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); } _appendCodePoint(buffer, lexeme, value, index, currentIndex); return currentIndex + 1; } else { if (currentIndex + 3 >= length) { // Illegal escape sequence: not enough hex digits _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); return length; } int firstDigit = currentChar; int secondDigit = lexeme.codeUnitAt(currentIndex + 1); int thirdDigit = lexeme.codeUnitAt(currentIndex + 2); int fourthDigit = lexeme.codeUnitAt(currentIndex + 3); if (!_isHexDigit(firstDigit) || !_isHexDigit(secondDigit) || !_isHexDigit(thirdDigit) || !_isHexDigit(fourthDigit)) { // Illegal escape sequence: invalid hex digits _reportErrorForCurrentToken(ParserErrorCode.INVALID_UNICODE_ESCAPE); } else { _appendCodePoint( buffer, lexeme, (((((Character.digit(firstDigit, 16) << 4) + Character.digit(secondDigit, 16)) << 4) + Character.digit(thirdDigit, 16)) << 4) + Character.digit(fourthDigit, 16), index, currentIndex + 3); } return currentIndex + 4; } } else { buffer.writeCharCode(currentChar); } return currentIndex + 1; } /// Decrements the error reporting lock level. If level is more than `0`, then /// [reportError] wont report any error. void _unlockErrorListener() { if (_errorListenerLock == 0) { throw new StateError("Attempt to unlock not locked error listener."); } _errorListenerLock--; } /// Validate that the given [parameterList] does not contain any field /// initializers. void _validateFormalParameterList(FormalParameterList parameterList) { for (FormalParameter parameter in parameterList.parameters) { if (parameter is FieldFormalParameter) { _reportErrorForNode( ParserErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR, parameter.identifier); } } } /// Validate that the given set of [modifiers] is appropriate for a class and /// return the 'abstract' keyword if there is one. Token _validateModifiersForClass(Modifiers modifiers) { _validateModifiersForTopLevelDeclaration(modifiers); if (modifiers.constKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_CLASS, modifiers.constKeyword); } if (modifiers.externalKeyword != null) { _reportErrorForToken( ParserErrorCode.EXTERNAL_CLASS, modifiers.externalKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken(ParserErrorCode.FINAL_CLASS, modifiers.finalKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken(ParserErrorCode.VAR_CLASS, modifiers.varKeyword); } return modifiers.abstractKeyword; } /// Validate that the given set of [modifiers] is appropriate for a /// constructor and return the 'const' keyword if there is one. Token _validateModifiersForConstructor(Modifiers modifiers) { if (modifiers.abstractKeyword != null) { _reportErrorForToken( ParserErrorCode.ABSTRACT_CLASS_MEMBER, modifiers.abstractKeyword); } if (modifiers.covariantKeyword != null) { _reportErrorForToken( ParserErrorCode.COVARIANT_CONSTRUCTOR, modifiers.covariantKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken( ParserErrorCode.FINAL_CONSTRUCTOR, modifiers.finalKeyword); } if (modifiers.staticKeyword != null) { _reportErrorForToken( ParserErrorCode.STATIC_CONSTRUCTOR, modifiers.staticKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken( ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE, modifiers.varKeyword); } Token externalKeyword = modifiers.externalKeyword; Token constKeyword = modifiers.constKeyword; Token factoryKeyword = modifiers.factoryKeyword; if (externalKeyword != null && constKeyword != null && constKeyword.offset < externalKeyword.offset) { _reportErrorForToken( ParserErrorCode.EXTERNAL_AFTER_CONST, externalKeyword); } if (externalKeyword != null && factoryKeyword != null && factoryKeyword.offset < externalKeyword.offset) { _reportErrorForToken( ParserErrorCode.EXTERNAL_AFTER_FACTORY, externalKeyword); } return constKeyword; } /// Validate that the given set of [modifiers] is appropriate for an enum and /// return the 'abstract' keyword if there is one. void _validateModifiersForEnum(Modifiers modifiers) { _validateModifiersForTopLevelDeclaration(modifiers); if (modifiers.abstractKeyword != null) { _reportErrorForToken( ParserErrorCode.ABSTRACT_ENUM, modifiers.abstractKeyword); } if (modifiers.constKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_ENUM, modifiers.constKeyword); } if (modifiers.externalKeyword != null) { _reportErrorForToken( ParserErrorCode.EXTERNAL_ENUM, modifiers.externalKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken(ParserErrorCode.FINAL_ENUM, modifiers.finalKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken(ParserErrorCode.VAR_ENUM, modifiers.varKeyword); } } /// Validate that the given set of [modifiers] is appropriate for a field and /// return the 'final', 'const' or 'var' keyword if there is one. Token _validateModifiersForField(Modifiers modifiers) { if (modifiers.abstractKeyword != null) { _reportErrorForCurrentToken(ParserErrorCode.ABSTRACT_CLASS_MEMBER); } if (modifiers.externalKeyword != null) { _reportErrorForToken( ParserErrorCode.EXTERNAL_FIELD, modifiers.externalKeyword); } if (modifiers.factoryKeyword != null) { _reportErrorForToken( ParserErrorCode.NON_CONSTRUCTOR_FACTORY, modifiers.factoryKeyword); } Token staticKeyword = modifiers.staticKeyword; Token covariantKeyword = modifiers.covariantKeyword; Token constKeyword = modifiers.constKeyword; Token finalKeyword = modifiers.finalKeyword; Token varKeyword = modifiers.varKeyword; if (constKeyword != null) { if (covariantKeyword != null) { _reportErrorForToken( ParserErrorCode.CONST_AND_COVARIANT, covariantKeyword); } if (finalKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_AND_FINAL, finalKeyword); } if (varKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_AND_VAR, varKeyword); } if (staticKeyword != null && constKeyword.offset < staticKeyword.offset) { _reportErrorForToken(ParserErrorCode.STATIC_AFTER_CONST, staticKeyword); } } else if (finalKeyword != null) { if (covariantKeyword != null) { _reportErrorForToken( ParserErrorCode.FINAL_AND_COVARIANT, covariantKeyword); } if (varKeyword != null) { _reportErrorForToken(ParserErrorCode.FINAL_AND_VAR, varKeyword); } if (staticKeyword != null && finalKeyword.offset < staticKeyword.offset) { _reportErrorForToken(ParserErrorCode.STATIC_AFTER_FINAL, staticKeyword); } } else if (varKeyword != null) { if (staticKeyword != null && varKeyword.offset < staticKeyword.offset) { _reportErrorForToken(ParserErrorCode.STATIC_AFTER_VAR, staticKeyword); } if (covariantKeyword != null && varKeyword.offset < covariantKeyword.offset) { _reportErrorForToken( ParserErrorCode.COVARIANT_AFTER_VAR, covariantKeyword); } } if (covariantKeyword != null && staticKeyword != null) { _reportErrorForToken(ParserErrorCode.COVARIANT_AND_STATIC, staticKeyword); } return Token.lexicallyFirst([constKeyword, finalKeyword, varKeyword]); } /// Validate that the given set of [modifiers] is appropriate for a local /// function. void _validateModifiersForFunctionDeclarationStatement(Modifiers modifiers) { if (modifiers.abstractKeyword != null || modifiers.constKeyword != null || modifiers.externalKeyword != null || modifiers.factoryKeyword != null || modifiers.finalKeyword != null || modifiers.staticKeyword != null || modifiers.varKeyword != null) { _reportErrorForCurrentToken( ParserErrorCode.LOCAL_FUNCTION_DECLARATION_MODIFIER); } } /// Validate that the given set of [modifiers] is appropriate for a getter, /// setter, or method. void _validateModifiersForGetterOrSetterOrMethod(Modifiers modifiers) { if (modifiers.abstractKeyword != null) { _reportErrorForCurrentToken(ParserErrorCode.ABSTRACT_CLASS_MEMBER); } if (modifiers.constKeyword != null) { _reportErrorForToken( ParserErrorCode.CONST_METHOD, modifiers.constKeyword); } if (modifiers.covariantKeyword != null) { _reportErrorForToken( ParserErrorCode.COVARIANT_MEMBER, modifiers.covariantKeyword); } if (modifiers.factoryKeyword != null) { _reportErrorForToken( ParserErrorCode.NON_CONSTRUCTOR_FACTORY, modifiers.factoryKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken( ParserErrorCode.FINAL_METHOD, modifiers.finalKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken( ParserErrorCode.VAR_RETURN_TYPE, modifiers.varKeyword); } Token externalKeyword = modifiers.externalKeyword; Token staticKeyword = modifiers.staticKeyword; if (externalKeyword != null && staticKeyword != null && staticKeyword.offset < externalKeyword.offset) { _reportErrorForToken( ParserErrorCode.EXTERNAL_AFTER_STATIC, externalKeyword); } } /// Validate that the given set of [modifiers] is appropriate for a getter, /// setter, or method. void _validateModifiersForOperator(Modifiers modifiers) { if (modifiers.abstractKeyword != null) { _reportErrorForCurrentToken(ParserErrorCode.ABSTRACT_CLASS_MEMBER); } if (modifiers.constKeyword != null) { _reportErrorForToken( ParserErrorCode.CONST_METHOD, modifiers.constKeyword); } if (modifiers.factoryKeyword != null) { _reportErrorForToken( ParserErrorCode.NON_CONSTRUCTOR_FACTORY, modifiers.factoryKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken( ParserErrorCode.FINAL_METHOD, modifiers.finalKeyword); } if (modifiers.staticKeyword != null) { _reportErrorForToken( ParserErrorCode.STATIC_OPERATOR, modifiers.staticKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken( ParserErrorCode.VAR_RETURN_TYPE, modifiers.varKeyword); } } /// Validate that the given set of [modifiers] is appropriate for a top-level /// declaration. void _validateModifiersForTopLevelDeclaration(Modifiers modifiers) { if (modifiers.covariantKeyword != null) { _reportErrorForToken(ParserErrorCode.COVARIANT_TOP_LEVEL_DECLARATION, modifiers.covariantKeyword); } if (modifiers.factoryKeyword != null) { _reportErrorForToken(ParserErrorCode.FACTORY_TOP_LEVEL_DECLARATION, modifiers.factoryKeyword); } if (modifiers.staticKeyword != null) { _reportErrorForToken(ParserErrorCode.STATIC_TOP_LEVEL_DECLARATION, modifiers.staticKeyword); } } /// Validate that the given set of [modifiers] is appropriate for a top-level /// function. void _validateModifiersForTopLevelFunction(Modifiers modifiers) { _validateModifiersForTopLevelDeclaration(modifiers); if (modifiers.abstractKeyword != null) { _reportErrorForCurrentToken(ParserErrorCode.ABSTRACT_TOP_LEVEL_FUNCTION); } if (modifiers.constKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_CLASS, modifiers.constKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken(ParserErrorCode.FINAL_CLASS, modifiers.finalKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken( ParserErrorCode.VAR_RETURN_TYPE, modifiers.varKeyword); } } /// Validate that the given set of [modifiers] is appropriate for a field and /// return the 'final', 'const' or 'var' keyword if there is one. Token _validateModifiersForTopLevelVariable(Modifiers modifiers) { _validateModifiersForTopLevelDeclaration(modifiers); if (modifiers.abstractKeyword != null) { _reportErrorForCurrentToken(ParserErrorCode.ABSTRACT_TOP_LEVEL_VARIABLE); } if (modifiers.externalKeyword != null) { _reportErrorForToken( ParserErrorCode.EXTERNAL_FIELD, modifiers.externalKeyword); } Token constKeyword = modifiers.constKeyword; Token finalKeyword = modifiers.finalKeyword; Token varKeyword = modifiers.varKeyword; if (constKeyword != null) { if (finalKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_AND_FINAL, finalKeyword); } if (varKeyword != null) { _reportErrorForToken(ParserErrorCode.CONST_AND_VAR, varKeyword); } } else if (finalKeyword != null) { if (varKeyword != null) { _reportErrorForToken(ParserErrorCode.FINAL_AND_VAR, varKeyword); } } return Token.lexicallyFirst([constKeyword, finalKeyword, varKeyword]); } /// Validate that the given set of [modifiers] is appropriate for a class and /// return the 'abstract' keyword if there is one. void _validateModifiersForTypedef(Modifiers modifiers) { _validateModifiersForTopLevelDeclaration(modifiers); if (modifiers.abstractKeyword != null) { _reportErrorForToken( ParserErrorCode.ABSTRACT_TYPEDEF, modifiers.abstractKeyword); } if (modifiers.constKeyword != null) { _reportErrorForToken( ParserErrorCode.CONST_TYPEDEF, modifiers.constKeyword); } if (modifiers.externalKeyword != null) { _reportErrorForToken( ParserErrorCode.EXTERNAL_TYPEDEF, modifiers.externalKeyword); } if (modifiers.finalKeyword != null) { _reportErrorForToken( ParserErrorCode.FINAL_TYPEDEF, modifiers.finalKeyword); } if (modifiers.varKeyword != null) { _reportErrorForToken(ParserErrorCode.VAR_TYPEDEF, modifiers.varKeyword); } } } /// Instances of this class are thrown when the parser detects that AST has /// too many nested expressions to be parsed safely and avoid possibility of /// [StackOverflowError] in the parser or during later analysis. class _TooDeepTreeError {}
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/interner.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:front_end/src/scanner/interner.dart'; export 'package:front_end/src/scanner/interner.dart' show Interner, NullInterner; /** * The class `MappedInterner` implements an interner that uses a map to manage * the strings that have been interned. */ class MappedInterner implements Interner { /** * A table mapping strings to themselves. */ Map<String, String> _table = new HashMap<String, String>(); @override String intern(String string) { String original = _table[string]; if (original == null) { _table[string] = string; return string; } return original; } }
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/element_handle.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. @deprecated library analyzer.src.generated.element_handle; export 'package:analyzer/src/dart/element/handle.dart'; /** * TODO(scheglov) invalid implementation */ class WeakReference<T> { final T value; WeakReference(this.value); T get() => 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/generated/java_engine.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/src/generated/interner.dart'; import 'package:analyzer/src/generated/java_core.dart'; export 'package:analyzer/exception/exception.dart'; /** * A predicate is a one-argument function that returns a boolean value. */ typedef bool Predicate<E>(E argument); class FileNameUtilities { static String getExtension(String fileName) { if (fileName == null) { return ""; } int index = fileName.lastIndexOf('.'); if (index >= 0) { return fileName.substring(index + 1); } return ""; } } class StringUtilities { static const String EMPTY = ''; static const List<String> EMPTY_ARRAY = const <String>[]; static Interner INTERNER = new NullInterner(); /** * Compute line starts for the given [content]. * Lines end with `\r`, `\n` or `\r\n`. */ static List<int> computeLineStarts(String content) { List<int> lineStarts = <int>[0]; int length = content.length; int unit; for (int index = 0; index < length; index++) { unit = content.codeUnitAt(index); // Special-case \r\n. if (unit == 0x0D /* \r */) { // Peek ahead to detect a following \n. if ((index + 1 < length) && content.codeUnitAt(index + 1) == 0x0A) { // Line start will get registered at next index at the \n. } else { lineStarts.add(index + 1); } } // \n if (unit == 0x0A) { lineStarts.add(index + 1); } } return lineStarts; } static endsWith3(String str, int c1, int c2, int c3) { var length = str.length; return length >= 3 && str.codeUnitAt(length - 3) == c1 && str.codeUnitAt(length - 2) == c2 && str.codeUnitAt(length - 1) == c3; } static endsWithChar(String str, int c) { int length = str.length; return length > 0 && str.codeUnitAt(length - 1) == c; } static int indexOf1(String str, int start, int c) { int index = start; int last = str.length; while (index < last) { if (str.codeUnitAt(index) == c) { return index; } index++; } return -1; } static int indexOf2(String str, int start, int c1, int c2) { int index = start; int last = str.length - 1; while (index < last) { if (str.codeUnitAt(index) == c1 && str.codeUnitAt(index + 1) == c2) { return index; } index++; } return -1; } static int indexOf4( String string, int start, int c1, int c2, int c3, int c4) { int index = start; int last = string.length - 3; while (index < last) { if (string.codeUnitAt(index) == c1 && string.codeUnitAt(index + 1) == c2 && string.codeUnitAt(index + 2) == c3 && string.codeUnitAt(index + 3) == c4) { return index; } index++; } return -1; } static int indexOf5( String str, int start, int c1, int c2, int c3, int c4, int c5) { int index = start; int last = str.length - 4; while (index < last) { if (str.codeUnitAt(index) == c1 && str.codeUnitAt(index + 1) == c2 && str.codeUnitAt(index + 2) == c3 && str.codeUnitAt(index + 3) == c4 && str.codeUnitAt(index + 4) == c5) { return index; } index++; } return -1; } /** * Return the index of the first not letter/digit character in the [string] * that is at or after the [startIndex]. Return the length of the [string] if * all characters to the end are letters/digits. */ static int indexOfFirstNotLetterDigit(String string, int startIndex) { int index = startIndex; int last = string.length; while (index < last) { int c = string.codeUnitAt(index); if (!Character.isLetterOrDigit(c)) { return index; } index++; } return last; } static String intern(String string) => INTERNER.intern(string); static bool isEmpty(String s) { return s == null || s.isEmpty; } static bool isTagName(String s) { if (s == null || s.isEmpty) { return false; } int sz = s.length; for (int i = 0; i < sz; i++) { int c = s.codeUnitAt(i); if (!Character.isLetter(c)) { if (i == 0) { return false; } if (!Character.isDigit(c) && c != 0x2D) { return false; } } } return true; } /** * Produce a string containing all of the names in the given array, surrounded by single quotes, * and separated by commas. The list must contain at least two elements. * * @param names the names to be printed * @return the result of printing the names */ static String printListOfQuotedNames(List<String> names) { if (names == null) { throw new ArgumentError("The list must not be null"); } int count = names.length; if (count < 2) { throw new ArgumentError("The list must contain at least two names"); } StringBuffer buffer = new StringBuffer(); buffer.write("'"); buffer.write(names[0]); buffer.write("'"); for (int i = 1; i < count - 1; i++) { buffer.write(", '"); buffer.write(names[i]); buffer.write("'"); } buffer.write(" and '"); buffer.write(names[count - 1]); buffer.write("'"); return buffer.toString(); } static startsWith2(String str, int start, int c1, int c2) { return str.length - start >= 2 && str.codeUnitAt(start) == c1 && str.codeUnitAt(start + 1) == c2; } static startsWith3(String str, int start, int c1, int c2, int c3) { return str.length - start >= 3 && str.codeUnitAt(start) == c1 && str.codeUnitAt(start + 1) == c2 && str.codeUnitAt(start + 2) == c3; } static startsWith4(String str, int start, int c1, int c2, int c3, int c4) { return str.length - start >= 4 && str.codeUnitAt(start) == c1 && str.codeUnitAt(start + 1) == c2 && str.codeUnitAt(start + 2) == c3 && str.codeUnitAt(start + 3) == c4; } static startsWith5( String str, int start, int c1, int c2, int c3, int c4, int c5) { return str.length - start >= 5 && str.codeUnitAt(start) == c1 && str.codeUnitAt(start + 1) == c2 && str.codeUnitAt(start + 2) == c3 && str.codeUnitAt(start + 3) == c4 && str.codeUnitAt(start + 4) == c5; } static startsWith6( String str, int start, int c1, int c2, int c3, int c4, int c5, int c6) { return str.length - start >= 6 && str.codeUnitAt(start) == c1 && str.codeUnitAt(start + 1) == c2 && str.codeUnitAt(start + 2) == c3 && str.codeUnitAt(start + 3) == c4 && str.codeUnitAt(start + 4) == c5 && str.codeUnitAt(start + 5) == c6; } static startsWithChar(String str, int c) { return str.isNotEmpty && str.codeUnitAt(0) == c; } static String substringBefore(String str, String separator) { if (str == null || str.isEmpty) { return str; } if (separator == null) { return str; } int pos = str.indexOf(separator); if (pos < 0) { return str; } return str.substring(0, pos); } static String substringBeforeChar(String str, int c) { if (isEmpty(str)) { return str; } int pos = indexOf1(str, 0, c); if (pos < 0) { return str; } return str.substring(0, pos); } } class UUID { static int __nextId = 0; final String id; UUID(this.id); String toString() => id; static UUID randomUUID() => new UUID((__nextId).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/generated/source_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:collection'; import 'package:analyzer/exception/exception.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/java_io.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:path/path.dart' as path; export 'package:analyzer/src/generated/source.dart'; /** * Instances of the class [ExplicitSourceResolver] map URIs to files on disk * using a fixed mapping provided at construction time. */ @deprecated class ExplicitSourceResolver extends UriResolver { final Map<Uri, JavaFile> uriToFileMap; final Map<String, Uri> pathToUriMap; /** * Construct an [ExplicitSourceResolver] based on the given [uriToFileMap]. */ ExplicitSourceResolver(Map<Uri, JavaFile> uriToFileMap) : uriToFileMap = uriToFileMap, pathToUriMap = _computePathToUriMap(uriToFileMap); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { JavaFile file = uriToFileMap[uri]; actualUri ??= uri; if (file == null) { return null; } else { return new FileBasedSource(file, actualUri); } } @override Uri restoreAbsolute(Source source) { return pathToUriMap[source.fullName]; } /** * Build the inverse mapping of [uriToSourceMap]. */ static Map<String, Uri> _computePathToUriMap( Map<Uri, JavaFile> uriToSourceMap) { Map<String, Uri> pathToUriMap = <String, Uri>{}; uriToSourceMap.forEach((Uri uri, JavaFile file) { pathToUriMap[file.getAbsolutePath()] = uri; }); return pathToUriMap; } } /** * Instances of the class `FileBasedSource` implement a source that represents a file. */ class FileBasedSource extends Source { /** * A function that changes the way that files are read off of disk. */ static Function fileReadMode = (String s) => s; /** * Map from encoded URI/filepath pair to a unique integer identifier. This * identifier is used for equality tests and hash codes. * * The URI and filepath are joined into a pair by separating them with an '@' * character. */ static final Map<String, int> _idTable = new HashMap<String, int>(); /** * The URI from which this source was originally derived. */ @override final Uri uri; /** * The unique ID associated with this [FileBasedSource]. */ final int id; /** * The file represented by this source. */ final JavaFile file; /** * The cached absolute path of this source. */ String _absolutePath; /** * The cached encoding for this source. */ String _encoding; /** * Initialize a newly created source object to represent the given [file]. If * a [uri] is given, then it will be used as the URI from which the source was * derived, otherwise a `file:` URI will be created based on the [file]. */ FileBasedSource(JavaFile file, [Uri uri]) : this.uri = uri ?? file.toURI(), this.file = file, id = _idTable.putIfAbsent( '${uri ?? file.toURI()}@${file.getPath()}', () => _idTable.length); @override TimestampedData<String> get contents { return PerformanceStatistics.io.makeCurrentWhile(() { return contentsFromFile; }); } /** * Get the contents and timestamp of the underlying file. * * 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 of the source paired with the modification stamp of the source * @throws Exception if the contents of this source could not be accessed * See [contents]. */ TimestampedData<String> get contentsFromFile { return new TimestampedData<String>( file.lastModified(), fileReadMode(file.readAsStringSync())); } @override String get encoding { if (_encoding == null) { _encoding = uri.toString(); } return _encoding; } @override String get fullName { if (_absolutePath == null) { _absolutePath = file.getAbsolutePath(); } return _absolutePath; } @override int get hashCode => uri.hashCode; @override bool get isInSystemLibrary => uri.scheme == DartUriResolver.DART_SCHEME; @override int get modificationStamp => file.lastModified(); @override String get shortName => file.getName(); @override UriKind get uriKind { String scheme = uri.scheme; return UriKind.fromScheme(scheme); } @override bool operator ==(Object object) { if (object is FileBasedSource) { return id == object.id; } else if (object is Source) { return uri == object.uri; } return false; } @override bool exists() => file.isFile(); @override String toString() { if (file == null) { return "<unknown source>"; } return file.getAbsolutePath(); } } /** * Instances of the class `FileUriResolver` resolve `file` URI's. * * This class is now deprecated, 'new FileUriResolver()' is equivalent to * 'new ResourceUriResolver(PhysicalResourceProvider.INSTANCE)'. */ @deprecated class FileUriResolver extends UriResolver { /** * The name of the `file` scheme. */ static String FILE_SCHEME = "file"; @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!isFileUri(uri)) { return null; } return new FileBasedSource(new JavaFile.fromUri(uri), actualUri ?? uri); } @override Uri restoreAbsolute(Source source) { return new Uri.file(source.fullName); } /** * Return `true` if the given URI is a `file` URI. * * @param uri the URI being tested * @return `true` if the given URI is a `file` URI */ static bool isFileUri(Uri uri) => uri.scheme == FILE_SCHEME; } /** * 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; } /** * Instances of the class `PackageUriResolver` resolve `package` URI's in the context of * an application. * * For the purposes of sharing analysis, the path to each package under the "packages" directory * should be canonicalized, but to preserve relative links within a package, the remainder of the * path from the package directory to the leaf should not. */ @deprecated class PackageUriResolver extends UriResolver { /** * The name of the `package` scheme. */ static String PACKAGE_SCHEME = "package"; /** * Log exceptions thrown with the message "Required key not available" only once. */ static bool _CanLogRequiredKeyIoException = true; /** * The package directories that `package` URI's are assumed to be relative to. */ final List<JavaFile> _packagesDirectories; /** * Initialize a newly created resolver to resolve `package` URI's relative to the given * package directories. * * @param packagesDirectories the package directories that `package` URI's are assumed to be * relative to */ PackageUriResolver(this._packagesDirectories) { if (_packagesDirectories.isEmpty) { throw new ArgumentError( "At least one package directory must be provided"); } } /** * If the list of package directories contains one element, return it. * Otherwise raise an exception. Intended for testing. */ String get packagesDirectory_forTesting { int length = _packagesDirectories.length; if (length != 1) { throw new Exception('Expected 1 package directory, found $length'); } return _packagesDirectories[0].getPath(); } /** * Answer the canonical file for the specified package. * * @param packagesDirectory the "packages" directory (not `null`) * @param pkgName the package name (not `null`, not empty) * @param relPath the path relative to the package directory (not `null`, no leading slash, * but may be empty string) * @return the file (not `null`) */ JavaFile getCanonicalFile( JavaFile packagesDirectory, String pkgName, String relPath) { JavaFile pkgDir = new JavaFile.relative(packagesDirectory, pkgName); try { pkgDir = pkgDir.getCanonicalFile(); } catch (exception, stackTrace) { if (!exception.toString().contains("Required key not available")) { AnalysisEngine.instance.logger.logError("Canonical failed: $pkgDir", new CaughtException(exception, stackTrace)); } else if (_CanLogRequiredKeyIoException) { _CanLogRequiredKeyIoException = false; AnalysisEngine.instance.logger.logError("Canonical failed: $pkgDir", new CaughtException(exception, stackTrace)); } } return new JavaFile.relative( pkgDir, relPath.replaceAll( '/', new String.fromCharCode(JavaFile.separatorChar))); } @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!isPackageUri(uri)) { return null; } String path = uri.path; if (path == null) { path = uri.path; if (path == null) { return null; } } String pkgName; String relPath; int index = path.indexOf('/'); if (index == -1) { // No slash pkgName = path; relPath = ""; } else if (index == 0) { // Leading slash is invalid return null; } else { // <pkgName>/<relPath> pkgName = path.substring(0, index); relPath = path.substring(index + 1); } for (JavaFile packagesDirectory in _packagesDirectories) { JavaFile resolvedFile = new JavaFile.relative(packagesDirectory, path); if (resolvedFile.exists()) { JavaFile canonicalFile = getCanonicalFile(packagesDirectory, pkgName, relPath); if (actualUri != null) { return new FileBasedSource(canonicalFile, actualUri); } if (_isSelfReference(packagesDirectory, canonicalFile)) { uri = canonicalFile.toURI(); } return new FileBasedSource(canonicalFile, uri); } } return new FileBasedSource( getCanonicalFile(_packagesDirectories[0], pkgName, relPath), actualUri ?? uri); } @override Uri restoreAbsolute(Source source) { String sourceUri = _toFileUri(source.fullName); for (JavaFile packagesDirectory in _packagesDirectories) { List<JavaFile> pkgFolders = packagesDirectory.listFiles(); if (pkgFolders != null) { for (JavaFile pkgFolder in pkgFolders) { try { String pkgCanonicalUri = _toFileUri(pkgFolder.getCanonicalPath()); if (sourceUri.startsWith(pkgCanonicalUri)) { String relPath = sourceUri.substring(pkgCanonicalUri.length); return Uri.parse( "$PACKAGE_SCHEME:${pkgFolder.getName()}$relPath"); } } catch (e) {} } } } return null; } /** * @return `true` if "file" was found in "packagesDir", and it is part of the "lib" folder * of the application that contains in this "packagesDir". */ bool _isSelfReference(JavaFile packagesDir, JavaFile file) { JavaFile rootDir = packagesDir.getParentFile(); if (rootDir == null) { return false; } String rootPath = rootDir.getAbsolutePath(); String filePath = file.getAbsolutePath(); return filePath.startsWith("$rootPath/lib"); } /** * Convert the given file path to a "file:" URI. On Windows, this transforms * backslashes to forward slashes. */ String _toFileUri(String filePath) => path.context.toUri(filePath).toString(); /** * Return `true` if the given URI is a `package` URI. * * @param uri the URI being tested * @return `true` if the given URI is a `package` URI */ static bool isPackageUri(Uri uri) => PACKAGE_SCHEME == uri.scheme; } /** * Instances of the class `RelativeFileUriResolver` resolve `file` URI's. * * This class is now deprecated, file URI resolution should be done with * ResourceUriResolver, i.e. * 'new ResourceUriResolver(PhysicalResourceProvider.INSTANCE)'. */ @deprecated class RelativeFileUriResolver extends UriResolver { /** * The name of the `file` scheme. */ static String FILE_SCHEME = "file"; /** * The directories for the relatvie URI's */ final List<JavaFile> _relativeDirectories; /** * The root directory for all the source trees */ final JavaFile _rootDirectory; /** * Initialize a newly created resolver to resolve `file` URI's relative to the given root * directory. */ RelativeFileUriResolver(this._rootDirectory, this._relativeDirectories) : super(); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { String rootPath = _rootDirectory.toURI().path; String uriPath = uri.path; if (uriPath != null && uriPath.startsWith(rootPath)) { String filePath = uri.path.substring(rootPath.length); for (JavaFile dir in _relativeDirectories) { JavaFile file = new JavaFile.relative(dir, filePath); if (file.exists()) { return new FileBasedSource(file, actualUri ?? uri); } } } return null; } /** * Return `true` if the given URI is a `file` URI. * * @param uri the URI being tested * @return `true` if the given URI is a `file` URI */ static bool isFileUri(Uri uri) => uri.scheme == FILE_SCHEME; }
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_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:path/path.dart' as path; class JavaFile { @deprecated static path.Context pathContext = path.context; static final String separator = Platform.pathSeparator; static final int separatorChar = Platform.pathSeparator.codeUnitAt(0); String _path; JavaFile(String path) { _path = path; } JavaFile.fromUri(Uri uri) : this(path.context.fromUri(uri)); JavaFile.relative(JavaFile base, String child) { if (child.isEmpty) { this._path = base._path; } else { this._path = path.context.join(base._path, child); } } @override int get hashCode => _path.hashCode; @override bool operator ==(other) { return other is JavaFile && other._path == _path; } bool exists() { if (_newFile().existsSync()) { return true; } if (_newDirectory().existsSync()) { return true; } return false; } JavaFile getAbsoluteFile() => new JavaFile(getAbsolutePath()); String getAbsolutePath() { String abolutePath = path.context.absolute(_path); abolutePath = path.context.normalize(abolutePath); return abolutePath; } JavaFile getCanonicalFile() => new JavaFile(getCanonicalPath()); String getCanonicalPath() { return _newFile().resolveSymbolicLinksSync(); } String getName() => path.context.basename(_path); String getParent() { var result = path.context.dirname(_path); // "." or "/" or "C:\" if (result.length < 4) return null; return result; } JavaFile getParentFile() { var parent = getParent(); if (parent == null) return null; return new JavaFile(parent); } String getPath() => _path; bool isDirectory() { return _newDirectory().existsSync(); } bool isExecutable() { return _newFile().statSync().mode & 0x111 != 0; } bool isFile() { return _newFile().existsSync(); } int lastModified() { try { return _newFile().lastModifiedSync().millisecondsSinceEpoch; } catch (exception) { return -1; } } List<JavaFile> listFiles() { var files = <JavaFile>[]; var entities = _newDirectory().listSync(); for (FileSystemEntity entity in entities) { files.add(new JavaFile(entity.path)); } return files; } String readAsStringSync() => _newFile().readAsStringSync(); @override String toString() => _path.toString(); Uri toURI() { String absolutePath = getAbsolutePath(); return path.context.toUri(absolutePath); } Directory _newDirectory() => new Directory(_path); File _newFile() => new File(_path); } @Deprecated("Only used by `DirectoryBasedDartSdk`, which is also deprecated.") class JavaSystemIO { static Map<String, String> _properties = new Map(); static String getenv(String name) => Platform.environment[name]; static String getProperty(String name) { { String value = _properties[name]; if (value != null) { return value; } } if (name == 'os.name') { return Platform.operatingSystem; } if (name == 'line.separator') { if (Platform.isWindows) { return '\r\n'; } return '\n'; } if (name == 'com.google.dart.sdk') { String exec = Platform.executable; if (exec.isNotEmpty) { String sdkPath; // may be "xcodebuild/ReleaseIA32/dart" with "sdk" sibling { var outDir = path.context.dirname(path.context.dirname(exec)); sdkPath = path.context.join(path.context.dirname(outDir), "sdk"); if (new Directory(sdkPath).existsSync()) { _properties[name] = sdkPath; return sdkPath; } } // probably be "dart-sdk/bin/dart" sdkPath = path.context.dirname(path.context.dirname(exec)); _properties[name] = sdkPath; return sdkPath; } } return null; } /// Only needed when when using `DirectoryBasedDartSdk`, which is also /// deprecated. /// /// When using `FolderBasedDartSdk`, there is no need to set /// `com.google.dart.sdk`. @deprecated static String setProperty(String name, String value) { String oldValue = _properties[name]; _properties[name] = value; return oldValue; } }
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/scanner.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. @deprecated library analyzer.src.generated.scanner; export 'package:analyzer/dart/ast/token.dart'; export 'package:analyzer/src/dart/ast/token.dart' hide SimpleToken; export 'package:analyzer/src/dart/scanner/reader.dart'; export 'package:analyzer/src/dart/scanner/scanner.dart';
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/declaration_resolver.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 '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/exception/exception.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/builder.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/generated/resolver.dart'; /// A visitor that resolves declarations in an AST structure to already built /// elements. /// /// The resulting AST must have everything resolved that would have been /// resolved by a [CompilationUnitBuilder] (that is, must be a valid /// [RESOLVED_UNIT1]). This class must not assume that the /// [CompilationUnitElement] passed to it is any more complete than a /// [COMPILATION_UNIT_ELEMENT]. class DeclarationResolver extends RecursiveAstVisitor<void> { /// The compilation unit containing the AST nodes being visited. CompilationUnitElementImpl _enclosingUnit; /// The [ElementWalker] we are using to keep track of progress through the /// element model. ElementWalker _walker; DeclarationResolver(); /// Resolve the declarations within the given compilation [unit] to the /// elements rooted at the given [element]. Throw an /// [ElementMismatchException] if the element model and compilation unit do /// not match each other. void resolve(CompilationUnit unit, CompilationUnitElement element) { _enclosingUnit = element; _walker = new ElementWalker.forCompilationUnit(element); unit.element = element; try { unit.accept(this); _walker.validate(); } on Error catch (e, st) { throw new _ElementMismatchException( element, _walker.element, new CaughtException(e, st)); } } @override void visitAnnotation(Annotation node) { // Annotations can only contain elements in certain erroneous situations, // in which case the elements are disconnected from the rest of the element // model, thus we can't reconnect to them. To avoid crashes, just create // fresh elements. ElementHolder elementHolder = new ElementHolder(); new ElementBuilder(elementHolder, _enclosingUnit).visitAnnotation(node); } @override void visitBlockFunctionBody(BlockFunctionBody node) { if (_isBodyToCreateElementsFor(node)) { _walker.consumeLocalElements(); node.accept(_walker.elementBuilder); } else { super.visitBlockFunctionBody(node); } } @override void visitCatchClause(CatchClause node) { _walker.elementBuilder.buildCatchVariableElements(node); super.visitCatchClause(node); } @override void visitClassDeclaration(ClassDeclaration node) { ClassElement element = _match(node.name, _walker.getClass()); _walk(new ElementWalker.forClass(element), () { super.visitClassDeclaration(node); }); resolveMetadata(node, node.metadata, element); } @override void visitClassTypeAlias(ClassTypeAlias node) { ClassElement element = _match(node.name, _walker.getClass()); _walk(new ElementWalker.forClass(element), () { super.visitClassTypeAlias(node); }); resolveMetadata(node, node.metadata, element); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { ConstructorElement element = _match(node.name, _walker.getConstructor(), offset: node.name?.offset ?? node.returnType.offset); _walk(new ElementWalker.forExecutable(element, _enclosingUnit), () { (node as ConstructorDeclarationImpl).declaredElement = element; super.visitConstructorDeclaration(node); }); resolveMetadata(node, node.metadata, element); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { // Declared identifiers can only occur inside executable elements. _walker.elementBuilder.visitDeclaredIdentifier(node); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { NormalFormalParameter normalParameter = node.parameter; ParameterElement element = _match(normalParameter.identifier, _walker.getParameter()); if (normalParameter is SimpleFormalParameterImpl) { normalParameter.declaredElement = element; _setGenericFunctionType(normalParameter.type, element.type); } if (normalParameter is FieldFormalParameterImpl) { _setGenericFunctionType(normalParameter.type, element.type); } Expression defaultValue = node.defaultValue; if (defaultValue != null) { _walk( new ElementWalker.forExecutable(element.initializer, _enclosingUnit), () { defaultValue.accept(this); }); } _walk(new ElementWalker.forParameter(element), () { normalParameter.accept(this); }); resolveMetadata(node, node.metadata, element); } @override void visitEnumDeclaration(EnumDeclaration node) { ClassElement element = _match(node.name, _walker.getEnum()); resolveMetadata(node, node.metadata, element); _walk(new ElementWalker.forClass(element), () { for (EnumConstantDeclaration constant in node.constants) { VariableElement field = _match(constant.name, _walker.getVariable()); resolveMetadata(node, constant.metadata, field); constant.name.staticElement = field; constant.name.staticType = field.type; } _walker.getFunction(); // toString() super.visitEnumDeclaration(node); }); } @override void visitExportDirective(ExportDirective node) { super.visitExportDirective(node); List<ElementAnnotation> annotations = _enclosingUnit.getAnnotations(node.offset); if (annotations.isEmpty && node.metadata.isNotEmpty) { int index = (node.parent as CompilationUnit) .directives .where((directive) => directive is ExportDirective) .toList() .indexOf(node); annotations = _walker.element.library.exports[index].metadata; } resolveAnnotations(node, node.metadata, annotations); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { if (_isBodyToCreateElementsFor(node)) { _walker.consumeLocalElements(); node.accept(_walker.elementBuilder); } else { super.visitExpressionFunctionBody(node); } } @override void visitExtensionDeclaration(ExtensionDeclaration node) { ExtensionElement element = _match(node.name, _walker.getExtension()); (node as ExtensionDeclarationImpl).declaredElement = element; _walk(new ElementWalker.forExtension(element), () { super.visitExtensionDeclaration(node); }); resolveMetadata(node, node.metadata, element); } @override void visitFieldDeclaration(FieldDeclaration node) { super.visitFieldDeclaration(node); FieldElement firstFieldElement = node.fields.variables[0].declaredElement; resolveMetadata(node, node.metadata, firstFieldElement); } @override void visitFieldFormalParameter(FieldFormalParameter node) { if (node.parent is! DefaultFormalParameter) { ParameterElement element = _match(node.identifier, _walker.getParameter()); _walk(new ElementWalker.forParameter(element), () { super.visitFieldFormalParameter(node); }); resolveMetadata(node, node.metadata, element); _setGenericFunctionType(node.type, element.type); } else { super.visitFieldFormalParameter(node); } } @override void visitFunctionDeclaration(FunctionDeclaration node) { SimpleIdentifier functionName = node.name; Token property = node.propertyKeyword; ExecutableElement element; if (property == null) { element = _match(functionName, _walker.getFunction()); } else { if (_walker.element is ExecutableElement) { element = _match(functionName, _walker.getFunction()); } else if (property.keyword == Keyword.GET) { element = _match(functionName, _walker.getAccessor()); } else { assert(property.keyword == Keyword.SET); element = _match(functionName, _walker.getAccessor(), elementName: functionName.name + '='); } } _setGenericFunctionType(node.returnType, element.returnType); (node.functionExpression as FunctionExpressionImpl).declaredElement = element; node.returnType?.accept(this); _walker._elementHolder?.addFunction(element); _walk(new ElementWalker.forExecutable(element, _enclosingUnit), () { super.visitFunctionDeclaration(node); }); resolveMetadata(node, node.metadata, element); } @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is! FunctionDeclaration) { node.accept(_walker.elementBuilder); } else { super.visitFunctionExpression(node); } } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { FunctionTypeAliasElement element = _match(node.name, _walker.getTypedef()); _walk(new ElementWalker.forTypedef(element), () { super.visitFunctionTypeAlias(node); }); resolveMetadata(node, node.metadata, element); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { if (node.parent is! DefaultFormalParameter) { ParameterElement element = _match(node.identifier, _walker.getParameter()); _walk(new ElementWalker.forParameter(element), () { super.visitFunctionTypedFormalParameter(node); }); resolveMetadata(node, node.metadata, element); } else { super.visitFunctionTypedFormalParameter(node); } } @override void visitGenericFunctionType(GenericFunctionType node) { var builder = new LocalElementBuilder(ElementHolder(), _enclosingUnit); node.accept(builder); var nodeImpl = node as GenericFunctionTypeImpl; _enclosingUnit.encloseElement( nodeImpl.declaredElement as GenericFunctionTypeElementImpl, ); } @override void visitGenericTypeAlias(GenericTypeAlias node) { GenericTypeAliasElementImpl element = _match(node.name, _walker.getTypedef()); _setGenericFunctionType(node.functionType, element.function?.type); _walk(new ElementWalker.forGenericTypeAlias(element), () { super.visitGenericTypeAlias(node); }); resolveMetadata(node, node.metadata, element); } @override void visitImportDirective(ImportDirective node) { super.visitImportDirective(node); List<ElementAnnotation> annotations = _enclosingUnit.getAnnotations(node.offset); if (annotations.isEmpty && node.metadata.isNotEmpty) { int index = (node.parent as CompilationUnit) .directives .where((directive) => directive is ImportDirective) .toList() .indexOf(node); annotations = _walker.element.library.imports[index].metadata; } resolveAnnotations(node, node.metadata, annotations); } @override void visitLabeledStatement(LabeledStatement node) { bool onSwitchStatement = node.statement is SwitchStatement; _walker.elementBuilder .buildLabelElements(node.labels, onSwitchStatement, false); super.visitLabeledStatement(node); } @override void visitLibraryDirective(LibraryDirective node) { super.visitLibraryDirective(node); List<ElementAnnotation> annotations = _enclosingUnit.getAnnotations(node.offset); if (annotations.isEmpty && node.metadata.isNotEmpty) { annotations = _walker.element.library.metadata; } resolveAnnotations(node, node.metadata, annotations); } @override void visitMethodDeclaration(MethodDeclaration node) { Token property = node.propertyKeyword; SimpleIdentifier methodName = node.name; String nameOfMethod = methodName.name; ExecutableElement element; if (property == null) { String elementName = nameOfMethod == '-' && node.parameters != null && node.parameters.parameters.isEmpty ? 'unary-' : nameOfMethod; element = _match(methodName, _walker.getFunction(), elementName: elementName); } else { if (property.keyword == Keyword.GET) { element = _match(methodName, _walker.getAccessor()); } else { assert(property.keyword == Keyword.SET); element = _match(methodName, _walker.getAccessor(), elementName: nameOfMethod + '='); } } _setGenericFunctionType(node.returnType, element.returnType); node.returnType?.accept(this); _walk(new ElementWalker.forExecutable(element, _enclosingUnit), () { super.visitMethodDeclaration(node); }); resolveMetadata(node, node.metadata, element); } @override void visitMixinDeclaration(MixinDeclaration node) { ClassElement element = _match(node.name, _walker.getMixin()); _walk(new ElementWalker.forClass(element), () { super.visitMixinDeclaration(node); }); resolveMetadata(node, node.metadata, element); } @override void visitPartDirective(PartDirective node) { super.visitPartDirective(node); List<ElementAnnotation> annotations = _enclosingUnit.getAnnotations(node.offset); if (annotations.isEmpty && node.metadata.isNotEmpty) { int index = (node.parent as CompilationUnit) .directives .where((directive) => directive is PartDirective) .toList() .indexOf(node); annotations = _walker.element.library.parts[index].metadata; } resolveAnnotations(node, node.metadata, annotations); } @override void visitPartOfDirective(PartOfDirective node) { node.element = _enclosingUnit.library; super.visitPartOfDirective(node); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { if (node.parent is! DefaultFormalParameter) { ParameterElement element = _match(node.identifier, _walker.getParameter()); (node as SimpleFormalParameterImpl).declaredElement = element; _setGenericFunctionType(node.type, element.type); _walk(new ElementWalker.forParameter(element), () { super.visitSimpleFormalParameter(node); }); resolveMetadata(node, node.metadata, element); } else { super.visitSimpleFormalParameter(node); } } @override void visitSwitchCase(SwitchCase node) { _walker.elementBuilder.buildLabelElements(node.labels, false, true); super.visitSwitchCase(node); } @override void visitSwitchDefault(SwitchDefault node) { _walker.elementBuilder.buildLabelElements(node.labels, false, true); super.visitSwitchDefault(node); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { super.visitTopLevelVariableDeclaration(node); VariableElement firstElement = node.variables.variables[0].declaredElement; resolveMetadata(node, node.metadata, firstElement); } @override void visitTypeParameter(TypeParameter node) { TypeParameterElement element = _match(node.name, _walker.getTypeParameter()); _setGenericFunctionType(node.bound, element.bound); super.visitTypeParameter(node); resolveMetadata(node, node.metadata, element); } @override void visitVariableDeclaration(VariableDeclaration node) { VariableElement element = _match(node.name, _walker.getVariable()); Expression initializer = node.initializer; if (initializer != null) { _walk( new ElementWalker.forExecutable(element.initializer, _enclosingUnit), () { super.visitVariableDeclaration(node); }); } else { super.visitVariableDeclaration(node); } } @override void visitVariableDeclarationList(VariableDeclarationList node) { if (_walker.elementBuilder != null) { _walker.elementBuilder.visitVariableDeclarationList(node); } else { node.variables.accept(this); VariableElement firstVariable = node.variables[0].declaredElement; _setGenericFunctionType(node.type, firstVariable.type); node.type?.accept(this); if (node.parent is! FieldDeclaration && node.parent is! TopLevelVariableDeclaration) { resolveMetadata(node, node.metadata, firstVariable); } } } /// Updates [identifier] to point to [element], after ensuring that the /// element has the expected name. /// /// If no [elementName] is given, it defaults to the name of the [identifier] /// (or the empty string if [identifier] is `null`). /// /// If [identifier] is `null`, nothing is updated, but the element name is /// still checked. E _match<E extends Element>(SimpleIdentifier identifier, E element, {String elementName, int offset}) { elementName ??= identifier?.name ?? ''; offset ??= identifier?.offset ?? -1; if (element.name != elementName) { throw new StateError( 'Expected an element matching `$elementName`, got `${element.name}`'); } identifier?.staticElement = element; _matchOffset(element, offset); return element; } void _matchOffset(Element element, int offset) { if (element.nameOffset > 0 && element.nameOffset != offset) { throw new StateError('Element offset mismatch'); } else { (element as ElementImpl).nameOffset = offset; } } /// If the given [typeNode] is a [GenericFunctionType], set its [type]. void _setGenericFunctionType(TypeAnnotation typeNode, DartType type) { if (typeNode is GenericFunctionTypeImpl) { typeNode.type = type; typeNode.declaredElement = type.element; } else if (typeNode is NamedType) { typeNode.type = type; if (type is ParameterizedType) { List<TypeAnnotation> nodes = typeNode.typeArguments?.arguments ?? const []; List<DartType> types = type.typeArguments; if (nodes.length == types.length) { for (int i = 0; i < nodes.length; i++) { _setGenericFunctionType(nodes[i], types[i]); } } } } } /// Recurses through the element model and AST, verifying that all elements /// are matched. /// /// Executes [callback] with [_walker] pointing to the given [walker] (which /// should be a new instance of [ElementWalker]). Once [callback] returns, /// uses [ElementWalker.validate] to verify that all expected elements have /// been matched. void _walk(ElementWalker walker, void callback()) { ElementWalker outerWalker = _walker; _walker = walker; callback(); walker.validate(); _walker = outerWalker; } /// Associate each of the annotation [nodes] with the corresponding /// [ElementAnnotation] in [annotations]. If there is a problem, report it /// against the given [parent] node. static void resolveAnnotations(AstNode parent, NodeList<Annotation> nodes, List<ElementAnnotation> annotations) { int nodeCount = nodes.length; if (nodeCount != annotations.length) { throw new StateError('Found $nodeCount annotation nodes and ' '${annotations.length} element annotations'); } for (int i = 0; i < nodeCount; i++) { nodes[i].elementAnnotation = annotations[i]; } } /// If [element] is not `null`, associate each of the annotation [nodes] with /// the corresponding [ElementAnnotation] in [element.metadata]. If there is a /// problem, report it against the given [parent] node. /// /// If [element] is `null`, do nothing--this allows us to be robust in the /// case where we are operating on an element model that hasn't been fully /// built. static void resolveMetadata( AstNode parent, NodeList<Annotation> nodes, Element element) { if (element != null) { resolveAnnotations(parent, nodes, element.metadata); } } static bool _isBodyToCreateElementsFor(FunctionBody node) { AstNode parent = node.parent; return parent is ConstructorDeclaration || parent is MethodDeclaration || parent.parent is FunctionDeclaration && parent.parent.parent is CompilationUnit; } } /// Keeps track of the set of non-synthetic child elements of an element, /// yielding them one at a time in response to "get" method calls. class ElementWalker { /// The element whose child elements are being walked. final Element element; /// If [element] is an executable element, an element builder which is /// accumulating the executable element's local variables and labels. /// Otherwise `null`. LocalElementBuilder elementBuilder; /// If [element] is an executable element, the element holder associated with /// [elementBuilder]. Otherwise `null`. ElementHolder _elementHolder; List<PropertyAccessorElement> _accessors; int _accessorIndex = 0; List<ClassElement> _classes; int _classIndex = 0; List<ConstructorElement> _constructors; int _constructorIndex = 0; List<ClassElement> _enums; int _enumIndex = 0; List<ExtensionElement> _extensions; int _extensionIndex = 0; List<ExecutableElement> _functions; int _functionIndex = 0; List<ClassElement> _mixins; int _mixinIndex = 0; List<ParameterElement> _parameters; int _parameterIndex = 0; List<FunctionTypeAliasElement> _typedefs; int _typedefIndex = 0; List<TypeParameterElement> _typeParameters; int _typeParameterIndex = 0; List<VariableElement> _variables; int _variableIndex = 0; /// Creates an [ElementWalker] which walks the child elements of a class /// element. ElementWalker.forClass(ClassElement element) : element = element, _accessors = element.accessors.where(_isNotSynthetic).toList(), _constructors = element.isMixinApplication ? null : element.constructors.where(_isNotSynthetic).toList(), _functions = element.methods, _typeParameters = element.typeParameters, _variables = element.fields.where(_isNotSynthetic).toList(); /// Creates an [ElementWalker] which walks the child elements of a compilation /// unit element. ElementWalker.forCompilationUnit(CompilationUnitElement compilationUnit) : element = compilationUnit, _accessors = compilationUnit.accessors.where(_isNotSynthetic).toList(), _classes = compilationUnit.types, _enums = compilationUnit.enums, _extensions = compilationUnit.extensions, _functions = compilationUnit.functions, _mixins = compilationUnit.mixins, _typedefs = compilationUnit.functionTypeAliases, _variables = compilationUnit.topLevelVariables.where(_isNotSynthetic).toList(); /// Creates an [ElementWalker] which walks the child elements of a compilation /// unit element. ElementWalker.forExecutable( ExecutableElement element, CompilationUnitElement compilationUnit) : this._forExecutable(element, compilationUnit, new ElementHolder()); /// Creates an [ElementWalker] which walks the child elements of an extension /// element. ElementWalker.forExtension(ExtensionElement element) : element = element, _accessors = element.accessors.where(_isNotSynthetic).toList(), _functions = element.methods, _typeParameters = element.typeParameters, _variables = element.fields.where(_isNotSynthetic).toList(); /// Creates an [ElementWalker] which walks the child elements of a typedef /// element. ElementWalker.forGenericFunctionType(GenericFunctionTypeElement element) : element = element, _parameters = element.parameters, _typeParameters = element.typeParameters; /// Creates an [ElementWalker] which walks the child elements of a typedef /// element defined using a generic function type. ElementWalker.forGenericTypeAlias(FunctionTypeAliasElement element) : element = element, _typeParameters = element.typeParameters; /// Creates an [ElementWalker] which walks the child elements of a parameter /// element. ElementWalker.forParameter(ParameterElement element) : element = element, _parameters = element.parameters, _typeParameters = element.typeParameters; /// Creates an [ElementWalker] which walks the child elements of a typedef /// element. ElementWalker.forTypedef(GenericTypeAliasElementImpl element) : element = element, _parameters = element.parameters, _typeParameters = element.typeParameters; ElementWalker._forExecutable(ExecutableElement element, CompilationUnitElement compilationUnit, ElementHolder elementHolder) : element = element, elementBuilder = new LocalElementBuilder(elementHolder, compilationUnit), _elementHolder = elementHolder, _functions = const <ExecutableElement>[], _parameters = element.parameters, _typeParameters = element.typeParameters; void consumeLocalElements() { _functionIndex = _functions.length; } void consumeParameters() { _parameterIndex = _parameters.length; } /// Returns the next non-synthetic child of [element] which is an accessor; /// throws an [IndexError] if there are no more. PropertyAccessorElement getAccessor() => _accessors[_accessorIndex++]; /// Returns the next non-synthetic child of [element] which is a class; throws /// an [IndexError] if there are no more. ClassElement getClass() => _classes[_classIndex++]; /// Returns the next non-synthetic child of [element] which is a constructor; /// throws an [IndexError] if there are no more. ConstructorElement getConstructor() => _constructors[_constructorIndex++]; /// Returns the next non-synthetic child of [element] which is an enum; throws /// an [IndexError] if there are no more. ClassElement getEnum() => _enums[_enumIndex++]; ExtensionElement getExtension() => _extensions[_extensionIndex++]; /// Returns the next non-synthetic child of [element] which is a top level /// function, method, or local function; throws an [IndexError] if there are /// no more. ExecutableElement getFunction() => _functions[_functionIndex++]; /// Returns the next non-synthetic child of [element] which is a mixin; throws /// an [IndexError] if there are no more. ClassElement getMixin() => _mixins[_mixinIndex++]; /// Returns the next non-synthetic child of [element] which is a parameter; /// throws an [IndexError] if there are no more. ParameterElement getParameter() => _parameters[_parameterIndex++]; /// Returns the next non-synthetic child of [element] which is a typedef; /// throws an [IndexError] if there are no more. FunctionTypeAliasElement getTypedef() => _typedefs[_typedefIndex++]; /// Returns the next non-synthetic child of [element] which is a type /// parameter; throws an [IndexError] if there are no more. TypeParameterElement getTypeParameter() => _typeParameters[_typeParameterIndex++]; /// Returns the next non-synthetic child of [element] which is a top level /// variable, field, or local variable; throws an [IndexError] if there are no /// more. VariableElement getVariable() => _variables[_variableIndex++]; /// Verifies that all non-synthetic children of [element] have been obtained /// from their corresponding "get" method calls; if not, throws a /// [StateError]. void validate() { void check(List<Element> elements, int index) { if (elements != null && elements.length != index) { throw new StateError( 'Unmatched ${elements[index].runtimeType} ${elements[index]}'); } } check(_accessors, _accessorIndex); check(_classes, _classIndex); check(_constructors, _constructorIndex); check(_enums, _enumIndex); check(_functions, _functionIndex); check(_parameters, _parameterIndex); check(_typedefs, _typedefIndex); check(_typeParameters, _typeParameterIndex); check(_variables, _variableIndex); Element element = this.element; if (element is ExecutableElementImpl) { element.encloseElements(_elementHolder.functions); element.encloseElements(_elementHolder.labels); element.encloseElements(_elementHolder.localVariables); } } static bool _isNotSynthetic(Element e) => !e.isSynthetic; } class _ElementMismatchException extends AnalysisException { /// Creates an exception to refer to the given [compilationUnit], [element], /// and [cause]. _ElementMismatchException( CompilationUnitElement compilationUnit, Element element, [CaughtException cause]) : super('Element mismatch in $compilationUnit at $element', cause); }
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/timestamped_data.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. /** * Analysis data for which we have a modification time. */ class TimestampedData<E> { /** * The modification time of the source from which the data was created. */ final int modificationTime; /** * The data that was created from the source. */ final E data; /** * Initialize a newly created holder to associate the given [data] with the * given [modificationTime]. */ TimestampedData(this.modificationTime, this.data); }
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/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 'dart:collection'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/ast_factory.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/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/exception/exception.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/context/builder.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/ast_factory.dart'; import 'package:analyzer/src/dart/ast/utilities.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' show ConstructorMember; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/resolver/exit_detector.dart'; import 'package:analyzer/src/dart/resolver/extension_member_resolver.dart'; import 'package:analyzer/src/dart/resolver/flow_analysis_visitor.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/diagnostic/diagnostic_factory.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/constant.dart'; import 'package:analyzer/src/generated/element_resolver.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/static_type_analyzer.dart'; import 'package:analyzer/src/generated/type_promotion_manager.dart'; import 'package:analyzer/src/generated/type_system.dart'; import 'package:analyzer/src/generated/variable_type_provider.dart'; import 'package:analyzer/src/lint/linter.dart'; import 'package:analyzer/src/workspace/workspace.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; export 'package:analyzer/src/dart/constant/constant_verifier.dart'; export 'package:analyzer/src/dart/resolver/exit_detector.dart'; export 'package:analyzer/src/dart/resolver/inheritance_manager.dart'; export 'package:analyzer/src/dart/resolver/scope.dart'; export 'package:analyzer/src/generated/type_system.dart'; /// Instances of the class `BestPracticesVerifier` traverse an AST structure /// looking for violations of Dart best practices. class BestPracticesVerifier extends RecursiveAstVisitor<void> { // static String _HASHCODE_GETTER_NAME = "hashCode"; static String _NULL_TYPE_NAME = "Null"; static String _TO_INT_METHOD_NAME = "toInt"; /// The class containing the AST nodes being visited, or `null` if we are not /// in the scope of a class. ClassElementImpl _enclosingClass; /// A flag indicating whether a surrounding member (compilation unit or class) /// is deprecated. bool _inDeprecatedMember; /// The error reporter by which errors will be reported. final ErrorReporter _errorReporter; /// The type [Null]. final InterfaceType _nullType; /// The type system primitives final TypeSystem _typeSystem; /// The inheritance manager to access interface type hierarchy. final InheritanceManager3 _inheritanceManager; /// The current library final LibraryElement _currentLibrary; final _InvalidAccessVerifier _invalidAccessVerifier; /// The [WorkspacePackage] in which [_currentLibrary] is declared. WorkspacePackage _workspacePackage; /// The [LinterContext] used for possible const calculations. LinterContext _linterContext; /// Is `true` if NNBD is enabled for the library being analyzed. final bool _isNonNullable; /// True if inference failures should be reported, otherwise false. final bool _strictInference; /// Create a new instance of the [BestPracticesVerifier]. /// /// @param errorReporter the error reporter BestPracticesVerifier( this._errorReporter, TypeProvider typeProvider, this._currentLibrary, CompilationUnit unit, String content, { TypeSystem typeSystem, @required InheritanceManager3 inheritanceManager, ResourceProvider resourceProvider, DeclaredVariables declaredVariables, AnalysisOptions analysisOptions, }) : _nullType = typeProvider.nullType, _typeSystem = typeSystem ?? new Dart2TypeSystem(typeProvider), _isNonNullable = unit.featureSet.isEnabled(Feature.non_nullable), _strictInference = (analysisOptions as AnalysisOptionsImpl).strictInference, _inheritanceManager = inheritanceManager, _invalidAccessVerifier = new _InvalidAccessVerifier(_errorReporter, _currentLibrary) { _inDeprecatedMember = _currentLibrary.hasDeprecated; String libraryPath = _currentLibrary.source.fullName; ContextBuilder builder = new ContextBuilder( resourceProvider, null /* sdkManager */, null /* contentCache */); Workspace workspace = ContextBuilder.createWorkspace(resourceProvider, libraryPath, builder); _workspacePackage = workspace.findPackageFor(libraryPath); _linterContext = LinterContextImpl( null /* allUnits */, new LinterContextUnit(content, unit), declaredVariables, typeProvider, _typeSystem, _inheritanceManager, analysisOptions); } @override void visitAnnotation(Annotation node) { ElementAnnotation element = node.elementAnnotation; AstNode parent = node.parent; if (element?.isFactory == true) { if (parent is MethodDeclaration) { _checkForInvalidFactory(parent); } else { _errorReporter .reportErrorForNode(HintCode.INVALID_FACTORY_ANNOTATION, node, []); } } else if (element?.isImmutable == true) { if (parent is! ClassOrMixinDeclaration && parent is! ClassTypeAlias) { _errorReporter.reportErrorForNode( HintCode.INVALID_IMMUTABLE_ANNOTATION, node, []); } } else if (element?.isLiteral == true) { if (parent is! ConstructorDeclaration || (parent as ConstructorDeclaration).constKeyword == null) { _errorReporter .reportErrorForNode(HintCode.INVALID_LITERAL_ANNOTATION, node, []); } } else if (element?.isSealed == true) { if (!(parent is ClassDeclaration || parent is ClassTypeAlias)) { _errorReporter.reportErrorForNode( HintCode.INVALID_SEALED_ANNOTATION, node, [node.element.name]); } } else if (element?.isVisibleForTemplate == true || element?.isVisibleForTesting == true) { if (parent is Declaration) { reportInvalidAnnotation(Element declaredElement) { _errorReporter.reportErrorForNode( HintCode.INVALID_VISIBILITY_ANNOTATION, node, [declaredElement.name, node.name.name]); } if (parent is TopLevelVariableDeclaration) { for (VariableDeclaration variable in parent.variables.variables) { if (Identifier.isPrivateName(variable.declaredElement.name)) { reportInvalidAnnotation(variable.declaredElement); } } } else if (parent is FieldDeclaration) { for (VariableDeclaration variable in parent.fields.variables) { if (Identifier.isPrivateName(variable.declaredElement.name)) { reportInvalidAnnotation(variable.declaredElement); } } } else if (parent.declaredElement != null && Identifier.isPrivateName(parent.declaredElement.name)) { reportInvalidAnnotation(parent.declaredElement); } } else { // Something other than a declaration was annotated. Whatever this is, // it probably warrants a Hint, but this has not been specified on // visibleForTemplate or visibleForTesting, so leave it alone for now. } } super.visitAnnotation(node); } @override void visitArgumentList(ArgumentList node) { for (Expression argument in node.arguments) { ParameterElement parameter = argument.staticParameterElement; if (parameter?.isOptionalPositional == true) { _checkForDeprecatedMemberUse(parameter, argument); } } super.visitArgumentList(node); } @override void visitAsExpression(AsExpression node) { _checkForUnnecessaryCast(node); super.visitAsExpression(node); } @override void visitAssignmentExpression(AssignmentExpression node) { TokenType operatorType = node.operator.type; if (operatorType != TokenType.EQ) { _checkForDeprecatedMemberUse(node.staticElement, node); } super.visitAssignmentExpression(node); } @override void visitBinaryExpression(BinaryExpression node) { _checkForDivisionOptimizationHint(node); _checkForDeprecatedMemberUse(node.staticElement, node); super.visitBinaryExpression(node); } @override void visitClassDeclaration(ClassDeclaration node) { var element = AbstractClassElementImpl.getImpl(node.declaredElement); _enclosingClass = element; _invalidAccessVerifier._enclosingClass = element; bool wasInDeprecatedMember = _inDeprecatedMember; if (element != null && element.hasDeprecated) { _inDeprecatedMember = true; } try { // Commented out until we decide that we want this hint in the analyzer // checkForOverrideEqualsButNotHashCode(node); _checkForImmutable(node); _checkForInvalidSealedSuperclass(node); super.visitClassDeclaration(node); } finally { _enclosingClass = null; _invalidAccessVerifier._enclosingClass = null; _inDeprecatedMember = wasInDeprecatedMember; } } @override void visitClassTypeAlias(ClassTypeAlias node) { _checkForImmutable(node); _checkForInvalidSealedSuperclass(node); super.visitClassTypeAlias(node); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { if (node.declaredElement.isFactory) { if (node.body is BlockFunctionBody) { // Check the block for a return statement, if not, create the hint. if (!ExitDetector.exits(node.body)) { _errorReporter.reportErrorForNode( HintCode.MISSING_RETURN, node, [node.returnType.name]); } } } _checkStrictInferenceInParameters(node.parameters); super.visitConstructorDeclaration(node); } @override void visitExportDirective(ExportDirective node) { _checkForDeprecatedMemberUse(node.uriElement, node); super.visitExportDirective(node); } @override void visitFieldDeclaration(FieldDeclaration node) { bool wasInDeprecatedMember = _inDeprecatedMember; if (_hasDeprecatedAnnotation(node.metadata)) { _inDeprecatedMember = true; } try { super.visitFieldDeclaration(node); } finally { _inDeprecatedMember = wasInDeprecatedMember; } } @override void visitFormalParameterList(FormalParameterList node) { _checkRequiredParameter(node); super.visitFormalParameterList(node); } @override void visitFunctionDeclaration(FunctionDeclaration node) { bool wasInDeprecatedMember = _inDeprecatedMember; ExecutableElement element = node.declaredElement; if (element != null && element.hasDeprecated) { _inDeprecatedMember = true; } try { _checkForMissingReturn( node.returnType, node.functionExpression.body, element, node); // Return types are inferred only on non-recursive local functions. if (node.parent is CompilationUnit) { _checkStrictInferenceReturnType(node.returnType, node, node.name.name); } _checkStrictInferenceInParameters(node.functionExpression.parameters); super.visitFunctionDeclaration(node); } finally { _inDeprecatedMember = wasInDeprecatedMember; } } @override void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) { // TODO(srawlins): Check strict-inference return type on recursive // local functions. super.visitFunctionDeclarationStatement(node); } @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is! FunctionDeclaration) { _checkForMissingReturn(null, node.body, node.declaredElement, node); } DartType functionType = InferenceContext.getContext(node); if (functionType is! FunctionType) { _checkStrictInferenceInParameters(node.parameters); } super.visitFunctionExpression(node); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { _checkStrictInferenceReturnType(node.returnType, node, node.name.name); super.visitFunctionTypeAlias(node); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { _checkStrictInferenceReturnType( node.returnType, node, node.identifier.name); _checkStrictInferenceInParameters(node.parameters); super.visitFunctionTypedFormalParameter(node); } @override void visitGenericFunctionType(GenericFunctionType node) { // GenericTypeAlias is handled in [visitGenericTypeAlias], where a proper // name can be reported in any message. if (node.parent is! GenericTypeAlias) { _checkStrictInferenceReturnType(node.returnType, node, node.toString()); } super.visitGenericFunctionType(node); } @override void visitGenericTypeAlias(GenericTypeAlias node) { if (node.functionType != null) { _checkStrictInferenceReturnType( node.functionType.returnType, node, node.name.name); } super.visitGenericTypeAlias(node); } @override void visitImportDirective(ImportDirective node) { _checkForDeprecatedMemberUse(node.uriElement, node); ImportElement importElement = node.element; if (importElement != null && importElement.isDeferred) { _checkForLoadLibraryFunction(node, importElement); } super.visitImportDirective(node); } @override void visitIndexExpression(IndexExpression node) { _checkForDeprecatedMemberUse(node.staticElement, node); super.visitIndexExpression(node); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { _checkForDeprecatedMemberUse(node.staticElement, node); _checkForLiteralConstructorUse(node); super.visitInstanceCreationExpression(node); } @override void visitIsExpression(IsExpression node) { _checkAllTypeChecks(node); super.visitIsExpression(node); } @override void visitMethodDeclaration(MethodDeclaration node) { bool wasInDeprecatedMember = _inDeprecatedMember; ExecutableElement element = node.declaredElement; bool elementIsOverride() { if (element is ClassMemberElement) { Name name = new Name(_currentLibrary.source.uri, element.name); Element enclosingElement = element.enclosingElement; if (enclosingElement is ClassElement) { InterfaceType classType = enclosingElement.thisType; return _inheritanceManager.getOverridden(classType, name) != null; } } return false; } if (element != null && element.hasDeprecated) { _inDeprecatedMember = true; } try { // This was determined to not be a good hint, see: dartbug.com/16029 //checkForOverridingPrivateMember(node); _checkForMissingReturn(node.returnType, node.body, element, node); _checkForUnnecessaryNoSuchMethod(node); if (_strictInference && !node.isSetter && !elementIsOverride()) { _checkStrictInferenceReturnType(node.returnType, node, node.name.name); } _checkStrictInferenceInParameters(node.parameters); super.visitMethodDeclaration(node); } finally { _inDeprecatedMember = wasInDeprecatedMember; } } @override void visitMethodInvocation(MethodInvocation node) { _checkForNullAwareHints(node, node.operator); DartType staticInvokeType = node.staticInvokeType; Element callElement = staticInvokeType?.element; if (callElement is MethodElement && callElement.name == FunctionElement.CALL_METHOD_NAME) { _checkForDeprecatedMemberUse(callElement, node); } super.visitMethodInvocation(node); } @override void visitMixinDeclaration(MixinDeclaration node) { _enclosingClass = node.declaredElement; _invalidAccessVerifier._enclosingClass = _enclosingClass; bool wasInDeprecatedMember = _inDeprecatedMember; if (_hasDeprecatedAnnotation(node.metadata)) { _inDeprecatedMember = true; } try { _checkForImmutable(node); _checkForInvalidSealedSuperclass(node); super.visitMixinDeclaration(node); } finally { _enclosingClass = null; _invalidAccessVerifier._enclosingClass = null; _inDeprecatedMember = wasInDeprecatedMember; } } @override void visitPostfixExpression(PostfixExpression node) { _checkForDeprecatedMemberUse(node.staticElement, node); super.visitPostfixExpression(node); } @override void visitPrefixExpression(PrefixExpression node) { _checkForDeprecatedMemberUse(node.staticElement, node); super.visitPrefixExpression(node); } @override void visitPropertyAccess(PropertyAccess node) { _checkForNullAwareHints(node, node.operator); super.visitPropertyAccess(node); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { _checkForDeprecatedMemberUse(node.staticElement, node); super.visitRedirectingConstructorInvocation(node); } @override void visitSimpleIdentifier(SimpleIdentifier node) { _checkForDeprecatedMemberUseAtIdentifier(node); _invalidAccessVerifier.verify(node); super.visitSimpleIdentifier(node); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { _checkForDeprecatedMemberUse(node.staticElement, node); super.visitSuperConstructorInvocation(node); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { bool wasInDeprecatedMember = _inDeprecatedMember; if (_hasDeprecatedAnnotation(node.metadata)) { _inDeprecatedMember = true; } try { super.visitTopLevelVariableDeclaration(node); } finally { _inDeprecatedMember = wasInDeprecatedMember; } } /// Check for the passed is expression for the unnecessary type check hint /// codes as well as null checks expressed using an is expression. /// /// @param node the is expression to check /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.TYPE_CHECK_IS_NOT_NULL], [HintCode.TYPE_CHECK_IS_NULL], /// [HintCode.UNNECESSARY_TYPE_CHECK_TRUE], and /// [HintCode.UNNECESSARY_TYPE_CHECK_FALSE]. bool _checkAllTypeChecks(IsExpression node) { Expression expression = node.expression; TypeAnnotation typeName = node.type; DartType lhsType = expression.staticType; DartType rhsType = typeName.type; if (lhsType == null || rhsType == null) { return false; } String rhsNameStr = typeName is TypeName ? typeName.name.name : null; // if x is dynamic if (rhsType.isDynamic && rhsNameStr == Keyword.DYNAMIC.lexeme) { if (node.notOperator == null) { // the is case _errorReporter.reportErrorForNode( HintCode.UNNECESSARY_TYPE_CHECK_TRUE, node); } else { // the is not case _errorReporter.reportErrorForNode( HintCode.UNNECESSARY_TYPE_CHECK_FALSE, node); } return true; } Element rhsElement = rhsType.element; LibraryElement libraryElement = rhsElement?.library; if (libraryElement != null && libraryElement.isDartCore) { // if x is Object or null is Null if (rhsType.isObject || (expression is NullLiteral && rhsNameStr == _NULL_TYPE_NAME)) { if (node.notOperator == null) { // the is case _errorReporter.reportErrorForNode( HintCode.UNNECESSARY_TYPE_CHECK_TRUE, node); } else { // the is not case _errorReporter.reportErrorForNode( HintCode.UNNECESSARY_TYPE_CHECK_FALSE, node); } return true; } else if (rhsNameStr == _NULL_TYPE_NAME) { if (node.notOperator == null) { // the is case _errorReporter.reportErrorForNode(HintCode.TYPE_CHECK_IS_NULL, node); } else { // the is not case _errorReporter.reportErrorForNode( HintCode.TYPE_CHECK_IS_NOT_NULL, node); } return true; } } return false; } /// Given some [element], look at the associated metadata and report the use /// of the member if it is declared as deprecated. If a diagnostic is reported /// it should be reported at the given [node]. void _checkForDeprecatedMemberUse(Element element, AstNode node) { bool isDeprecated(Element element) { if (element is PropertyAccessorElement && element.isSynthetic) { // TODO(brianwilkerson) Why isn't this the implementation for PropertyAccessorElement? Element variable = element.variable; if (variable == null) { return false; } return variable.hasDeprecated; } return element.hasDeprecated; } bool isLocalParameter(Element element, AstNode node) { if (element is ParameterElement) { ExecutableElement definingFunction = element.enclosingElement; FunctionBody body = node.thisOrAncestorOfType<FunctionBody>(); while (body != null) { ExecutableElement enclosingFunction; AstNode parent = body.parent; if (parent is ConstructorDeclaration) { enclosingFunction = parent.declaredElement; } else if (parent is FunctionExpression) { enclosingFunction = parent.declaredElement; } else if (parent is MethodDeclaration) { enclosingFunction = parent.declaredElement; } if (enclosingFunction == definingFunction) { return true; } body = parent?.thisOrAncestorOfType<FunctionBody>(); } } return false; } if (!_inDeprecatedMember && element != null && isDeprecated(element) && !isLocalParameter(element, node)) { String displayName = element.displayName; if (element is ConstructorElement) { // TODO(jwren) We should modify ConstructorElement.getDisplayName(), // or have the logic centralized elsewhere, instead of doing this logic // here. displayName = element.enclosingElement.displayName; if (element.displayName.isNotEmpty) { displayName = "$displayName.${element.displayName}"; } } else if (element is LibraryElement) { displayName = element.definingCompilationUnit.source.uri.toString(); } else if (displayName == FunctionElement.CALL_METHOD_NAME && node is MethodInvocation && node.staticInvokeType is InterfaceType) { DartType staticInvokeType = node.staticInvokeType; displayName = "${staticInvokeType.displayName}.${element.displayName}"; } LibraryElement library = element is LibraryElement ? element : element.library; String message = _deprecatedMessage(element); if (message == null || message.isEmpty) { HintCode hintCode = _isLibraryInWorkspacePackage(library) ? HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE : HintCode.DEPRECATED_MEMBER_USE; _errorReporter.reportErrorForNode(hintCode, node, [displayName]); } else { HintCode hintCode = _isLibraryInWorkspacePackage(library) ? HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE_WITH_MESSAGE : HintCode.DEPRECATED_MEMBER_USE_WITH_MESSAGE; _errorReporter .reportErrorForNode(hintCode, node, [displayName, message]); } } } /// For [SimpleIdentifier]s, only call [checkForDeprecatedMemberUse] /// if the node is not in a declaration context. /// /// Also, if the identifier is a constructor name in a constructor invocation, /// then calls to the deprecated constructor will be caught by /// [visitInstanceCreationExpression] and /// [visitSuperConstructorInvocation], and can be ignored by /// this visit method. /// /// @param identifier some simple identifier to check for deprecated use of /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.DEPRECATED_MEMBER_USE]. void _checkForDeprecatedMemberUseAtIdentifier(SimpleIdentifier identifier) { if (identifier.inDeclarationContext()) { return; } AstNode parent = identifier.parent; if ((parent is ConstructorName && identical(identifier, parent.name)) || (parent is ConstructorDeclaration && identical(identifier, parent.returnType)) || (parent is SuperConstructorInvocation && identical(identifier, parent.constructorName)) || parent is HideCombinator) { return; } _checkForDeprecatedMemberUse(identifier.staticElement, identifier); } /// Check for the passed binary expression for the /// [HintCode.DIVISION_OPTIMIZATION]. /// /// @param node the binary expression to check /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.DIVISION_OPTIMIZATION]. bool _checkForDivisionOptimizationHint(BinaryExpression node) { // Return if the operator is not '/' if (node.operator.type != TokenType.SLASH) { return false; } // Return if the '/' operator is not defined in core, or if we don't know // its static type MethodElement methodElement = node.staticElement; if (methodElement == null) { return false; } LibraryElement libraryElement = methodElement.library; if (libraryElement != null && !libraryElement.isDartCore) { return false; } // Report error if the (x/y) has toInt() invoked on it AstNode parent = node.parent; if (parent is ParenthesizedExpression) { ParenthesizedExpression parenthesizedExpression = _wrapParenthesizedExpression(parent); AstNode grandParent = parenthesizedExpression.parent; if (grandParent is MethodInvocation) { if (_TO_INT_METHOD_NAME == grandParent.methodName.name && grandParent.argumentList.arguments.isEmpty) { _errorReporter.reportErrorForNode( HintCode.DIVISION_OPTIMIZATION, grandParent); return true; } } } return false; } /// Checks whether [node] violates the rules of [immutable]. /// /// If [node] is marked with [immutable] or inherits from a class or mixin /// marked with [immutable], this function searches the fields of [node] and /// its superclasses, reporting a hint if any non-final instance fields are /// found. void _checkForImmutable(NamedCompilationUnitMember node) { /// Return `true` if the given class [element] is annotated with the /// `@immutable` annotation. bool isImmutable(ClassElement element) { for (ElementAnnotation annotation in element.metadata) { if (annotation.isImmutable) { return true; } } return false; } /// Return `true` if the given class [element] or any superclass of it is /// annotated with the `@immutable` annotation. bool isOrInheritsImmutable( ClassElement element, HashSet<ClassElement> visited) { if (visited.add(element)) { if (isImmutable(element)) { return true; } for (InterfaceType interface in element.mixins) { if (isOrInheritsImmutable(interface.element, visited)) { return true; } } for (InterfaceType mixin in element.interfaces) { if (isOrInheritsImmutable(mixin.element, visited)) { return true; } } if (element.supertype != null) { return isOrInheritsImmutable(element.supertype.element, visited); } } return false; } /// Return `true` if the given class [element] defines a non-final instance /// field. Iterable<String> nonFinalInstanceFields(ClassElement element) { return element.fields .where((FieldElement field) => !field.isSynthetic && !field.isFinal && !field.isStatic) .map((FieldElement field) => '${element.name}.${field.name}'); } /// Return `true` if the given class [element] defines or inherits a /// non-final field. Iterable<String> definedOrInheritedNonFinalInstanceFields( ClassElement element, HashSet<ClassElement> visited) { Iterable<String> nonFinalFields = []; if (visited.add(element)) { nonFinalFields = nonFinalInstanceFields(element); nonFinalFields = nonFinalFields.followedBy(element.mixins.expand( (InterfaceType mixin) => nonFinalInstanceFields(mixin.element))); if (element.supertype != null) { nonFinalFields = nonFinalFields.followedBy( definedOrInheritedNonFinalInstanceFields( element.supertype.element, visited)); } } return nonFinalFields; } ClassElement element = node.declaredElement; if (isOrInheritsImmutable(element, new HashSet<ClassElement>())) { Iterable<String> nonFinalFields = definedOrInheritedNonFinalInstanceFields( element, new HashSet<ClassElement>()); if (nonFinalFields.isNotEmpty) { _errorReporter.reportErrorForNode( HintCode.MUST_BE_IMMUTABLE, node.name, [nonFinalFields.join(', ')]); } } } void _checkForInvalidFactory(MethodDeclaration decl) { // Check declaration. // Note that null return types are expected to be flagged by other analyses. DartType returnType = decl.returnType?.type; if (returnType is VoidType) { _errorReporter.reportErrorForNode(HintCode.INVALID_FACTORY_METHOD_DECL, decl.name, [decl.name.toString()]); return; } // Check implementation. FunctionBody body = decl.body; if (body is EmptyFunctionBody) { // Abstract methods are OK. return; } // `new Foo()` or `null`. bool factoryExpression(Expression expression) => expression is InstanceCreationExpression || expression is NullLiteral; if (body is ExpressionFunctionBody && factoryExpression(body.expression)) { return; } else if (body is BlockFunctionBody) { NodeList<Statement> statements = body.block.statements; if (statements.isNotEmpty) { Statement last = statements.last; if (last is ReturnStatement && factoryExpression(last.expression)) { return; } } } _errorReporter.reportErrorForNode(HintCode.INVALID_FACTORY_METHOD_IMPL, decl.name, [decl.name.toString()]); } void _checkForInvalidSealedSuperclass(NamedCompilationUnitMember node) { bool currentPackageContains(Element element) { return _isLibraryInWorkspacePackage(element.library); } // [NamedCompilationUnitMember.declaredElement] is not necessarily a // ClassElement, but [_checkForInvalidSealedSuperclass] should only be // called with a [ClassOrMixinDeclaration], or a [ClassTypeAlias]. The // `declaredElement` of these specific classes is a [ClassElement]. ClassElement element = node.declaredElement; // TODO(srawlins): Perhaps replace this with a getter on Element, like // `Element.hasOrInheritsSealed`? for (InterfaceType supertype in element.allSupertypes) { ClassElement superclass = supertype.element; if (superclass.hasSealed) { if (!currentPackageContains(superclass)) { if (element.superclassConstraints.contains(supertype)) { // This is a special violation of the sealed class contract, // requiring specific messaging. _errorReporter.reportErrorForNode(HintCode.MIXIN_ON_SEALED_CLASS, node, [superclass.name.toString()]); } else { // This is a regular violation of the sealed class contract. _errorReporter.reportErrorForNode(HintCode.SUBTYPE_OF_SEALED_CLASS, node, [superclass.name.toString()]); } } } } } /// Check that the instance creation node is const if the constructor is /// marked with [literal]. _checkForLiteralConstructorUse(InstanceCreationExpression node) { ConstructorName constructorName = node.constructorName; ConstructorElement constructor = constructorName.staticElement; if (constructor == null) { return; } if (!node.isConst && constructor.hasLiteral && _linterContext.canBeConst(node)) { // Echoing jwren's TODO from _checkForDeprecatedMemberUse: // TODO(jwren) We should modify ConstructorElement.getDisplayName(), or // have the logic centralized elsewhere, instead of doing this logic // here. String fullConstructorName = constructorName.type.name.name; if (constructorName.name != null) { fullConstructorName = '$fullConstructorName.${constructorName.name}'; } HintCode hint = node.keyword?.keyword == Keyword.NEW ? HintCode.NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR_USING_NEW : HintCode.NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR; _errorReporter.reportErrorForNode(hint, node, [fullConstructorName]); } } /// Check that the imported library does not define a loadLibrary function. /// The import has already been determined to be deferred when this is called. /// /// @param node the import directive to evaluate /// @param importElement the [ImportElement] retrieved from the node /// @return `true` if and only if an error code is generated on the passed /// node /// See [CompileTimeErrorCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION]. bool _checkForLoadLibraryFunction( ImportDirective node, ImportElement importElement) { LibraryElement importedLibrary = importElement.importedLibrary; if (importedLibrary == null) { return false; } if (importedLibrary.hasLoadLibraryFunction) { _errorReporter.reportErrorForNode( HintCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION, node, [importedLibrary.name]); return true; } return false; } /// Generate a hint for functions or methods that have a return type, but do /// not have a return statement on all branches. At the end of blocks with no /// return, Dart implicitly returns `null`, avoiding these implicit returns is /// considered a best practice. /// /// Note: for async functions/methods, this hint only applies when the /// function has a return type that Future<Null> is not assignable to. /// /// @param node the binary expression to check /// @param body the function body /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.MISSING_RETURN]. void _checkForMissingReturn(TypeAnnotation returnNode, FunctionBody body, ExecutableElement element, AstNode functionNode) { if (body is BlockFunctionBody) { // Prefer the type from the element model, in case we've inferred one. DartType returnType = element?.returnType ?? returnNode?.type; AstNode errorNode = returnNode ?? functionNode; // Skip the check if we're missing a return type (e.g. erroneous code). // Generators are never required to have a return statement. if (returnType == null || body.isGenerator) { return; } var flattenedType = body.isAsynchronous ? _typeSystem.flatten(returnType) : returnType; // Function expressions without a return will have their return type set // to `Null` regardless of their context type. So we need to figure out // if a return type was expected from the original downwards context. // // This helps detect hint cases like `int Function() f = () {}`. // See https://github.com/dart-lang/sdk/issues/28233 for context. if (flattenedType.isDartCoreNull && functionNode is FunctionExpression) { var contextType = InferenceContext.getContext(functionNode); if (contextType is FunctionType) { returnType = contextType.returnType; flattenedType = body.isAsynchronous ? _typeSystem.flatten(returnType) : returnType; } } // dynamic, Null, void, and FutureOr<T> where T is (dynamic, Null, void) // are allowed to omit a return. if (flattenedType.isDartAsyncFutureOr) { flattenedType = (flattenedType as InterfaceType).typeArguments[0]; } if (flattenedType.isDynamic || flattenedType.isDartCoreNull || flattenedType.isVoid) { return; } // Otherwise issue a warning if the block doesn't have a return. if (!ExitDetector.exits(body)) { _errorReporter.reportErrorForNode( HintCode.MISSING_RETURN, errorNode, [returnType.displayName]); } } } /// Produce several null-aware related hints. void _checkForNullAwareHints(Expression node, Token operator) { if (_isNonNullable) { return; } if (operator == null || operator.type != TokenType.QUESTION_PERIOD) { return; } // childOfParent is used to know from which branch node comes. var childOfParent = node; var parent = node.parent; while (parent is ParenthesizedExpression) { childOfParent = parent; parent = parent.parent; } // CAN_BE_NULL_AFTER_NULL_AWARE if (parent is MethodInvocation && !parent.isNullAware && _nullType.lookUpMethod(parent.methodName.name, _currentLibrary) == null) { _errorReporter.reportErrorForNode( HintCode.CAN_BE_NULL_AFTER_NULL_AWARE, childOfParent); return; } if (parent is PropertyAccess && !parent.isNullAware && _nullType.lookUpGetter(parent.propertyName.name, _currentLibrary) == null) { _errorReporter.reportErrorForNode( HintCode.CAN_BE_NULL_AFTER_NULL_AWARE, childOfParent); return; } if (parent is CascadeExpression && parent.target == childOfParent) { _errorReporter.reportErrorForNode( HintCode.CAN_BE_NULL_AFTER_NULL_AWARE, childOfParent); return; } // NULL_AWARE_IN_CONDITION if (parent is IfStatement && parent.condition == childOfParent || parent is ForPartsWithDeclarations && parent.condition == childOfParent || parent is DoStatement && parent.condition == childOfParent || parent is WhileStatement && parent.condition == childOfParent || parent is ConditionalExpression && parent.condition == childOfParent || parent is AssertStatement && parent.condition == childOfParent) { _errorReporter.reportErrorForNode( HintCode.NULL_AWARE_IN_CONDITION, childOfParent); return; } // NULL_AWARE_IN_LOGICAL_OPERATOR if (parent is PrefixExpression && parent.operator.type == TokenType.BANG || parent is BinaryExpression && [TokenType.BAR_BAR, TokenType.AMPERSAND_AMPERSAND] .contains(parent.operator.type)) { _errorReporter.reportErrorForNode( HintCode.NULL_AWARE_IN_LOGICAL_OPERATOR, childOfParent); return; } // NULL_AWARE_BEFORE_OPERATOR if (parent is BinaryExpression && ![TokenType.EQ_EQ, TokenType.BANG_EQ, TokenType.QUESTION_QUESTION] .contains(parent.operator.type) && parent.leftOperand == childOfParent) { _errorReporter.reportErrorForNode( HintCode.NULL_AWARE_BEFORE_OPERATOR, childOfParent); return; } } /// Check for the passed as expression for the [HintCode.UNNECESSARY_CAST] /// hint code. /// /// @param node the as expression to check /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.UNNECESSARY_CAST]. bool _checkForUnnecessaryCast(AsExpression node) { // TODO(jwren) After dartbug.com/13732, revisit this, we should be able to // remove the (x is! TypeParameterType) checks. AstNode parent = node.parent; if (parent is ConditionalExpression && (node == parent.thenExpression || node == parent.elseExpression)) { Expression thenExpression = parent.thenExpression; DartType thenType; if (thenExpression is AsExpression) { thenType = thenExpression.expression.staticType; } else { thenType = thenExpression.staticType; } Expression elseExpression = parent.elseExpression; DartType elseType; if (elseExpression is AsExpression) { elseType = elseExpression.expression.staticType; } else { elseType = elseExpression.staticType; } if (thenType != null && elseType != null && !thenType.isDynamic && !elseType.isDynamic && !_typeSystem.isSubtypeOf(thenType, elseType) && !_typeSystem.isSubtypeOf(elseType, thenType)) { return false; } } DartType lhsType = node.expression.staticType; DartType rhsType = node.type.type; if (lhsType != null && rhsType != null && !lhsType.isDynamic && !rhsType.isDynamic && _typeSystem.isSubtypeOf(lhsType, rhsType)) { _errorReporter.reportErrorForNode(HintCode.UNNECESSARY_CAST, node); return true; } return false; } /// Generate a hint for `noSuchMethod` methods that do nothing except of /// calling another `noSuchMethod` that is not defined by `Object`. /// /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.UNNECESSARY_NO_SUCH_METHOD]. bool _checkForUnnecessaryNoSuchMethod(MethodDeclaration node) { if (node.name.name != FunctionElement.NO_SUCH_METHOD_METHOD_NAME) { return false; } bool isNonObjectNoSuchMethodInvocation(Expression invocation) { if (invocation is MethodInvocation && invocation.target is SuperExpression && invocation.argumentList.arguments.length == 1) { SimpleIdentifier name = invocation.methodName; if (name.name == FunctionElement.NO_SUCH_METHOD_METHOD_NAME) { Element methodElement = name.staticElement; Element classElement = methodElement?.enclosingElement; return methodElement is MethodElement && classElement is ClassElement && !classElement.isDartCoreObject; } } return false; } FunctionBody body = node.body; if (body is ExpressionFunctionBody) { if (isNonObjectNoSuchMethodInvocation(body.expression)) { _errorReporter.reportErrorForNode( HintCode.UNNECESSARY_NO_SUCH_METHOD, node); return true; } } else if (body is BlockFunctionBody) { List<Statement> statements = body.block.statements; if (statements.length == 1) { Statement returnStatement = statements.first; if (returnStatement is ReturnStatement && isNonObjectNoSuchMethodInvocation(returnStatement.expression)) { _errorReporter.reportErrorForNode( HintCode.UNNECESSARY_NO_SUCH_METHOD, node); return true; } } } return false; } void _checkRequiredParameter(FormalParameterList node) { final requiredParameters = node.parameters.where((p) => p.declaredElement?.hasRequired == true); final nonNamedParamsWithRequired = requiredParameters.where((p) => p.isPositional); final namedParamsWithRequiredAndDefault = requiredParameters .where((p) => p.isNamed) .where((p) => p.declaredElement.defaultValueCode != null); for (final param in nonNamedParamsWithRequired.where((p) => p.isOptional)) { _errorReporter.reportErrorForNode( HintCode.INVALID_REQUIRED_OPTIONAL_POSITIONAL_PARAM, param, [param.identifier.name]); } for (final param in nonNamedParamsWithRequired.where((p) => p.isRequired)) { _errorReporter.reportErrorForNode( HintCode.INVALID_REQUIRED_POSITIONAL_PARAM, param, [param.identifier.name]); } for (final param in namedParamsWithRequiredAndDefault) { _errorReporter.reportErrorForNode(HintCode.INVALID_REQUIRED_NAMED_PARAM, param, [param.identifier.name]); } } /// In "strict-inference" mode, check that each of the [parameters]' type is /// specified. _checkStrictInferenceInParameters(FormalParameterList parameters) { void checkParameterTypeIsKnown(SimpleFormalParameter parameter) { if (parameter.type == null) { ParameterElement element = parameter.declaredElement; _errorReporter.reportTypeErrorForNode( HintCode.INFERENCE_FAILURE_ON_UNTYPED_PARAMETER, parameter, [element.displayName], ); } } if (_strictInference && parameters != null) { for (FormalParameter parameter in parameters.parameters) { if (parameter is SimpleFormalParameter) { checkParameterTypeIsKnown(parameter); } else if (parameter is DefaultFormalParameter) { if (parameter.parameter is SimpleFormalParameter) { checkParameterTypeIsKnown(parameter.parameter); } } } } } /// In "strict-inference" mode, check that [returnNode]'s return type is /// specified. void _checkStrictInferenceReturnType( AstNode returnType, AstNode reportNode, String displayName) { if (!_strictInference) { return; } if (returnType == null) { _errorReporter.reportErrorForNode( HintCode.INFERENCE_FAILURE_ON_FUNCTION_RETURN_TYPE, reportNode, [displayName]); } } bool _isLibraryInWorkspacePackage(LibraryElement library) { if (_workspacePackage == null || library == null) { // Better to not make a big claim that they _are_ in the same package, // if we were unable to determine what package [_currentLibrary] is in. return false; } return _workspacePackage.contains(library.source); } /// Return the message in the deprecated annotation on the given [element], or /// `null` if the element doesn't have a deprecated annotation or if the /// annotation does not have a message. static String _deprecatedMessage(Element element) { ElementAnnotationImpl annotation = element.metadata.firstWhere( (e) => e.isDeprecated, orElse: () => null, ); if (annotation == null || annotation.element is PropertyAccessorElement) { return null; } DartObject constantValue = annotation.computeConstantValue(); return constantValue?.getField('message')?.toStringValue() ?? constantValue?.getField('expires')?.toStringValue(); } /// Check for the passed class declaration for the /// [HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE] hint code. /// /// @param node the class declaration to check /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE]. // bool _checkForOverrideEqualsButNotHashCode(ClassDeclaration node) { // ClassElement classElement = node.element; // if (classElement == null) { // return false; // } // MethodElement equalsOperatorMethodElement = // classElement.getMethod(sc.TokenType.EQ_EQ.lexeme); // if (equalsOperatorMethodElement != null) { // PropertyAccessorElement hashCodeElement = // classElement.getGetter(_HASHCODE_GETTER_NAME); // if (hashCodeElement == null) { // _errorReporter.reportErrorForNode( // HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE, // node.name, // [classElement.displayName]); // return true; // } // } // return false; // } // // /// Return `true` if the given [type] represents `Future<void>`. // bool _isFutureVoid(DartType type) { // if (type.isDartAsyncFuture) { // List<DartType> typeArgs = (type as InterfaceType).typeArguments; // if (typeArgs.length == 1 && typeArgs[0].isVoid) { // return true; // } // } // return false; // } static bool _hasDeprecatedAnnotation(List<Annotation> annotations) { for (var i = 0; i < annotations.length; i++) { if (annotations[i].elementAnnotation.isDeprecated) { return true; } } return false; } /// Given a parenthesized expression, this returns the parent (or recursively /// grand-parent) of the expression that is a parenthesized expression, but /// whose parent is not a parenthesized expression. /// /// For example given the code `(((e)))`: `(e) -> (((e)))`. /// /// @param parenthesizedExpression some expression whose parent is a /// parenthesized expression /// @return the first parent or grand-parent that is a parenthesized /// expression, that does not have a parenthesized expression parent static ParenthesizedExpression _wrapParenthesizedExpression( ParenthesizedExpression parenthesizedExpression) { AstNode parent = parenthesizedExpression.parent; if (parent is ParenthesizedExpression) { return _wrapParenthesizedExpression(parent); } return parenthesizedExpression; } } /// Utilities for [LibraryElementImpl] building. class BuildLibraryElementUtils { /// Look through all of the compilation units defined for the given [library], /// looking for getters and setters that are defined in different compilation /// units but that have the same names. If any are found, make sure that they /// have the same variable element. static void patchTopLevelAccessors(LibraryElementImpl library) { // Without parts getters/setters already share the same variable element. List<CompilationUnitElement> parts = library.parts; if (parts.isEmpty) { return; } // Collect getters and setters. Map<String, PropertyAccessorElement> getters = new HashMap<String, PropertyAccessorElement>(); List<PropertyAccessorElement> setters = <PropertyAccessorElement>[]; _collectAccessors(getters, setters, library.definingCompilationUnit); int partLength = parts.length; for (int i = 0; i < partLength; i++) { CompilationUnitElement unit = parts[i]; _collectAccessors(getters, setters, unit); } // Move every setter to the corresponding getter's variable (if exists). int setterLength = setters.length; for (int j = 0; j < setterLength; j++) { PropertyAccessorElement setter = setters[j]; PropertyAccessorElement getter = getters[setter.displayName]; if (getter != null) { TopLevelVariableElementImpl variable = getter.variable; TopLevelVariableElementImpl setterVariable = setter.variable; CompilationUnitElementImpl setterUnit = setterVariable.enclosingElement; setterUnit.replaceTopLevelVariable(setterVariable, variable); variable.setter = setter; (setter as PropertyAccessorElementImpl).variable = variable; } } } /// Add all of the non-synthetic [getters] and [setters] defined in the given /// [unit] that have no corresponding accessor to one of the given /// collections. static void _collectAccessors(Map<String, PropertyAccessorElement> getters, List<PropertyAccessorElement> setters, CompilationUnitElement unit) { List<PropertyAccessorElement> accessors = unit.accessors; int length = accessors.length; for (int i = 0; i < length; i++) { PropertyAccessorElement accessor = accessors[i]; if (accessor.isGetter) { if (!accessor.isSynthetic && accessor.correspondingSetter == null) { getters[accessor.displayName] = accessor; } } else { if (!accessor.isSynthetic && accessor.correspondingGetter == null) { setters.add(accessor); } } } } } /// Instances of the class `Dart2JSVerifier` traverse an AST structure looking /// for hints for code that will be compiled to JS, such as /// [HintCode.IS_DOUBLE]. class Dart2JSVerifier extends RecursiveAstVisitor<void> { /// The name of the `double` type. static String _DOUBLE_TYPE_NAME = "double"; /// The error reporter by which errors will be reported. final ErrorReporter _errorReporter; /// Create a new instance of the [Dart2JSVerifier]. /// /// @param errorReporter the error reporter Dart2JSVerifier(this._errorReporter); @override void visitIsExpression(IsExpression node) { _checkForIsDoubleHints(node); super.visitIsExpression(node); } /// Check for instances of `x is double`, `x is int`, `x is! double` and /// `x is! int`. /// /// @param node the is expression to check /// @return `true` if and only if a hint code is generated on the passed node /// See [HintCode.IS_DOUBLE], /// [HintCode.IS_INT], /// [HintCode.IS_NOT_DOUBLE], and /// [HintCode.IS_NOT_INT]. bool _checkForIsDoubleHints(IsExpression node) { DartType type = node.type.type; Element element = type?.element; if (element != null) { String typeNameStr = element.name; LibraryElement libraryElement = element.library; // if (typeNameStr.equals(INT_TYPE_NAME) && libraryElement != null // && libraryElement.isDartCore()) { // if (node.getNotOperator() == null) { // errorReporter.reportError(HintCode.IS_INT, node); // } else { // errorReporter.reportError(HintCode.IS_NOT_INT, node); // } // return true; // } else if (typeNameStr == _DOUBLE_TYPE_NAME && libraryElement != null && libraryElement.isDartCore) { if (node.notOperator == null) { _errorReporter.reportErrorForNode(HintCode.IS_DOUBLE, node); } else { _errorReporter.reportErrorForNode(HintCode.IS_NOT_DOUBLE, node); } return true; } } return false; } } /// A visitor that finds dead code and unused labels. class DeadCodeVerifier extends RecursiveAstVisitor<void> { /// The error reporter by which errors will be reported. final ErrorReporter _errorReporter; /// The type system for this visitor final TypeSystem _typeSystem; /// The object used to track the usage of labels within a given label scope. _LabelTracker labelTracker; /// Is `true` if this unit has been parsed as non-nullable. final bool _isNonNullableUnit; /// Initialize a newly created dead code verifier that will report dead code /// to the given [errorReporter] and will use the given [typeSystem] if one is /// provided. DeadCodeVerifier(this._errorReporter, FeatureSet featureSet, {TypeSystem typeSystem}) : this._typeSystem = typeSystem ?? new Dart2TypeSystem(null), _isNonNullableUnit = featureSet.isEnabled(Feature.non_nullable); @override void visitAssignmentExpression(AssignmentExpression node) { TokenType operatorType = node.operator.type; if (operatorType == TokenType.QUESTION_QUESTION_EQ) { _checkForDeadNullCoalesce( node.leftHandSide.staticType, node.rightHandSide); } super.visitAssignmentExpression(node); } @override void visitBinaryExpression(BinaryExpression node) { Token operator = node.operator; bool isAmpAmp = operator.type == TokenType.AMPERSAND_AMPERSAND; bool isBarBar = operator.type == TokenType.BAR_BAR; bool isQuestionQuestion = operator.type == TokenType.QUESTION_QUESTION; if (isAmpAmp || isBarBar) { Expression lhsCondition = node.leftOperand; if (!_isDebugConstant(lhsCondition)) { EvaluationResultImpl lhsResult = _getConstantBooleanValue(lhsCondition); if (lhsResult != null) { bool value = lhsResult.value.toBoolValue(); if (value == true && isBarBar) { // Report error on "else" block: true || !e! _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, node.rightOperand); // Only visit the LHS: lhsCondition?.accept(this); return; } else if (value == false && isAmpAmp) { // Report error on "if" block: false && !e! _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, node.rightOperand); // Only visit the LHS: lhsCondition?.accept(this); return; } } } // How do we want to handle the RHS? It isn't dead code, but "pointless" // or "obscure"... // Expression rhsCondition = node.getRightOperand(); // ValidResult rhsResult = getConstantBooleanValue(rhsCondition); // if (rhsResult != null) { // if (rhsResult == ValidResult.RESULT_TRUE && isBarBar) { // // report error on else block: !e! || true // errorReporter.reportError(HintCode.DEAD_CODE, node.getRightOperand()); // // only visit the RHS: // rhsCondition?.accept(this); // return null; // } else if (rhsResult == ValidResult.RESULT_FALSE && isAmpAmp) { // // report error on if block: !e! && false // errorReporter.reportError(HintCode.DEAD_CODE, node.getRightOperand()); // // only visit the RHS: // rhsCondition?.accept(this); // return null; // } // } } else if (isQuestionQuestion && _isNonNullableUnit) { _checkForDeadNullCoalesce(node.leftOperand.staticType, node.rightOperand); } super.visitBinaryExpression(node); } /// For each block, this method reports and error on all statements between /// the end of the block and the first return statement (assuming there it is /// not at the end of the block.) @override void visitBlock(Block node) { NodeList<Statement> statements = node.statements; _checkForDeadStatementsInNodeList(statements); } @override void visitBreakStatement(BreakStatement node) { labelTracker?.recordUsage(node.label?.name); } @override void visitConditionalExpression(ConditionalExpression node) { Expression conditionExpression = node.condition; conditionExpression?.accept(this); if (!_isDebugConstant(conditionExpression)) { EvaluationResultImpl result = _getConstantBooleanValue(conditionExpression); if (result != null) { if (result.value.toBoolValue() == true) { // Report error on "else" block: true ? 1 : !2! _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, node.elseExpression); node.thenExpression?.accept(this); return; } else { // Report error on "if" block: false ? !1! : 2 _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, node.thenExpression); node.elseExpression?.accept(this); return; } } } super.visitConditionalExpression(node); } @override void visitContinueStatement(ContinueStatement node) { labelTracker?.recordUsage(node.label?.name); } @override void visitExportDirective(ExportDirective node) { ExportElement exportElement = node.element; if (exportElement != null) { // The element is null when the URI is invalid. LibraryElement library = exportElement.exportedLibrary; if (library != null && !library.isSynthetic) { for (Combinator combinator in node.combinators) { _checkCombinator(library, combinator); } } } super.visitExportDirective(node); } @override void visitIfElement(IfElement node) { Expression conditionExpression = node.condition; conditionExpression?.accept(this); if (!_isDebugConstant(conditionExpression)) { EvaluationResultImpl result = _getConstantBooleanValue(conditionExpression); if (result != null) { if (result.value.toBoolValue() == true) { // Report error on else block: if(true) {} else {!} CollectionElement elseElement = node.elseElement; if (elseElement != null) { _errorReporter.reportErrorForNode(HintCode.DEAD_CODE, elseElement); node.thenElement?.accept(this); return; } } else { // Report error on if block: if (false) {!} else {} _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, node.thenElement); node.elseElement?.accept(this); return; } } } super.visitIfElement(node); } @override void visitIfStatement(IfStatement node) { Expression conditionExpression = node.condition; conditionExpression?.accept(this); if (!_isDebugConstant(conditionExpression)) { EvaluationResultImpl result = _getConstantBooleanValue(conditionExpression); if (result != null) { if (result.value.toBoolValue() == true) { // Report error on else block: if(true) {} else {!} Statement elseStatement = node.elseStatement; if (elseStatement != null) { _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, elseStatement); node.thenStatement?.accept(this); return; } } else { // Report error on if block: if (false) {!} else {} _errorReporter.reportErrorForNode( HintCode.DEAD_CODE, node.thenStatement); node.elseStatement?.accept(this); return; } } } super.visitIfStatement(node); } @override void visitImportDirective(ImportDirective node) { ImportElement importElement = node.element; if (importElement != null) { // The element is null when the URI is invalid, but not when the URI is // valid but refers to a non-existent file. LibraryElement library = importElement.importedLibrary; if (library != null && !library.isSynthetic) { for (Combinator combinator in node.combinators) { _checkCombinator(library, combinator); } } } super.visitImportDirective(node); } @override void visitLabeledStatement(LabeledStatement node) { _pushLabels(node.labels); try { super.visitLabeledStatement(node); } finally { _popLabels(); } } @override void visitSwitchCase(SwitchCase node) { _checkForDeadStatementsInNodeList(node.statements, allowMandated: true); super.visitSwitchCase(node); } @override void visitSwitchDefault(SwitchDefault node) { _checkForDeadStatementsInNodeList(node.statements, allowMandated: true); super.visitSwitchDefault(node); } @override void visitSwitchStatement(SwitchStatement node) { List<Label> labels = <Label>[]; for (SwitchMember member in node.members) { labels.addAll(member.labels); } _pushLabels(labels); try { super.visitSwitchStatement(node); } finally { _popLabels(); } } @override void visitTryStatement(TryStatement node) { node.body?.accept(this); node.finallyBlock?.accept(this); NodeList<CatchClause> catchClauses = node.catchClauses; int numOfCatchClauses = catchClauses.length; List<DartType> visitedTypes = new List<DartType>(); for (int i = 0; i < numOfCatchClauses; i++) { CatchClause catchClause = catchClauses[i]; if (catchClause.onKeyword != null) { // An on-catch clause was found; verify that the exception type is not a // subtype of a previous on-catch exception type. DartType currentType = catchClause.exceptionType?.type; if (currentType != null) { if (currentType.isObject) { // Found catch clause clause that has Object as an exception type, // this is equivalent to having a catch clause that doesn't have an // exception type, visit the block, but generate an error on any // following catch clauses (and don't visit them). catchClause?.accept(this); if (i + 1 != numOfCatchClauses) { // This catch clause is not the last in the try statement. CatchClause nextCatchClause = catchClauses[i + 1]; CatchClause lastCatchClause = catchClauses[numOfCatchClauses - 1]; int offset = nextCatchClause.offset; int length = lastCatchClause.end - offset; _errorReporter.reportErrorForOffset( HintCode.DEAD_CODE_CATCH_FOLLOWING_CATCH, offset, length); return; } } int length = visitedTypes.length; for (int j = 0; j < length; j++) { DartType type = visitedTypes[j]; if (_typeSystem.isSubtypeOf(currentType, type)) { CatchClause lastCatchClause = catchClauses[numOfCatchClauses - 1]; int offset = catchClause.offset; int length = lastCatchClause.end - offset; _errorReporter.reportErrorForOffset( HintCode.DEAD_CODE_ON_CATCH_SUBTYPE, offset, length, [currentType.displayName, type.displayName]); return; } } visitedTypes.add(currentType); } catchClause?.accept(this); } else { // Found catch clause clause that doesn't have an exception type, // visit the block, but generate an error on any following catch clauses // (and don't visit them). catchClause?.accept(this); if (i + 1 != numOfCatchClauses) { // This catch clause is not the last in the try statement. CatchClause nextCatchClause = catchClauses[i + 1]; CatchClause lastCatchClause = catchClauses[numOfCatchClauses - 1]; int offset = nextCatchClause.offset; int length = lastCatchClause.end - offset; _errorReporter.reportErrorForOffset( HintCode.DEAD_CODE_CATCH_FOLLOWING_CATCH, offset, length); return; } } } } @override void visitWhileStatement(WhileStatement node) { Expression conditionExpression = node.condition; conditionExpression?.accept(this); if (!_isDebugConstant(conditionExpression)) { EvaluationResultImpl result = _getConstantBooleanValue(conditionExpression); if (result != null) { if (result.value.toBoolValue() == false) { // Report error on while block: while (false) {!} _errorReporter.reportErrorForNode(HintCode.DEAD_CODE, node.body); return; } } } node.body?.accept(this); } /// Resolve the names in the given [combinator] in the scope of the given /// [library]. void _checkCombinator(LibraryElement library, Combinator combinator) { Namespace namespace = new NamespaceBuilder().createExportNamespaceForLibrary(library); NodeList<SimpleIdentifier> names; ErrorCode hintCode; if (combinator is HideCombinator) { names = combinator.hiddenNames; hintCode = HintCode.UNDEFINED_HIDDEN_NAME; } else { names = (combinator as ShowCombinator).shownNames; hintCode = HintCode.UNDEFINED_SHOWN_NAME; } for (SimpleIdentifier name in names) { String nameStr = name.name; Element element = namespace.get(nameStr); if (element == null) { element = namespace.get("$nameStr="); } if (element == null) { _errorReporter .reportErrorForNode(hintCode, name, [library.identifier, nameStr]); } } } void _checkForDeadNullCoalesce(TypeImpl lhsType, Expression rhs) { if (_isNonNullableUnit && _typeSystem.isNonNullable(lhsType)) { _errorReporter.reportErrorForNode(HintCode.DEAD_CODE, rhs, []); } } /// Given some list of [statements], loop through the list searching for dead /// statements. If [allowMandated] is true, then allow dead statements that /// are mandated by the language spec. This allows for a final break, /// continue, return, or throw statement at the end of a switch case, that are /// mandated by the language spec. void _checkForDeadStatementsInNodeList(NodeList<Statement> statements, {bool allowMandated: false}) { bool statementExits(Statement statement) { if (statement is BreakStatement) { return statement.label == null; } else if (statement is ContinueStatement) { return statement.label == null; } return ExitDetector.exits(statement); } int size = statements.length; for (int i = 0; i < size; i++) { Statement currentStatement = statements[i]; currentStatement?.accept(this); if (statementExits(currentStatement) && i != size - 1) { Statement nextStatement = statements[i + 1]; Statement lastStatement = statements[size - 1]; // If mandated statements are allowed, and only the last statement is // dead, and it's a BreakStatement, then assume it is a statement // mandated by the language spec, there to avoid a // CASE_BLOCK_NOT_TERMINATED error. if (allowMandated && i == size - 2 && nextStatement is BreakStatement) { return; } int offset = nextStatement.offset; int length = lastStatement.end - offset; _errorReporter.reportErrorForOffset(HintCode.DEAD_CODE, offset, length); return; } } } /// Given some [expression], return [ValidResult.RESULT_TRUE] if it is `true`, /// [ValidResult.RESULT_FALSE] if it is `false`, or `null` if the expression /// is not a constant boolean value. EvaluationResultImpl _getConstantBooleanValue(Expression expression) { if (expression is BooleanLiteral) { if (expression.value) { return new EvaluationResultImpl( new DartObjectImpl(null, BoolState.from(true))); } else { return new EvaluationResultImpl( new DartObjectImpl(null, BoolState.from(false))); } } // Don't consider situations where we could evaluate to a constant boolean // expression with the ConstantVisitor // else { // EvaluationResultImpl result = expression.accept(new ConstantVisitor()); // if (result == ValidResult.RESULT_TRUE) { // return ValidResult.RESULT_TRUE; // } else if (result == ValidResult.RESULT_FALSE) { // return ValidResult.RESULT_FALSE; // } // return null; // } return null; } /// Return `true` if the given [expression] is resolved to a constant /// variable. bool _isDebugConstant(Expression expression) { Element element; if (expression is Identifier) { element = expression.staticElement; } else if (expression is PropertyAccess) { element = expression.propertyName.staticElement; } if (element is PropertyAccessorElement) { PropertyInducingElement variable = element.variable; return variable != null && variable.isConst; } return false; } /// Exit the most recently entered label scope after reporting any labels that /// were not referenced within that scope. void _popLabels() { for (Label label in labelTracker.unusedLabels()) { _errorReporter .reportErrorForNode(HintCode.UNUSED_LABEL, label, [label.label.name]); } labelTracker = labelTracker.outerTracker; } /// Enter a new label scope in which the given [labels] are defined. void _pushLabels(List<Label> labels) { labelTracker = new _LabelTracker(labelTracker, labels); } } /// A visitor that resolves directives in an AST structure to already built /// elements. /// /// The resulting AST must have everything resolved that would have been /// resolved by a [DirectiveElementBuilder]. class DirectiveResolver extends SimpleAstVisitor { final Map<Source, int> sourceModificationTimeMap; final Map<Source, SourceKind> importSourceKindMap; final Map<Source, SourceKind> exportSourceKindMap; final List<AnalysisError> errors = <AnalysisError>[]; LibraryElement _enclosingLibrary; DirectiveResolver(this.sourceModificationTimeMap, this.importSourceKindMap, this.exportSourceKindMap); @override void visitCompilationUnit(CompilationUnit node) { _enclosingLibrary = node.declaredElement.library; for (Directive directive in node.directives) { directive.accept(this); } } @override void visitExportDirective(ExportDirective node) { int nodeOffset = node.offset; node.element = null; for (ExportElement element in _enclosingLibrary.exports) { if (element.nameOffset == nodeOffset) { node.element = element; // Verify the exported source kind. LibraryElement exportedLibrary = element.exportedLibrary; if (exportedLibrary != null) { Source exportedSource = exportedLibrary.source; int exportedTime = sourceModificationTimeMap[exportedSource] ?? -1; if (exportedTime >= 0 && exportSourceKindMap[exportedSource] != SourceKind.LIBRARY) { StringLiteral uriLiteral = node.uri; errors.add(new AnalysisError( _enclosingLibrary.source, uriLiteral.offset, uriLiteral.length, CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY, [uriLiteral.toSource()])); } } break; } } } @override void visitImportDirective(ImportDirective node) { int nodeOffset = node.offset; node.element = null; for (ImportElement element in _enclosingLibrary.imports) { if (element.nameOffset == nodeOffset) { node.element = element; // Verify the imported source kind. LibraryElement importedLibrary = element.importedLibrary; if (importedLibrary != null) { Source importedSource = importedLibrary.source; int importedTime = sourceModificationTimeMap[importedSource] ?? -1; if (importedTime >= 0 && importSourceKindMap[importedSource] != SourceKind.LIBRARY) { StringLiteral uriLiteral = node.uri; errors.add(new AnalysisError( _enclosingLibrary.source, uriLiteral.offset, uriLiteral.length, CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY, [uriLiteral.toSource()])); } } break; } } } @override void visitLibraryDirective(LibraryDirective node) { node.element = _enclosingLibrary; } } /// Instances of the class `ElementHolder` hold on to elements created while /// traversing an AST structure so that they can be accessed when creating their /// enclosing element. class ElementHolder { List<PropertyAccessorElement> _accessors; List<ConstructorElement> _constructors; List<ClassElement> _enums; List<FieldElement> _fields; List<FunctionElement> _functions; List<LabelElement> _labels; List<LocalVariableElement> _localVariables; List<MethodElement> _methods; List<ClassElement> _mixins; List<ParameterElement> _parameters; List<TopLevelVariableElement> _topLevelVariables; List<ClassElement> _types; List<FunctionTypeAliasElement> _typeAliases; List<TypeParameterElement> _typeParameters; List<PropertyAccessorElement> get accessors { if (_accessors == null) { return const <PropertyAccessorElement>[]; } List<PropertyAccessorElement> result = _accessors; _accessors = null; return result; } List<ConstructorElement> get constructors { if (_constructors == null) { return const <ConstructorElement>[]; } List<ConstructorElement> result = _constructors; _constructors = null; return result; } List<ClassElement> get enums { if (_enums == null) { return const <ClassElement>[]; } List<ClassElement> result = _enums; _enums = null; return result; } List<FieldElement> get fields { if (_fields == null) { return const <FieldElement>[]; } List<FieldElement> result = _fields; _fields = null; return result; } List<FieldElement> get fieldsWithoutFlushing { if (_fields == null) { return const <FieldElement>[]; } List<FieldElement> result = _fields; return result; } List<FunctionElement> get functions { if (_functions == null) { return const <FunctionElement>[]; } List<FunctionElement> result = _functions; _functions = null; return result; } List<LabelElement> get labels { if (_labels == null) { return const <LabelElement>[]; } List<LabelElement> result = _labels; _labels = null; return result; } List<LocalVariableElement> get localVariables { if (_localVariables == null) { return const <LocalVariableElement>[]; } List<LocalVariableElement> result = _localVariables; _localVariables = null; return result; } List<MethodElement> get methods { if (_methods == null) { return const <MethodElement>[]; } List<MethodElement> result = _methods; _methods = null; return result; } List<ClassElement> get mixins { if (_mixins == null) { return const <ClassElement>[]; } List<ClassElement> result = _mixins; _mixins = null; return result; } List<ParameterElement> get parameters { if (_parameters == null) { return const <ParameterElement>[]; } List<ParameterElement> result = _parameters; _parameters = null; return result; } List<TopLevelVariableElement> get topLevelVariables { if (_topLevelVariables == null) { return const <TopLevelVariableElement>[]; } List<TopLevelVariableElement> result = _topLevelVariables; _topLevelVariables = null; return result; } List<FunctionTypeAliasElement> get typeAliases { if (_typeAliases == null) { return const <FunctionTypeAliasElement>[]; } List<FunctionTypeAliasElement> result = _typeAliases; _typeAliases = null; return result; } List<TypeParameterElement> get typeParameters { if (_typeParameters == null) { return const <TypeParameterElement>[]; } List<TypeParameterElement> result = _typeParameters; _typeParameters = null; return result; } List<ClassElement> get types { if (_types == null) { return const <ClassElement>[]; } List<ClassElement> result = _types; _types = null; return result; } void addAccessor(PropertyAccessorElement element) { if (_accessors == null) { _accessors = new List<PropertyAccessorElement>(); } _accessors.add(element); } void addConstructor(ConstructorElement element) { if (_constructors == null) { _constructors = new List<ConstructorElement>(); } _constructors.add(element); } void addEnum(ClassElement element) { if (_enums == null) { _enums = new List<ClassElement>(); } _enums.add(element); } void addField(FieldElement element) { if (_fields == null) { _fields = new List<FieldElement>(); } _fields.add(element); } void addFunction(FunctionElement element) { if (_functions == null) { _functions = new List<FunctionElement>(); } _functions.add(element); } void addLabel(LabelElement element) { if (_labels == null) { _labels = new List<LabelElement>(); } _labels.add(element); } void addLocalVariable(LocalVariableElement element) { if (_localVariables == null) { _localVariables = new List<LocalVariableElement>(); } _localVariables.add(element); } void addMethod(MethodElement element) { if (_methods == null) { _methods = new List<MethodElement>(); } _methods.add(element); } void addMixin(ClassElement element) { if (_mixins == null) { _mixins = new List<ClassElement>(); } _mixins.add(element); } void addParameter(ParameterElement element) { if (_parameters == null) { _parameters = new List<ParameterElement>(); } _parameters.add(element); } void addTopLevelVariable(TopLevelVariableElement element) { if (_topLevelVariables == null) { _topLevelVariables = new List<TopLevelVariableElement>(); } _topLevelVariables.add(element); } void addType(ClassElement element) { if (_types == null) { _types = new List<ClassElement>(); } _types.add(element); } void addTypeAlias(FunctionTypeAliasElement element) { if (_typeAliases == null) { _typeAliases = new List<FunctionTypeAliasElement>(); } _typeAliases.add(element); } void addTypeParameter(TypeParameterElement element) { if (_typeParameters == null) { _typeParameters = new List<TypeParameterElement>(); } _typeParameters.add(element); } FieldElement getField(String fieldName, {bool synthetic: false}) { if (_fields == null) { return null; } int length = _fields.length; for (int i = 0; i < length; i++) { FieldElement field = _fields[i]; if (field.name == fieldName && field.isSynthetic == synthetic) { return field; } } return null; } TopLevelVariableElement getTopLevelVariable(String variableName) { if (_topLevelVariables == null) { return null; } int length = _topLevelVariables.length; for (int i = 0; i < length; i++) { TopLevelVariableElement variable = _topLevelVariables[i]; if (variable.name == variableName) { return variable; } } return null; } void validate() { StringBuffer buffer = new StringBuffer(); if (_accessors != null) { buffer.write(_accessors.length); buffer.write(" accessors"); } if (_constructors != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_constructors.length); buffer.write(" constructors"); } if (_fields != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_fields.length); buffer.write(" fields"); } if (_functions != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_functions.length); buffer.write(" functions"); } if (_labels != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_labels.length); buffer.write(" labels"); } if (_localVariables != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_localVariables.length); buffer.write(" local variables"); } if (_methods != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_methods.length); buffer.write(" methods"); } if (_parameters != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_parameters.length); buffer.write(" parameters"); } if (_topLevelVariables != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_topLevelVariables.length); buffer.write(" top-level variables"); } if (_types != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_types.length); buffer.write(" types"); } if (_typeAliases != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_typeAliases.length); buffer.write(" type aliases"); } if (_typeParameters != null) { if (buffer.length > 0) { buffer.write("; "); } buffer.write(_typeParameters.length); buffer.write(" type parameters"); } if (buffer.length > 0) { AnalysisEngine.instance.logger .logError("Failed to capture elements: $buffer"); } } } /// An [AstVisitor] that fills [UsedLocalElements]. class GatherUsedLocalElementsVisitor extends RecursiveAstVisitor { final UsedLocalElements usedElements = new UsedLocalElements(); final LibraryElement _enclosingLibrary; ClassElement _enclosingClass; ExecutableElement _enclosingExec; GatherUsedLocalElementsVisitor(this._enclosingLibrary); @override visitCatchClause(CatchClause node) { SimpleIdentifier exceptionParameter = node.exceptionParameter; SimpleIdentifier stackTraceParameter = node.stackTraceParameter; if (exceptionParameter != null) { Element element = exceptionParameter.staticElement; usedElements.addCatchException(element); if (stackTraceParameter != null || node.onKeyword == null) { usedElements.addElement(element); } } if (stackTraceParameter != null) { Element element = stackTraceParameter.staticElement; usedElements.addCatchStackTrace(element); } super.visitCatchClause(node); } @override visitClassDeclaration(ClassDeclaration node) { ClassElement enclosingClassOld = _enclosingClass; try { _enclosingClass = node.declaredElement; super.visitClassDeclaration(node); } finally { _enclosingClass = enclosingClassOld; } } @override visitFunctionDeclaration(FunctionDeclaration node) { ExecutableElement enclosingExecOld = _enclosingExec; try { _enclosingExec = node.declaredElement; super.visitFunctionDeclaration(node); } finally { _enclosingExec = enclosingExecOld; } } @override visitFunctionExpression(FunctionExpression node) { if (node.parent is! FunctionDeclaration) { usedElements.addElement(node.declaredElement); } super.visitFunctionExpression(node); } @override visitMethodDeclaration(MethodDeclaration node) { ExecutableElement enclosingExecOld = _enclosingExec; try { _enclosingExec = node.declaredElement; super.visitMethodDeclaration(node); } finally { _enclosingExec = enclosingExecOld; } } @override visitSimpleIdentifier(SimpleIdentifier node) { if (node.inDeclarationContext()) { return; } Element element = node.staticElement; bool isIdentifierRead = _isReadIdentifier(node); if (element is PropertyAccessorElement && element.isSynthetic && isIdentifierRead && element.variable is TopLevelVariableElement) { usedElements.addElement(element.variable); } else if (element is LocalVariableElement) { if (isIdentifierRead) { usedElements.addElement(element); } } else { _useIdentifierElement(node); if (element == null || element.enclosingElement is ClassElement && !identical(element, _enclosingExec)) { usedElements.members.add(node.name); if (isIdentifierRead) { usedElements.readMembers.add(node.name); } } } } /// Marks an [Element] of [node] as used in the library. void _useIdentifierElement(Identifier node) { Element element = node.staticElement; if (element == null) { return; } // check if a local element if (!identical(element.library, _enclosingLibrary)) { return; } // ignore references to an element from itself if (identical(element, _enclosingClass)) { return; } if (identical(element, _enclosingExec)) { return; } // ignore places where the element is not actually used if (node.parent is TypeName) { if (element is ClassElement) { AstNode parent2 = node.parent.parent; if (parent2 is IsExpression) { return; } if (parent2 is VariableDeclarationList) { // If it's a field's type, it still counts as used. if (parent2.parent is! FieldDeclaration) { return; } } } } // OK usedElements.addElement(element); } static bool _isReadIdentifier(SimpleIdentifier node) { // not reading at all if (!node.inGetterContext()) { return false; } // check if useless reading AstNode parent = node.parent; if (parent.parent is ExpressionStatement) { if (parent is PrefixExpression || parent is PostfixExpression) { // v++; // ++v; return false; } if (parent is AssignmentExpression && parent.leftHandSide == node) { // v ??= doSomething(); // vs. // v += 2; TokenType operatorType = parent.operator?.type; return operatorType == TokenType.QUESTION_QUESTION_EQ; } } // OK return true; } } /// Maintains and manages contextual type information used for /// inferring types. class InferenceContext { // TODO(leafp): Consider replacing these node properties with a // hash table help in an instance of this class. static const String _typeProperty = 'analyzer.src.generated.InferenceContext.contextType'; /// The error listener on which to record inference information. final ErrorReporter _errorReporter; /// If true, emit hints when types are inferred final bool _inferenceHints; /// Type provider, needed for type matching. final TypeProvider _typeProvider; /// The type system in use. final TypeSystem _typeSystem; /// When no context type is available, this will track the least upper bound /// of all return statements in a lambda. /// /// This will always be kept in sync with [_returnStack]. final List<DartType> _inferredReturn = <DartType>[]; /// A stack of return types for all of the enclosing /// functions and methods. final List<DartType> _returnStack = <DartType>[]; InferenceContext._(TypeProvider typeProvider, this._typeSystem, this._inferenceHints, this._errorReporter) : _typeProvider = typeProvider; /// Get the return type of the current enclosing function, if any. /// /// The type returned for a function is the type that is expected /// to be used in a return or yield context. For ordinary functions /// this is the same as the return type of the function. For async /// functions returning Future<T> and for generator functions /// returning Stream<T> or Iterable<T>, this is T. DartType get returnContext => _returnStack.isNotEmpty ? _returnStack.last : null; /// Records the type of the expression of a return statement. /// /// This will be used for inferring a block bodied lambda, if no context /// type was available. void addReturnOrYieldType(DartType type) { if (_returnStack.isEmpty) { return; } DartType inferred = _inferredReturn.last; inferred = _typeSystem.getLeastUpperBound(type, inferred); _inferredReturn[_inferredReturn.length - 1] = inferred; } /// Pop a return type off of the return stack. /// /// Also record any inferred return type using [setType], unless this node /// already has a context type. This recorded type will be the least upper /// bound of all types added with [addReturnOrYieldType]. void popReturnContext(FunctionBody node) { if (_returnStack.isNotEmpty && _inferredReturn.isNotEmpty) { DartType context = _returnStack.removeLast() ?? DynamicTypeImpl.instance; DartType inferred = _inferredReturn.removeLast(); if (_typeSystem.isSubtypeOf(inferred, context)) { setType(node, inferred); } } else { assert(false); } } /// Push a block function body's return type onto the return stack. void pushReturnContext(FunctionBody node) { _returnStack.add(getContext(node)); _inferredReturn.add(_typeProvider.nullType); } /// Place an info node into the error stream indicating that a /// [type] has been inferred as the type of [node]. void recordInference(Expression node, DartType type) { if (!_inferenceHints) { return; } ErrorCode error; if (node is Literal) { error = StrongModeCode.INFERRED_TYPE_LITERAL; } else if (node is InstanceCreationExpression) { error = StrongModeCode.INFERRED_TYPE_ALLOCATION; } else if (node is FunctionExpression) { error = StrongModeCode.INFERRED_TYPE_CLOSURE; } else { error = StrongModeCode.INFERRED_TYPE; } _errorReporter.reportErrorForNode(error, node, [node, type]); } /// Clear the type information associated with [node]. static void clearType(AstNode node) { node?.setProperty(_typeProperty, null); } /// Look for contextual type information attached to [node], and returns /// the type if found. /// /// The returned type may be partially or completely unknown, denoted with an /// unknown type `?`, for example `List<?>` or `(?, int) -> void`. /// You can use [Dart2TypeSystem.upperBoundForType] or /// [Dart2TypeSystem.lowerBoundForType] if you would prefer a known type /// that represents the bound of the context type. static DartType getContext(AstNode node) => node?.getProperty(_typeProperty); /// Attach contextual type information [type] to [node] for use during /// inference. static void setType(AstNode node, DartType type) { if (type == null || type.isDynamic) { clearType(node); } else { node?.setProperty(_typeProperty, type); } } /// Attach contextual type information [type] to [node] for use during /// inference. static void setTypeFromNode(AstNode innerNode, AstNode outerNode) { setType(innerNode, getContext(outerNode)); } } /// The four states of a field initialization state through a constructor /// signature, not initialized, initialized in the field declaration, /// initialized in the field formal, and finally, initialized in the /// initializers list. class INIT_STATE implements Comparable<INIT_STATE> { static const INIT_STATE NOT_INIT = const INIT_STATE('NOT_INIT', 0); static const INIT_STATE INIT_IN_DECLARATION = const INIT_STATE('INIT_IN_DECLARATION', 1); static const INIT_STATE INIT_IN_FIELD_FORMAL = const INIT_STATE('INIT_IN_FIELD_FORMAL', 2); static const INIT_STATE INIT_IN_INITIALIZERS = const INIT_STATE('INIT_IN_INITIALIZERS', 3); static const List<INIT_STATE> values = const [ NOT_INIT, INIT_IN_DECLARATION, INIT_IN_FIELD_FORMAL, INIT_IN_INITIALIZERS ]; /// The name of this init state. final String name; /// The ordinal value of the init state. final int ordinal; const INIT_STATE(this.name, this.ordinal); @override int get hashCode => ordinal; @override int compareTo(INIT_STATE other) => ordinal - other.ordinal; @override String toString() => name; } /// An AST visitor that is used to re-resolve the initializers of instance /// fields. Although this class is an AST visitor, clients are expected to use /// the method [resolveCompilationUnit] to run it over a compilation unit. class InstanceFieldResolverVisitor extends ResolverVisitor { /// Initialize a newly created visitor to resolve the nodes in an AST node. /// /// The [definingLibrary] is the element for the library containing the node /// being visited. The [source] is the source representing the compilation /// unit containing the node being visited. The [typeProvider] is the object /// used to access the types from the core library. The [errorListener] is the /// error listener that will be informed of any errors that are found during /// resolution. The [nameScope] is the scope used to resolve identifiers in /// the node that will first be visited. If `null` or unspecified, a new /// [LibraryScope] will be created based on the [definingLibrary]. InstanceFieldResolverVisitor( InheritanceManager3 inheritance, LibraryElement definingLibrary, Source source, TypeProvider typeProvider, AnalysisErrorListener errorListener, FeatureSet featureSet, {Scope nameScope}) : super(inheritance, definingLibrary, source, typeProvider, errorListener, featureSet: featureSet, nameScope: nameScope); /// Resolve the instance fields in the given compilation unit [node]. void resolveCompilationUnit(CompilationUnit node) { NodeList<CompilationUnitMember> declarations = node.declarations; int declarationCount = declarations.length; for (int i = 0; i < declarationCount; i++) { CompilationUnitMember declaration = declarations[i]; if (declaration is ClassDeclaration) { _resolveClassDeclaration(declaration); } } } /// Resolve the instance fields in the given class declaration [node]. void _resolveClassDeclaration(ClassDeclaration node) { _enclosingClassDeclaration = node; ClassElement outerType = enclosingClass; Scope outerScope = nameScope; try { enclosingClass = node.declaredElement; typeAnalyzer.thisType = enclosingClass?.thisType; if (enclosingClass == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for class declaration ${node.name.name} in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); // Don't try to re-resolve the initializers if we cannot set up the // right name scope for resolution. } else { nameScope = new ClassScope(nameScope, enclosingClass); NodeList<ClassMember> members = node.members; int length = members.length; for (int i = 0; i < length; i++) { ClassMember member = members[i]; if (member is FieldDeclaration) { _resolveFieldDeclaration(member); } } } } finally { nameScope = outerScope; typeAnalyzer.thisType = outerType?.thisType; enclosingClass = outerType; _enclosingClassDeclaration = null; } } /// Resolve the instance fields in the given field declaration [node]. void _resolveFieldDeclaration(FieldDeclaration node) { if (!node.isStatic) { for (VariableDeclaration field in node.fields.variables) { if (field.initializer != null) { field.initializer.accept(this); FieldElement fieldElement = field.name.staticElement; if (fieldElement.initializer != null) { (fieldElement.initializer as ExecutableElementImpl).returnType = field.initializer.staticType; } } } } } } /// Instances of the class `OverrideVerifier` visit all of the declarations in a /// compilation unit to verify that if they have an override annotation it is /// being used correctly. class OverrideVerifier extends RecursiveAstVisitor { /// The inheritance manager used to find overridden methods. final InheritanceManager3 _inheritance; /// The URI of the library being verified. final Uri _libraryUri; /// The error reporter used to report errors. final ErrorReporter _errorReporter; /// The current class or mixin. InterfaceType _currentType; OverrideVerifier( this._inheritance, LibraryElement library, this._errorReporter) : _libraryUri = library.source.uri; @override visitClassDeclaration(ClassDeclaration node) { _currentType = node.declaredElement.thisType; super.visitClassDeclaration(node); _currentType = null; } @override visitFieldDeclaration(FieldDeclaration node) { for (VariableDeclaration field in node.fields.variables) { FieldElement fieldElement = field.declaredElement; if (fieldElement.hasOverride) { PropertyAccessorElement getter = fieldElement.getter; if (getter != null && _isOverride(getter)) continue; PropertyAccessorElement setter = fieldElement.setter; if (setter != null && _isOverride(setter)) continue; _errorReporter.reportErrorForNode( HintCode.OVERRIDE_ON_NON_OVERRIDING_FIELD, field.name, ); } } } @override visitMethodDeclaration(MethodDeclaration node) { ExecutableElement element = node.declaredElement; if (element.hasOverride && !_isOverride(element)) { if (element is MethodElement) { _errorReporter.reportErrorForNode( HintCode.OVERRIDE_ON_NON_OVERRIDING_METHOD, node.name, ); } else if (element is PropertyAccessorElement) { if (element.isGetter) { _errorReporter.reportErrorForNode( HintCode.OVERRIDE_ON_NON_OVERRIDING_GETTER, node.name, ); } else { _errorReporter.reportErrorForNode( HintCode.OVERRIDE_ON_NON_OVERRIDING_SETTER, node.name, ); } } } } @override visitMixinDeclaration(MixinDeclaration node) { _currentType = node.declaredElement.thisType; super.visitMixinDeclaration(node); _currentType = null; } /// Return `true` if the [member] overrides a member from a superinterface. bool _isOverride(ExecutableElement member) { var name = new Name(_libraryUri, member.name); return _inheritance.getOverridden(_currentType, name) != null; } } /// An AST visitor that is used to resolve some of the nodes within a single /// compilation unit. The nodes that are skipped are those that are within /// function bodies. class PartialResolverVisitor extends ResolverVisitor { /// The static variables and fields that have an initializer. These are the /// variables that need to be re-resolved after static variables have their /// types inferred. A subset of these variables are those whose types should /// be inferred. final List<VariableElement> staticVariables = <VariableElement>[]; /// Initialize a newly created visitor to resolve the nodes in an AST node. /// /// The [definingLibrary] is the element for the library containing the node /// being visited. The [source] is the source representing the compilation /// unit containing the node being visited. The [typeProvider] is the object /// used to access the types from the core library. The [errorListener] is the /// error listener that will be informed of any errors that are found during /// resolution. The [nameScope] is the scope used to resolve identifiers in /// the node that will first be visited. If `null` or unspecified, a new /// [LibraryScope] will be created based on [definingLibrary] and /// [typeProvider]. PartialResolverVisitor( InheritanceManager3 inheritance, LibraryElement definingLibrary, Source source, TypeProvider typeProvider, AnalysisErrorListener errorListener, FeatureSet featureSet, {Scope nameScope}) : super(inheritance, definingLibrary, source, typeProvider, errorListener, featureSet: featureSet, nameScope: nameScope); @override void visitBlockFunctionBody(BlockFunctionBody node) { if (_shouldBeSkipped(node)) { return null; } super.visitBlockFunctionBody(node); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { if (_shouldBeSkipped(node)) { return null; } super.visitExpressionFunctionBody(node); } @override void visitFieldDeclaration(FieldDeclaration node) { if (node.isStatic) { _addStaticVariables(node.fields.variables); } super.visitFieldDeclaration(node); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { _addStaticVariables(node.variables.variables); super.visitTopLevelVariableDeclaration(node); } /// Add all of the [variables] with initializers to the list of variables /// whose type can be inferred. Technically, we only infer the types of /// variables that do not have a static type, but all variables with /// initializers potentially need to be re-resolved after inference because /// they might refer to a field whose type was inferred. void _addStaticVariables(List<VariableDeclaration> variables) { int length = variables.length; for (int i = 0; i < length; i++) { VariableDeclaration variable = variables[i]; if (variable.name.name.isNotEmpty && variable.initializer != null) { staticVariables.add(variable.declaredElement); } } } /// Return `true` if the given function body should be skipped because it is /// the body of a top-level function, method or constructor. bool _shouldBeSkipped(FunctionBody body) { AstNode parent = body.parent; if (parent is MethodDeclaration) { return parent.body == body; } if (parent is ConstructorDeclaration) { return parent.body == body; } if (parent is FunctionExpression) { AstNode parent2 = parent.parent; if (parent2 is FunctionDeclaration && parent2.parent is! FunctionDeclarationStatement) { return parent.body == body; } } return false; } } /// The enumeration `ResolverErrorCode` defines the error codes used for errors /// detected by the resolver. 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 ResolverErrorCode extends ErrorCode { static const ResolverErrorCode BREAK_LABEL_ON_SWITCH_MEMBER = const ResolverErrorCode('BREAK_LABEL_ON_SWITCH_MEMBER', "Break label resolves to case or default statement"); static const ResolverErrorCode CONTINUE_LABEL_ON_SWITCH = const ResolverErrorCode('CONTINUE_LABEL_ON_SWITCH', "A continue label resolves to switch, must be loop or switch member"); /// Parts: It is a static warning if the referenced part declaration /// <i>p</i> names a library that does not have a library tag. /// /// Parameters: /// 0: the URI of the expected library /// 1: the non-matching actual library name from the "part of" declaration static const ResolverErrorCode PART_OF_UNNAMED_LIBRARY = const ResolverErrorCode( 'PART_OF_UNNAMED_LIBRARY', "Library is unnamed. Expected a URI not a library name '{0}' in the " "part-of directive.", correction: "Try changing the part-of directive to a URI, or try including a" " different part."); /// 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 ResolverErrorCode(String name, String message, {String correction, bool hasPublishedDocs}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs ?? false); @override ErrorSeverity get errorSeverity => type.severity; @override ErrorType get type => ErrorType.COMPILE_TIME_ERROR; } /// Instances of the class `ResolverVisitor` are used to resolve the nodes /// within a single compilation unit. class ResolverVisitor extends ScopedVisitor { /** * The manager for the inheritance mappings. */ final InheritanceManager3 inheritance; final AnalysisOptionsImpl _analysisOptions; /** * The feature set that is enabled for the current unit. */ final FeatureSet _featureSet; final bool _uiAsCodeEnabled; /// Helper for extension method resolution. ExtensionMemberResolver extensionResolver; /// The object used to resolve the element associated with the current node. ElementResolver elementResolver; /// The object used to compute the type associated with the current node. StaticTypeAnalyzer typeAnalyzer; /// The type system in use during resolution. Dart2TypeSystem typeSystem; /// The class declaration representing the class containing the current node, /// or `null` if the current node is not contained in a class. ClassDeclaration _enclosingClassDeclaration; /// The function type alias representing the function type containing the /// current node, or `null` if the current node is not contained in a function /// type alias. FunctionTypeAlias _enclosingFunctionTypeAlias; /// The element representing the function containing the current node, or /// `null` if the current node is not contained in a function. ExecutableElement _enclosingFunction; /// The mixin declaration representing the class containing the current node, /// or `null` if the current node is not contained in a mixin. MixinDeclaration _enclosingMixinDeclaration; InferenceContext inferenceContext; /// The object keeping track of which elements have had their types promoted. TypePromotionManager _promoteManager; final FlowAnalysisHelper _flowAnalysis; /// A comment before a function should be resolved in the context of the /// function. But when we incrementally resolve a comment, we don't want to /// resolve the whole function. /// /// So, this flag is set to `true`, when just context of the function should /// be built and the comment resolved. bool resolveOnlyCommentInFunctionBody = false; /// The type of the expression of the immediately enclosing [SwitchStatement], /// or `null` if not in a [SwitchStatement]. DartType _enclosingSwitchStatementExpressionType; /// Initialize a newly created visitor to resolve the nodes in an AST node. /// /// [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. /// /// The [definingLibrary] is the element for the library containing the node /// being visited. The [source] is the source representing the compilation /// unit containing the node being visited. The [typeProvider] is the object /// used to access the types from the core library. The [errorListener] is the /// error listener that will be informed of any errors that are found during /// resolution. The [nameScope] is the scope used to resolve identifiers in /// the node that will first be visited. If `null` or unspecified, a new /// [LibraryScope] will be created based on [definingLibrary] and /// [typeProvider]. /// /// TODO(paulberry): make [featureSet] a required parameter (this will be a /// breaking change). ResolverVisitor( InheritanceManagerBase inheritanceManager, LibraryElement definingLibrary, Source source, TypeProvider typeProvider, AnalysisErrorListener errorListener, {FeatureSet featureSet, Scope nameScope, bool propagateTypes: true, reportConstEvaluationErrors: true, FlowAnalysisHelper flowAnalysisHelper}) : this._( inheritanceManager.asInheritanceManager3, definingLibrary, source, typeProvider, errorListener, featureSet ?? definingLibrary.context.analysisOptions.contextFeatures, nameScope, propagateTypes, reportConstEvaluationErrors, flowAnalysisHelper); ResolverVisitor._( this.inheritance, LibraryElement definingLibrary, Source source, TypeProvider typeProvider, AnalysisErrorListener errorListener, FeatureSet featureSet, Scope nameScope, bool propagateTypes, reportConstEvaluationErrors, this._flowAnalysis) : _analysisOptions = definingLibrary.context.analysisOptions, _featureSet = featureSet, _uiAsCodeEnabled = featureSet.isEnabled(Feature.control_flow_collections) || featureSet.isEnabled(Feature.spread_collections), super(definingLibrary, source, typeProvider, errorListener, nameScope: nameScope) { this.typeSystem = definingLibrary.context.typeSystem; this._promoteManager = TypePromotionManager(typeSystem); this.extensionResolver = ExtensionMemberResolver(this); this.elementResolver = new ElementResolver(this, reportConstEvaluationErrors: reportConstEvaluationErrors); bool strongModeHints = false; AnalysisOptions options = _analysisOptions; if (options is AnalysisOptionsImpl) { strongModeHints = options.strongModeHints; } this.inferenceContext = new InferenceContext._( typeProvider, typeSystem, strongModeHints, errorReporter); this.typeAnalyzer = new StaticTypeAnalyzer(this, featureSet); } /// Return the element representing the function containing the current node, /// or `null` if the current node is not contained in a function. /// /// @return the element representing the function containing the current node ExecutableElement get enclosingFunction => _enclosingFunction; /// Return the object providing promoted or declared types of variables. LocalVariableTypeProvider get localVariableTypeProvider { if (_flowAnalysis != null) { return _flowAnalysis.localVariableTypeProvider; } else { return _promoteManager.localVariableTypeProvider; } } 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); /// Return the static element associated with the given expression whose type /// can be overridden, or `null` if there is no element whose type can be /// overridden. /// /// @param expression the expression with which the element is associated /// @return the element associated with the given expression VariableElement getOverridableStaticElement(Expression expression) { Element element; if (expression is SimpleIdentifier) { element = expression.staticElement; } else if (expression is PrefixedIdentifier) { element = expression.staticElement; } else if (expression is PropertyAccess) { element = expression.propertyName.staticElement; } if (element is VariableElement) { return element; } return null; } /// Given a downward inference type [fnType], and the declared /// [typeParameterList] for a function expression, determines if we can enable /// downward inference and if so, returns the function type to use for /// inference. /// /// This will return null if inference is not possible. This happens when /// there is no way we can find a subtype of the function type, given the /// provided type parameter list. FunctionType matchFunctionTypeParameters( TypeParameterList typeParameterList, FunctionType fnType) { if (typeParameterList == null) { if (fnType.typeFormals.isEmpty) { return fnType; } // A non-generic function cannot be a subtype of a generic one. return null; } NodeList<TypeParameter> typeParameters = typeParameterList.typeParameters; if (fnType.typeFormals.isEmpty) { // TODO(jmesserly): this is a legal subtype. We don't currently infer // here, but we could. This is similar to // Dart2TypeSystem.inferFunctionTypeInstantiation, but we don't // have the FunctionType yet for the current node, so it's not quite // straightforward to apply. return null; } if (fnType.typeFormals.length != typeParameters.length) { // A subtype cannot have different number of type formals. return null; } // Same number of type formals. Instantiate the function type so its // parameter and return type are in terms of the surrounding context. return fnType.instantiate(typeParameters.map((TypeParameter t) { return t.declaredElement.instantiate( nullabilitySuffix: noneOrStarSuffix, ); }).toList()); } /// If it is appropriate to do so, override 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 overridden /// @param potentialType the potential type of the elements /// @param allowPrecisionLoss see @{code overrideVariable} docs void overrideExpression(Expression expression, DartType potentialType, bool allowPrecisionLoss, bool setExpressionType) { // TODO(brianwilkerson) Remove this method. } /// Set the enclosing function body when partial AST is resolved. void prepareCurrentFunctionBody(FunctionBody body) { _promoteManager.enterFunctionBody(body); } /// Set information about enclosing declarations. void prepareEnclosingDeclarations({ ClassElement enclosingClassElement, ExecutableElement enclosingExecutableElement, }) { _enclosingClassDeclaration = null; enclosingClass = enclosingClassElement; typeAnalyzer.thisType = enclosingClass?.thisType; _enclosingFunction = enclosingExecutableElement; } /// A client is about to resolve a member in the given class declaration. void prepareToResolveMembersInClass(ClassDeclaration node) { _enclosingClassDeclaration = node; enclosingClass = node.declaredElement; typeAnalyzer.thisType = enclosingClass?.thisType; } /// Visit the given [comment] if it is not `null`. void safelyVisitComment(Comment comment) { if (comment != null) { super.visitComment(comment); } } @override void visitAnnotation(Annotation node) { AstNode parent = node.parent; if (identical(parent, _enclosingClassDeclaration) || identical(parent, _enclosingFunctionTypeAlias) || identical(parent, _enclosingMixinDeclaration)) { return; } node.name?.accept(this); node.constructorName?.accept(this); Element element = node.element; if (element is ExecutableElement) { InferenceContext.setType(node.arguments, element.type); } node.arguments?.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); ElementAnnotationImpl elementAnnotationImpl = node.elementAnnotation; if (elementAnnotationImpl == null) { // Analyzer ignores annotations on "part of" directives. assert(parent is PartOfDirective); } else { elementAnnotationImpl.annotationAst = _createCloner().cloneNode(node); } } @override void visitArgumentList(ArgumentList node) { DartType callerType = InferenceContext.getContext(node); if (callerType is FunctionType) { Map<String, DartType> namedParameterTypes = callerType.namedParameterTypes; List<DartType> normalParameterTypes = callerType.normalParameterTypes; List<DartType> optionalParameterTypes = callerType.optionalParameterTypes; int normalCount = normalParameterTypes.length; int optionalCount = optionalParameterTypes.length; NodeList<Expression> arguments = node.arguments; Iterable<Expression> positional = arguments.takeWhile((l) => l is! NamedExpression); Iterable<Expression> required = positional.take(normalCount); Iterable<Expression> optional = positional.skip(normalCount).take(optionalCount); Iterable<Expression> named = arguments.skipWhile((l) => l is! NamedExpression); //TODO(leafp): Consider using the parameter elements here instead. //TODO(leafp): Make sure that the parameter elements are getting // setup correctly with inference. int index = 0; for (Expression argument in required) { InferenceContext.setType(argument, normalParameterTypes[index++]); } index = 0; for (Expression argument in optional) { InferenceContext.setType(argument, optionalParameterTypes[index++]); } for (Expression argument in named) { if (argument is NamedExpression) { DartType type = namedParameterTypes[argument.name.label.name]; if (type != null) { InferenceContext.setType(argument, type); } } } } super.visitArgumentList(node); } @override void visitAssertInitializer(AssertInitializer node) { InferenceContext.setType(node.condition, typeProvider.boolType); super.visitAssertInitializer(node); } @override void visitAssertStatement(AssertStatement node) { InferenceContext.setType(node.condition, typeProvider.boolType); super.visitAssertStatement(node); } @override void visitAssignmentExpression(AssignmentExpression node) { var left = node.leftHandSide; var right = node.rightHandSide; left?.accept(this); var leftLocalVariable = _flowAnalysis?.assignmentExpression(node); TokenType operator = node.operator.type; if (operator == TokenType.EQ || operator == TokenType.QUESTION_QUESTION_EQ) { InferenceContext.setType(right, left.staticType); } right?.accept(this); _flowAnalysis?.assignmentExpression_afterRight(leftLocalVariable, right); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitAwaitExpression(AwaitExpression node) { DartType contextType = InferenceContext.getContext(node); if (contextType != null) { var futureUnion = _createFutureOr(contextType); InferenceContext.setType(node.expression, futureUnion); } super.visitAwaitExpression(node); } @override void visitBinaryExpression(BinaryExpression node) { TokenType operator = node.operator.type; Expression left = node.leftOperand; Expression right = node.rightOperand; var flow = _flowAnalysis?.flow; if (operator == TokenType.AMPERSAND_AMPERSAND) { InferenceContext.setType(left, typeProvider.boolType); InferenceContext.setType(right, typeProvider.boolType); // TODO(scheglov) Do we need these checks for null? left?.accept(this); if (_flowAnalysis != null) { flow?.logicalBinaryOp_rightBegin(left, isAnd: true); _flowAnalysis.checkUnreachableNode(right); right.accept(this); flow?.logicalBinaryOp_end(node, right, isAnd: true); } else { _promoteManager.visitBinaryExpression_and_rhs( left, right, () { right.accept(this); }, ); } node.accept(elementResolver); } else if (operator == TokenType.BAR_BAR) { InferenceContext.setType(left, typeProvider.boolType); InferenceContext.setType(right, typeProvider.boolType); left?.accept(this); flow?.logicalBinaryOp_rightBegin(left, isAnd: false); _flowAnalysis?.checkUnreachableNode(right); right.accept(this); flow?.logicalBinaryOp_end(node, right, isAnd: false); node.accept(elementResolver); } else if (operator == TokenType.BANG_EQ || operator == TokenType.EQ_EQ) { left.accept(this); right.accept(this); node.accept(elementResolver); _flowAnalysis?.binaryExpression_equal(node, left, right, notEqual: operator == TokenType.BANG_EQ); } else { if (operator == TokenType.QUESTION_QUESTION) { InferenceContext.setTypeFromNode(left, node); } left?.accept(this); // Call ElementResolver.visitBinaryExpression to resolve the user-defined // operator method, if applicable. node.accept(elementResolver); if (operator == TokenType.QUESTION_QUESTION) { // Set the right side, either from the context, or using the information // from the left side if it is more precise. DartType contextType = InferenceContext.getContext(node); DartType leftType = left?.staticType; if (contextType == null || contextType.isDynamic) { contextType = leftType; } InferenceContext.setType(right, contextType); } else { var invokeType = node.staticInvokeType; if (invokeType != null && invokeType.parameters.isNotEmpty) { // If this is a user-defined operator, set the right operand context // using the operator method's parameter type. var rightParam = invokeType.parameters[0]; InferenceContext.setType(right, rightParam.type); } } if (operator == TokenType.QUESTION_QUESTION) { flow?.ifNullExpression_rightBegin(); right.accept(this); flow?.ifNullExpression_end(); } else { right?.accept(this); } } node.accept(typeAnalyzer); } @override void visitBlockFunctionBody(BlockFunctionBody node) { try { _flowAnalysis?.functionBody_enter(node); inferenceContext.pushReturnContext(node); super.visitBlockFunctionBody(node); } finally { inferenceContext.popReturnContext(node); _flowAnalysis?.functionBody_exit(node); } } @override void visitBooleanLiteral(BooleanLiteral node) { _flowAnalysis?.flow?.booleanLiteral(node, node.value); super.visitBooleanLiteral(node); } @override void visitBreakStatement(BreakStatement node) { // // We do not visit the label because it needs to be visited in the context // of the statement. // node.accept(elementResolver); node.accept(typeAnalyzer); _flowAnalysis?.breakStatement(node); } @override void visitCascadeExpression(CascadeExpression node) { InferenceContext.setTypeFromNode(node.target, node); super.visitCascadeExpression(node); } @override void visitClassDeclaration(ClassDeclaration node) { // // Resolve the metadata in the library scope. // node.metadata?.accept(this); _enclosingClassDeclaration = node; // // Continue the class resolution. // ClassElement outerType = enclosingClass; try { enclosingClass = node.declaredElement; typeAnalyzer.thisType = enclosingClass?.thisType; super.visitClassDeclaration(node); node.accept(elementResolver); node.accept(typeAnalyzer); } finally { typeAnalyzer.thisType = outerType?.thisType; enclosingClass = outerType; _enclosingClassDeclaration = null; } } @override void visitComment(Comment node) { AstNode parent = node.parent; if (parent is FunctionDeclaration || parent is FunctionTypeAlias || parent is ConstructorDeclaration || parent is MethodDeclaration) { return; } super.visitComment(node); } @override void visitCommentReference(CommentReference node) { // // We do not visit the identifier because it needs to be visited in the // context of the reference. // node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitCompilationUnit(CompilationUnit node) { NodeList<Directive> directives = node.directives; int directiveCount = directives.length; for (int i = 0; i < directiveCount; i++) { directives[i].accept(this); } NodeList<CompilationUnitMember> declarations = node.declarations; int declarationCount = declarations.length; for (int i = 0; i < declarationCount; i++) { declarations[i].accept(this); } node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitConditionalExpression(ConditionalExpression node) { Expression condition = node.condition; var flow = _flowAnalysis?.flow; // TODO(scheglov) Do we need these checks for null? condition?.accept(this); Expression thenExpression = node.thenExpression; InferenceContext.setTypeFromNode(thenExpression, node); if (_flowAnalysis != null) { if (flow != null) { flow.conditional_thenBegin(condition); _flowAnalysis.checkUnreachableNode(thenExpression); } thenExpression.accept(this); } else { _promoteManager.visitConditionalExpression_then( condition, thenExpression, () { thenExpression.accept(this); }, ); } Expression elseExpression = node.elseExpression; InferenceContext.setTypeFromNode(elseExpression, node); if (flow != null) { flow.conditional_elseBegin(thenExpression); _flowAnalysis.checkUnreachableNode(elseExpression); elseExpression.accept(this); flow.conditional_end(node, elseExpression); } else { elseExpression.accept(this); } node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; try { _promoteManager.enterFunctionBody(node.body); _enclosingFunction = node.declaredElement; FunctionType type = _enclosingFunction.type; InferenceContext.setType(node.body, type.returnType); super.visitConstructorDeclaration(node); } finally { _promoteManager.exitFunctionBody(); _enclosingFunction = outerFunction; } ConstructorElementImpl constructor = node.declaredElement; constructor.constantInitializers = _createCloner().cloneNodeList(node.initializers); } @override void visitConstructorDeclarationInScope(ConstructorDeclaration node) { super.visitConstructorDeclarationInScope(node); // Because of needing a different scope for the initializer list, the // overridden implementation of this method cannot cause the visitNode // method to be invoked. As a result, we have to hard-code using the // element resolver and type analyzer to visit the constructor declaration. node.accept(elementResolver); node.accept(typeAnalyzer); safelyVisitComment(node.documentationComment); } @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { // // We visit the expression, but do not visit the field name because it needs // to be visited in the context of the constructor field initializer node. // FieldElement fieldElement = enclosingClass.getField(node.fieldName.name); InferenceContext.setType(node.expression, fieldElement?.type); node.expression?.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitConstructorName(ConstructorName node) { // // We do not visit either the type name, because it won't be visited anyway, // or the name, because it needs to be visited in the context of the // constructor name. // node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitContinueStatement(ContinueStatement node) { // // We do not visit the label because it needs to be visited in the context // of the statement. // node.accept(elementResolver); node.accept(typeAnalyzer); _flowAnalysis?.continueStatement(node); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { InferenceContext.setType(node.defaultValue, node.declaredElement?.type); super.visitDefaultFormalParameter(node); ParameterElement element = node.declaredElement; if (element.initializer != null && node.defaultValue != null) { (element.initializer as FunctionElementImpl).returnType = node.defaultValue.staticType; } // Clone the ASTs for default formal parameters, so that we can use them // during constant evaluation. if (element is ConstVariableElement && !_hasSerializedConstantInitializer(element)) { (element as ConstVariableElement).constantInitializer = _createCloner().cloneNode(node.defaultValue); } } @override void visitDoStatementInScope(DoStatement node) { _flowAnalysis?.checkUnreachableNode(node); var body = node.body; var condition = node.condition; InferenceContext.setType(node.condition, typeProvider.boolType); _flowAnalysis?.flow?.doStatement_bodyBegin( node, _flowAnalysis.assignedVariables.writtenInNode(node), ); visitStatementInScope(body); _flowAnalysis?.flow?.doStatement_conditionBegin(); condition.accept(this); _flowAnalysis?.flow?.doStatement_end(node.condition); } @override void visitEmptyFunctionBody(EmptyFunctionBody node) { if (resolveOnlyCommentInFunctionBody) { return; } super.visitEmptyFunctionBody(node); } @override void visitEnumDeclaration(EnumDeclaration node) { // // Resolve the metadata in the library scope // and associate the annotations with the element. // if (node.metadata != null) { node.metadata.accept(this); ElementResolver.resolveMetadata(node); node.constants.forEach(ElementResolver.resolveMetadata); } // // Continue the enum resolution. // ClassElement outerType = enclosingClass; try { enclosingClass = node.declaredElement; typeAnalyzer.thisType = enclosingClass?.thisType; super.visitEnumDeclaration(node); node.accept(elementResolver); node.accept(typeAnalyzer); } finally { typeAnalyzer.thisType = outerType?.thisType; enclosingClass = outerType; _enclosingClassDeclaration = null; } } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { if (resolveOnlyCommentInFunctionBody) { return; } try { _flowAnalysis?.functionBody_enter(node); InferenceContext.setTypeFromNode(node.expression, node); inferenceContext.pushReturnContext(node); super.visitExpressionFunctionBody(node); DartType type = node.expression.staticType; if (_enclosingFunction.isAsynchronous) { type = typeSystem.flatten(type); } if (type != null) { inferenceContext.addReturnOrYieldType(type); } } finally { inferenceContext.popReturnContext(node); _flowAnalysis?.functionBody_exit(node); } } @override void visitExtensionDeclaration(ExtensionDeclaration node) { // // Resolve the metadata in the library scope // and associate the annotations with the element. // if (node.metadata != null) { node.metadata.accept(this); ElementResolver.resolveMetadata(node); } // // Continue the extension resolution. // try { DartType extendedType = node.declaredElement.extendedType; typeAnalyzer.thisType = typeSystem.resolveToBound(extendedType); super.visitExtensionDeclaration(node); node.accept(elementResolver); node.accept(typeAnalyzer); } finally { typeAnalyzer.thisType = null; } } @override void visitExtensionOverride(ExtensionOverride node) { node.extensionName.accept(this); node.typeArguments?.accept(this); ExtensionMemberResolver(this).setOverrideReceiverContextType(node); node.argumentList.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitForElementInScope(ForElement node) { ForLoopParts forLoopParts = node.forLoopParts; if (forLoopParts is ForParts) { if (forLoopParts is ForPartsWithDeclarations) { forLoopParts.variables?.accept(this); } else if (forLoopParts is ForPartsWithExpression) { forLoopParts.initialization?.accept(this); } var condition = forLoopParts.condition; InferenceContext.setType(condition, typeProvider.boolType); _flowAnalysis?.for_conditionBegin(node, condition); condition?.accept(this); _flowAnalysis?.for_bodyBegin(node, condition); node.body?.accept(this); _flowAnalysis?.flow?.for_updaterBegin(); forLoopParts.updaters.accept(this); _flowAnalysis?.flow?.for_end(); } else if (forLoopParts is ForEachParts) { Expression iterable = forLoopParts.iterable; DeclaredIdentifier loopVariable; DartType valueType; Element identifierElement; if (forLoopParts is ForEachPartsWithDeclaration) { loopVariable = forLoopParts.loopVariable; valueType = loopVariable?.type?.type ?? UnknownInferredType.instance; } else if (forLoopParts is ForEachPartsWithIdentifier) { SimpleIdentifier identifier = forLoopParts.identifier; identifier?.accept(this); identifierElement = identifier?.staticElement; if (identifierElement is VariableElement) { valueType = identifierElement.type; } else if (identifierElement is PropertyAccessorElement) { if (identifierElement.parameters.isNotEmpty) { valueType = identifierElement.parameters[0].type; } } } if (valueType != null) { InterfaceType targetType = (node.awaitKeyword == null) ? typeProvider.iterableType2(valueType) : typeProvider.streamType2(valueType); InferenceContext.setType(iterable, targetType); } // // We visit the iterator before the loop variable because the loop // variable cannot be in scope while visiting the iterator. // iterable?.accept(this); loopVariable?.accept(this); _flowAnalysis?.flow?.forEach_bodyBegin( _flowAnalysis.assignedVariables.writtenInNode(node), identifierElement is VariableElement ? identifierElement : loopVariable.declaredElement); node.body?.accept(this); _flowAnalysis?.flow?.forEach_end(); node.accept(elementResolver); node.accept(typeAnalyzer); } } @override void visitForStatementInScope(ForStatement node) { _flowAnalysis?.checkUnreachableNode(node); ForLoopParts forLoopParts = node.forLoopParts; if (forLoopParts is ForParts) { if (forLoopParts is ForPartsWithDeclarations) { forLoopParts.variables?.accept(this); } else if (forLoopParts is ForPartsWithExpression) { forLoopParts.initialization?.accept(this); } var condition = forLoopParts.condition; InferenceContext.setType(condition, typeProvider.boolType); _flowAnalysis?.for_conditionBegin(node, condition); if (condition != null) { condition.accept(this); } _flowAnalysis?.for_bodyBegin(node, condition); visitStatementInScope(node.body); _flowAnalysis?.flow?.for_updaterBegin(); forLoopParts.updaters.accept(this); _flowAnalysis?.flow?.for_end(); } else if (forLoopParts is ForEachParts) { Expression iterable = forLoopParts.iterable; DeclaredIdentifier loopVariable; SimpleIdentifier identifier; Element identifierElement; if (forLoopParts is ForEachPartsWithDeclaration) { loopVariable = forLoopParts.loopVariable; } else if (forLoopParts is ForEachPartsWithIdentifier) { identifier = forLoopParts.identifier; identifier?.accept(this); } DartType valueType; if (loopVariable != null) { TypeAnnotation typeAnnotation = loopVariable.type; valueType = typeAnnotation?.type ?? UnknownInferredType.instance; } if (identifier != null) { identifierElement = identifier.staticElement; if (identifierElement is VariableElement) { valueType = identifierElement.type; } else if (identifierElement is PropertyAccessorElement) { if (identifierElement.parameters.isNotEmpty) { valueType = identifierElement.parameters[0].type; } } } if (valueType != null) { InterfaceType targetType = (node.awaitKeyword == null) ? typeProvider.iterableType2(valueType) : typeProvider.streamType2(valueType); InferenceContext.setType(iterable, targetType); } // // We visit the iterator before the loop variable because the loop variable // cannot be in scope while visiting the iterator. // iterable?.accept(this); loopVariable?.accept(this); _flowAnalysis?.flow?.forEach_bodyBegin( _flowAnalysis.assignedVariables.writtenInNode(node), identifierElement is VariableElement ? identifierElement : loopVariable.declaredElement); Statement body = node.body; if (body != null) { visitStatementInScope(body); } _flowAnalysis?.flow?.forEach_end(); node.accept(elementResolver); node.accept(typeAnalyzer); } } @override void visitFunctionDeclaration(FunctionDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; try { SimpleIdentifier functionName = node.name; _promoteManager.enterFunctionBody(node.functionExpression.body); _enclosingFunction = functionName.staticElement as ExecutableElement; InferenceContext.setType( node.functionExpression, _enclosingFunction.type); super.visitFunctionDeclaration(node); } finally { _promoteManager.exitFunctionBody(); _enclosingFunction = outerFunction; } } @override void visitFunctionDeclarationInScope(FunctionDeclaration node) { super.visitFunctionDeclarationInScope(node); safelyVisitComment(node.documentationComment); } @override void visitFunctionExpression(FunctionExpression node) { ExecutableElement outerFunction = _enclosingFunction; try { if (_flowAnalysis != null) { _flowAnalysis.flow?.functionExpression_begin(); } else { _promoteManager.enterFunctionBody(node.body); } _enclosingFunction = node.declaredElement; DartType functionType = InferenceContext.getContext(node); if (functionType is FunctionType) { functionType = matchFunctionTypeParameters(node.typeParameters, functionType); if (functionType is FunctionType) { _inferFormalParameterList(node.parameters, functionType); InferenceContext.setType( node.body, _computeReturnOrYieldType(functionType.returnType)); } } super.visitFunctionExpression(node); } finally { if (_flowAnalysis != null) { _flowAnalysis.flow?.functionExpression_end(); } else { _promoteManager.exitFunctionBody(); } _enclosingFunction = outerFunction; } } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { node.function?.accept(this); node.accept(elementResolver); _inferArgumentTypesForInvocation(node); node.argumentList?.accept(this); node.accept(typeAnalyzer); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { // Resolve the metadata in the library scope. if (node.metadata != null) { node.metadata.accept(this); } FunctionTypeAlias outerAlias = _enclosingFunctionTypeAlias; _enclosingFunctionTypeAlias = node; try { super.visitFunctionTypeAlias(node); } finally { _enclosingFunctionTypeAlias = outerAlias; } } @override void visitFunctionTypeAliasInScope(FunctionTypeAlias node) { super.visitFunctionTypeAliasInScope(node); safelyVisitComment(node.documentationComment); } @override void visitGenericTypeAliasInFunctionScope(GenericTypeAlias node) { super.visitGenericTypeAliasInFunctionScope(node); safelyVisitComment(node.documentationComment); } @override void visitHideCombinator(HideCombinator node) {} @override void visitIfElement(IfElement node) { Expression condition = node.condition; InferenceContext.setType(condition, typeProvider.boolType); // TODO(scheglov) Do we need these checks for null? condition?.accept(this); CollectionElement thenElement = node.thenElement; _promoteManager.visitIfElement_thenElement( condition, thenElement, () { thenElement.accept(this); }, ); node.elseElement?.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitIfStatement(IfStatement node) { _flowAnalysis?.checkUnreachableNode(node); Expression condition = node.condition; InferenceContext.setType(condition, typeProvider.boolType); condition?.accept(this); Statement thenStatement = node.thenStatement; if (_flowAnalysis != null) { _flowAnalysis.flow.ifStatement_thenBegin(condition); visitStatementInScope(thenStatement); } else { _promoteManager.visitIfStatement_thenStatement( condition, thenStatement, () { visitStatementInScope(thenStatement); }, ); } Statement elseStatement = node.elseStatement; if (elseStatement != null) { _flowAnalysis?.flow?.ifStatement_elseBegin(); visitStatementInScope(elseStatement); } _flowAnalysis?.flow?.ifStatement_end(elseStatement != null); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitIndexExpression(IndexExpression node) { node.target?.accept(this); node.accept(elementResolver); var method = node.staticElement; if (method != null && method.parameters.isNotEmpty) { var indexParam = node.staticElement.parameters[0]; InferenceContext.setType(node.index, indexParam.type); } node.index?.accept(this); node.accept(typeAnalyzer); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { node.constructorName?.accept(this); _inferArgumentTypesForInstanceCreate(node); node.argumentList?.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitIsExpression(IsExpression node) { super.visitIsExpression(node); _flowAnalysis?.isExpression(node); } @override void visitLabel(Label node) {} @override void visitLibraryIdentifier(LibraryIdentifier node) {} @override void visitListLiteral(ListLiteral node) { InterfaceType listType; TypeArgumentList typeArguments = node.typeArguments; if (typeArguments != null) { if (typeArguments.arguments.length == 1) { DartType elementType = typeArguments.arguments[0].type; if (!elementType.isDynamic) { listType = typeProvider.listType2(elementType); } } } else { listType = typeAnalyzer.inferListType(node, downwards: true); } if (listType != null) { DartType elementType = listType.typeArguments[0]; DartType iterableType = typeProvider.iterableType2(elementType); _pushCollectionTypesDownToAll(node.elements, elementType: elementType, iterableType: iterableType); InferenceContext.setType(node, listType); } else { InferenceContext.clearType(node); } super.visitListLiteral(node); } @override void visitMethodDeclaration(MethodDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; try { _promoteManager.enterFunctionBody(node.body); _enclosingFunction = node.declaredElement; DartType returnType = _computeReturnOrYieldType(_enclosingFunction.type?.returnType); InferenceContext.setType(node.body, returnType); super.visitMethodDeclaration(node); } finally { _promoteManager.exitFunctionBody(); _enclosingFunction = outerFunction; } } @override void visitMethodDeclarationInScope(MethodDeclaration node) { super.visitMethodDeclarationInScope(node); safelyVisitComment(node.documentationComment); } @override void visitMethodInvocation(MethodInvocation node) { // // We visit the target and argument list, but do not visit the method name // because it needs to be visited in the context of the invocation. // node.target?.accept(this); node.typeArguments?.accept(this); node.accept(elementResolver); _inferArgumentTypesForInvocation(node); node.argumentList?.accept(this); node.accept(typeAnalyzer); } @override void visitMixinDeclaration(MixinDeclaration node) { // // Resolve the metadata in the library scope. // node.metadata?.accept(this); _enclosingMixinDeclaration = node; // // Continue the class resolution. // ClassElement outerType = enclosingClass; try { enclosingClass = node.declaredElement; typeAnalyzer.thisType = enclosingClass?.thisType; super.visitMixinDeclaration(node); node.accept(elementResolver); node.accept(typeAnalyzer); } finally { typeAnalyzer.thisType = outerType?.thisType; enclosingClass = outerType; _enclosingMixinDeclaration = null; } } @override void visitNamedExpression(NamedExpression node) { InferenceContext.setTypeFromNode(node.expression, node); super.visitNamedExpression(node); } @override void visitNode(AstNode node) { _flowAnalysis?.checkUnreachableNode(node); node.visitChildren(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitParenthesizedExpression(ParenthesizedExpression node) { InferenceContext.setTypeFromNode(node.expression, node); super.visitParenthesizedExpression(node); } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { // // We visit the prefix, but do not visit the identifier because it needs to // be visited in the context of the prefix. // node.prefix?.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitPrefixExpression(PrefixExpression node) { super.visitPrefixExpression(node); var operator = node.operator.type; if (operator == TokenType.BANG) { _flowAnalysis?.flow?.logicalNot_end(node, node.operand); } } @override void visitPropertyAccess(PropertyAccess node) { // // We visit the target, but do not visit the property name because it needs // to be visited in the context of the property access node. // node.target?.accept(this); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { // // We visit the argument list, but do not visit the optional identifier // because it needs to be visited in the context of the constructor // invocation. // node.accept(elementResolver); InferenceContext.setType(node.argumentList, node.staticElement?.type); node.argumentList?.accept(this); node.accept(typeAnalyzer); } @override void visitRethrowExpression(RethrowExpression node) { super.visitRethrowExpression(node); _flowAnalysis?.flow?.handleExit(); } @override void visitReturnStatement(ReturnStatement node) { Expression e = node.expression; InferenceContext.setType(e, inferenceContext.returnContext); super.visitReturnStatement(node); DartType type = e?.staticType; // Generators cannot return values, so don't try to do any inference if // we're processing erroneous code. if (type != null && _enclosingFunction?.isGenerator == false) { if (_enclosingFunction.isAsynchronous) { type = typeSystem.flatten(type); } inferenceContext.addReturnOrYieldType(type); } _flowAnalysis?.flow?.handleExit(); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { var typeArguments = node.typeArguments?.arguments; InterfaceType literalType; var literalResolution = _computeSetOrMapResolution(node); if (literalResolution.kind == _LiteralResolutionKind.set) { if (typeArguments != null && typeArguments.length == 1) { var elementType = typeArguments[0].type; literalType = typeProvider.setType2(elementType); } else { literalType = typeAnalyzer.inferSetTypeDownwards( node, literalResolution.contextType); } } else if (literalResolution.kind == _LiteralResolutionKind.map) { if (typeArguments != null && typeArguments.length == 2) { var keyType = typeArguments[0].type; var valueType = typeArguments[1].type; literalType = typeProvider.mapType2(keyType, valueType); } else { literalType = typeAnalyzer.inferMapTypeDownwards( node, literalResolution.contextType); } } else { assert(literalResolution.kind == _LiteralResolutionKind.ambiguous); literalType = null; } if (literalType is InterfaceType) { List<DartType> typeArguments = literalType.typeArguments; if (typeArguments.length == 1) { DartType elementType = literalType.typeArguments[0]; DartType iterableType = typeProvider.iterableType2(elementType); _pushCollectionTypesDownToAll(node.elements, elementType: elementType, iterableType: iterableType); if (!_uiAsCodeEnabled && node.elements.isEmpty && node.typeArguments == null && node.isMap) { // The node is really an empty set literal with no type arguments. (node as SetOrMapLiteralImpl).becomeMap(); } } else if (typeArguments.length == 2) { DartType keyType = typeArguments[0]; DartType valueType = typeArguments[1]; _pushCollectionTypesDownToAll(node.elements, iterableType: literalType, keyType: keyType, valueType: valueType); } (node as SetOrMapLiteralImpl).contextType = literalType; } else { (node as SetOrMapLiteralImpl).contextType = null; } super.visitSetOrMapLiteral(node); } @override void visitShowCombinator(ShowCombinator node) {} @override void visitSimpleIdentifier(SimpleIdentifier node) { if (_flowAnalysis != null && _flowAnalysis.isPotentiallyNonNullableLocalReadBeforeWrite(node)) { errorReporter.reportErrorForNode( CompileTimeErrorCode .NOT_ASSIGNED_POTENTIALLY_NON_NULLABLE_LOCAL_VARIABLE, node, [node.name], ); } super.visitSimpleIdentifier(node); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { // // We visit the argument list, but do not visit the optional identifier // because it needs to be visited in the context of the constructor // invocation. // node.accept(elementResolver); InferenceContext.setType(node.argumentList, node.staticElement?.type); node.argumentList?.accept(this); node.accept(typeAnalyzer); } @override void visitSwitchCase(SwitchCase node) { _flowAnalysis?.checkUnreachableNode(node); InferenceContext.setType( node.expression, _enclosingSwitchStatementExpressionType); super.visitSwitchCase(node); } @override void visitSwitchStatementInScope(SwitchStatement node) { _flowAnalysis?.checkUnreachableNode(node); var previousExpressionType = _enclosingSwitchStatementExpressionType; try { var expression = node.expression; expression.accept(this); _enclosingSwitchStatementExpressionType = expression.staticType; if (_flowAnalysis != null) { var flow = _flowAnalysis.flow; var assignedInCases = _flowAnalysis.assignedVariables.writtenInNode(node); flow.switchStatement_expressionEnd(node); var hasDefault = false; var members = node.members; for (var member in members) { flow.switchStatement_beginCase( member.labels.isNotEmpty, assignedInCases, ); member.accept(this); if (member is SwitchDefault) { hasDefault = true; } } flow.switchStatement_end(hasDefault); } else { node.members.accept(this); } } finally { _enclosingSwitchStatementExpressionType = previousExpressionType; } } @override void visitThrowExpression(ThrowExpression node) { super.visitThrowExpression(node); _flowAnalysis?.flow?.handleExit(); } @override void visitTryStatement(TryStatement node) { if (_flowAnalysis == null) { return super.visitTryStatement(node); } _flowAnalysis.checkUnreachableNode(node); var flow = _flowAnalysis.flow; var body = node.body; var catchClauses = node.catchClauses; var finallyBlock = node.finallyBlock; if (finallyBlock != null) { flow.tryFinallyStatement_bodyBegin(); } flow.tryCatchStatement_bodyBegin(); body.accept(this); flow.tryCatchStatement_bodyEnd( _flowAnalysis.assignedVariables.writtenInNode(body), ); var catchLength = catchClauses.length; for (var i = 0; i < catchLength; ++i) { var catchClause = catchClauses[i]; flow.tryCatchStatement_catchBegin(); if (catchClause.exceptionParameter != null) { flow.write(catchClause.exceptionParameter.staticElement); } if (catchClause.stackTraceParameter != null) { flow.write(catchClause.stackTraceParameter.staticElement); } catchClause.accept(this); flow.tryCatchStatement_catchEnd(); } flow.tryCatchStatement_end(); if (finallyBlock != null) { flow.tryFinallyStatement_finallyBegin( _flowAnalysis.assignedVariables.writtenInNode(body), ); finallyBlock.accept(this); flow.tryFinallyStatement_end( _flowAnalysis.assignedVariables.writtenInNode(finallyBlock), ); } } @override void visitTypeName(TypeName node) {} @override void visitVariableDeclaration(VariableDeclaration node) { InferenceContext.setTypeFromNode(node.initializer, node); super.visitVariableDeclaration(node); VariableElement element = node.declaredElement; if (element.initializer != null && node.initializer != null) { (element.initializer as FunctionElementImpl).returnType = node.initializer.staticType; } // Note: in addition to cloning the initializers for const variables, we // have to clone the initializers for non-static final fields (because if // they occur in a class with a const constructor, they will be needed to // evaluate the const constructor). if (element is ConstVariableElement) { (element as ConstVariableElement).constantInitializer = _createCloner().cloneNode(node.initializer); } } @override void visitVariableDeclarationList(VariableDeclarationList node) { _flowAnalysis?.variableDeclarationList(node); for (VariableDeclaration decl in node.variables) { VariableElement variableElement = decl.declaredElement; InferenceContext.setType(decl, variableElement?.type); } super.visitVariableDeclarationList(node); } @override void visitWhileStatement(WhileStatement node) { _flowAnalysis?.checkUnreachableNode(node); // Note: since we don't call the base class, we have to maintain // _implicitLabelScope ourselves. ImplicitLabelScope outerImplicitScope = _implicitLabelScope; try { _implicitLabelScope = _implicitLabelScope.nest(node); Expression condition = node.condition; InferenceContext.setType(condition, typeProvider.boolType); _flowAnalysis?.flow?.whileStatement_conditionBegin( _flowAnalysis.assignedVariables.writtenInNode(node), ); condition?.accept(this); Statement body = node.body; if (body != null) { _flowAnalysis?.flow?.whileStatement_bodyBegin(node, condition); visitStatementInScope(body); _flowAnalysis?.flow?.whileStatement_end(); } } finally { _implicitLabelScope = outerImplicitScope; } // TODO(brianwilkerson) If the loop can only be exited because the condition // is false, then propagateFalseState(condition); node.accept(elementResolver); node.accept(typeAnalyzer); } @override void visitYieldStatement(YieldStatement node) { Expression e = node.expression; DartType returnType = inferenceContext.returnContext; bool isGenerator = _enclosingFunction?.isGenerator ?? false; if (returnType != null && isGenerator) { // If we're not in a generator ([a]sync*, then we shouldn't have a yield. // so don't infer // If this just a yield, then we just pass on the element type DartType type = returnType; if (node.star != null) { // If this is a yield*, then we wrap the element return type // If it's synchronous, we expect Iterable<T>, otherwise Stream<T> type = _enclosingFunction.isSynchronous ? typeProvider.iterableType2(type) : typeProvider.streamType2(type); } InferenceContext.setType(e, type); } super.visitYieldStatement(node); DartType type = e?.staticType; if (type != null && isGenerator) { // If this just a yield, then we just pass on the element type if (node.star != null) { // If this is a yield*, then we unwrap the element return type // If it's synchronous, we expect Iterable<T>, otherwise Stream<T> if (type is InterfaceType) { ClassElement wrapperElement = _enclosingFunction.isSynchronous ? typeProvider.iterableElement : typeProvider.streamElement; var asInstanceType = (type as InterfaceTypeImpl).asInstanceOf(wrapperElement); if (asInstanceType != null) { type = asInstanceType.typeArguments[0]; } } } if (type != null) { inferenceContext.addReturnOrYieldType(type); } } } /// Given the declared return type of a function, compute the type of the /// values which should be returned or yielded as appropriate. If a type /// cannot be computed from the declared return type, return null. DartType _computeReturnOrYieldType(DartType declaredType) { bool isGenerator = _enclosingFunction.isGenerator; bool isAsynchronous = _enclosingFunction.isAsynchronous; // Ordinary functions just return their declared types. if (!isGenerator && !isAsynchronous) { return declaredType; } if (declaredType is InterfaceType) { if (isGenerator) { // If it's sync* we expect Iterable<T> // If it's async* we expect Stream<T> // Match the types to instantiate the type arguments if possible List<DartType> targs = declaredType.typeArguments; if (targs.length == 1) { var arg = targs[0]; if (isAsynchronous) { if (typeProvider.streamType2(arg) == declaredType) { return arg; } } else { if (typeProvider.iterableType2(arg) == declaredType) { return arg; } } } } // async functions expect `Future<T> | T` var futureTypeParam = typeSystem.flatten(declaredType); return _createFutureOr(futureTypeParam); } return declaredType; } /// Compute the context type for the given set or map [literal]. _LiteralResolution _computeSetOrMapResolution(SetOrMapLiteral literal) { _LiteralResolution typeArgumentsResolution = _fromTypeArguments(literal.typeArguments); DartType contextType = InferenceContext.getContext(literal); _LiteralResolution contextResolution = _fromContextType(contextType); _LeafElements elementCounts = new _LeafElements(literal.elements); _LiteralResolution elementResolution = elementCounts.resolution; List<_LiteralResolution> unambiguousResolutions = []; Set<_LiteralResolutionKind> kinds = new Set<_LiteralResolutionKind>(); if (typeArgumentsResolution.kind != _LiteralResolutionKind.ambiguous) { unambiguousResolutions.add(typeArgumentsResolution); kinds.add(typeArgumentsResolution.kind); } if (contextResolution.kind != _LiteralResolutionKind.ambiguous) { unambiguousResolutions.add(contextResolution); kinds.add(contextResolution.kind); } if (elementResolution.kind != _LiteralResolutionKind.ambiguous) { unambiguousResolutions.add(elementResolution); kinds.add(elementResolution.kind); } if (kinds.length == 2) { // It looks like it needs to be both a map and a set. Attempt to recover. if (elementResolution.kind == _LiteralResolutionKind.ambiguous && elementResolution.contextType != null) { return elementResolution; } else if (typeArgumentsResolution.kind != _LiteralResolutionKind.ambiguous && typeArgumentsResolution.contextType != null) { return typeArgumentsResolution; } else if (contextResolution.kind != _LiteralResolutionKind.ambiguous && contextResolution.contextType != null) { return contextResolution; } } else if (unambiguousResolutions.length >= 2) { // If there are three resolutions, the last resolution is guaranteed to be // from the elements, which always has a context type of `null` (when it // is not ambiguous). So, whether there are 2 or 3 resolutions only the // first two are potentially interesting. return unambiguousResolutions[0].contextType == null ? unambiguousResolutions[1] : unambiguousResolutions[0]; } else if (unambiguousResolutions.length == 1) { return unambiguousResolutions[0]; } else if (literal.elements.isEmpty) { return _LiteralResolution( _LiteralResolutionKind.map, typeProvider.mapType2( typeProvider.dynamicType, typeProvider.dynamicType)); } return _LiteralResolution(_LiteralResolutionKind.ambiguous, null); } /// Return a newly created cloner that can be used to clone constant /// expressions. ConstantAstCloner _createCloner() { return new ConstantAstCloner(); } /// Creates a union of `T | Future<T>`, unless `T` is already a /// future-union, in which case it simply returns `T`. DartType _createFutureOr(DartType type) { if (type.isDartAsyncFutureOr) { return type; } return typeProvider.futureOrType2(type); } /// If [contextType] is defined and is a subtype of `Iterable<Object>` and /// [contextType] is not a subtype of `Map<Object, Object>`, then *e* is a set /// literal. /// /// If [contextType] is defined and is a subtype of `Map<Object, Object>` and /// [contextType] is not a subtype of `Iterable<Object>` then *e* is a map /// literal. _LiteralResolution _fromContextType(DartType contextType) { if (contextType != null) { DartType unwrap(DartType type) { if (type is InterfaceType && type.isDartAsyncFutureOr && type.typeArguments.length == 1) { return unwrap(type.typeArguments[0]); } return type; } DartType unwrappedContextType = unwrap(contextType); // TODO(brianwilkerson) Find out what the "greatest closure" is and use that // where [unwrappedContextType] is used below. bool isIterable = typeSystem.isSubtypeOf( unwrappedContextType, typeProvider.iterableObjectType); bool isMap = typeSystem.isSubtypeOf( unwrappedContextType, typeProvider.mapObjectObjectType); if (isIterable && !isMap) { return _LiteralResolution( _LiteralResolutionKind.set, unwrappedContextType); } else if (isMap && !isIterable) { return _LiteralResolution( _LiteralResolutionKind.map, unwrappedContextType); } } return _LiteralResolution(_LiteralResolutionKind.ambiguous, null); } /// Return the resolution that is indicated by the given [typeArgumentList]. _LiteralResolution _fromTypeArguments(TypeArgumentList typeArgumentList) { if (typeArgumentList != null) { NodeList<TypeAnnotation> arguments = typeArgumentList.arguments; if (arguments.length == 1) { return _LiteralResolution(_LiteralResolutionKind.set, typeProvider.setType2(arguments[0].type)); } else if (arguments.length == 2) { return _LiteralResolution(_LiteralResolutionKind.map, typeProvider.mapType2(arguments[0].type, arguments[1].type)); } } return _LiteralResolution(_LiteralResolutionKind.ambiguous, null); } /// Return `true` if the given [parameter] element of the AST being resolved /// is resynthesized and is an API-level, not local, so has its initializer /// serialized. bool _hasSerializedConstantInitializer(ParameterElement parameter) { Element executable = parameter.enclosingElement; if (executable is MethodElement || executable is FunctionElement && executable.enclosingElement is CompilationUnitElement) { return LibraryElementImpl.hasResolutionCapability( definingLibrary, LibraryResolutionCapability.constantExpressions); } return false; } FunctionType _inferArgumentTypesForGeneric(AstNode inferenceNode, DartType uninstantiatedType, TypeArgumentList typeArguments, {AstNode errorNode, bool isConst: false}) { errorNode ??= inferenceNode; if (typeArguments == null && uninstantiatedType is FunctionType && uninstantiatedType.typeFormals.isNotEmpty) { var typeArguments = typeSystem.inferGenericFunctionOrType( typeParameters: uninstantiatedType.typeFormals, parameters: const <ParameterElement>[], declaredReturnType: uninstantiatedType.returnType, argumentTypes: const <DartType>[], contextReturnType: InferenceContext.getContext(inferenceNode), downwards: true, isConst: isConst, errorReporter: errorReporter, errorNode: errorNode, ); if (typeArguments != null) { return uninstantiatedType.instantiate(typeArguments); } } return null; } void _inferArgumentTypesForInstanceCreate(InstanceCreationExpression node) { ConstructorName constructor = node.constructorName; TypeName classTypeName = constructor?.type; if (classTypeName == null) { return; } ConstructorElement originalElement = constructor.staticElement; FunctionType inferred; // 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 (classTypeName.typeArguments == null && originalElement is ConstructorMember) { // 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.baseElement; FunctionType constructorType = StaticTypeAnalyzer.constructorToGenericFunctionType(rawElement); inferred = _inferArgumentTypesForGeneric( node, constructorType, constructor.type.typeArguments, isConst: node.isConst, errorNode: node.constructorName); if (inferred != null) { ArgumentList arguments = node.argumentList; InferenceContext.setType(arguments, inferred); // Fix up the parameter elements based on inferred method. arguments.correspondingStaticParameters = resolveArgumentsToParameters(arguments, inferred.parameters, null); constructor.type.type = inferred.returnType; if (UnknownInferredType.isKnown(inferred)) { inferenceContext.recordInference(node, 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; } } if (inferred == null) { InferenceContext.setType(node.argumentList, originalElement?.type); } } void _inferArgumentTypesForInvocation(InvocationExpression node) { DartType inferred = _inferArgumentTypesForGeneric( node, node.function.staticType, node.typeArguments); InferenceContext.setType( node.argumentList, inferred ?? node.staticInvokeType); } void _inferFormalParameterList(FormalParameterList node, DartType type) { if (typeAnalyzer.inferFormalParameterList(node, type)) { // TODO(leafp): This gets dropped on the floor if we're in the field // inference task. We should probably keep these infos. // // TODO(jmesserly): this is reporting the context type, and therefore not // necessarily the correct inferred type for the lambda. // // For example, `([x]) {}` could be passed to `int -> void` but its type // will really be `([int]) -> void`. Similar issue for named arguments. // It can also happen if the return type is inferred later on to be // more precise. // // This reporting bug defeats the deduplication of error messages and // results in the same inference message being reported twice. // // To get this right, we'd have to delay reporting until we have the // complete type including return type. inferenceContext.recordInference(node.parent, type); } } void _pushCollectionTypesDown(CollectionElement element, {DartType elementType, @required DartType iterableType, DartType keyType, DartType valueType}) { if (element is ForElement) { _pushCollectionTypesDown(element.body, elementType: elementType, iterableType: iterableType, keyType: keyType, valueType: valueType); } else if (element is IfElement) { _pushCollectionTypesDown(element.thenElement, elementType: elementType, iterableType: iterableType, keyType: keyType, valueType: valueType); _pushCollectionTypesDown(element.elseElement, elementType: elementType, iterableType: iterableType, keyType: keyType, valueType: valueType); } else if (element is Expression) { InferenceContext.setType(element, elementType); } else if (element is MapLiteralEntry) { InferenceContext.setType(element.key, keyType); InferenceContext.setType(element.value, valueType); } else if (element is SpreadElement) { InferenceContext.setType(element.expression, iterableType); } } void _pushCollectionTypesDownToAll(List<CollectionElement> elements, {DartType elementType, @required DartType iterableType, DartType keyType, DartType valueType}) { assert(iterableType != null); for (CollectionElement element in elements) { _pushCollectionTypesDown(element, elementType: elementType, iterableType: iterableType, keyType: keyType, valueType: valueType); } } /// Given an [argumentList] and the [parameters] related to the element that /// will be invoked using those arguments, compute the list of parameters that /// correspond to the list of arguments. /// /// An error will be reported to [onError] if any of the arguments cannot be /// matched to a parameter. onError can be null to ignore the error. /// /// Returns the parameters that correspond to the arguments. If no parameter /// matched an argument, that position will be `null` in the list. static List<ParameterElement> resolveArgumentsToParameters( ArgumentList argumentList, List<ParameterElement> parameters, void onError(ErrorCode errorCode, AstNode node, [List<Object> arguments])) { if (parameters.isEmpty && argumentList.arguments.isEmpty) { return const <ParameterElement>[]; } int requiredParameterCount = 0; int unnamedParameterCount = 0; List<ParameterElement> unnamedParameters = new List<ParameterElement>(); Map<String, ParameterElement> namedParameters; int length = parameters.length; for (int i = 0; i < length; i++) { ParameterElement parameter = parameters[i]; if (parameter.isRequiredPositional) { unnamedParameters.add(parameter); unnamedParameterCount++; requiredParameterCount++; } else if (parameter.isOptionalPositional) { unnamedParameters.add(parameter); unnamedParameterCount++; } else { namedParameters ??= new HashMap<String, ParameterElement>(); namedParameters[parameter.name] = parameter; } } int unnamedIndex = 0; NodeList<Expression> arguments = argumentList.arguments; int argumentCount = arguments.length; List<ParameterElement> resolvedParameters = new List<ParameterElement>(argumentCount); int positionalArgumentCount = 0; HashSet<String> usedNames; bool noBlankArguments = true; for (int i = 0; i < argumentCount; i++) { Expression argument = arguments[i]; if (argument is NamedExpression) { SimpleIdentifier nameNode = argument.name.label; String name = nameNode.name; ParameterElement element = namedParameters != null ? namedParameters[name] : null; if (element == null) { if (onError != null) { onError(CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER, nameNode, [name]); } } else { resolvedParameters[i] = element; nameNode.staticElement = element; } usedNames ??= new HashSet<String>(); if (!usedNames.add(name)) { if (onError != null) { onError(CompileTimeErrorCode.DUPLICATE_NAMED_ARGUMENT, nameNode, [name]); } } } else { if (argument is SimpleIdentifier && argument.name.isEmpty) { noBlankArguments = false; } positionalArgumentCount++; if (unnamedIndex < unnamedParameterCount) { resolvedParameters[i] = unnamedParameters[unnamedIndex++]; } } } if (positionalArgumentCount < requiredParameterCount && noBlankArguments) { if (onError != null) { onError(CompileTimeErrorCode.NOT_ENOUGH_POSITIONAL_ARGUMENTS, argumentList, [requiredParameterCount, positionalArgumentCount]); } } else if (positionalArgumentCount > unnamedParameterCount && noBlankArguments) { ErrorCode errorCode; int namedParameterCount = namedParameters?.length ?? 0; int namedArgumentCount = usedNames?.length ?? 0; if (namedParameterCount > namedArgumentCount) { errorCode = CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED; } else { errorCode = CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS; } if (onError != null) { onError(errorCode, argumentList, [unnamedParameterCount, positionalArgumentCount]); } } return resolvedParameters; } } /// The abstract class `ScopedVisitor` maintains name and label scopes as an AST /// structure is being visited. abstract class ScopedVisitor extends UnifyingAstVisitor<void> { /// The element for the library containing the compilation unit being visited. final LibraryElement definingLibrary; /// The source representing the compilation unit being visited. final Source source; /// The object used to access the types from the core library. final TypeProvider typeProvider; /// The error reporter that will be informed of any errors that are found /// during resolution. final ErrorReporter errorReporter; /// The scope used to resolve identifiers. Scope nameScope; /// The scope used to resolve unlabeled `break` and `continue` statements. ImplicitLabelScope _implicitLabelScope = ImplicitLabelScope.ROOT; /// The scope used to resolve labels for `break` and `continue` statements, or /// `null` if no labels have been defined in the current context. LabelScope labelScope; /// The class containing the AST nodes being visited, /// or `null` if we are not in the scope of a class. ClassElement enclosingClass; /// The element representing the extension containing the AST nodes being /// visited, or `null` if we are not in the scope of an extension. ExtensionElement enclosingExtension; /// Initialize a newly created visitor to resolve the nodes in a compilation /// unit. /// /// [definingLibrary] is the element for the library containing the /// compilation unit being visited. /// [source] is the source representing the compilation unit being visited. /// [typeProvider] is the object used to access the types from the core /// library. /// [errorListener] is the error listener that will be informed of any errors /// that are found during resolution. /// [nameScope] is the scope used to resolve identifiers in the node that will /// first be visited. If `null` or unspecified, a new [LibraryScope] will be /// created based on [definingLibrary] and [typeProvider]. ScopedVisitor(this.definingLibrary, Source source, this.typeProvider, AnalysisErrorListener errorListener, {Scope nameScope}) : source = source, errorReporter = new ErrorReporter(errorListener, source) { if (nameScope == null) { this.nameScope = new LibraryScope(definingLibrary); } else { this.nameScope = nameScope; } } /// Return the implicit label scope in which the current node is being /// resolved. ImplicitLabelScope get implicitLabelScope => _implicitLabelScope; /// Replaces the current [Scope] with the enclosing [Scope]. /// /// @return the enclosing [Scope]. Scope popNameScope() { nameScope = nameScope.enclosingScope; return nameScope; } /// Pushes a new [Scope] into the visitor. /// /// @return the new [Scope]. Scope pushNameScope() { Scope newScope = new EnclosedScope(nameScope); nameScope = newScope; return nameScope; } @override void visitBlock(Block node) { Scope outerScope = nameScope; try { EnclosedScope enclosedScope = new BlockScope(nameScope, node); nameScope = enclosedScope; super.visitBlock(node); } finally { nameScope = outerScope; } } @override void visitBlockFunctionBody(BlockFunctionBody node) { ImplicitLabelScope implicitOuterScope = _implicitLabelScope; try { _implicitLabelScope = ImplicitLabelScope.ROOT; super.visitBlockFunctionBody(node); } finally { _implicitLabelScope = implicitOuterScope; } } @override void visitCatchClause(CatchClause node) { SimpleIdentifier exception = node.exceptionParameter; if (exception != null) { Scope outerScope = nameScope; try { nameScope = new EnclosedScope(nameScope); nameScope.define(exception.staticElement); SimpleIdentifier stackTrace = node.stackTraceParameter; if (stackTrace != null) { nameScope.define(stackTrace.staticElement); } super.visitCatchClause(node); } finally { nameScope = outerScope; } } else { super.visitCatchClause(node); } } @override void visitClassDeclaration(ClassDeclaration node) { ClassElement classElement = node.declaredElement; Scope outerScope = nameScope; try { if (classElement == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for class declaration ${node.name.name} in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); super.visitClassDeclaration(node); } else { ClassElement outerClass = enclosingClass; try { enclosingClass = node.declaredElement; nameScope = new TypeParameterScope(nameScope, classElement); visitClassDeclarationInScope(node); nameScope = new ClassScope(nameScope, classElement); visitClassMembersInScope(node); } finally { enclosingClass = outerClass; } } } finally { nameScope = outerScope; } } void visitClassDeclarationInScope(ClassDeclaration node) { node.name?.accept(this); node.typeParameters?.accept(this); node.extendsClause?.accept(this); node.withClause?.accept(this); node.implementsClause?.accept(this); node.nativeClause?.accept(this); } void visitClassMembersInScope(ClassDeclaration node) { node.documentationComment?.accept(this); node.metadata.accept(this); node.members.accept(this); } @override void visitClassTypeAlias(ClassTypeAlias node) { Scope outerScope = nameScope; try { ClassElement element = node.declaredElement; nameScope = new ClassScope(new TypeParameterScope(nameScope, element), element); super.visitClassTypeAlias(node); } finally { nameScope = outerScope; } } @override void visitConstructorDeclaration(ConstructorDeclaration node) { ConstructorElement constructorElement = node.declaredElement; if (constructorElement == null) { StringBuffer buffer = new StringBuffer(); buffer.write("Missing element for constructor "); buffer.write(node.returnType.name); if (node.name != null) { buffer.write("."); buffer.write(node.name.name); } buffer.write(" in "); buffer.write(definingLibrary.source.fullName); AnalysisEngine.instance.logger.logInformation(buffer.toString(), new CaughtException(new AnalysisException(), null)); } Scope outerScope = nameScope; try { if (constructorElement != null) { nameScope = new FunctionScope(nameScope, constructorElement); } node.documentationComment?.accept(this); node.metadata.accept(this); node.returnType?.accept(this); node.name?.accept(this); node.parameters?.accept(this); Scope functionScope = nameScope; try { if (constructorElement != null) { nameScope = new ConstructorInitializerScope(nameScope, constructorElement); } node.initializers.accept(this); } finally { nameScope = functionScope; } node.redirectedConstructor?.accept(this); visitConstructorDeclarationInScope(node); } finally { nameScope = outerScope; } } void visitConstructorDeclarationInScope(ConstructorDeclaration node) { node.body?.accept(this); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { VariableElement element = node.declaredElement; if (element != null) { nameScope.define(element); } super.visitDeclaredIdentifier(node); } @override void visitDoStatement(DoStatement node) { ImplicitLabelScope outerImplicitScope = _implicitLabelScope; try { _implicitLabelScope = _implicitLabelScope.nest(node); visitDoStatementInScope(node); } finally { _implicitLabelScope = outerImplicitScope; } } void visitDoStatementInScope(DoStatement node) { visitStatementInScope(node.body); node.condition?.accept(this); } @override void visitEnumDeclaration(EnumDeclaration node) { ClassElement classElement = node.declaredElement; Scope outerScope = nameScope; try { if (classElement == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for enum declaration ${node.name.name} in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); super.visitEnumDeclaration(node); } else { ClassElement outerClass = enclosingClass; try { enclosingClass = node.declaredElement; nameScope = new ClassScope(nameScope, classElement); visitEnumMembersInScope(node); } finally { enclosingClass = outerClass; } } } finally { nameScope = outerScope; } } void visitEnumMembersInScope(EnumDeclaration node) { node.documentationComment?.accept(this); node.metadata.accept(this); node.constants.accept(this); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { ExtensionElement extensionElement = node.declaredElement; Scope outerScope = nameScope; try { if (extensionElement == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for extension declaration ${node.name.name} " "in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); super.visitExtensionDeclaration(node); } else { ExtensionElement outerExtension = enclosingExtension; try { enclosingExtension = extensionElement; nameScope = new TypeParameterScope(nameScope, extensionElement); visitExtensionDeclarationInScope(node); nameScope = ExtensionScope(nameScope, extensionElement); visitExtensionMembersInScope(node); } finally { enclosingExtension = outerExtension; } } } finally { nameScope = outerScope; } } void visitExtensionDeclarationInScope(ExtensionDeclaration node) { node.name?.accept(this); node.typeParameters?.accept(this); node.extendedType?.accept(this); } void visitExtensionMembersInScope(ExtensionDeclaration node) { node.documentationComment?.accept(this); node.metadata.accept(this); node.members.accept(this); } @override void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) { // // We visit the iterator before the loop variable because the loop variable // cannot be in scope while visiting the iterator. // node.iterable?.accept(this); node.loopVariable?.accept(this); } @override void visitForElement(ForElement node) { Scope outerNameScope = nameScope; try { nameScope = new EnclosedScope(nameScope); visitForElementInScope(node); } finally { nameScope = outerNameScope; } } /// Visit the given [node] after it's scope has been created. This replaces /// the normal call to the inherited visit method so that ResolverVisitor can /// intervene when type propagation is enabled. void visitForElementInScope(ForElement node) { // TODO(brianwilkerson) Investigate the possibility of removing the // visit...InScope methods now that type propagation is no longer done. node.forLoopParts?.accept(this); node.body?.accept(this); } @override void visitFormalParameterList(FormalParameterList node) { super.visitFormalParameterList(node); // We finished resolving function signature, now include formal parameters // scope. Note: we must not do this if the parent is a // FunctionTypedFormalParameter, because in that case we aren't finished // resolving the full function signature, just a part of it. if (nameScope is FunctionScope && node.parent is! FunctionTypedFormalParameter) { (nameScope as FunctionScope).defineParameters(); } if (nameScope is FunctionTypeScope) { (nameScope as FunctionTypeScope).defineParameters(); } } @override void visitForStatement(ForStatement node) { Scope outerNameScope = nameScope; ImplicitLabelScope outerImplicitScope = _implicitLabelScope; try { nameScope = new EnclosedScope(nameScope); _implicitLabelScope = _implicitLabelScope.nest(node); visitForStatementInScope(node); } finally { nameScope = outerNameScope; _implicitLabelScope = outerImplicitScope; } } /// Visit the given [node] after it's scope has been created. This replaces /// the normal call to the inherited visit method so that ResolverVisitor can /// intervene when type propagation is enabled. void visitForStatementInScope(ForStatement node) { // TODO(brianwilkerson) Investigate the possibility of removing the // visit...InScope methods now that type propagation is no longer done. node.forLoopParts?.accept(this); visitStatementInScope(node.body); } @override void visitFunctionDeclaration(FunctionDeclaration node) { ExecutableElement functionElement = node.declaredElement; if (functionElement != null && functionElement.enclosingElement is! CompilationUnitElement) { nameScope.define(functionElement); } Scope outerScope = nameScope; try { if (functionElement == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for top-level function ${node.name.name} in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); } else { nameScope = new FunctionScope(nameScope, functionElement); } visitFunctionDeclarationInScope(node); } finally { nameScope = outerScope; } } void visitFunctionDeclarationInScope(FunctionDeclaration node) { super.visitFunctionDeclaration(node); } @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is FunctionDeclaration) { // We have already created a function scope and don't need to do so again. super.visitFunctionExpression(node); } else { Scope outerScope = nameScope; try { ExecutableElement functionElement = node.declaredElement; if (functionElement == null) { StringBuffer buffer = new StringBuffer(); buffer.write("Missing element for function "); AstNode parent = node.parent; while (parent != null) { if (parent is Declaration) { Element parentElement = parent.declaredElement; buffer.write(parentElement == null ? "<unknown> " : "${parentElement.name} "); } parent = parent.parent; } buffer.write("in "); buffer.write(definingLibrary.source.fullName); AnalysisEngine.instance.logger.logInformation(buffer.toString(), new CaughtException(new AnalysisException(), null)); } else { nameScope = new FunctionScope(nameScope, functionElement); } super.visitFunctionExpression(node); } finally { nameScope = outerScope; } } } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { Scope outerScope = nameScope; try { nameScope = new FunctionTypeScope(nameScope, node.declaredElement); visitFunctionTypeAliasInScope(node); } finally { nameScope = outerScope; } } void visitFunctionTypeAliasInScope(FunctionTypeAlias node) { super.visitFunctionTypeAlias(node); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { Scope outerScope = nameScope; try { ParameterElement parameterElement = node.declaredElement; if (parameterElement == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for function typed formal parameter ${node.identifier.name} in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); } else { nameScope = new EnclosedScope(nameScope); var typeParameters = parameterElement.typeParameters; int length = typeParameters.length; for (int i = 0; i < length; i++) { nameScope.define(typeParameters[i]); } } super.visitFunctionTypedFormalParameter(node); } finally { nameScope = outerScope; } } @override void visitGenericFunctionType(GenericFunctionType node) { DartType type = node.type; if (type == null) { // The function type hasn't been resolved yet, so we can't create a scope // for its parameters. super.visitGenericFunctionType(node); return; } GenericFunctionTypeElement element = (node as GenericFunctionTypeImpl).declaredElement; Scope outerScope = nameScope; try { if (element == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for generic function type in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); super.visitGenericFunctionType(node); } else { nameScope = new TypeParameterScope(nameScope, element); super.visitGenericFunctionType(node); } } finally { nameScope = outerScope; } } @override void visitGenericTypeAlias(GenericTypeAlias node) { GenericTypeAliasElement element = node.declaredElement; Scope outerScope = nameScope; try { if (element == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for generic function type in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); super.visitGenericTypeAlias(node); } else { nameScope = new TypeParameterScope(nameScope, element); super.visitGenericTypeAlias(node); GenericFunctionTypeElement functionElement = element.function; if (functionElement != null) { nameScope = new FunctionScope(nameScope, functionElement) ..defineParameters(); visitGenericTypeAliasInFunctionScope(node); } } } finally { nameScope = outerScope; } } void visitGenericTypeAliasInFunctionScope(GenericTypeAlias node) {} @override void visitIfStatement(IfStatement node) { node.condition?.accept(this); visitStatementInScope(node.thenStatement); visitStatementInScope(node.elseStatement); } @override void visitLabeledStatement(LabeledStatement node) { LabelScope outerScope = _addScopesFor(node.labels, node.unlabeled); try { super.visitLabeledStatement(node); } finally { labelScope = outerScope; } } @override void visitMethodDeclaration(MethodDeclaration node) { Scope outerScope = nameScope; try { ExecutableElement methodElement = node.declaredElement; if (methodElement == null) { AnalysisEngine.instance.logger.logInformation( "Missing element for method ${node.name.name} in ${definingLibrary.source.fullName}", new CaughtException(new AnalysisException(), null)); } else { nameScope = new FunctionScope(nameScope, methodElement); } visitMethodDeclarationInScope(node); } finally { nameScope = outerScope; } } void visitMethodDeclarationInScope(MethodDeclaration node) { super.visitMethodDeclaration(node); } @override void visitMixinDeclaration(MixinDeclaration node) { ClassElement element = node.declaredElement; Scope outerScope = nameScope; ClassElement outerClass = enclosingClass; try { enclosingClass = element; nameScope = new TypeParameterScope(nameScope, element); visitMixinDeclarationInScope(node); nameScope = new ClassScope(nameScope, element); visitMixinMembersInScope(node); } finally { nameScope = outerScope; enclosingClass = outerClass; } } void visitMixinDeclarationInScope(MixinDeclaration node) { node.name?.accept(this); node.typeParameters?.accept(this); node.onClause?.accept(this); node.implementsClause?.accept(this); } void visitMixinMembersInScope(MixinDeclaration node) { node.documentationComment?.accept(this); node.metadata.accept(this); node.members.accept(this); } /// Visit the given statement after it's scope has been created. This is used /// by ResolverVisitor to correctly visit the 'then' and 'else' statements of /// an 'if' statement. /// /// @param node the statement to be visited void visitStatementInScope(Statement node) { if (node is Block) { // Don't create a scope around a block because the block will create it's // own scope. visitBlock(node); } else if (node != null) { Scope outerNameScope = nameScope; try { nameScope = new EnclosedScope(nameScope); node.accept(this); } finally { nameScope = outerNameScope; } } } @override void visitSwitchCase(SwitchCase node) { node.expression.accept(this); Scope outerNameScope = nameScope; try { nameScope = new EnclosedScope(nameScope); node.statements.accept(this); } finally { nameScope = outerNameScope; } } @override void visitSwitchDefault(SwitchDefault node) { Scope outerNameScope = nameScope; try { nameScope = new EnclosedScope(nameScope); node.statements.accept(this); } finally { nameScope = outerNameScope; } } @override void visitSwitchStatement(SwitchStatement node) { LabelScope outerScope = labelScope; ImplicitLabelScope outerImplicitScope = _implicitLabelScope; try { _implicitLabelScope = _implicitLabelScope.nest(node); for (SwitchMember member in node.members) { for (Label label in member.labels) { SimpleIdentifier labelName = label.label; LabelElement labelElement = labelName.staticElement as LabelElement; labelScope = new LabelScope(labelScope, labelName.name, member, labelElement); } } visitSwitchStatementInScope(node); } finally { labelScope = outerScope; _implicitLabelScope = outerImplicitScope; } } void visitSwitchStatementInScope(SwitchStatement node) { super.visitSwitchStatement(node); } @override void visitVariableDeclaration(VariableDeclaration node) { super.visitVariableDeclaration(node); if (node.parent.parent is! TopLevelVariableDeclaration && node.parent.parent is! FieldDeclaration) { VariableElement element = node.declaredElement; if (element != null) { nameScope.define(element); } } } @override void visitWhileStatement(WhileStatement node) { node.condition?.accept(this); ImplicitLabelScope outerImplicitScope = _implicitLabelScope; try { _implicitLabelScope = _implicitLabelScope.nest(node); visitStatementInScope(node.body); } finally { _implicitLabelScope = outerImplicitScope; } } /// Add scopes for each of the given labels. /// /// @param labels the labels for which new scopes are to be added /// @return the scope that was in effect before the new scopes were added LabelScope _addScopesFor(NodeList<Label> labels, AstNode node) { LabelScope outerScope = labelScope; for (Label label in labels) { SimpleIdentifier labelNameNode = label.label; String labelName = labelNameNode.name; LabelElement labelElement = labelNameNode.staticElement as LabelElement; labelScope = new LabelScope(labelScope, labelName, node, labelElement); } return outerScope; } } /// Instances of the class `ToDoFinder` find to-do comments in Dart code. class ToDoFinder { /// The error reporter by which to-do comments will be reported. final ErrorReporter _errorReporter; /// Initialize a newly created to-do finder to report to-do comments to the /// given reporter. /// /// @param errorReporter the error reporter by which to-do comments will be /// reported ToDoFinder(this._errorReporter); /// Search the comments in the given compilation unit for to-do comments and /// report an error for each. /// /// @param unit the compilation unit containing the to-do comments void findIn(CompilationUnit unit) { _gatherTodoComments(unit.beginToken); } /// Search the comment tokens reachable from the given token and create errors /// for each to-do comment. /// /// @param token the head of the list of tokens being searched void _gatherTodoComments(Token token) { while (token != null && token.type != TokenType.EOF) { Token commentToken = token.precedingComments; while (commentToken != null) { if (commentToken.type == TokenType.SINGLE_LINE_COMMENT || commentToken.type == TokenType.MULTI_LINE_COMMENT) { _scrapeTodoComment(commentToken); } commentToken = commentToken.next; } token = token.next; } } /// Look for user defined tasks in comments and convert them into info level /// analysis issues. /// /// @param commentToken the comment token to analyze void _scrapeTodoComment(Token commentToken) { Iterable<Match> matches = TodoCode.TODO_REGEX.allMatches(commentToken.lexeme); for (Match match in matches) { int offset = commentToken.offset + match.start + match.group(1).length; int length = match.group(2).length; _errorReporter.reportErrorForOffset( TodoCode.TODO, offset, length, [match.group(2)]); } } } /// Helper for resolving types. /// /// The client must set [nameScope] before calling [resolveTypeName]. class TypeNameResolver { final Dart2TypeSystem typeSystem; final DartType dynamicType; final bool isNonNullableUnit; final AnalysisOptionsImpl analysisOptions; final LibraryElement definingLibrary; final Source source; final AnalysisErrorListener errorListener; /// Indicates whether bare typenames in "with" clauses should have their type /// inferred type arguments loaded from the element model. /// /// This is needed for mixin type inference, but is incompatible with the old /// task model. final bool shouldUseWithClauseInferredTypes; Scope nameScope; TypeNameResolver( this.typeSystem, TypeProvider typeProvider, this.isNonNullableUnit, this.definingLibrary, this.source, this.errorListener, {this.shouldUseWithClauseInferredTypes: true}) : dynamicType = typeProvider.dynamicType, analysisOptions = definingLibrary.context.analysisOptions; NullabilitySuffix get _noneOrStarSuffix { return isNonNullableUnit ? NullabilitySuffix.none : NullabilitySuffix.star; } /// Report an error with the given error code and arguments. /// /// @param errorCode the error code of the error to be reported /// @param node the node specifying the location of the error /// @param arguments the arguments to the error, used to compose the error /// message void reportErrorForNode(ErrorCode errorCode, AstNode node, [List<Object> arguments]) { errorListener.onError(new AnalysisError( source, node.offset, node.length, errorCode, arguments)); } /// Resolve the given [TypeName] - set its element and static type. Only the /// given [node] is resolved, all its children must be already resolved. /// /// The client must set [nameScope] before calling [resolveTypeName]. void resolveTypeName(TypeName node) { Identifier typeName = node.name; _setElement(typeName, null); // Clear old Elements from previous run. TypeArgumentList argumentList = node.typeArguments; Element element = nameScope.lookup(typeName, definingLibrary); if (element == null) { // // Check to see whether the type name is either 'dynamic' or 'void', // neither of which are in the name scope and hence will not be found by // normal means. // VoidTypeImpl voidType = VoidTypeImpl.instance; if (typeName.name == voidType.name) { // There is no element for 'void'. // if (argumentList != null) { // // TODO(brianwilkerson) Report this error // reporter.reportError(StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS, node, voidType.getName(), 0, argumentList.getArguments().size()); // } typeName.staticType = voidType; node.type = voidType; return; } if (nameScope.shouldIgnoreUndefined(typeName)) { typeName.staticType = dynamicType; node.type = dynamicType; return; } // // If not, the look to see whether we might have created the wrong AST // structure for a constructor name. If so, fix the AST structure and then // proceed. // AstNode parent = node.parent; if (typeName is PrefixedIdentifier && parent is ConstructorName && argumentList == null) { ConstructorName name = parent; if (name.name == null) { PrefixedIdentifier prefixedIdentifier = typeName as PrefixedIdentifier; SimpleIdentifier prefix = prefixedIdentifier.prefix; element = nameScope.lookup(prefix, definingLibrary); if (element is PrefixElement) { if (nameScope.shouldIgnoreUndefined(typeName)) { typeName.staticType = dynamicType; node.type = dynamicType; return; } AstNode grandParent = parent.parent; if (grandParent is InstanceCreationExpression && grandParent.isConst) { // If, if this is a const expression, then generate a // CompileTimeErrorCode.CONST_WITH_NON_TYPE error. reportErrorForNode( CompileTimeErrorCode.CONST_WITH_NON_TYPE, prefixedIdentifier.identifier, [prefixedIdentifier.identifier.name]); } else { // Else, if this expression is a new expression, report a // NEW_WITH_NON_TYPE warning. reportErrorForNode( StaticWarningCode.NEW_WITH_NON_TYPE, prefixedIdentifier.identifier, [prefixedIdentifier.identifier.name]); } _setElement(prefix, element); return; } else if (element != null) { // // Rewrite the constructor name. The parser, when it sees a // constructor named "a.b", cannot tell whether "a" is a prefix and // "b" is a class name, or whether "a" is a class name and "b" is a // constructor name. It arbitrarily chooses the former, but in this // case was wrong. // name.name = prefixedIdentifier.identifier; name.period = prefixedIdentifier.period; node.name = prefix; typeName = prefix; } } } if (nameScope.shouldIgnoreUndefined(typeName)) { typeName.staticType = dynamicType; node.type = dynamicType; return; } } // check element bool elementValid = element is! MultiplyDefinedElement; if (elementValid && element != null && element is! ClassElement && _isTypeNameInInstanceCreationExpression(node)) { SimpleIdentifier typeNameSimple = _getTypeSimpleIdentifier(typeName); InstanceCreationExpression creation = node.parent.parent as InstanceCreationExpression; if (creation.isConst) { reportErrorForNode(CompileTimeErrorCode.CONST_WITH_NON_TYPE, typeNameSimple, [typeName]); elementValid = false; } else { reportErrorForNode( StaticWarningCode.NEW_WITH_NON_TYPE, typeNameSimple, [typeName]); elementValid = false; } } if (elementValid && element == null) { // We couldn't resolve the type name. elementValid = false; // TODO(jwren) Consider moving the check for // CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE from the // ErrorVerifier, so that we don't have two errors on a built in // identifier being used as a class name. // See CompileTimeErrorCodeTest.test_builtInIdentifierAsType(). SimpleIdentifier typeNameSimple = _getTypeSimpleIdentifier(typeName); if (_isBuiltInIdentifier(node) && _isTypeAnnotation(node)) { reportErrorForNode(CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE, typeName, [typeName.name]); } else if (typeNameSimple.name == "boolean") { reportErrorForNode( StaticWarningCode.UNDEFINED_CLASS_BOOLEAN, typeNameSimple, []); } else if (_isTypeNameInCatchClause(node)) { reportErrorForNode(StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE, typeName, [typeName.name]); } else if (_isTypeNameInAsExpression(node)) { reportErrorForNode( StaticWarningCode.CAST_TO_NON_TYPE, typeName, [typeName.name]); } else if (_isTypeNameInIsExpression(node)) { reportErrorForNode(StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME, typeName, [typeName.name]); } else if (_isRedirectingConstructor(node)) { reportErrorForNode(CompileTimeErrorCode.REDIRECT_TO_NON_CLASS, typeName, [typeName.name]); } else if (_isTypeNameInTypeArgumentList(node)) { reportErrorForNode(StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT, typeName, [typeName.name]); } else if (typeName is PrefixedIdentifier && node.parent is ConstructorName && argumentList != null) { SimpleIdentifier prefix = (typeName as PrefixedIdentifier).prefix; SimpleIdentifier identifier = (typeName as PrefixedIdentifier).identifier; Element prefixElement = nameScope.lookup(prefix, definingLibrary); ClassElement classElement; ConstructorElement constructorElement; if (prefixElement is ClassElement) { classElement = prefixElement; constructorElement = prefixElement.getNamedConstructor(identifier.name); } if (constructorElement != null) { reportErrorForNode( StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR, argumentList, [prefix.name, identifier.name]); prefix.staticElement = prefixElement; prefix.staticType = classElement.instantiate( typeArguments: List.filled( classElement.typeParameters.length, dynamicType, ), nullabilitySuffix: _noneOrStarSuffix, ); identifier.staticElement = constructorElement; identifier.staticType = constructorElement.type; typeName.staticType = prefix.staticType; AstNode grandParent = node.parent.parent; if (grandParent is InstanceCreationExpressionImpl) { grandParent.staticElement = constructorElement; grandParent.staticType = typeName.staticType; // // Re-write the AST to reflect the resolution. // AstFactory astFactory = new AstFactoryImpl(); TypeName newTypeName = astFactory.typeName(prefix, null); ConstructorName newConstructorName = astFactory.constructorName( newTypeName, (typeName as PrefixedIdentifier).period, identifier); newConstructorName.staticElement = constructorElement; NodeReplacer.replace(node.parent, newConstructorName); grandParent.typeArguments = node.typeArguments; // Re-assign local variables that have effectively changed. node = newTypeName; typeName = prefix; element = prefixElement; argumentList = null; elementValid = true; } } else { reportErrorForNode( CompileTimeErrorCode.UNDEFINED_CLASS, typeName, [typeName.name]); } } else { reportErrorForNode( CompileTimeErrorCode.UNDEFINED_CLASS, typeName, [typeName.name]); } } if (!elementValid) { if (element is MultiplyDefinedElement) { _setElement(typeName, element); } typeName.staticType = dynamicType; node.type = dynamicType; return; } if (element is ClassElement) { _resolveClassElement(node, typeName, argumentList, element); return; } DartType type; if (element == DynamicElementImpl.instance) { _setElement(typeName, element); type = DynamicTypeImpl.instance; } else if (element is NeverElementImpl) { _setElement(typeName, element); type = element.instantiate( nullabilitySuffix: _getNullability(node.question != null), ); } else if (element is FunctionTypeAliasElement) { _setElement(typeName, element); } else if (element is TypeParameterElement) { _setElement(typeName, element); type = element.instantiate( nullabilitySuffix: _getNullability(node.question != null), ); } else if (element is MultiplyDefinedElement) { var elements = (element as MultiplyDefinedElement).conflictingElements; element = _getElementWhenMultiplyDefined(elements); } else { // The name does not represent a type. if (_isTypeNameInCatchClause(node)) { reportErrorForNode(StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE, typeName, [typeName.name]); } else if (_isTypeNameInAsExpression(node)) { reportErrorForNode( StaticWarningCode.CAST_TO_NON_TYPE, typeName, [typeName.name]); } else if (_isTypeNameInIsExpression(node)) { reportErrorForNode(StaticWarningCode.TYPE_TEST_WITH_NON_TYPE, typeName, [typeName.name]); } else if (_isRedirectingConstructor(node)) { reportErrorForNode(CompileTimeErrorCode.REDIRECT_TO_NON_CLASS, typeName, [typeName.name]); } else if (_isTypeNameInTypeArgumentList(node)) { reportErrorForNode(StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT, typeName, [typeName.name]); } else { AstNode parent = typeName.parent; while (parent is TypeName) { parent = parent.parent; } if (parent is ExtendsClause || parent is ImplementsClause || parent is WithClause || parent is ClassTypeAlias) { // Ignored. The error will be reported elsewhere. } else if (element is LocalVariableElement || (element is FunctionElement && element.enclosingElement is ExecutableElement)) { errorListener.onError(new DiagnosticFactory() .referencedBeforeDeclaration(source, typeName, element: element)); } else { reportErrorForNode( StaticWarningCode.NOT_A_TYPE, typeName, [typeName.name]); } } typeName.staticType = dynamicType; node.type = dynamicType; return; } if (argumentList != null) { var parameters = const <TypeParameterElement>[]; if (element is ClassElement) { parameters = element.typeParameters; } else if (element is FunctionTypeAliasElement) { parameters = element.typeParameters; } NodeList<TypeAnnotation> arguments = argumentList.arguments; int argumentCount = arguments.length; int parameterCount = parameters.length; List<DartType> typeArguments = new List<DartType>(parameterCount); if (argumentCount == parameterCount) { for (int i = 0; i < parameterCount; i++) { typeArguments[i] = _getType(arguments[i]); } } else { reportErrorForNode(_getInvalidTypeParametersErrorCode(node), node, [typeName.name, parameterCount, argumentCount]); for (int i = 0; i < parameterCount; i++) { typeArguments[i] = dynamicType; } } if (element is GenericTypeAliasElementImpl) { type = GenericTypeAliasElementImpl.typeAfterSubstitution( element, typeArguments) ?? dynamicType; } else { type = typeSystem.instantiateType(type, typeArguments); } type = (type as TypeImpl).withNullability( _getNullability(node.question != null), ); } else { if (element is GenericTypeAliasElementImpl) { List<DartType> typeArguments = typeSystem.instantiateTypeFormalsToBounds2(element); type = GenericTypeAliasElementImpl.typeAfterSubstitution( element, typeArguments) ?? dynamicType; type = (type as TypeImpl).withNullability( _getNullability(node.question != null), ); } else { type = typeSystem.instantiateToBounds(type); } } typeName.staticType = type; node.type = type; } /// Given the multiple elements to which a single name could potentially be /// resolved, return the single [ClassElement] that should be used, or `null` /// if there is no clear choice. /// /// @param elements the elements to which a single name could potentially be /// resolved /// @return the single interface type that should be used for the type name ClassElement _getElementWhenMultiplyDefined(List<Element> elements) { int length = elements.length; for (int i = 0; i < length; i++) { Element element = elements[i]; if (element is ClassElement) { return element; } } return null; } DartType _getInferredMixinType( ClassElement classElement, ClassElement mixinElement) { for (var candidateMixin in classElement.mixins) { if (candidateMixin.element == mixinElement) return candidateMixin; } return null; // Not found } /// The number of type arguments in the given [typeName] does not match the /// number of parameters in the corresponding class element. Return the error /// code that should be used to report this error. ErrorCode _getInvalidTypeParametersErrorCode(TypeName typeName) { AstNode parent = typeName.parent; if (parent is ConstructorName) { parent = parent.parent; if (parent is InstanceCreationExpression) { if (parent.isConst) { return CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS; } else { return StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS; } } } return StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS; } NullabilitySuffix _getNullability(bool hasQuestion) { NullabilitySuffix nullability; if (isNonNullableUnit) { if (hasQuestion) { nullability = NullabilitySuffix.question; } else { nullability = NullabilitySuffix.none; } } else { nullability = NullabilitySuffix.star; } return nullability; } /// Return the type represented by the given type [annotation]. DartType _getType(TypeAnnotation annotation) { DartType type = annotation.type; if (type == null) { return dynamicType; } return type; } /// Returns the simple identifier of the given (may be qualified) type name. /// /// @param typeName the (may be qualified) qualified type name /// @return the simple identifier of the given (may be qualified) type name. SimpleIdentifier _getTypeSimpleIdentifier(Identifier typeName) { if (typeName is SimpleIdentifier) { return typeName; } else { PrefixedIdentifier prefixed = typeName; SimpleIdentifier prefix = prefixed.prefix; // The prefixed identifier can be: // 1. new importPrefix.TypeName() // 2. new TypeName.constructorName() // 3. new unresolved.Unresolved() if (prefix.staticElement is PrefixElement) { return prefixed.identifier; } else { return prefix; } } } /// If the [node] is the type name in a redirected factory constructor, /// infer type arguments using the enclosing class declaration. Return `null` /// otherwise. List<DartType> _inferTypeArgumentsForRedirectedConstructor( TypeName node, ClassElement typeElement) { AstNode constructorName = node.parent; AstNode enclosingConstructor = constructorName?.parent; if (constructorName is ConstructorName && enclosingConstructor is ConstructorDeclaration && enclosingConstructor.redirectedConstructor == constructorName) { ClassOrMixinDeclaration enclosingClassNode = enclosingConstructor.parent; var enclosingClassElement = enclosingClassNode.declaredElement; if (enclosingClassElement == typeElement) { return typeElement.thisType.typeArguments; } else { return typeSystem.inferGenericFunctionOrType( typeParameters: typeElement.typeParameters, parameters: const [], declaredReturnType: typeElement.thisType, argumentTypes: const [], contextReturnType: enclosingClassElement.thisType, ); } } return null; } /// Return `true` if the given [typeName] is the target in a redirected /// constructor. bool _isRedirectingConstructor(TypeName typeName) { AstNode parent = typeName.parent; if (parent is ConstructorName) { AstNode grandParent = parent.parent; if (grandParent is ConstructorDeclaration) { if (identical(grandParent.redirectedConstructor, parent)) { return true; } } } return false; } /// Checks if the given [typeName] is used as the type in an as expression. bool _isTypeNameInAsExpression(TypeName typeName) { AstNode parent = typeName.parent; if (parent is AsExpression) { return identical(parent.type, typeName); } return false; } /// Checks if the given [typeName] is used as the exception type in a catch /// clause. bool _isTypeNameInCatchClause(TypeName typeName) { AstNode parent = typeName.parent; if (parent is CatchClause) { return identical(parent.exceptionType, typeName); } return false; } /// Checks if the given [typeName] is used as the type in an instance creation /// expression. bool _isTypeNameInInstanceCreationExpression(TypeName typeName) { AstNode parent = typeName.parent; if (parent is ConstructorName && parent.parent is InstanceCreationExpression) { return parent != null && identical(parent.type, typeName); } return false; } /// Checks if the given [typeName] is used as the type in an is expression. bool _isTypeNameInIsExpression(TypeName typeName) { AstNode parent = typeName.parent; if (parent is IsExpression) { return identical(parent.type, typeName); } return false; } /// Checks if the given [typeName] used in a type argument list. bool _isTypeNameInTypeArgumentList(TypeName typeName) => typeName.parent is TypeArgumentList; /// Given a [typeName] that has a question mark, report an error and return /// `true` if it appears in a location where a nullable type is not allowed. void _reportInvalidNullableType(TypeName typeName) { AstNode parent = typeName.parent; if (parent is ExtendsClause || parent is ClassTypeAlias) { reportErrorForNode( CompileTimeErrorCode.NULLABLE_TYPE_IN_EXTENDS_CLAUSE, typeName); } else if (parent is ImplementsClause) { reportErrorForNode( CompileTimeErrorCode.NULLABLE_TYPE_IN_IMPLEMENTS_CLAUSE, typeName); } else if (parent is OnClause) { reportErrorForNode( CompileTimeErrorCode.NULLABLE_TYPE_IN_ON_CLAUSE, typeName); } else if (parent is WithClause) { reportErrorForNode( CompileTimeErrorCode.NULLABLE_TYPE_IN_WITH_CLAUSE, typeName); } } void _resolveClassElement(TypeName node, Identifier typeName, TypeArgumentList argumentList, ClassElement element) { _setElement(typeName, element); var typeParameters = element.typeParameters; var parameterCount = typeParameters.length; List<DartType> typeArguments; if (argumentList != null) { var argumentNodes = argumentList.arguments; var argumentCount = argumentNodes.length; typeArguments = new List<DartType>(parameterCount); if (argumentCount == parameterCount) { for (int i = 0; i < parameterCount; i++) { typeArguments[i] = _getType(argumentNodes[i]); } } else { reportErrorForNode(_getInvalidTypeParametersErrorCode(node), node, [typeName.name, parameterCount, argumentCount]); for (int i = 0; i < parameterCount; i++) { typeArguments[i] = dynamicType; } } } else if (parameterCount == 0) { typeArguments = const <DartType>[]; } else { typeArguments = _inferTypeArgumentsForRedirectedConstructor(node, element); if (typeArguments == null) { typeArguments = typeSystem.instantiateTypeFormalsToBounds2(element); } } var parent = node.parent; NullabilitySuffix nullabilitySuffix; if (parent is ClassTypeAlias || parent is ExtendsClause || parent is ImplementsClause || parent is OnClause || parent is WithClause) { if (node.question != null) { _reportInvalidNullableType(node); } if (isNonNullableUnit) { nullabilitySuffix = NullabilitySuffix.none; } else { nullabilitySuffix = NullabilitySuffix.star; } } else { nullabilitySuffix = _getNullability(node.question != null); } var type = InterfaceTypeImpl.explicit(element, typeArguments, nullabilitySuffix: nullabilitySuffix); if (shouldUseWithClauseInferredTypes) { if (parent is WithClause && parameterCount != 0) { // Get the (possibly inferred) mixin type from the element model. var grandParent = parent.parent; if (grandParent is ClassDeclaration) { type = _getInferredMixinType(grandParent.declaredElement, element); } else if (grandParent is ClassTypeAlias) { type = _getInferredMixinType(grandParent.declaredElement, element); } else { assert(false, 'Unexpected context for "with" clause'); } } } typeName.staticType = type; node.type = type; } /// Records the new Element for a TypeName's Identifier. /// /// A null may be passed in to indicate that the element can't be resolved. /// (During a re-run of a task, it's important to clear any previous value /// of the element.) void _setElement(Identifier typeName, Element element) { if (typeName is SimpleIdentifier) { typeName.staticElement = element; } else if (typeName is PrefixedIdentifier) { typeName.identifier.staticElement = element; SimpleIdentifier prefix = typeName.prefix; prefix.staticElement = nameScope.lookup(prefix, definingLibrary); } } /// Return `true` if the name of the given [typeName] is an built-in /// identifier. static bool _isBuiltInIdentifier(TypeName typeName) { Token token = typeName.name.beginToken; return token.type.isKeyword; } /// @return `true` if given [typeName] is used as a type annotation. static bool _isTypeAnnotation(TypeName typeName) { AstNode parent = typeName.parent; if (parent is VariableDeclarationList) { return identical(parent.type, typeName); } else if (parent is FieldFormalParameter) { return identical(parent.type, typeName); } else if (parent is SimpleFormalParameter) { return identical(parent.type, typeName); } return false; } } /// This class resolves bounds of type parameters of classes, class and function /// type aliases. class TypeParameterBoundsResolver { final TypeSystem typeSystem; final LibraryElement library; final Source source; final AnalysisErrorListener errorListener; Scope libraryScope; TypeNameResolver typeNameResolver; TypeParameterBoundsResolver(this.typeSystem, this.library, this.source, this.errorListener, FeatureSet featureSet) : libraryScope = new LibraryScope(library), typeNameResolver = new TypeNameResolver( typeSystem, typeSystem.typeProvider, featureSet.isEnabled(Feature.non_nullable), library, source, errorListener); /// Resolve bounds of type parameters of classes, class and function type /// aliases. void resolveTypeBounds(CompilationUnit unit) { for (CompilationUnitMember unitMember in unit.declarations) { if (unitMember is ClassDeclaration) { _resolveTypeParameters( unitMember.typeParameters, () => new TypeParameterScope( libraryScope, unitMember.declaredElement)); } else if (unitMember is ClassTypeAlias) { _resolveTypeParameters( unitMember.typeParameters, () => new TypeParameterScope( libraryScope, unitMember.declaredElement)); } else if (unitMember is FunctionTypeAlias) { _resolveTypeParameters( unitMember.typeParameters, () => new FunctionTypeScope( libraryScope, unitMember.declaredElement)); } else if (unitMember is GenericTypeAlias) { _resolveTypeParameters( unitMember.typeParameters, () => new FunctionTypeScope( libraryScope, unitMember.declaredElement)); } } } void _resolveTypeName(TypeAnnotation type) { if (type is TypeName) { type.typeArguments?.arguments?.forEach(_resolveTypeName); typeNameResolver.resolveTypeName(type); // TODO(scheglov) report error when don't apply type bounds for type bounds } else if (type is GenericFunctionType) { // While GenericFunctionTypes with free types are not allowed as bounds, // those free types *should* ideally be recognized as type parameter types // rather than classnames. Create a scope to accomplish that. Scope previousScope = typeNameResolver.nameScope; try { Scope typeParametersScope = new TypeParameterScope( typeNameResolver.nameScope, type.type.element); typeNameResolver.nameScope = typeParametersScope; void resolveTypeParameter(TypeParameter t) { _resolveTypeName(t.bound); } void resolveParameter(FormalParameter p) { if (p is SimpleFormalParameter) { _resolveTypeName(p.type); } else if (p is DefaultFormalParameter) { resolveParameter(p.parameter); } else if (p is FieldFormalParameter) { _resolveTypeName(p.type); } else if (p is FunctionTypedFormalParameter) { _resolveTypeName(p.returnType); p.typeParameters?.typeParameters?.forEach(resolveTypeParameter); p.parameters?.parameters?.forEach(resolveParameter); } } _resolveTypeName(type.returnType); type.typeParameters?.typeParameters?.forEach(resolveTypeParameter); type.parameters?.parameters?.forEach(resolveParameter); } finally { typeNameResolver.nameScope = previousScope; } } } void _resolveTypeParameters( TypeParameterList typeParameters, Scope createTypeParametersScope()) { if (typeParameters != null) { Scope typeParametersScope; for (TypeParameter typeParameter in typeParameters.typeParameters) { TypeAnnotation bound = typeParameter.bound; if (bound != null) { Element typeParameterElement = typeParameter.name.staticElement; if (typeParameterElement is TypeParameterElementImpl) { if (LibraryElementImpl.hasResolutionCapability( library, LibraryResolutionCapability.resolvedTypeNames)) { if (bound is TypeName) { bound.type = typeParameterElement.bound; } else if (bound is GenericFunctionTypeImpl) { bound.type = typeParameterElement.bound; } } else { typeParametersScope ??= createTypeParametersScope(); // _resolveTypeParameters is the entry point into each declaration // with a separate scope. We can safely, and should, clobber the // old scope here. typeNameResolver.nameScope = typeParametersScope; _resolveTypeName(bound); typeParameterElement.bound = bound.type; } } } } } } } /// The interface `TypeProvider` defines the behavior of objects that provide /// access to types defined by the language. abstract class TypeProvider { /// Return the type representing the built-in type 'bool'. InterfaceType get boolType; /// Return the type representing the type 'bottom'. DartType get bottomType; /// Return the type representing the built-in type 'Deprecated'. InterfaceType get deprecatedType; /// Return the type representing the built-in type 'double'. InterfaceType get doubleType; /// Return the type representing the built-in type 'dynamic'. DartType get dynamicType; /// Return the type representing the built-in type 'Function'. InterfaceType get functionType; /// Return the type representing 'Future<dynamic>'. InterfaceType get futureDynamicType; /// Return the element representing the built-in class 'Future'. ClassElement get futureElement; /// Return the type representing 'Future<Null>'. InterfaceType get futureNullType; /// Return the element representing the built-in class 'FutureOr'. ClassElement get futureOrElement; /// Return the type representing 'FutureOr<Null>'. InterfaceType get futureOrNullType; /// Return the type representing the built-in type 'FutureOr'. @Deprecated('Use futureOrType2() instead.') InterfaceType get futureOrType; /// Return the type representing the built-in type 'Future'. @Deprecated('Use futureType2() instead.') InterfaceType get futureType; /// Return the type representing the built-in type 'int'. InterfaceType get intType; /// Return the type representing the type 'Iterable<dynamic>'. InterfaceType get iterableDynamicType; /// Return the element representing the built-in class 'Iterable'. ClassElement get iterableElement; /// Return the type representing the type 'Iterable<Object>'. InterfaceType get iterableObjectType; /// Return the type representing the built-in type 'Iterable'. @Deprecated('Use iterableType2() instead.') InterfaceType get iterableType; /// Return the element representing the built-in class 'List'. ClassElement get listElement; /// Return the type representing the built-in type 'List'. @Deprecated('Use listType2() instead.') InterfaceType get listType; /// Return the element representing the built-in class 'Map'. ClassElement get mapElement; /// Return the type representing 'Map<Object, Object>'. InterfaceType get mapObjectObjectType; /// Return the type representing the built-in type 'Map'. @Deprecated('Use mapType2() instead.') InterfaceType get mapType; /// Return the type representing the built-in type 'Never'. DartType get neverType; /// Return a list containing all of the types that cannot be either extended /// or implemented. List<InterfaceType> get nonSubtypableTypes; /// Return a [DartObjectImpl] representing the `null` object. DartObjectImpl get nullObject; /// Return the type representing the built-in type 'Null'. InterfaceType get nullType; /// Return the type representing the built-in type 'num'. InterfaceType get numType; /// Return the type representing the built-in type 'Object'. InterfaceType get objectType; /// Return the element representing the built-in class 'Set'. ClassElement get setElement; /// Return the type representing the built-in type 'Set'. @Deprecated('Use setType2() instead.') InterfaceType get setType; /// Return the type representing the built-in type 'StackTrace'. InterfaceType get stackTraceType; /// Return the type representing 'Stream<dynamic>'. InterfaceType get streamDynamicType; /// Return the element representing the built-in class 'Stream'. ClassElement get streamElement; /// Return the type representing the built-in type 'Stream'. @Deprecated('Use streamType2() instead.') InterfaceType get streamType; /// Return the type representing the built-in type 'String'. InterfaceType get stringType; /// Return the element representing the built-in class 'Symbol'. ClassElement get symbolElement; /// Return the type representing the built-in type 'Symbol'. InterfaceType get symbolType; /// Return the type representing the built-in type 'Type'. InterfaceType get typeType; /// Return the type representing the built-in type `void`. VoidType get voidType; /// Return the instantiation of the built-in class 'FutureOr' with the /// given [valueType]. The type has the nullability suffix of this provider. InterfaceType futureOrType2(DartType valueType); /// Return the instantiation of the built-in class 'Future' with the /// given [valueType]. The type has the nullability suffix of this provider. InterfaceType futureType2(DartType valueType); /// Return 'true' if [id] is the name of a getter on /// the Object type. bool isObjectGetter(String id); /// Return 'true' if [id] is the name of a method or getter on /// the Object type. bool isObjectMember(String id); /// Return 'true' if [id] is the name of a method on /// the Object type. bool isObjectMethod(String id); /// Return the instantiation of the built-in class 'Iterable' with the /// given [elementType]. The type has the nullability suffix of this provider. InterfaceType iterableType2(DartType elementType); /// Return the instantiation of the built-in class 'List' with the /// given [elementType]. The type has the nullability suffix of this provider. InterfaceType listType2(DartType elementType); /// Return the instantiation of the built-in class 'List' with the /// given [keyType] and [valueType]. The type has the nullability suffix of /// this provider. InterfaceType mapType2(DartType keyType, DartType valueType); /// Return the instantiation of the built-in class 'Set' with the /// given [elementType]. The type has the nullability suffix of this provider. InterfaceType setType2(DartType elementType); /// Return the instantiation of the built-in class 'Stream' with the /// given [elementType]. The type has the nullability suffix of this provider. InterfaceType streamType2(DartType elementType); } /// Modes in which [TypeResolverVisitor] works. enum TypeResolverMode { /// Resolve all names types of all nodes. everything, /// Resolve only type names outside of function bodies, variable initializers, /// and parameter default values. api, /// Resolve only type names that would be skipped during [api]. /// /// Resolution must start from a unit member or a class member. For example /// it is not allowed to resolve types in a separate statement, or a function /// body. local } /// Instances of the class `TypeResolverVisitor` are used to resolve the types /// associated with the elements in the element model. This includes the types /// of superclasses, mixins, interfaces, fields, methods, parameters, and local /// variables. As a side-effect, this also finishes building the type hierarchy. class TypeResolverVisitor extends ScopedVisitor { /// The type representing the type 'dynamic'. DartType _dynamicType; /// The flag specifying if currently visited class references 'super' /// expression. bool _hasReferenceToSuper = false; /// True if we're analyzing in strong mode. final bool _strongMode = true; /// Type type system in use for this resolver pass. TypeSystem _typeSystem; /// Whether the compilation unit is non-nullable. final bool isNonNullableUnit; /// The helper to resolve types. TypeNameResolver _typeNameResolver; final TypeResolverMode mode; /// Is `true` when we are visiting all nodes in [TypeResolverMode.local] mode. bool _localModeVisitAll = false; /// Is `true` if we are in [TypeResolverMode.local] mode, and the initial /// [nameScope] was computed. bool _localModeScopeReady = false; /// Initialize a newly created visitor to resolve the nodes in an AST node. /// /// [definingLibrary] is the element for the library containing the node being /// visited. /// [source] is the source representing the compilation unit containing the /// node being visited. /// [typeProvider] is the object used to access the types from the core /// library. /// [errorListener] is the error listener that will be informed of any errors /// that are found during resolution. /// [nameScope] is the scope used to resolve identifiers in the node that will /// first be visited. If `null` or unspecified, a new [LibraryScope] will be /// created based on [definingLibrary] and [typeProvider]. /// /// Note: in a future release of the analyzer, the [featureSet] parameter will /// be required. TypeResolverVisitor(LibraryElement definingLibrary, Source source, TypeProvider typeProvider, AnalysisErrorListener errorListener, {Scope nameScope, @Deprecated('Use featureSet instead') bool isNonNullableUnit: false, FeatureSet featureSet, this.mode: TypeResolverMode.everything, bool shouldUseWithClauseInferredTypes: true}) : isNonNullableUnit = featureSet?.isEnabled(Feature.non_nullable) ?? // ignore: deprecated_member_use_from_same_package isNonNullableUnit, super(definingLibrary, source, typeProvider, errorListener, nameScope: nameScope) { _dynamicType = typeProvider.dynamicType; _typeSystem = TypeSystem.create(definingLibrary.context); _typeNameResolver = new TypeNameResolver(_typeSystem, typeProvider, this.isNonNullableUnit, definingLibrary, source, errorListener, shouldUseWithClauseInferredTypes: shouldUseWithClauseInferredTypes); } @override void visitAnnotation(Annotation node) { // // Visit annotations, if the annotation is @proxy, on a class, and "proxy" // resolves to the proxy annotation in dart.core, then resolve the // ElementAnnotation. // // Element resolution is done in the ElementResolver, and this work will be // done in the general case for all annotations in the ElementResolver. // The reason we resolve this particular element early is so that // ClassElement.isProxy() returns the correct information during all // phases of the ElementResolver. // super.visitAnnotation(node); Identifier identifier = node.name; if (identifier.name.endsWith(ElementAnnotationImpl.PROXY_VARIABLE_NAME) && node.parent is ClassDeclaration) { Element element = nameScope.lookup(identifier, definingLibrary); if (element != null && element.library.isDartCore && element is PropertyAccessorElement) { // This is the @proxy from dart.core ElementAnnotationImpl elementAnnotation = node.elementAnnotation; elementAnnotation.element = element; } } } @override void visitCatchClause(CatchClause node) { super.visitCatchClause(node); SimpleIdentifier exception = node.exceptionParameter; if (exception != null) { // If an 'on' clause is provided the type of the exception parameter is // the type in the 'on' clause. Otherwise, the type of the exception // parameter is 'Object'. TypeAnnotation exceptionTypeName = node.exceptionType; DartType exceptionType; if (exceptionTypeName == null) { exceptionType = typeProvider.dynamicType; } else { exceptionType = _typeNameResolver._getType(exceptionTypeName); } _recordType(exception, exceptionType); Element element = exception.staticElement; if (element is VariableElementImpl) { element.declaredType = exceptionType; } else { // TODO(brianwilkerson) Report the internal error } } SimpleIdentifier stackTrace = node.stackTraceParameter; if (stackTrace != null) { _recordType(stackTrace, typeProvider.stackTraceType); Element element = stackTrace.staticElement; if (element is VariableElementImpl) { element.declaredType = typeProvider.stackTraceType; } else { // TODO(brianwilkerson) Report the internal error } } } @override void visitClassDeclaration(ClassDeclaration node) { _hasReferenceToSuper = false; super.visitClassDeclaration(node); ClassElementImpl classElement = _getClassElement(node.name); if (classElement != null) { // Clear this flag, as we just invalidated any inferred member types. classElement.hasBeenInferred = false; classElement.hasReferenceToSuper = _hasReferenceToSuper; } } @override void visitClassDeclarationInScope(ClassDeclaration node) { super.visitClassDeclarationInScope(node); ExtendsClause extendsClause = node.extendsClause; WithClause withClause = node.withClause; ImplementsClause implementsClause = node.implementsClause; ClassElementImpl classElement = _getClassElement(node.name); if (extendsClause != null) { ErrorCode errorCode = (withClause == null ? CompileTimeErrorCode.EXTENDS_NON_CLASS : CompileTimeErrorCode.MIXIN_WITH_NON_CLASS_SUPERCLASS); _resolveType(extendsClause.superclass, errorCode, asClass: true); } _resolveWithClause(classElement, withClause); _resolveImplementsClause(classElement, implementsClause); } @override void visitClassMembersInScope(ClassDeclaration node) { node.documentationComment?.accept(this); node.metadata.accept(this); // // Process field declarations before constructors and methods so that the // types of field formal parameters can be correctly resolved. // List<ClassMember> nonFields = new List<ClassMember>(); NodeList<ClassMember> members = node.members; int length = members.length; for (int i = 0; i < length; i++) { ClassMember member = members[i]; if (member is ConstructorDeclaration) { nonFields.add(member); } else { member.accept(this); } } int count = nonFields.length; for (int i = 0; i < count; i++) { nonFields[i].accept(this); } } @override void visitClassTypeAlias(ClassTypeAlias node) { super.visitClassTypeAlias(node); _resolveType( node.superclass, CompileTimeErrorCode.MIXIN_WITH_NON_CLASS_SUPERCLASS, asClass: true, ); ClassElementImpl classElement = _getClassElement(node.name); _resolveWithClause(classElement, node.withClause); _resolveImplementsClause(classElement, node.implementsClause); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { super.visitConstructorDeclaration(node); if (node.declaredElement == null) { ClassDeclaration classNode = node.thisOrAncestorOfType<ClassDeclaration>(); StringBuffer buffer = new StringBuffer(); buffer.write("The element for the constructor "); buffer.write(node.name == null ? "<unnamed>" : node.name.name); buffer.write(" in "); if (classNode == null) { buffer.write("<unknown class>"); } else { buffer.write(classNode.name.name); } buffer.write(" in "); buffer.write(source.fullName); buffer.write(" was not set while trying to resolve types."); AnalysisEngine.instance.logger.logError(buffer.toString(), new CaughtException(new AnalysisException(), null)); } } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { super.visitDeclaredIdentifier(node); DartType declaredType; TypeAnnotation typeName = node.type; if (typeName == null) { declaredType = _dynamicType; } else { declaredType = _typeNameResolver._getType(typeName); } LocalVariableElementImpl element = node.declaredElement as LocalVariableElementImpl; element.declaredType = declaredType; } @override void visitFieldFormalParameter(FieldFormalParameter node) { super.visitFieldFormalParameter(node); Element element = node.identifier.staticElement; if (element is ParameterElementImpl) { FormalParameterList parameterList = node.parameters; if (parameterList == null) { DartType type; TypeAnnotation typeName = node.type; if (typeName == null) { element.hasImplicitType = true; if (element is FieldFormalParameterElement) { FieldElement fieldElement = (element as FieldFormalParameterElement).field; type = fieldElement?.type; } } else { type = _typeNameResolver._getType(typeName); } element.declaredType = type ?? _dynamicType; } else { _setFunctionTypedParameterType(element, node.type, node.parameters); } } else { // TODO(brianwilkerson) Report this internal error } } @override void visitFunctionDeclaration(FunctionDeclaration node) { super.visitFunctionDeclaration(node); ExecutableElementImpl element = node.declaredElement as ExecutableElementImpl; if (element == null) { StringBuffer buffer = new StringBuffer(); buffer.write("The element for the top-level function "); buffer.write(node.name); buffer.write(" in "); buffer.write(source.fullName); buffer.write(" was not set while trying to resolve types."); AnalysisEngine.instance.logger.logError(buffer.toString(), new CaughtException(new AnalysisException(), null)); } element.declaredReturnType = _computeReturnType(node.returnType); element.type = new FunctionTypeImpl(element); _inferSetterReturnType(element); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { var element = node.declaredElement as GenericTypeAliasElementImpl; super.visitFunctionTypeAlias(node); element.function.returnType = _computeReturnType(node.returnType); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { super.visitFunctionTypedFormalParameter(node); Element element = node.identifier.staticElement; if (element is ParameterElementImpl) { _setFunctionTypedParameterType(element, node.returnType, node.parameters); } else { // TODO(brianwilkerson) Report this internal error } } @override void visitGenericFunctionType(GenericFunctionType node) { GenericFunctionTypeElementImpl element = (node as GenericFunctionTypeImpl).declaredElement; if (node.type != null) { var nullability = _typeNameResolver._getNullability(node.question != null); (node as GenericFunctionTypeImpl).type = (node.type as TypeImpl).withNullability(nullability); } if (element != null) { super.visitGenericFunctionType(node); element.returnType = _computeReturnType(node.returnType) ?? DynamicTypeImpl.instance; } } @override void visitMethodDeclaration(MethodDeclaration node) { super.visitMethodDeclaration(node); ExecutableElementImpl element = node.declaredElement as ExecutableElementImpl; if (element == null) { ClassDeclaration classNode = node.thisOrAncestorOfType<ClassDeclaration>(); StringBuffer buffer = new StringBuffer(); buffer.write("The element for the method "); buffer.write(node.name.name); buffer.write(" in "); if (classNode == null) { buffer.write("<unknown class>"); } else { buffer.write(classNode.name.name); } buffer.write(" in "); buffer.write(source.fullName); buffer.write(" was not set while trying to resolve types."); AnalysisEngine.instance.logger.logError(buffer.toString(), new CaughtException(new AnalysisException(), null)); } // When the library is resynthesized, types of all of its elements are // already set - statically or inferred. We don't want to overwrite them. if (LibraryElementImpl.hasResolutionCapability( definingLibrary, LibraryResolutionCapability.resolvedTypeNames)) { return; } element.declaredReturnType = _computeReturnType(node.returnType); element.type = new FunctionTypeImpl(element); _inferSetterReturnType(element); _inferOperatorReturnType(element); if (element is PropertyAccessorElement) { PropertyAccessorElement accessor = element as PropertyAccessorElement; PropertyInducingElementImpl variable = accessor.variable as PropertyInducingElementImpl; if (accessor.isGetter) { variable.declaredType = element.returnType; } else if (variable.type == null) { List<ParameterElement> parameters = element.parameters; DartType type = parameters != null && parameters.isNotEmpty ? parameters[0].type : _dynamicType; variable.declaredType = type; } } } @override void visitMixinDeclarationInScope(MixinDeclaration node) { super.visitMixinDeclarationInScope(node); MixinElementImpl element = node.declaredElement; _resolveOnClause(element, node.onClause); _resolveImplementsClause(element, node.implementsClause); } @override void visitNode(AstNode node) { // In API mode we need to skip: // - function bodies; // - default values of parameters; // - initializers of top-level variables. if (mode == TypeResolverMode.api) { if (node is FunctionBody) { return; } if (node is DefaultFormalParameter) { node.parameter.accept(this); return; } if (node is VariableDeclaration) { return; } } // In local mode we need to resolve only: // - function bodies; // - default values of parameters; // - initializers of top-level variables. // So, we carefully visit only nodes that are, or contain, these nodes. // The client may choose to start visiting any node, but we still want to // resolve only type names that are local. if (mode == TypeResolverMode.local) { // We are in the state of visiting all nodes. if (_localModeVisitAll) { super.visitNode(node); return; } // Ensure that the name scope is ready. if (!_localModeScopeReady) { void fillNameScope(AstNode node) { if (node is FunctionBody || node is FormalParameterList || node is VariableDeclaration) { throw new StateError( 'Local type resolution must start from a class or unit member.'); } // Create enclosing name scopes. AstNode parent = node.parent; if (parent != null) { fillNameScope(parent); } // Create the name scope for the node. if (node is ClassDeclaration) { ClassElement classElement = node.declaredElement; nameScope = new TypeParameterScope(nameScope, classElement); nameScope = new ClassScope(nameScope, classElement); } } fillNameScope(node); _localModeScopeReady = true; } /// Visit the given [node] and all its children. void visitAllNodes(AstNode node) { if (node != null) { bool wasVisitAllInLocalMode = _localModeVisitAll; try { _localModeVisitAll = true; node.accept(this); } finally { _localModeVisitAll = wasVisitAllInLocalMode; } } } // Visit only nodes that may contain type names to resolve. if (node is CompilationUnit) { node.declarations.forEach(visitNode); } else if (node is ClassDeclaration) { node.members.forEach(visitNode); } else if (node is DefaultFormalParameter) { visitAllNodes(node.defaultValue); } else if (node is FieldDeclaration) { visitNode(node.fields); } else if (node is FunctionBody) { visitAllNodes(node); } else if (node is FunctionDeclaration) { visitNode(node.functionExpression.parameters); visitAllNodes(node.functionExpression.body); } else if (node is FormalParameterList) { node.parameters.accept(this); } else if (node is MethodDeclaration) { visitNode(node.parameters); visitAllNodes(node.body); } else if (node is TopLevelVariableDeclaration) { visitNode(node.variables); } else if (node is VariableDeclaration) { visitAllNodes(node.initializer); } else if (node is VariableDeclarationList) { node.variables.forEach(visitNode); } return; } // The mode in which we visit all nodes. super.visitNode(node); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { super.visitSimpleFormalParameter(node); DartType declaredType; TypeAnnotation typeName = node.type; if (typeName == null) { declaredType = _dynamicType; } else { declaredType = _typeNameResolver._getType(typeName); } Element element = node.declaredElement; if (element is ParameterElementImpl) { element.declaredType = declaredType; } else { // TODO(brianwilkerson) Report the internal error. } } @override void visitSuperExpression(SuperExpression node) { _hasReferenceToSuper = true; super.visitSuperExpression(node); } @override void visitTypeName(TypeName node) { super.visitTypeName(node); _typeNameResolver.nameScope = this.nameScope; _typeNameResolver.resolveTypeName(node); } @override void visitTypeParameter(TypeParameter node) { super.visitTypeParameter(node); AstNode parent2 = node.parent?.parent; if (parent2 is ClassDeclaration || parent2 is ClassTypeAlias || parent2 is FunctionTypeAlias || parent2 is GenericTypeAlias) { // Bounds of parameters of classes and function type aliases are // already resolved. } else { TypeAnnotation bound = node.bound; if (bound != null) { TypeParameterElementImpl typeParameter = node.name.staticElement as TypeParameterElementImpl; if (typeParameter != null) { typeParameter.bound = bound.type; } } } } @override void visitVariableDeclaration(VariableDeclaration node) { super.visitVariableDeclaration(node); var variableList = node.parent as VariableDeclarationList; // When the library is resynthesized, the types of field elements are // already set - statically or inferred. We don't want to overwrite them. if (variableList.parent is FieldDeclaration && LibraryElementImpl.hasResolutionCapability( definingLibrary, LibraryResolutionCapability.resolvedTypeNames)) { return; } // Resolve the type. DartType declaredType; TypeAnnotation typeName = variableList.type; if (typeName == null) { declaredType = _dynamicType; } else { declaredType = _typeNameResolver._getType(typeName); } Element element = node.name.staticElement; if (element is VariableElementImpl) { element.declaredType = declaredType; } } /// Given the [returnType] of a function, compute the return type of the /// function. DartType _computeReturnType(TypeAnnotation returnType) { if (returnType == null) { return _dynamicType; } else { return _typeNameResolver._getType(returnType); } } /// Return the class element that represents the class whose name was /// provided. /// /// @param identifier the name from the declaration of a class /// @return the class element that represents the class ClassElementImpl _getClassElement(SimpleIdentifier identifier) { // TODO(brianwilkerson) Seems like we should be using // ClassDeclaration.getElement(). if (identifier == null) { // TODO(brianwilkerson) Report this // Internal error: We should never build a class declaration without a // name. return null; } Element element = identifier.staticElement; if (element is ClassElementImpl) { return element; } // TODO(brianwilkerson) Report this // Internal error: Failed to create an element for a class declaration. return null; } /// In strong mode we infer "void" as the return type of operator []= (as void /// is the only legal return type for []=). This allows us to give better /// errors later if an invalid type is returned. void _inferOperatorReturnType(ExecutableElementImpl element) { if (_strongMode && element.isOperator && element.name == '[]=' && element.hasImplicitReturnType) { element.declaredReturnType = VoidTypeImpl.instance; } } /// In strong mode we infer "void" as the setter return type (as void is the /// only legal return type for a setter). This allows us to give better /// errors later if an invalid type is returned. void _inferSetterReturnType(ExecutableElementImpl element) { if (_strongMode && element is PropertyAccessorElementImpl && element.isSetter && element.hasImplicitReturnType) { element.declaredReturnType = VoidTypeImpl.instance; } } /// 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 Object _recordType(Expression expression, DartType type) { if (type == null) { expression.staticType = _dynamicType; } else { expression.staticType = type; } return null; } void _resolveImplementsClause( ClassElementImpl classElement, ImplementsClause clause) { if (clause != null) { _resolveTypes( clause.interfaces, CompileTimeErrorCode.IMPLEMENTS_NON_CLASS); } } void _resolveOnClause(MixinElementImpl classElement, OnClause clause) { List<InterfaceType> types; if (clause != null) { _resolveTypes(clause.superclassConstraints, CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_NON_INTERFACE); } if (types == null || types.isEmpty) { types = [typeProvider.objectType]; } } /// Return the [InterfaceType] of the given [typeName]. /// /// If the resulting type is not a valid interface type, return `null`. /// /// The flag [asClass] specifies if the type will be used as a class, so mixin /// declarations are not valid (they declare interfaces and mixins, but not /// classes). void _resolveType(TypeName typeName, ErrorCode errorCode, {bool asClass: false}) { DartType type = typeName.type; if (type is InterfaceType) { ClassElement element = type.element; if (element != null) { if (element.isEnum || element.isMixin && asClass) { errorReporter.reportErrorForNode(errorCode, typeName); return; } } return; } // If the type is not an InterfaceType, then visitTypeName() sets the type // to be a DynamicTypeImpl Identifier name = typeName.name; if (!nameScope.shouldIgnoreUndefined(name)) { errorReporter.reportErrorForNode(errorCode, name, [name.name]); } } /// Resolve the types in the given list of type names. /// /// @param typeNames the type names to be resolved /// @param nonTypeError the error to produce if the type name is defined to be /// something other than a type /// @param enumTypeError the error to produce if the type name is defined to /// be an enum /// @param dynamicTypeError the error to produce if the type name is "dynamic" /// @return an array containing all of the types that were resolved. void _resolveTypes(NodeList<TypeName> typeNames, ErrorCode errorCode) { for (TypeName typeName in typeNames) { _resolveType(typeName, errorCode); } } void _resolveWithClause(ClassElementImpl classElement, WithClause clause) { if (clause != null) { _resolveTypes(clause.mixinTypes, CompileTimeErrorCode.MIXIN_OF_NON_CLASS); } } /// Given a function typed [parameter] with [FunctionType] based on a /// [GenericFunctionTypeElementImpl], compute and set the return type for the /// function element. void _setFunctionTypedParameterType(ParameterElementImpl parameter, TypeAnnotation returnType, FormalParameterList parameterList) { DartType type = parameter.type; GenericFunctionTypeElementImpl typeElement = type.element; // With summary2 we use synthetic FunctionType(s). if (typeElement != null) { typeElement.returnType = _computeReturnType(returnType); } } } /// Instances of the class [UnusedLocalElementsVerifier] traverse an AST /// looking for cases of [HintCode.UNUSED_ELEMENT], [HintCode.UNUSED_FIELD], /// [HintCode.UNUSED_LOCAL_VARIABLE], etc. class UnusedLocalElementsVerifier extends RecursiveAstVisitor { /// The error listener to which errors will be reported. final AnalysisErrorListener _errorListener; /// The elements know to be used. final UsedLocalElements _usedElements; /// Create a new instance of the [UnusedLocalElementsVerifier]. UnusedLocalElementsVerifier(this._errorListener, this._usedElements); visitSimpleIdentifier(SimpleIdentifier node) { if (node.inDeclarationContext()) { var element = node.staticElement; if (element is ClassElement) { _visitClassElement(element); } else if (element is FieldElement) { _visitFieldElement(element); } else if (element is FunctionElement) { _visitFunctionElement(element); } else if (element is FunctionTypeAliasElement) { _visitFunctionTypeAliasElement(element); } else if (element is LocalVariableElement) { _visitLocalVariableElement(element); } else if (element is MethodElement) { _visitMethodElement(element); } else if (element is PropertyAccessorElement) { _visitPropertyAccessorElement(element); } else if (element is TopLevelVariableElement) { _visitTopLevelVariableElement(element); } } } bool _isNamedUnderscore(LocalVariableElement element) { String name = element.name; if (name != null) { for (int index = name.length - 1; index >= 0; --index) { if (name.codeUnitAt(index) != 0x5F) { // 0x5F => '_' return false; } } return true; } return false; } bool _isReadMember(Element element) { if (element.isPublic) { return true; } if (element.isSynthetic) { return true; } return _usedElements.readMembers.contains(element.displayName); } bool _isUsedElement(Element element) { if (element.isSynthetic) { return true; } if (element is LocalVariableElement || element is FunctionElement && !element.isStatic) { // local variable or function } else { if (element.isPublic) { return true; } } return _usedElements.elements.contains(element); } bool _isUsedMember(Element element) { if (element.isPublic) { return true; } if (element.isSynthetic) { return true; } if (_usedElements.members.contains(element.displayName)) { return true; } return _usedElements.elements.contains(element); } void _reportErrorForElement( ErrorCode errorCode, Element element, List<Object> arguments) { if (element != null) { _errorListener.onError(new AnalysisError(element.source, element.nameOffset, element.nameLength, errorCode, arguments)); } } _visitClassElement(ClassElement element) { if (!_isUsedElement(element)) { _reportErrorForElement( HintCode.UNUSED_ELEMENT, element, [element.displayName]); } } _visitFieldElement(FieldElement element) { if (!_isReadMember(element)) { _reportErrorForElement( HintCode.UNUSED_FIELD, element, [element.displayName]); } } _visitFunctionElement(FunctionElement element) { if (!_isUsedElement(element)) { _reportErrorForElement( HintCode.UNUSED_ELEMENT, element, [element.displayName]); } } _visitFunctionTypeAliasElement(FunctionTypeAliasElement element) { if (!_isUsedElement(element)) { _reportErrorForElement( HintCode.UNUSED_ELEMENT, element, [element.displayName]); } } _visitLocalVariableElement(LocalVariableElement element) { if (!_isUsedElement(element) && !_isNamedUnderscore(element)) { HintCode errorCode; if (_usedElements.isCatchException(element)) { errorCode = HintCode.UNUSED_CATCH_CLAUSE; } else if (_usedElements.isCatchStackTrace(element)) { errorCode = HintCode.UNUSED_CATCH_STACK; } else { errorCode = HintCode.UNUSED_LOCAL_VARIABLE; } _reportErrorForElement(errorCode, element, [element.displayName]); } } _visitMethodElement(MethodElement element) { if (!_isUsedMember(element)) { _reportErrorForElement( HintCode.UNUSED_ELEMENT, element, [element.displayName]); } } _visitPropertyAccessorElement(PropertyAccessorElement element) { if (!_isUsedMember(element)) { _reportErrorForElement( HintCode.UNUSED_ELEMENT, element, [element.displayName]); } } _visitTopLevelVariableElement(TopLevelVariableElement element) { if (!_isUsedElement(element)) { _reportErrorForElement( HintCode.UNUSED_ELEMENT, element, [element.displayName]); } } } /// A container with sets of used [Element]s. /// All these elements are defined in a single compilation unit or a library. class UsedLocalElements { /// Resolved, locally defined elements that are used or potentially can be /// used. final HashSet<Element> elements = new HashSet<Element>(); /// [LocalVariableElement]s that represent exceptions in [CatchClause]s. final HashSet<LocalVariableElement> catchExceptionElements = new HashSet<LocalVariableElement>(); /// [LocalVariableElement]s that represent stack traces in [CatchClause]s. final HashSet<LocalVariableElement> catchStackTraceElements = new HashSet<LocalVariableElement>(); /// Names of resolved or unresolved class members that are referenced in the /// library. final HashSet<String> members = new HashSet<String>(); /// Names of resolved or unresolved class members that are read in the /// library. final HashSet<String> readMembers = new HashSet<String>(); UsedLocalElements(); factory UsedLocalElements.merge(List<UsedLocalElements> parts) { UsedLocalElements result = new UsedLocalElements(); int length = parts.length; for (int i = 0; i < length; i++) { UsedLocalElements part = parts[i]; result.elements.addAll(part.elements); result.catchExceptionElements.addAll(part.catchExceptionElements); result.catchStackTraceElements.addAll(part.catchStackTraceElements); result.members.addAll(part.members); result.readMembers.addAll(part.readMembers); } return result; } void addCatchException(LocalVariableElement element) { if (element != null) { catchExceptionElements.add(element); } } void addCatchStackTrace(LocalVariableElement element) { if (element != null) { catchStackTraceElements.add(element); } } void addElement(Element element) { if (element != null) { elements.add(element); } } bool isCatchException(LocalVariableElement element) { return catchExceptionElements.contains(element); } bool isCatchStackTrace(LocalVariableElement element) { return catchStackTraceElements.contains(element); } } /// Instances of the class `VariableResolverVisitor` are used to resolve /// [SimpleIdentifier]s to local variables and formal parameters. class VariableResolverVisitor extends ScopedVisitor { /// The method or function that we are currently visiting, or `null` if we are /// not inside a method or function. ExecutableElement _enclosingFunction; /// Information about local variables in the enclosing function or method. LocalVariableInfo _localVariableInfo; /// Initialize a newly created visitor to resolve the nodes in an AST node. /// /// [definingLibrary] is the element for the library containing the node being /// visited. /// [source] is the source representing the compilation unit containing the /// node being visited /// [typeProvider] is the object used to access the types from the core /// library. /// [errorListener] is the error listener that will be informed of any errors /// that are found during resolution. /// [nameScope] is the scope used to resolve identifiers in the node that will /// first be visited. If `null` or unspecified, a new [LibraryScope] will be /// created based on [definingLibrary] and [typeProvider]. VariableResolverVisitor(LibraryElement definingLibrary, Source source, TypeProvider typeProvider, AnalysisErrorListener errorListener, {Scope nameScope, LocalVariableInfo localVariableInfo}) : _localVariableInfo = localVariableInfo, super(definingLibrary, source, typeProvider, errorListener, nameScope: nameScope); @override void visitBlockFunctionBody(BlockFunctionBody node) { assert(_localVariableInfo != null); super.visitBlockFunctionBody(node); } @override void visitCompilationUnit(CompilationUnit node) { _localVariableInfo = (node as CompilationUnitImpl).localVariableInfo; super.visitCompilationUnit(node); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; LocalVariableInfo outerLocalVariableInfo = _localVariableInfo; try { _localVariableInfo ??= new LocalVariableInfo(); (node.body as FunctionBodyImpl).localVariableInfo = _localVariableInfo; _enclosingFunction = node.declaredElement; super.visitConstructorDeclaration(node); } finally { _localVariableInfo = outerLocalVariableInfo; _enclosingFunction = outerFunction; } } @override void visitExportDirective(ExportDirective node) {} @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { assert(_localVariableInfo != null); super.visitExpressionFunctionBody(node); } @override void visitFunctionDeclaration(FunctionDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; LocalVariableInfo outerLocalVariableInfo = _localVariableInfo; try { _localVariableInfo ??= new LocalVariableInfo(); (node.functionExpression.body as FunctionBodyImpl).localVariableInfo = _localVariableInfo; _enclosingFunction = node.declaredElement; super.visitFunctionDeclaration(node); } finally { _localVariableInfo = outerLocalVariableInfo; _enclosingFunction = outerFunction; } } @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is! FunctionDeclaration) { ExecutableElement outerFunction = _enclosingFunction; LocalVariableInfo outerLocalVariableInfo = _localVariableInfo; try { _localVariableInfo ??= new LocalVariableInfo(); (node.body as FunctionBodyImpl).localVariableInfo = _localVariableInfo; _enclosingFunction = node.declaredElement; super.visitFunctionExpression(node); } finally { _localVariableInfo = outerLocalVariableInfo; _enclosingFunction = outerFunction; } } else { super.visitFunctionExpression(node); } } @override void visitImportDirective(ImportDirective node) {} @override void visitMethodDeclaration(MethodDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; LocalVariableInfo outerLocalVariableInfo = _localVariableInfo; try { _localVariableInfo ??= new LocalVariableInfo(); (node.body as FunctionBodyImpl).localVariableInfo = _localVariableInfo; _enclosingFunction = node.declaredElement; super.visitMethodDeclaration(node); } finally { _localVariableInfo = outerLocalVariableInfo; _enclosingFunction = outerFunction; } } @override void visitSimpleIdentifier(SimpleIdentifier node) { // Ignore if already resolved - declaration or type. if (node.inDeclarationContext()) { return; } // Ignore if it cannot be a reference to a local variable. AstNode parent = node.parent; if (parent is FieldFormalParameter) { return; } else if (parent is ConstructorDeclaration && parent.returnType == node) { return; } else if (parent is ConstructorFieldInitializer && parent.fieldName == node) { return; } // Ignore if qualified. if (parent is PrefixedIdentifier && identical(parent.identifier, node)) { return; } if (parent is PropertyAccess && identical(parent.propertyName, node)) { return; } if (parent is MethodInvocation && identical(parent.methodName, node) && parent.realTarget != null) { return; } if (parent is ConstructorName) { return; } if (parent is Label) { return; } // Prepare VariableElement. Element element = nameScope.lookup(node, definingLibrary); if (element is! VariableElement) { return; } // Must be local or parameter. ElementKind kind = element.kind; if (kind == ElementKind.LOCAL_VARIABLE || kind == ElementKind.PARAMETER) { node.staticElement = element; if (node.inSetterContext()) { _localVariableInfo.potentiallyMutatedInScope.add(element); if (element.enclosingElement != _enclosingFunction) { _localVariableInfo.potentiallyMutatedInClosure.add(element); } } } } @override void visitTypeName(TypeName node) {} } class _InvalidAccessVerifier { static final _templateExtension = '.template'; static final _testDir = '${path.separator}test${path.separator}'; static final _testingDir = '${path.separator}testing${path.separator}'; final ErrorReporter _errorReporter; final LibraryElement _library; bool _inTemplateSource; bool _inTestDirectory; ClassElement _enclosingClass; _InvalidAccessVerifier(this._errorReporter, this._library) { var path = _library.source.fullName; _inTemplateSource = path.contains(_templateExtension); _inTestDirectory = path.contains(_testDir) || path.contains(_testingDir); } /// Produces a hint if [identifier] is accessed from an invalid location. In /// particular: /// /// * if the given identifier is a protected closure, field or /// getter/setter, method closure or invocation accessed outside a subclass, /// or accessed outside the library wherein the identifier is declared, or /// * if the given identifier is a closure, field, getter, setter, method /// closure or invocation which is annotated with `visibleForTemplate`, and /// is accessed outside of the defining library, and the current library /// does not have the suffix '.template' in its source path, or /// * if the given identifier is a closure, field, getter, setter, method /// closure or invocation which is annotated with `visibleForTesting`, and /// is accessed outside of the defining library, and the current library /// does not have a directory named 'test' or 'testing' in its path. void verify(SimpleIdentifier identifier) { if (identifier.inDeclarationContext() || _inCommentReference(identifier)) { return; } Element element = identifier.staticElement; if (element == null || _inCurrentLibrary(element)) { return; } bool hasProtected = _hasProtected(element); if (hasProtected) { ClassElement definingClass = element.enclosingElement; if (_hasTypeOrSuperType(_enclosingClass, definingClass)) { return; } } bool hasVisibleForTemplate = _hasVisibleForTemplate(element); if (hasVisibleForTemplate) { if (_inTemplateSource || _inExportDirective(identifier)) { return; } } bool hasVisibleForTesting = _hasVisibleForTesting(element); if (hasVisibleForTesting) { if (_inTestDirectory || _inExportDirective(identifier)) { return; } } // At this point, [identifier] was not cleared as protected access, nor // cleared as access for templates or testing. Report the appropriate // violation(s). Element definingClass = element.enclosingElement; if (hasProtected) { _errorReporter.reportErrorForNode( HintCode.INVALID_USE_OF_PROTECTED_MEMBER, identifier, [identifier.name, definingClass.source.uri]); } if (hasVisibleForTemplate) { _errorReporter.reportErrorForNode( HintCode.INVALID_USE_OF_VISIBLE_FOR_TEMPLATE_MEMBER, identifier, [identifier.name, definingClass.source.uri]); } if (hasVisibleForTesting) { _errorReporter.reportErrorForNode( HintCode.INVALID_USE_OF_VISIBLE_FOR_TESTING_MEMBER, identifier, [identifier.name, definingClass.source.uri]); } } bool _hasProtected(Element element) { if (element is PropertyAccessorElement && element.enclosingElement is ClassElement && (element.hasProtected || element.variable.hasProtected)) { return true; } if (element is MethodElement && element.enclosingElement is ClassElement && element.hasProtected) { return true; } return false; } bool _hasTypeOrSuperType(ClassElement element, ClassElement superElement) { if (element == null) { return false; } if (element == superElement) { return true; } // TODO(scheglov) `allSupertypes` is very expensive var allSupertypes = element.allSupertypes; for (var i = 0; i < allSupertypes.length; i++) { var supertype = allSupertypes[i]; if (supertype.element == superElement) { return true; } } return false; } bool _hasVisibleForTemplate(Element element) { if (element == null) { return false; } if (element.hasVisibleForTemplate) { return true; } if (element is PropertyAccessorElement && element.enclosingElement is ClassElement && element.variable.hasVisibleForTemplate) { return true; } return false; } bool _hasVisibleForTesting(Element element) { if (element == null) { return false; } if (element.hasVisibleForTesting) { return true; } if (element is PropertyAccessorElement && element.enclosingElement is ClassElement && element.variable.hasVisibleForTesting) { return true; } return false; } bool _inCommentReference(SimpleIdentifier identifier) { var parent = identifier.parent; return parent is CommentReference || parent?.parent is CommentReference; } bool _inCurrentLibrary(Element element) => element.library == _library; bool _inExportDirective(SimpleIdentifier identifier) => identifier.parent is Combinator && identifier.parent.parent is ExportDirective; } /// An object used to track the usage of labels within a single label scope. class _LabelTracker { /// The tracker for the outer label scope. final _LabelTracker outerTracker; /// The labels whose usage is being tracked. final List<Label> labels; /// A list of flags corresponding to the list of [labels] indicating whether /// the corresponding label has been used. List<bool> used; /// A map from the names of labels to the index of the label in [labels]. final Map<String, int> labelMap = <String, int>{}; /// Initialize a newly created label tracker. _LabelTracker(this.outerTracker, this.labels) { used = new List.filled(labels.length, false); for (int i = 0; i < labels.length; i++) { labelMap[labels[i].label.name] = i; } } /// Record that the label with the given [labelName] has been used. void recordUsage(String labelName) { if (labelName != null) { int index = labelMap[labelName]; if (index != null) { used[index] = true; } else if (outerTracker != null) { outerTracker.recordUsage(labelName); } } } /// Return the unused labels. Iterable<Label> unusedLabels() sync* { for (int i = 0; i < labels.length; i++) { if (!used[i]) { yield labels[i]; } } } } /// A set of counts of the kinds of leaf elements in a collection, used to help /// disambiguate map and set literals. class _LeafElements { /// The number of expressions found in the collection. int expressionCount = 0; /// The number of map entries found in the collection. int mapEntryCount = 0; /// Initialize a newly created set of counts based on the given collection /// [elements]. _LeafElements(List<CollectionElement> elements) { for (CollectionElement element in elements) { _count(element); } } /// Return the resolution suggested by the set elements. _LiteralResolution get resolution { if (expressionCount > 0 && mapEntryCount == 0) { return _LiteralResolution(_LiteralResolutionKind.set, null); } else if (mapEntryCount > 0 && expressionCount == 0) { return _LiteralResolution(_LiteralResolutionKind.map, null); } return _LiteralResolution(_LiteralResolutionKind.ambiguous, null); } /// Recursively add the given collection [element] to the counts. void _count(CollectionElement element) { if (element is ForElement) { _count(element.body); } else if (element is IfElement) { _count(element.thenElement); _count(element.elseElement); } else if (element is Expression) { if (_isComplete(element)) { expressionCount++; } } else if (element is MapLiteralEntry) { if (_isComplete(element)) { mapEntryCount++; } } } /// Return `true` if the given collection [element] does not contain any /// synthetic tokens. bool _isComplete(CollectionElement element) { // TODO(paulberry,brianwilkerson): the code below doesn't work because it // assumes access to token offsets, which aren't available when working with // expressions resynthesized from summaries. For now we just assume the // collection element is complete. return true; // Token token = element.beginToken; // int endOffset = element.endToken.offset; // while (token != null && token.offset <= endOffset) { // if (token.isSynthetic) { // return false; // } // token = token.next; // } // return true; } } /// An indication of the way in which a set or map literal should be resolved to /// be either a set literal or a map literal. class _LiteralResolution { /// The kind of collection that the literal should be. final _LiteralResolutionKind kind; /// The type that should be used as the inference context when performing type /// inference for the literal. DartType contextType; /// Initialize a newly created resolution. _LiteralResolution(this.kind, this.contextType); @override String toString() { return '$kind ($contextType)'; } } /// The kind of literal to which an unknown literal should be resolved. enum _LiteralResolutionKind { ambiguous, map, set }
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.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. @deprecated library analyzer.src.generated.error; export 'package:analyzer/error/error.dart'; export 'package:analyzer/error/listener.dart'; export 'package:analyzer/src/error/codes.dart';
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/engine.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 'dart:typed_data'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/exception/exception.dart'; import 'package:analyzer/instrumentation/instrumentation.dart'; import 'package:analyzer/source/error_processor.dart'; import 'package:analyzer/src/context/context.dart'; import 'package:analyzer/src/dart/analysis/experiments.dart'; import 'package:analyzer/src/generated/constant.dart'; import 'package:analyzer/src/generated/java_engine.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/utilities_general.dart'; import 'package:analyzer/src/services/lint.dart'; import 'package:analyzer/src/summary/api_signature.dart'; import 'package:front_end/src/fasta/scanner/token.dart'; import 'package:path/path.dart' as pathos; import 'package:pub_semver/pub_semver.dart'; export 'package:analyzer/error/listener.dart' show RecordingErrorListener; export 'package:analyzer/src/generated/timestamped_data.dart' show TimestampedData; /// Used by [AnalysisOptions] to allow function bodies to be analyzed in some /// sources but not others. typedef bool AnalyzeFunctionBodiesPredicate(Source source); /// A context in which a single analysis can be performed and incrementally /// maintained. The context includes such information as the version of the SDK /// being analyzed against as well as the package-root used to resolve 'package:' /// URI's. (Both of which are known indirectly through the [SourceFactory].) /// /// An analysis context also represents the state of the analysis, which includes /// knowing which sources have been included in the analysis (either directly or /// indirectly) and the results of the analysis. Sources must be added and /// removed from the context using the method [applyChanges], which is also used /// to notify the context when sources have been modified and, consequently, /// previously known results might have been invalidated. /// /// There are two ways to access the results of the analysis. The most common is /// to use one of the 'get' methods to access the results. The 'get' methods have /// the advantage that they will always return quickly, but have the disadvantage /// that if the results are not currently available they will return either /// nothing or in some cases an incomplete result. The second way to access /// results is by using one of the 'compute' methods. The 'compute' methods will /// always attempt to compute the requested results but might block the caller /// for a significant period of time. /// /// When results have been invalidated, have never been computed (as is the case /// for newly added sources), or have been removed from the cache, they are /// <b>not</b> automatically recreated. They will only be recreated if one of the /// 'compute' methods is invoked. /// /// However, this is not always acceptable. Some clients need to keep the /// analysis results up-to-date. For such clients there is a mechanism that /// allows them to incrementally perform needed analysis and get notified of the /// consequent changes to the analysis results. This mechanism is realized by the /// method [performAnalysisTask]. /// /// Analysis engine allows for having more than one context. This can be used, /// for example, to perform one analysis based on the state of files on disk and /// a separate analysis based on the state of those files in open editors. It can /// also be used to perform an analysis based on a proposed future state, such as /// the state after a refactoring. abstract class AnalysisContext { /// Return the set of analysis options controlling the behavior of this /// context. Clients should not modify the returned set of options. AnalysisOptions get analysisOptions; /// Set the set of analysis options controlling the behavior of this context to /// the given [options]. Clients can safely assume that all necessary analysis /// results have been invalidated. void set analysisOptions(AnalysisOptions options); /// Return the set of declared variables used when computing constant values. DeclaredVariables get declaredVariables; /// Return the source factory used to create the sources that can be analyzed /// in this context. SourceFactory get sourceFactory; /// Set the source factory used to create the sources that can be analyzed in /// this context to the given source [factory]. Clients can safely assume that /// all analysis results have been invalidated. void set sourceFactory(SourceFactory factory); /// Return a type provider for this context or throw [AnalysisException] if /// either `dart:core` or `dart:async` cannot be resolved. TypeProvider get typeProvider; /// Return a type system for this context. TypeSystem get typeSystem; /// Apply the changes specified by the given [changeSet] to this context. Any /// analysis results that have been invalidated by these changes will be /// removed. /// TODO(scheglov) This method is referenced by the internal indexer tool. void applyChanges(ChangeSet changeSet); } /// The entry point for the functionality provided by the analysis engine. There /// is a single instance of this class. class AnalysisEngine { /// The suffix used for Dart source files. static const String SUFFIX_DART = "dart"; /// The short suffix used for HTML files. static const String SUFFIX_HTM = "htm"; /// The long suffix used for HTML files. static const String SUFFIX_HTML = "html"; /// The deprecated file name used for analysis options files. static const String ANALYSIS_OPTIONS_FILE = '.analysis_options'; /// The file name used for analysis options files. static const String ANALYSIS_OPTIONS_YAML_FILE = 'analysis_options.yaml'; /// The file name used for pubspec files. static const String PUBSPEC_YAML_FILE = 'pubspec.yaml'; /// The file name used for Android manifest files. static const String ANDROID_MANIFEST_FILE = 'AndroidManifest.xml'; /// The unique instance of this class. static final AnalysisEngine instance = new AnalysisEngine._(); /// The logger that should receive information about errors within the analysis /// engine. Logger _logger = Logger.NULL; /// The instrumentation service that is to be used by this analysis engine. InstrumentationService _instrumentationService = InstrumentationService.NULL_SERVICE; /// The partition manager being used to manage the shared partitions. final PartitionManager partitionManager = new PartitionManager(); AnalysisEngine._(); /// Return the instrumentation service that is to be used by this analysis /// engine. InstrumentationService get instrumentationService => _instrumentationService; /// Set the instrumentation service that is to be used by this analysis engine /// to the given [service]. void set instrumentationService(InstrumentationService service) { if (service == null) { _instrumentationService = InstrumentationService.NULL_SERVICE; } else { _instrumentationService = service; } } /// Return the logger that should receive information about errors within the /// analysis engine. Logger get logger => _logger; /// Set the logger that should receive information about errors within the /// analysis engine to the given [logger]. void set logger(Logger logger) { this._logger = logger ?? Logger.NULL; } /// Clear any caches holding on to analysis results so that a full re-analysis /// will be performed the next time an analysis context is created. void clearCaches() { partitionManager.clearCache(); // See https://github.com/dart-lang/sdk/issues/30314. StringToken.canonicalizer.clear(); } /// Create and return a new context in which analysis can be performed. AnalysisContext createAnalysisContext() { return new AnalysisContextImpl(); } /// A utility method that clients can use to process all of the required /// plugins. This method can only be used by clients that do not need to /// process any other plugins. @deprecated void processRequiredPlugins() {} /// Return `true` if the given [fileName] is an analysis options file. static bool isAnalysisOptionsFileName(String fileName, [pathos.Context context]) { if (fileName == null) { return false; } String basename = (context ?? pathos.posix).basename(fileName); return basename == ANALYSIS_OPTIONS_FILE || basename == ANALYSIS_OPTIONS_YAML_FILE; } /// Return `true` if the given [fileName] is assumed to contain Dart source /// code. static bool isDartFileName(String fileName) { if (fileName == null) { return false; } String extension = FileNameUtilities.getExtension(fileName).toLowerCase(); return extension == SUFFIX_DART; } /// Return `true` if the given [fileName] is AndroidManifest.xml static bool isManifestFileName(String fileName) { if (fileName == null) { return false; } return fileName.endsWith(AnalysisEngine.ANDROID_MANIFEST_FILE); } } /// The analysis errors and line information for the errors. abstract class AnalysisErrorInfo { /// Return the errors that as a result of the analysis, or `null` if there were /// no errors. List<AnalysisError> get errors; /// Return the line information associated with the errors, or `null` if there /// were no errors. LineInfo get lineInfo; } /// The analysis errors and line info associated with a source. class AnalysisErrorInfoImpl implements AnalysisErrorInfo { /// The analysis errors associated with a source, or `null` if there are no /// errors. @override final List<AnalysisError> errors; /// The line information associated with the errors, or `null` if there are no /// errors. final LineInfo lineInfo; /// Initialize an newly created error info with the given [errors] and /// [lineInfo]. AnalysisErrorInfoImpl(this.errors, this.lineInfo); } /// A set of analysis options used to control the behavior of an analysis /// context. abstract class AnalysisOptions { /// The length of the list returned by [signature]. static const int signatureLength = 4; /// Function that returns `true` if analysis is to parse and analyze function /// bodies for a given source. AnalyzeFunctionBodiesPredicate get analyzeFunctionBodiesPredicate; /// Return the maximum number of sources for which AST structures should be /// kept in the cache. /// /// DEPRECATED: This setting no longer has any effect. @deprecated int get cacheSize; /// A flag indicating whether to run checks on AndroidManifest.xml file to /// see if it is complaint with Chrome OS. bool get chromeOsManifestChecks; /// The set of features that are globally enabled for this context. FeatureSet get contextFeatures; /// Return `true` if analysis is to generate dart2js related hint results. bool get dart2jsHint; /// Return `true` if cache flushing should be disabled. Setting this option to /// `true` can improve analysis speed at the expense of memory usage. It may /// also be useful for working around bugs. /// /// This option should not be used when the analyzer is part of a long running /// process (such as the analysis server) because it has the potential to /// prevent memory from being reclaimed. bool get disableCacheFlushing; /// Return `true` if the parser is to parse asserts in the initializer list of /// a constructor. @deprecated bool get enableAssertInitializer; /// Return `true` to enable custom assert messages (DEP 37). @deprecated bool get enableAssertMessage; /// Return `true` to if analysis is to enable async support. @deprecated bool get enableAsync; /// Return `true` to enable interface libraries (DEP 40). @deprecated bool get enableConditionalDirectives; /// Return a list containing the names of the experiments that are enabled in /// the context associated with these options. /// /// The process around these experiments is described in this /// [doc](https://github.com/dart-lang/sdk/blob/master/docs/process/experimental-flags.md). List<String> get enabledExperiments; /// Return a list of the names of the packages for which, if they define a /// plugin, the plugin should be enabled. List<String> get enabledPluginNames; /// Return `true` to enable generic methods (DEP 22). @deprecated bool get enableGenericMethods => null; /// Return `true` if access to field formal parameters should be allowed in a /// constructor's initializer list. @deprecated bool get enableInitializingFormalAccess; /// Return `true` to enable the lazy compound assignment operators '&&=' and /// '||='. bool get enableLazyAssignmentOperators; /// Return `true` if mixins are allowed to inherit from types other than /// Object, and are allowed to reference `super`. @deprecated bool get enableSuperMixins; /// Return `true` if timing data should be gathered during execution. bool get enableTiming; /// Return `true` to enable the use of URIs in part-of directives. @deprecated bool get enableUriInPartOf; /// Return a list of error processors that are to be used when reporting /// errors in some analysis context. List<ErrorProcessor> get errorProcessors; /// Return a list of exclude patterns used to exclude some sources from /// analysis. List<String> get excludePatterns; /// Return `true` if errors, warnings and hints should be generated for sources /// that are implicitly being analyzed. The default value is `true`. bool get generateImplicitErrors; /// Return `true` if errors, warnings and hints should be generated for sources /// in the SDK. The default value is `false`. bool get generateSdkErrors; /// Return `true` if analysis is to generate hint results (e.g. type inference /// based information and pub best practices). bool get hint; /// Return `true` if analysis is to generate lint warnings. bool get lint; /// Return a list of the lint rules that are to be run in an analysis context /// if [lint] returns `true`. List<Linter> get lintRules; /// A mapping from Dart SDK library name (e.g. "dart:core") to a list of paths /// to patch files that should be applied to the library. Map<String, List<String>> get patchPaths; /// Return `true` if analysis is to parse comments. bool get preserveComments; /// Return `true` if analyzer should enable the use of Dart 2.0 features. /// /// This getter is deprecated, and is hard-coded to always return true. @Deprecated( 'This getter is deprecated and is hard-coded to always return true.') bool get previewDart2; /// The version range for the SDK specified in `pubspec.yaml`, or `null` if /// there is no `pubspec.yaml` or if it does not contain an SDK range. VersionConstraint get sdkVersionConstraint; /// Return the opaque signature of the options. /// /// The length of the list is guaranteed to equal [signatureLength]. Uint32List get signature; /// Return `true` if strong mode analysis should be used. /// /// This getter is deprecated, and is hard-coded to always return true. @Deprecated( 'This getter is deprecated and is hard-coded to always return true.') bool get strongMode; /// Return `true` if dependencies between computed results should be tracked /// by analysis cache. This option should only be set to `false` if analysis /// is performed in such a way that none of the inputs is ever changed /// during the life time of the context. bool get trackCacheDependencies; /// Return `true` if analyzer should use the Dart 2.0 Front End parser. bool get useFastaParser; /// Return `true` the lint with the given [name] is enabled. bool isLintEnabled(String name); /// Reset the state of this set of analysis options to its original state. void resetToDefaults(); /// Set the values of the cross-context options to match those in the given set /// of [options]. @deprecated void setCrossContextOptionsFrom(AnalysisOptions options); /// Determine whether two signatures returned by [signature] are equal. static bool signaturesEqual(Uint32List a, Uint32List b) { assert(a.length == signatureLength); assert(b.length == signatureLength); if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } } /// A set of analysis options used to control the behavior of an analysis /// context. class AnalysisOptionsImpl implements AnalysisOptions { /// DEPRECATED: The maximum number of sources for which data should be kept in /// the cache. /// /// This constant no longer has any effect. @deprecated static const int DEFAULT_CACHE_SIZE = 64; /// The length of the list returned by [unlinkedSignature]. static const int unlinkedSignatureLength = 4; /// A predicate indicating whether analysis is to parse and analyze function /// bodies. AnalyzeFunctionBodiesPredicate _analyzeFunctionBodiesPredicate = _analyzeAllFunctionBodies; /// The cached [unlinkedSignature]. Uint32List _unlinkedSignature; /// The cached [signature]. Uint32List _signature; @override VersionConstraint sdkVersionConstraint; @override @deprecated int cacheSize = 64; @override bool dart2jsHint = false; List<String> _enabledExperiments = const <String>[]; ExperimentStatus _contextFeatures = ExperimentStatus(); @override List<String> enabledPluginNames = const <String>[]; @override bool enableLazyAssignmentOperators = false; @override bool enableTiming = false; /// A list of error processors that are to be used when reporting errors in /// some analysis context. List<ErrorProcessor> _errorProcessors; /// A list of exclude patterns used to exclude some sources from analysis. List<String> _excludePatterns; @override bool generateImplicitErrors = true; @override bool generateSdkErrors = false; @override bool hint = true; @override bool lint = false; /// The lint rules that are to be run in an analysis context if [lint] returns /// `true`. List<Linter> _lintRules; Map<String, List<String>> patchPaths = {}; @override bool preserveComments = true; /// A flag indicating whether strong-mode inference hints should be /// used. This flag is not exposed in the interface, and should be /// replaced by something more general. // TODO(leafp): replace this with something more general bool strongModeHints = false; @override bool trackCacheDependencies = true; @override bool useFastaParser = true; @override bool disableCacheFlushing = false; /// A flag indicating whether implicit casts are allowed in [strongMode] /// (they are always allowed in Dart 1.0 mode). /// /// This option is experimental and subject to change. bool implicitCasts = true; /// A flag indicating whether implicit dynamic type is allowed, on by default. /// /// This flag can be used without necessarily enabling [strongMode], but it is /// designed with strong mode's type inference in mind. Without type inference, /// it will raise many errors. Also it does not provide type safety without /// strong mode. /// /// This option is experimental and subject to change. bool implicitDynamic = true; /// A flag indicating whether inference failures are allowed, off by default. /// /// This option is experimental and subject to change. bool strictInference = false; /// Whether raw types (types without explicit type arguments, such as `List`) /// should be reported as potential problems. /// /// Raw types are a common source of `dynamic` being introduced implicitly. /// This often leads to cast failures later on in the program. bool strictRawTypes = false; @override bool chromeOsManifestChecks = false; /// Initialize a newly created set of analysis options to have their default /// values. AnalysisOptionsImpl(); /// Initialize a newly created set of analysis options to have the same values /// as those in the given set of analysis [options]. AnalysisOptionsImpl.from(AnalysisOptions options) { analyzeFunctionBodiesPredicate = options.analyzeFunctionBodiesPredicate; dart2jsHint = options.dart2jsHint; enabledExperiments = options.enabledExperiments; enabledPluginNames = options.enabledPluginNames; enableLazyAssignmentOperators = options.enableLazyAssignmentOperators; enableTiming = options.enableTiming; errorProcessors = options.errorProcessors; excludePatterns = options.excludePatterns; generateImplicitErrors = options.generateImplicitErrors; generateSdkErrors = options.generateSdkErrors; hint = options.hint; lint = options.lint; lintRules = options.lintRules; preserveComments = options.preserveComments; useFastaParser = options.useFastaParser; if (options is AnalysisOptionsImpl) { strongModeHints = options.strongModeHints; implicitCasts = options.implicitCasts; implicitDynamic = options.implicitDynamic; strictInference = options.strictInference; strictRawTypes = options.strictRawTypes; } trackCacheDependencies = options.trackCacheDependencies; disableCacheFlushing = options.disableCacheFlushing; patchPaths = options.patchPaths; sdkVersionConstraint = options.sdkVersionConstraint; } bool get analyzeFunctionBodies { if (identical(analyzeFunctionBodiesPredicate, _analyzeAllFunctionBodies)) { return true; } else if (identical( analyzeFunctionBodiesPredicate, _analyzeNoFunctionBodies)) { return false; } else { throw new StateError('analyzeFunctionBodiesPredicate in use'); } } set analyzeFunctionBodies(bool value) { if (value) { analyzeFunctionBodiesPredicate = _analyzeAllFunctionBodies; } else { analyzeFunctionBodiesPredicate = _analyzeNoFunctionBodies; } } @override AnalyzeFunctionBodiesPredicate get analyzeFunctionBodiesPredicate => _analyzeFunctionBodiesPredicate; set analyzeFunctionBodiesPredicate(AnalyzeFunctionBodiesPredicate value) { if (value == null) { throw new ArgumentError.notNull('analyzeFunctionBodiesPredicate'); } _analyzeFunctionBodiesPredicate = value; } @override FeatureSet get contextFeatures => _contextFeatures; set contextFeatures(FeatureSet featureSet) { _contextFeatures = featureSet; _enabledExperiments = _contextFeatures.toStringList(); } @deprecated @override bool get enableAssertInitializer => true; @deprecated void set enableAssertInitializer(bool enable) {} @override @deprecated bool get enableAssertMessage => true; @deprecated void set enableAssertMessage(bool enable) {} @deprecated @override bool get enableAsync => true; @deprecated void set enableAsync(bool enable) {} /// A flag indicating whether interface libraries are to be supported (DEP 40). bool get enableConditionalDirectives => true; @deprecated void set enableConditionalDirectives(_) {} @override List<String> get enabledExperiments => _enabledExperiments; set enabledExperiments(List<String> enabledExperiments) { _enabledExperiments = enabledExperiments; _contextFeatures = ExperimentStatus.fromStrings(enabledExperiments); } @override @deprecated bool get enableGenericMethods => true; @deprecated void set enableGenericMethods(bool enable) {} @deprecated @override bool get enableInitializingFormalAccess => true; @deprecated void set enableInitializingFormalAccess(bool enable) {} @override @deprecated bool get enableSuperMixins => false; @deprecated void set enableSuperMixins(bool enable) { // Ignored. } @deprecated @override bool get enableUriInPartOf => true; @deprecated void set enableUriInPartOf(bool enable) {} @override List<ErrorProcessor> get errorProcessors => _errorProcessors ??= const <ErrorProcessor>[]; /// Set the list of error [processors] that are to be used when reporting /// errors in some analysis context. void set errorProcessors(List<ErrorProcessor> processors) { _errorProcessors = processors; } @override List<String> get excludePatterns => _excludePatterns ??= const <String>[]; /// Set the exclude patterns used to exclude some sources from analysis to /// those in the given list of [patterns]. void set excludePatterns(List<String> patterns) { _excludePatterns = patterns; } /// The set of enabled experiments. ExperimentStatus get experimentStatus => _contextFeatures; /// Return `true` to enable mixin declarations. /// https://github.com/dart-lang/language/issues/12 @deprecated bool get isMixinSupportEnabled => true; @deprecated set isMixinSupportEnabled(bool value) {} @override List<Linter> get lintRules => _lintRules ??= const <Linter>[]; /// Set the lint rules that are to be run in an analysis context if [lint] /// returns `true`. void set lintRules(List<Linter> rules) { _lintRules = rules; } @deprecated @override bool get previewDart2 => true; @deprecated set previewDart2(bool value) {} @override Uint32List get signature { if (_signature == null) { ApiSignature buffer = new ApiSignature(); // Append environment. if (sdkVersionConstraint != null) { buffer.addString(sdkVersionConstraint.toString()); } // Append boolean flags. buffer.addBool(enableLazyAssignmentOperators); buffer.addBool(implicitCasts); buffer.addBool(implicitDynamic); buffer.addBool(strictInference); buffer.addBool(strictRawTypes); buffer.addBool(strongModeHints); buffer.addBool(useFastaParser); // Append enabled experiments. buffer.addInt(enabledExperiments.length); for (String experimentName in enabledExperiments) { buffer.addString(experimentName); } // Append error processors. buffer.addInt(errorProcessors.length); for (ErrorProcessor processor in errorProcessors) { buffer.addString(processor.description); } // Append lints. buffer.addString(linterVersion ?? ''); buffer.addInt(lintRules.length); for (Linter lintRule in lintRules) { buffer.addString(lintRule.lintCode.uniqueName); } // Append plugin names. buffer.addInt(enabledPluginNames.length); for (String enabledPluginName in enabledPluginNames) { buffer.addString(enabledPluginName); } // Hash and convert to Uint32List. List<int> bytes = buffer.toByteList(); _signature = new Uint8List.fromList(bytes).buffer.asUint32List(); } return _signature; } @override bool get strongMode => true; @Deprecated( "The strongMode field is deprecated, and shouldn't be assigned to") set strongMode(bool value) {} /// Return the opaque signature of the options that affect unlinked data. /// /// The length of the list is guaranteed to equal [unlinkedSignatureLength]. Uint32List get unlinkedSignature { if (_unlinkedSignature == null) { ApiSignature buffer = new ApiSignature(); // Append boolean flags. buffer.addBool(enableLazyAssignmentOperators); buffer.addBool(useFastaParser); // Append enabled experiments. buffer.addInt(enabledExperiments.length); for (String experimentName in enabledExperiments) { buffer.addString(experimentName); } // Hash and convert to Uint32List. List<int> bytes = buffer.toByteList(); _unlinkedSignature = new Uint8List.fromList(bytes).buffer.asUint32List(); } return _unlinkedSignature; } @override bool isLintEnabled(String name) { return lintRules.any((rule) => rule.name == name); } @override void resetToDefaults() { dart2jsHint = false; disableCacheFlushing = false; enabledExperiments = const <String>[]; enabledPluginNames = const <String>[]; enableLazyAssignmentOperators = false; enableTiming = false; _errorProcessors = null; _excludePatterns = null; generateImplicitErrors = true; generateSdkErrors = false; hint = true; implicitCasts = true; implicitDynamic = true; strictInference = false; strictRawTypes = false; lint = false; _lintRules = null; patchPaths = {}; preserveComments = true; strongModeHints = false; trackCacheDependencies = true; useFastaParser = true; } @deprecated @override void setCrossContextOptionsFrom(AnalysisOptions options) { enableLazyAssignmentOperators = options.enableLazyAssignmentOperators; if (options is AnalysisOptionsImpl) { strongModeHints = options.strongModeHints; } } /// Return whether the given lists of lints are equal. static bool compareLints(List<Linter> a, List<Linter> b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i].lintCode != b[i].lintCode) { return false; } } return true; } /// Predicate used for [analyzeFunctionBodiesPredicate] when /// [analyzeFunctionBodies] is set to `true`. static bool _analyzeAllFunctionBodies(Source _) => true; /// Predicate used for [analyzeFunctionBodiesPredicate] when /// [analyzeFunctionBodies] is set to `false`. static bool _analyzeNoFunctionBodies(Source _) => false; } /// An indication of which sources have been added, changed, removed, or deleted. /// In the case of a changed source, there are multiple ways of indicating the /// nature of the change. /// /// No source should be added to the change set more than once, either with the /// same or a different kind of change. It does not make sense, for example, for /// a source to be both added and removed, and it is redundant for a source to be /// marked as changed in its entirety and changed in some specific range. class ChangeSet { /// A list containing the sources that have been added. final List<Source> addedSources = new List<Source>(); /// A list containing the sources that have been changed. final List<Source> changedSources = new List<Source>(); /// A table mapping the sources whose content has been changed to the current /// content of those sources. Map<Source, String> _changedContent = new HashMap<Source, String>(); /// A table mapping the sources whose content has been changed within a single /// range to the current content of those sources and information about the /// affected range. final HashMap<Source, ChangeSet_ContentChange> changedRanges = new HashMap<Source, ChangeSet_ContentChange>(); /// A list containing the sources that have been removed. final List<Source> removedSources = new List<Source>(); /// A list containing the source containers specifying additional sources that /// have been removed. final List<SourceContainer> removedContainers = new List<SourceContainer>(); /// Return a table mapping the sources whose content has been changed to the /// current content of those sources. Map<Source, String> get changedContents => _changedContent; /// Return `true` if this change set does not contain any changes. bool get isEmpty => addedSources.isEmpty && changedSources.isEmpty && _changedContent.isEmpty && changedRanges.isEmpty && removedSources.isEmpty && removedContainers.isEmpty; /// Record that the specified [source] has been added and that its content is /// the default contents of the source. void addedSource(Source source) { addedSources.add(source); } /// Record that the specified [source] has been changed and that its content is /// the given [contents]. void changedContent(Source source, String contents) { _changedContent[source] = contents; } /// Record that the specified [source] has been changed and that its content is /// the given [contents]. The [offset] is the offset into the current contents. /// The [oldLength] is the number of characters in the original contents that /// were replaced. The [newLength] is the number of characters in the /// replacement text. void changedRange(Source source, String contents, int offset, int oldLength, int newLength) { changedRanges[source] = new ChangeSet_ContentChange(contents, offset, oldLength, newLength); } /// Record that the specified [source] has been changed. If the content of the /// source was previously overridden, this has no effect (the content remains /// overridden). To cancel (or change) the override, use [changedContent] /// instead. void changedSource(Source source) { changedSources.add(source); } /// Record that the specified source [container] has been removed. void removedContainer(SourceContainer container) { if (container != null) { removedContainers.add(container); } } /// Record that the specified [source] has been removed. void removedSource(Source source) { if (source != null) { removedSources.add(source); } } @override String toString() { StringBuffer buffer = new StringBuffer(); bool needsSeparator = _appendSources(buffer, addedSources, false, "addedSources"); needsSeparator = _appendSources( buffer, changedSources, needsSeparator, "changedSources"); needsSeparator = _appendSources2( buffer, _changedContent, needsSeparator, "changedContent"); needsSeparator = _appendSources2(buffer, changedRanges, needsSeparator, "changedRanges"); needsSeparator = _appendSources( buffer, removedSources, needsSeparator, "removedSources"); int count = removedContainers.length; if (count > 0) { if (removedSources.isEmpty) { if (needsSeparator) { buffer.write("; "); } buffer.write("removed: from "); buffer.write(count); buffer.write(" containers"); } else { buffer.write(", and more from "); buffer.write(count); buffer.write(" containers"); } } return buffer.toString(); } /// Append the given [sources] to the given [buffer], prefixed with the given /// [label] and a separator if [needsSeparator] is `true`. Return `true` if /// future lists of sources will need a separator. bool _appendSources(StringBuffer buffer, List<Source> sources, bool needsSeparator, String label) { if (sources.isEmpty) { return needsSeparator; } if (needsSeparator) { buffer.write("; "); } buffer.write(label); String prefix = " "; for (Source source in sources) { buffer.write(prefix); buffer.write(source.fullName); prefix = ", "; } return true; } /// Append the given [sources] to the given [builder], prefixed with the given /// [label] and a separator if [needsSeparator] is `true`. Return `true` if /// future lists of sources will need a separator. bool _appendSources2(StringBuffer buffer, Map<Source, dynamic> sources, bool needsSeparator, String label) { if (sources.isEmpty) { return needsSeparator; } if (needsSeparator) { buffer.write("; "); } buffer.write(label); String prefix = " "; for (Source source in sources.keys.toSet()) { buffer.write(prefix); buffer.write(source.fullName); prefix = ", "; } return true; } } /// A change to the content of a source. class ChangeSet_ContentChange { /// The new contents of the source. final String contents; /// The offset into the current contents. final int offset; /// The number of characters in the original contents that were replaced final int oldLength; /// The number of characters in the replacement text. final int newLength; /// Initialize a newly created change object to represent a change to the /// content of a source. The [contents] is the new contents of the source. The /// [offset] is the offset into the current contents. The [oldLength] is the /// number of characters in the original contents that were replaced. The /// [newLength] is the number of characters in the replacement text. ChangeSet_ContentChange( this.contents, this.offset, this.oldLength, this.newLength); } /// Additional behavior for an analysis context that is required by internal /// users of the context. abstract class InternalAnalysisContext implements AnalysisContext { /// Sets the [TypeProvider] for this context. void set typeProvider(TypeProvider typeProvider); } /// An object that can be used to receive information about errors within the /// analysis engine. Implementations usually write this information to a file, /// but can also record the information for later use (such as during testing) or /// even ignore the information. abstract class Logger { /// A logger that ignores all logging. static final Logger NULL = new NullLogger(); /// Log the given message as an error. The [message] is expected to be an /// explanation of why the error occurred or what it means. The [exception] is /// expected to be the reason for the error. At least one argument must be /// provided. void logError(String message, [CaughtException exception]); /// Log the given informational message. The [message] is expected to be an /// explanation of why the error occurred or what it means. The [exception] is /// expected to be the reason for the error. void logInformation(String message, [CaughtException exception]); } /// An implementation of [Logger] that does nothing. class NullLogger implements Logger { @override void logError(String message, [CaughtException exception]) {} @override void logInformation(String message, [CaughtException exception]) {} } /// Container with global [AnalysisContext] performance statistics. class PerformanceStatistics { /// The [PerformanceTag] for `package:analyzer`. static PerformanceTag analyzer = new PerformanceTag('analyzer'); /// The [PerformanceTag] for time spent in reading files. static PerformanceTag io = analyzer.createChild('io'); /// The [PerformanceTag] for general phases of analysis. static PerformanceTag analysis = analyzer.createChild('analysis'); /// The [PerformanceTag] for time spent in scanning. static PerformanceTag scan = analyzer.createChild('scan'); /// The [PerformanceTag] for time spent in parsing. static PerformanceTag parse = analyzer.createChild('parse'); /// The [PerformanceTag] for time spent in resolving. static PerformanceTag resolve = new PerformanceTag('resolve'); /// The [PerformanceTag] for time spent in error verifier. static PerformanceTag errors = analysis.createChild('errors'); /// The [PerformanceTag] for time spent in hints generator. static PerformanceTag hints = analysis.createChild('hints'); /// The [PerformanceTag] for time spent in linting. static PerformanceTag lints = analysis.createChild('lints'); /// The [PerformanceTag] for time spent computing cycles. static PerformanceTag cycles = new PerformanceTag('cycles'); /// The [PerformanceTag] for time spent in summaries support. static PerformanceTag summary = analyzer.createChild('summary'); }
0