[roll] Update third-party dart packages
Updated:
Change-Id: I42b25c5536628247d74e1f035edde2bf61d80f63
diff --git a/analyzer_plugin/.gitignore b/analyzer_plugin/.gitignore
deleted file mode 100644
index 79f51c3..0000000
--- a/analyzer_plugin/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-.dart_tool
-.packages
-pubspec.lock
diff --git a/analyzer_plugin/BUILD.gn b/analyzer_plugin/BUILD.gn
deleted file mode 100644
index 24bbc39..0000000
--- a/analyzer_plugin/BUILD.gn
+++ /dev/null
@@ -1,23 +0,0 @@
-# This file is generated by importer.py for analyzer_plugin-0.2.1
-
-import("//build/dart/dart_library.gni")
-
-dart_library("analyzer_plugin") {
- package_name = "analyzer_plugin"
-
- # This parameter is left empty as we don't care about analysis or exporting
- # these sources outside of the tree.
- sources = []
-
- disable_analysis = true
-
- deps = [
- "//third_party/dart-pkg/pub/html",
- "//third_party/dart-pkg/pub/meta",
- "//third_party/dart-pkg/pub/pub_semver",
- "//third_party/dart-pkg/pub/path",
- "//third_party/dart-pkg/pub/charcode",
- "//third_party/dart-pkg/pub/analyzer",
- "//third_party/dart-pkg/pub/dart_style",
- ]
-}
diff --git a/analyzer_plugin/CHANGELOG.md b/analyzer_plugin/CHANGELOG.md
deleted file mode 100644
index 6172dd2..0000000
--- a/analyzer_plugin/CHANGELOG.md
+++ /dev/null
@@ -1,30 +0,0 @@
-## 0.2.1
-- Bump maximum supported version of the analyzer to `<0.39.0`.
-- Bug fixes: #37916, #38326.
-
-## 0.2.0
-- Change `DartEditBuilder.writeOverride()` to accept `ExecutableElement`
- instead of `FunctionType`.
-
-## 0.1.0
-
-- Support the latest `pkg:analyzer`.
-- remove the declared type of generated setters
-
-## 0.0.1-alpha.8
-
-- Support the latest `pkg:analyzer`.
-
-## 0.0.1-alpha.7
-
-- Remove CompletionSuggestion.elementUri, replaced with AvailableSuggestionSet.
-- Remove 'importUri' from CompletionSuggestion.
-- Include type parameters into suggested code completions.
-
-## 0.0.1-alpha.4
-
-- Upgrade the Dart SDK version constraint
-
-## 0.0.1
-
-- Initial version
diff --git a/analyzer_plugin/LICENSE b/analyzer_plugin/LICENSE
deleted file mode 100644
index 389ce98..0000000
--- a/analyzer_plugin/LICENSE
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright 2017, the Dart project authors. All rights reserved.
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
- * Neither the name of Google Inc. nor the names of its
- contributors may be used to endorse or promote products derived
- from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/analyzer_plugin/README.md b/analyzer_plugin/README.md
deleted file mode 100644
index 42cf20a..0000000
--- a/analyzer_plugin/README.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# analyzer_plugin
-
-A framework for building plugins for the analysis server.
-
-## Usage
-
-**Note:** The plugin support is not currently available for general use.
-
-Plugins are written in Dart and are run in the same VM as the analysis server.
-The analysis server runs each plugin in a separate isolate and communicates with
-the plugin using a [plugin API][pluginapi]. This API is similar to the API used
-by the analysis server to communicate with clients.
-
-Plugins are automatically discovered and run by the analysis server.
-
-This package contains support code to make it easier to write a plugin. There is
-a [tutorial][tutorial] describing how to use the support in this package.
-
-## Support
-
-Post issues and feature requests on the [issue tracker][issues].
-
-Questions and discussions are welcome at the
-[Dart Analyzer Discussion Group][list].
-
-## License
-
-See the [LICENSE] file.
-
-[issues]: https://github.com/dart-lang/sdk/issues
-[LICENSE]: https://github.com/dart-lang/sdk/blob/master/pkg/analyzer/LICENSE
-[list]: https://groups.google.com/a/dartlang.org/forum/#!forum/analyzer-discuss
-[pluginapi]: https://htmlpreview.github.io/?https://github.com/dart-lang/sdk/blob/master/pkg/analyzer_plugin/doc/api.html
-[tutorial]: doc/tutorial/tutorial.md
diff --git a/analyzer_plugin/analysis_options.yaml b/analyzer_plugin/analysis_options.yaml
deleted file mode 100644
index 6517645..0000000
--- a/analyzer_plugin/analysis_options.yaml
+++ /dev/null
@@ -1,13 +0,0 @@
-analyzer:
- strong-mode:
- implicit-casts: false
-linter:
- rules:
- - annotate_overrides
- - avoid_return_types_on_setters
- - empty_constructor_bodies
- - empty_statements
- #- prefer_single_quotes
- - unawaited_futures
- - unnecessary_brace_in_string_interps
- - valid_regexps
diff --git a/analyzer_plugin/doc/tutorial/assists.md b/analyzer_plugin/doc/tutorial/assists.md
deleted file mode 100644
index ade51d6..0000000
--- a/analyzer_plugin/doc/tutorial/assists.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# Providing Quick Assists
-
-A quick assist is used by clients to provide a set of possible changes to code
-that are based on the structure of the code. Quick assists are intended to help
-users safely make local changes to code when those changes do not require any
-user interaction. (Modifications that require interaction with users or that
-touch multiple files are usually implemented as refactorings.)
-
-For example, if the user has a function whose body consists of a single return
-statement in a block, server will provide an assist to convert the function body
-from a block to an expression (`=>`).
-
-Assists have a priority associated with them. The priority allows the client to
-display the assists that are most likely to be of use closer to the top of the
-list when there are multiple assists available.
-
-## Implementation details
-
-When appropriate, the analysis server will send your plugin an `edit.getAssists`
-request. The request includes the `file`, `offset` and `length` associated with
-the selected region of code.
-
-When an `edit.getAssists` request is received, the method `handleEditGetAssists`
-will be invoked. This method is responsible for returning a response that
-contains the available assists.
-
-The easiest way to implement this method is by adding the classes `AssistsMixin`
-and `DartAssistsMixin` (from `package:analyzer_plugin/plugin/assist_mixin.dart`)
-to the list of mixins for your subclass of `ServerPlugin`. This will leave you
-with one abstract method that you need to implement: `getAssistContributors`.
-That method is responsible for returning a list of `AssistContributor`s. It is
-the assist contributors that produce the actual assists. (Most plugins will only
-need a single assist contributor.)
-
-To write an assist contributor, create a class that implements
-`AssistContributor`. The interface defines a single method named
-`computeAssists`. The method has two arguments: an `AssistRequest` that
-describes the location at which assists were requested and an `AssistCollector`
-through which assists are to be added.
-
-If you mix in the class `DartAssistsMixin`, then the request will be an instance
-of `DartAssistRequest`, which also has analysis results.
-
-The class `AssistContributorMixin` defines a support method that makes it easier
-to implement `computeAssists`.
-
-## Example
-
-Start by creating a class that implements `AssistContributor` and that mixes in
-the class `AssistContributorMixin`, then implement the method `computeAssists`.
-This method is typically implemented as a sequence of invocations of methods
-that check to see whether a given assist is appropriate in the context of the
-request
-
-To learn about the support available for creating the edits, see
-[Creating Edits][creatingEdits].
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyAssistContributor extends Object
- with AssistContributorMixin
- implements AssistContributor {
- static AssistKind wrapInIf =
- new AssistKind('wrapInIf', 100, "Wrap in an 'if' statement");
-
- DartAssistRequest request;
-
- AssistCollector collector;
-
- AnalysisSession get session => request.result.session;
-
- @override
- void computeAssists(DartAssistRequest request, AssistCollector collector) {
- this.request = request;
- this.collector = collector;
- _wrapInIf();
- _wrapInWhile();
- // ...
- }
-
- void _wrapInIf() {
- ChangeBuilder builder = new DartChangeBuilder(session);
- // TODO Build the edit to wrap the selection in a 'if' statement.
- addAssist(wrapInIf, builder);
- }
-
- void _wrapInWhile() {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with AssistsMixin, DartAssistsMixin {
- // ...
-
- @override
- List<AssistContributor> getAssistContributors(AnalysisDriver driver) {
- return <AssistContributor>[new MyAssistContributor()];
- }
-}
-```
-
-[creatingEdits]: creating_edits.md
diff --git a/analyzer_plugin/doc/tutorial/completion.md b/analyzer_plugin/doc/tutorial/completion.md
deleted file mode 100644
index 18b1698..0000000
--- a/analyzer_plugin/doc/tutorial/completion.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# Providing Code Completions
-
-A code completion is used by clients to provide a set of possible completions to
-partially entered code. Completions are intended to address two use cases: to
-help users enter code with less effort and to help users discover the behavior
-of an object.
-
-For example, if the user has typed `o.toSt` and then requested completions, one
-suggestion might be `toString`.
-
-That said, the completion suggestions that your plugin returns should include
-all of the options that would be valid if the partial identifier did not exist.
-The reason is that most clients are implemented such that they send a single
-request for completions when the dialog with the user begins and cannot send any
-subsequent requests. If the user presses the backspace key during the dialog the
-client needs to have already received the expanded list of options that now
-match the prefix (or all options if the prefix has completely been deleted).
-Clients will filter the list of suggestions displayed as appropriate.
-
-Hence, in the example above, plugins should return suggestions as if the user
-had requested completions after typing `o.`;
-
-## Implementation details
-
-When appropriate, the analysis server will send your plugin a
-`completion.getSuggestions` request. The request includes the `file` and
-`offset` at which completions are being requested.
-
-When a `completion.getSuggestions` request is received, the method
-`handleCompletionGetSuggestions` will be invoked. This method is responsible for
-returning a response that contains the available suggestions.
-
-The easiest way to implement this method is by adding the classes
-`CompletionMixin` and `DartCompletionMixin` (from
-`package:analyzer_plugin/plugin/completion_mixin.dart`) to the list of mixins
-for your subclass of `ServerPlugin`. This will leave you with one abstract
-method that you need to implement: `getCompletionContributors`. That method is
-responsible for returning a list of `CompletionContributor`s. It is the
-completion contributors that produce the actual completion suggestions. (Most
-plugins will only need a single completion contributor.)
-
-To write a completion contributor, create a class that implements
-`CompletionContributor`. The interface defines a single method named
-`computeSuggestions`. The method has two arguments: a `CompletionRequest` that
-describes the where completions are being requested and a `CompletionCollector`
-through which suggestions are to be added.
-
-If you mix in the class `DartCompletionMixin`, then the request will be an
-instance of `DartCompletionRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `CompletionContributor`, then
-implement the method `computeSuggestions`. Your contributor should invoke the
-method `checkAborted`, defined on the `CompletionRequest` object, before
-starting any slow work. This allows the computation of completion suggestions
-to be preempted if the client no longer needs the results.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyCompletionContributor implements CompletionContributor {
- @override
- Future<void> computeSuggestions(DartCompletionRequest request,
- CompletionCollector collector) async {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with CompletionMixin, DartCompletionMixin {
- // ...
-
- @override
- List<CompletionContributor> getCompletionContributors(
- AnalysisDriverGeneric driver) {
- return <CompletionContributor>[new MyCompletionContributor()];
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/creating_edits.md b/analyzer_plugin/doc/tutorial/creating_edits.md
deleted file mode 100644
index 223786e..0000000
--- a/analyzer_plugin/doc/tutorial/creating_edits.md
+++ /dev/null
@@ -1,205 +0,0 @@
-# Creating `SourceChange`s
-
-Several of the response objects take a `SourceChange` (specifically, assists,
-fixes, and refactorings). Because `SourceChange` is a structured object that
-can be difficult to create correctly, this package provides a set of utility
-classes to help you build those structures.
-
-Using these classes will not only simplify the work you need to do to implement
-your plugin, but will ensure a consistent user experience in terms of the code
-being generated by the analysis server.
-
-## `DartChangeBuilder`
-
-The class used to create a `SourceChange` is `DartChangeBuilder`, defined in
-`package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart`.
-You can create a `DartChangeBuilder` with the following:
-
-```dart
-DartChangeBuilder changeBuilder = new DartChangeBuilder(session);
-```
-
-The constructor required an instance of the class `AnalysisSession`. How you get
-the correct instance depends on where the constructor is being invoked.
-
-A `SourceChange` can contain edits that are to be applied to multiple files. The
-edits for a single file are created by invoking the method `addFileEdit`, as
-illustrated by the following:
-
-```dart
-changeBuilder.addFileEdit(path, (DartFileEditBuilder fileEditBuilder) {
- // ...
-}
-```
-
-where the `path` is the path to the file to which the edits will be applied.
-
-## `DartFileEditBuilder`
-
-The class `DartFileEditBuilder` defines methods for creating three kinds of
-edits: deletions, insertions, and replacements.
-
-For deletions, you pass in the range of code to be deleted as a `SourceRange`.
-In addition to the constructor for `SourceRange`, there are a set of functions
-defined in `package:analyzer_plugin/utilities/range_factory.dart` that can be
-used to build a `SourceRange` from tokens, AST nodes, and elements.
-
-For example, if you need to remove the text in a given `range`, you could write:
-
-```dart
-fileEditBuilder.addDeletion(range);
-```
-
-In the case of insertions and replacements, there are two styles of method. The
-first takes the string that is to be inserted; the second takes a closure in
-which the string can be composed. Insertions take the offset of the insertion,
-while replacements take a `SourceRange` indicating the location of the text to
-be replaced.
-
-For example, if you need to insert `text` at offset `offset`, you could write
-
-```dart
-fileEditBuilder.addSimpleInsertion(offset, text);
-```
-
-The forms that take a closure are useful primarily because they give you access
-to a `DartEditBuilder`, which is described below.
-
-For example, to replace a given `range` of text with some yet to be constructed
-text, you could write:
-
-```dart
-fileEditBuilder.addReplacement(range, (DartEditBuilder editBuilder) {
- // ...
-}
-```
-
-In addition, `DartFileEditBuilder` has some methods that allow you to build some
-common sets of edits more easily. For example, `importLibraries` allows you to
-pass in the `Source`s for one or more libraries and will create one or more
-edits to insert `import` directives in the correct locations.
-
-## `DartEditBuilder`
-
-A `DartEditBuilder` allows you to compose source code by writing the individual
-pieces, much like a `StringSink`. It also provides additional methods to compose
-more complex code. For example, if you need to write a type annotation, the
-method `writeType` will handle writing all of the type arguments and will add
-import directives as needed. There are also methods to write class declarations
-and to write various members within a class.
-
-For example, if you're implementing a quick assist to insert a template for a
-class declaration, the code to create the insertion edit could look like the
-following:
-
-```dart
-String className = 'NewClass';
-fileEditBuilder.addReplacement(range, (DartEditBuilder editBuilder) {
- editBuilder.writeClassDeclaration(className, memberWriter: () {
- editBuilder.writeConstructorDeclaration(className);
- editBuilder.writeOverride(
- typeProvider.objectType.getMethod('toString').type);
- });
-});
-```
-
-## Linked Edits
-
-Many clients support a style of editing in which multiple regions of text can be
-edited simultaneously. Server refers to these as "linked" edit groups. Many
-clients also support having multiple groups associated with the edits in a file
-and allow users to tab from one group to the next. Essentially, these edit
-groups mark placeholders for text that users might want to change after the
-edits are applied.
-
-The class `DartEditBuilder` provides support for creating linked edits through
-the method `addLinkedEdit`. As with the insertion and replacement methods
-provided by `DartFileEditBuilder` (see above), there are both a "simple" and a
-closure-based version of this method.
-
-For example, if you're implementing a quick assist to insert a for loop, you
-should add the places where the loop variable name appears to a linked edit
-group. You should also add the name of the list being iterated over to a
-different group. The code to create the insertion edit could look like the
-following:
-
-```dart
-fileEditBuilder.addReplacement(range, (DartEditBuilder editBuilder) {
- String listName = 'list';
- String listGroup = 'list_variable';
- String variableName = 'i';
- String variableGroup = 'loop_variable';
-
- editBuilder.write('for (int ');
- editBuilder.addSimpleLinkedEdit(variableGroup, variableName);
- editBuilder.write(' = 0; ');
- editBuilder.addSimpleLinkedEdit(variableGroup, variableName);
- editBuilder.write(' < ');
- editBuilder.addSimpleLinkedEdit(listGroup, listName);
- editBuilder.write('.length; ');
- editBuilder.addSimpleLinkedEdit(variableGroup, variableName);
- editBuilder.write('++) {}');
-}
-```
-
-One of the advantages of the closure-based form of `addLinkedEdit` is that you
-can specify suggested replacements for the values of each group. You do that by
-invoking either `addSuggestion` or `addSuggestions`. In the example above, you
-might choose to suggest `j` and `k` as other likely loop variable names. You
-could do that by replacing one of the places where the variable name is written
-with code like the following:
-
-```dart
-editBuilder.addLinkedEdit(variableGroup, (LinkedEditBuilder linkedEditBuilder) {
- linkedEditBuilder.write(variableName);
- linkedEditBuilder.addSuggestions(['j', 'k']);
-});
-```
-
-A more interesting use of this feature would be to find the names of all of the
-list-valued variables within scope and suggest those names as alternatives for
-the name of the list.
-
-That said, most of the methods on `DartEditBuilder` that help you generate Dart
-code take one or more optional arguments that allow you to create linked edit
-groups for appropriate pieces of text and even to specify the suggestions for
-those groups.
-
-## Post-edit Selection
-
-A `SourceChange` also allows you to specify where the cursor should be placed
-after the edits are applied. There are two ways to specify this.
-
-The first is by invoking the method `setSelection` on a `DartChangeBuilder`.
-The method takes a `Position`, which encapsulates an offset in a particular
-file. This can be difficult to get right because the offset is required to be
-the offset *after* all of the edits for that file have been applied.
-
-The second, and easier, way is by invoking the method `selectHere` on a
-`DartEditBuilder`. This method does not require any arguments; it computes the
-offset for the position based on the edits that have previously been created.
-It does require that all of the edits that apply to text before the desired
-cursor location have been created before the method is invoked.
-
-For example, if you're implementing a quick assist to insert a to-do comment at
-the cursor location, the code to create the insertion edit could look like the
-following:
-
-```dart
-fileEditBuilder.addReplacement(range, (DartEditBuilder editBuilder) {
- editBuilder.write('/* TODO ');
- editBuilder.selectHere();
- editBuilder.write(' */');
-}
-```
-
-This will cause the cursor to be placed between the two spaces inside the
-comment.
-
-## Non-Dart Files
-
-All of the classes above are subclasses of more general classes (just drop the
-prefix "Dart" from the subclass names). If you are editing files that do not
-contain Dart code, the more general classes might be a better choice. These
-classes are defined in
-`package:analyzer_plugin/utilities/change_builder/change_builder_core.dart`.
diff --git a/analyzer_plugin/doc/tutorial/debugging.md b/analyzer_plugin/doc/tutorial/debugging.md
deleted file mode 100644
index d5905e5..0000000
--- a/analyzer_plugin/doc/tutorial/debugging.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Debugging Plugins
-
-Unfortunately, debugging a plugin is not well supported at this point. The
-server is typically run as a sub-process by a client. Some clients provide a way
-to add command-line arguments when invoking the server, others don't. To make
-matters worse, each plugin is run in a separate isolate.
-
-Nevertheless, there are a few ways to get some information about what's going on
-in a plugin. Those are outlined below. If you know of other useful techniques,
-or if you have a request for better support, please let us know.
-
-## Check the Status Pages
-
-The analysis server has the ability to host a set of web pages that describe the
-current state of the server. One of the pieces of information available through
-those pages is a list of the plugins that are currently being run.
-
-The server does not host these pages unless it has been requested to do so. You
-can request it by passing a command-line argument to the server when it is being
-started. The argument should be similar to `--port=10000` (any valid port number
-will work). You can then point your browser to `http://localhost:10000/status`.
-
-If you're using IntelliJ as your client, there is a gear icon on the Dart
-Analysis view's header that can be used to open the status pages.
-
-The plugin information can be displayed by clicking on "Plugins" in the list on
-the left.
-
-## Check the Instrumentation Log
-
-The analysis server has the ability to log debugging data to a file. For
-historic reasons this file is referred to as the _instrumentation log_. The data
-primarily consists of a record of the communications between the server and both
-the client that started it and any plugins that the server is running.
-
-The server does not write to this file unless it has been requested to do so.
-You can request it by passing a command-line argument to the server when it is
-being started. The argument should be similar to
-`--instrumentation-log-file=/path/to/file.txt`.
-
-## Println Debugging
-
-You cannot use the `print` function to get debugging information because server
-is run by the client in a child process, and hence doesn't have the ability to
-write to the console.
-
-The closest approximation is for the plugin to send notifications to the server
-that will be written to the instrumentation log file. Currently, the best choice
-for this is the `plugin.error` notification. Just be sure that `isFatal` has a
-value of `false`.
-
-## Using Observatory
-
-If the client you're using allows you to pass command-line flags to the VM, then
-you can also run the analysis server under the Observatory. Pass in both
-`--observe` and `--pause-isolates-on-start`, then point your browser to
-`http://localhost:8181`. To learn more, see the
-[observatory][observatory] documentation.
-
-If you're using IntelliJ as your client, open the "Registry..." dialog and edit
-the entry named "dart.server.vm.options".
-
-[observatory]: https://dart-lang.github.io/observatory/
\ No newline at end of file
diff --git a/analyzer_plugin/doc/tutorial/fixes.md b/analyzer_plugin/doc/tutorial/fixes.md
deleted file mode 100644
index c81548c..0000000
--- a/analyzer_plugin/doc/tutorial/fixes.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Providing Quick Fixes
-
-A quick fix is used by clients to provide a set of possible changes to code that
-are based on diagnostics reported against the code. Quick fixes are intended to
-help users resolve the issue being reported.
-
-If your plugin generates any diagnostics then you should consider providing
-support for automatically fixing those diagnostics. There is often more than one
-potential way of fixing a given problem, so it is possible for your plugin to
-provide multiple fixes for a single problem.
-
-For example, if an undefined identifier is used in the code, you might return
-a fix to create an appropriate definition for the identifier. If there is a
-similar identifier that is already defined, you might also return a second fix
-to replace the undefined identifier with the defined identifier.
-
-The latter example illustrates that fixes can be conditionally returned. You
-will produce a better UX if only those fixes that actually make sense in the
-given context are returned. If a lot of work is required to determine which
-fixes make sense, it is possible to improve performance by generating different
-diagnostics for the same issue, depending on the context in which the issue
-occurs.
-
-In addition, fixes have a priority associated with them. The priority allows the
-client to display the fixes that are most likely to be of use closer to the top
-of the list when there are multiple fixes available.
-
-## Implementation details
-
-When appropriate, the analysis server will send your plugin an `edit.getFixes`
-request. The request includes the `file` and `offset` associated with the
-diagnostics for which fixes should be generated. Fixes are typically produced
-for all of the diagnostics on a given line of code. Your plugin should only
-return fixes associated with the errors that it produced earlier.
-
-When an `edit.getFixes` request is received, the method `handleEditGetFixes`
-will be invoked. This method is responsible for returning a response that
-contains the available fixes.
-
-The easiest way to implement this method is by adding the classes `FixesMixin`
-and `DartFixesMixin` (from `package:analyzer_plugin/plugin/fix_mixin.dart`) to
-the list of mixins for your subclass of `ServerPlugin`. This will leave you with
-one abstract method that you need to implement: `getFixContributors`. That
-method is responsible for returning a list of `FixContributor`s. It is the fix
-contributors that produce the actual fixes. (Most plugins will only need a
-single fix contributor.)
-
-To write a fix contributor, create a class that implements `FixContributor`. The
-interface defines a single method named `computeFixes`. The method has two
-arguments: a `FixesRequest` that describes the errors that should be fixed and a
-`FixCollector` through which fixes are to be added.
-
-If you mix in the class `DartFixesMixin`, then the list of errors available
-through the request object will only include the errors for which fixes should
-be returned and the request will be an instance of `DartFixesRequest`, which
-also has analysis results.
-
-The class `FixContributorMixin` defines a simple implementation of this method
-that captures the two arguments in fields, iterates through the errors, and
-invokes a method named `computeFixesForError` for each of the errors for which
-fixes are to be computed.
-
-## Example
-
-Start by creating a class that implements `FixContributor` and that mixes in the
-class `FixContributorMixin`, then implement the method `computeFixesForError`.
-This method is typically implemented by a series of `if` statements that test
-the error code and invoke individual methods that compute the actual fixes to be
-proposed. (In addition to keeping the method `computeFixesForError` shorter,
-this also allows some fixes to be used for multiple error codes.)
-
-To learn about the support available for creating the edits, see
-[Creating Edits][creatingEdits].
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyFixContributor extends Object
- with FixContributorMixin
- implements FixContributor {
- static FixKind defineComponent =
- new FixKind('defineComponent', 100, "Define a component named {0}");
-
- AnalysisSession get session => request.result.session;
-
- @override
- void computeFixesForError(AnalysisError error) {
- ErrorCode code = error.errorCode;
- if (code == MyErrorCode.undefinedComponent) {
- _defineComponent(error);
- _useExistingComponent(error);
- }
- }
-
- void _defineComponent(AnalysisError error) {
- // TODO Get the name from the source code.
- String componentName = null;
- ChangeBuilder builder = new DartChangeBuilder(session);
- // TODO Build the edit to insert the definition of the component.
- addFix(error, defineComponent, builder, args: [componentName]);
- }
-
- void _useExistingComponent(AnalysisError error) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with FixesMixin, DartFixesMixin {
- // ...
-
- @override
- List<FixContributor> getFixContributors(
- AnalysisDriverGeneric driver) {
- return <FixContributor>[new MyFixContributor()];
- }
-}
-```
-
-[creatingEdits]: creating_edits.md
diff --git a/analyzer_plugin/doc/tutorial/folding.md b/analyzer_plugin/doc/tutorial/folding.md
deleted file mode 100644
index edb479e..0000000
--- a/analyzer_plugin/doc/tutorial/folding.md
+++ /dev/null
@@ -1,79 +0,0 @@
-# Providing Folding Information
-
-Folding information is used by clients to allow users to collapse portions of
-the code that are not interesting for their current task.
-
-## Implementation details
-
-Folding information is available through a subscription. If the server has
-subscribed for folding information in some set of files, then the plugin
-should send the information in an `analysis.folding` notification whenever
-the information needs to be updated.
-
-When a notification needs to be sent, the method `sendFoldingNotification`
-will be invoked. This method is responsible for sending the notification.
-
-The easiest way to add support for this notification is by adding the classes
-`FoldingMixin` and `DartFoldingMixin` (from
-`package:analyzer_plugin/plugin/folding_mixin.dart`) to the list of mixins
-for your subclass of `ServerPlugin`. This will leave you with one abstract
-method that you need to implement: `getFoldingContributors`. That method is
-responsible for returning a list of `FoldingContributor`s. It is the folding
-contributors that produce the actual folding regions. (Most plugins will only
-need a single folding contributor.)
-
-To write a folding contributor, create a class that implements
-`FoldingContributor`. The interface defines a single method named
-`computeFolding`. The method has two arguments: an `FoldingRequest` that
-describes the file for which folding information is being requested and an
-`FoldingCollector` through which folding regions are to be added.
-
-If you mix in the class `DartFoldingMixin`, then the request will be an
-instance of `DartFoldingRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `FoldingContributor`, then implement
-the method `computeFolding`. This method is typically implemented by creating a
-visitor (such as an AstVisitor) that can visit the results of the analysis (such
-as a CompilationUnit) and extract the folding regions from the analysis result.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyFoldingContributor implements FoldingContributor {
- @override
- void computeFolding(
- FoldingRequest request, FoldingCollector collector) {
- if (request is DartFoldingRequest) {
- FoldingVisitor visitor = new FoldingVisitor(collector);
- request.result.unit.accept(visitor);
- }
- }
-}
-
-class FoldingVisitor extends RecursiveAstVisitor {
- final FoldingCollector collector;
-
- FoldingVisitor(this.collector);
-
- @override
- void visitClassDeclaration(ClassDeclaration node) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with FoldingMixin, DartFoldingMixin {
- // ...
-
- @override
- List<FoldingContributor> getFoldingContributors(String path) {
- return <FoldingContributor>[new MyFoldingContributor()];
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/getting_started.md b/analyzer_plugin/doc/tutorial/getting_started.md
deleted file mode 100644
index 5352c9f..0000000
--- a/analyzer_plugin/doc/tutorial/getting_started.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Getting Started
-
-## Creating a Minimal Plugin
-
-To implement a plugin, start by creating a simple package and create a class
-that is a subclass of `ServerPlugin`. This class will need to implement a
-constructor, three getters, and two methods. The getters provide some basic
-information about your plugin: the name and version, both of which are included
-in error messages if there is a problem encountered, and a list of glob patterns
-for the files that the plugin cares about. The methods ...
-
-Here's an example of what a minimal plugin might look like.
-
-```dart
-class MyPlugin extends ServerPlugin {
- MyPlugin(ResourceProvider provider) : super(provider);
-
- @override
- List<String> get fileGlobsToAnalyze => <String>['**/*.dart'];
-
- @override
- String get name => 'My fantastic plugin';
-
- @override
- String get version => '1.0.0';
-
- @override
- AnalysisDriverGeneric createAnalysisDriver(ContextRoot contextRoot) {
- // TODO: implement createAnalysisDriver
- return null;
- }
-
- @override
- void sendNotificationsForSubscriptions(
- Map<String, List<AnalysisService>> subscriptions) {
- // TODO: implement sendNotificationsForSubscriptions
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/highlights.md b/analyzer_plugin/doc/tutorial/highlights.md
deleted file mode 100644
index 23c6b7f..0000000
--- a/analyzer_plugin/doc/tutorial/highlights.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# Providing Highlighting Information
-
-Highlighting information is used by clients to help users identify different
-syntactic and semantic regions of their code.
-
-Syntactic highlighting is highlighting that is based completely on the syntax of
-the code. For example, editors will often provide unique colors for comments,
-string literals, and numeric literals.
-
-Semantic highlighting is highlighting that is based on semantic information. For
-example, an editor could highlight references to fields differently than
-references to local variables. Editors could also highlight references to
-deprecated elements differently.
-
-## Implementation details
-
-Highlighting information is available through a subscription. If the server has
-subscribed for highlighting information in some set of files, then the plugin
-should send the information in an `analysis.highlights` notification whenever
-the information needs to be updated.
-
-When a notification needs to be sent, the method `sendHighlightsNotification`
-will be invoked. This method is responsible for sending the notification.
-
-The easiest way to add support for this notification is by adding the classes
-`HighlightsMixin` and `DartHighlightsMixin` (from
-`package:analyzer_plugin/plugin/highlights_mixin.dart`) to the list of mixins
-for your subclass of `ServerPlugin`. This will leave you with one abstract
-method that you need to implement: `getHighlightsContributors`. That method is
-responsible for returning a list of `HighlightsContributor`s. It is the
-highlights contributors that produce the actual highlighting information. (Most
-plugins will only need a single highlights contributor.)
-
-To write a highlights contributor, create a class that implements
-`HighlightsContributor`. The interface defines a single method named
-`computeHighlights`. The method has two arguments: an `HighlightsRequest` that
-describes the file for which highlighting information is being requested and an
-`HighlightsCollector` through which highlighting information is to be added.
-
-If you mix in the class `DartHighlightsMixin`, then the request will be an
-instance of `DartHighlightsRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `HighlightsContributor`, then
-implement the method `computeHighlights`. This method is typically implemented
-by creating a visitor (such as an AstVisitor) that can visit the results of the
-analysis (such as a CompilationUnit) and extract the highlighting information
-from the analysis result.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyHighlightsContributor implements HighlightsContributor {
- @override
- void computeHighlights(
- HighlightsRequest request, HighlightsCollector collector) {
- if (request is DartHighlightsRequest) {
- HighlightsVisitor visitor = new HighlightsVisitor(collector);
- request.result.unit.accept(visitor);
- }
- }
-}
-
-class HighlightsVisitor extends RecursiveAstVisitor {
- final HighlightsCollector collector;
-
- HighlightsVisitor(this.collector);
-
- @override
- void visitSimpleIdentifier(SimpleIdentifier node) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with HighlightsMixin, DartHighlightsMixin {
- // ...
-
- @override
- List<HighlightsContributor> getHighlightsContributors(String path) {
- return <HighlightsContributor>[new MyHighlightsContributor()];
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/introduction.md b/analyzer_plugin/doc/tutorial/introduction.md
deleted file mode 100644
index d2da2ff..0000000
--- a/analyzer_plugin/doc/tutorial/introduction.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# Introduction
-
-The purpose of this page is to give you an overview of what an analyzer plugin
-is and what it can do.
-
-## What is a plugin?
-
-An analyzer plugin is a piece of code that communicates with the analysis server
-to provide additional analysis support. The additional support is often specific
-to a package or set of packages. For example, there is a plugin that provides
-analysis specific to the Angular framework. Plugins are not required to be
-specific to a package, but if the additional analysis is general enough, we
-would urge you to consider contributing it back to the Dart project so that
-everyone can more easily benefit from your work.
-
-Plugins are written in Dart. They are executed by the analysis server by running
-them in the same VM as the analysis server, but each plugin is run in a separate
-isolate. The analysis server communicates with the plugins using a wire protocol
-that is specified in the [plugin API][pluginapi] document. This API is similar
-to the API used by the analysis server to communicate with clients.
-
-The API consists of three kinds of communication. When the analysis server needs
-information from the plugin, or needs to pass information to the plugin, it
-sends a *request*. The plugin is required to answer every request with a
-*response*. If the request was a request for information, then the response will
-contain the requested information. Otherwise, the response is merely an
-acknowledgement that the request was received. In addition, the plugin can send
-a *notification* to the server to provide information to the server.
-
-## What can plugins do?
-
-The scope of what a plugin can do is defined by the [plugin API][pluginapi], but
-it's useful to start with a high level overview.
-
-### Lifecycle management
-
-The API includes support for managing the lifecycle of a plugin. There is no
-guarantee about when plugins will be started or stopped relative to either the
-server or to each other.
-
-When a plugin is first started, the analysis server will send a
-`plugin.versionCheck` request to the plugin to verify that the plugin is using
-the same version of the API as the server and therefore can communicate with the
-server. This exchange also serves to communicate some other information between
-the two participants.
-
-When the server is asked to shut down, it will send a `plugin.shutdown` request
-to the plugin to shut it down. This gives the plugin an opportunity to release
-system resources or perform any other necessary actions. If a plugin encounters
-an error that causes it to need to shut down, it should send a `plugin.error`
-notification to the server to indicate that it is doing so.
-
-### Managing analysis
-
-The API includes support for managing which files are analyzed. There is no
-requirement for when a plugin should perform the analysis, but to optimize the
-user experience plugins should provide information to the server as quickly as
-possible.
-
-The analysis server sends an `analysis.setContextRoots` request to plugins to
-tell them which files to analyze. Each `ContextRoot` indicates the root
-directory containing the files to be analyzed (included) and any files and
-directories within the root that should *not* be analyzed (excluded). Plugins
-can read and use excluded files in the process of analyzing included files, but
-should not report results for excluded files.
-
-In order to improve the user experience, the analysis server will send an
-`analysis.setPriorityFiles` request to specify which files should take priority
-over other files. These are typically the files that are open and visible in the
-client.
-
-The analysis server will send an `analysis.handleWatchEvents` request to the
-plugin when one or more files (within a context root) have been modified. The
-plugin is expected to re-analyze those files in order to update the results for
-those files.
-
-The analysis server will send an `analysis.updateContent` request when the user
-has edited a file but the edited content has not yet been written to disk. This
-allows the plugin to provide analysis results as the user is typing.
-
-### Requesting Analysis Results
-
-In order to accommodate the workflow of clients, there are two ways for the
-server to request analysis results from a plugin.
-
-First, the server can send a request to request specific results for a specific
-file. This is typically used for client-side functionality that the user has to
-explicitly request and that clients will not retain long term. For example,
-there is a request to get code completion suggestions. These requests are
-discussed below.
-
-For functionality that is always available, or for results that can change
-without the client being aware that new data should be requested, there is a
-subscription model. The server will send an `analysis.setSubscriptions` request
-to the plugin. This request tells the plugin which results should be sent to the
-server when the results become available. The plugin does not send any results
-in the response to the request, but instead is expected to send a notification
-to the server when the results have been computed. The notifications that can be
-requested are also discussed below.
-
-If the server has explicitly requested results, either by a request or by a
-subscription, the plugin should provide those results even if the file is an
-excluded file. This exception to the general rule does *not* apply to the
-implicit subscription for diagnostics.
-
-Plugins should *not* send analysis results that duplicate the information
-computed by the analysis server itself. The expectation is for plugins to
-extend this information, not replicate it.
-
-### Diagnostics
-
-Plugins can generate diagnostics to make users aware of problems in the code
-that they have written. Diagnostics are typically displayed in the editor region
-and might also be displayed in a separate diagnostics view or as decorations on
-a directory structure view.
-
-Plugins are expected to send any diagnostics that they generate for any of the
-analyzed files (files that are included in a context root and not excluded).
-Essentially, there is an implicit subscription for errors for all (non-excluded)
-files. The plugin should send the errors in an `analysis.errors` notification.
-
-### Semantic highlighting
-
-Highlight information is used to color the content of the editor view.
-
-If the server has subscribed for highlighting information in some set of files,
-then the plugin should send the information in an `analysis.highlights`
-notification whenever the information needs to be updated.
-
-### Navigation
-
-Navigation information is used by clients to allow users to navigate to the
-location at which an identifier is defined.
-
-Navigation information can be requested both by an `analysis.getNavigation`
-request and by a subscription. If the server has subscribed for navigation
-information in some set of files, the the plugin should send the information in
-an `analysis.navigation` notification whenever the information needs to be
-updated.
-
-There is a tutorial explaining how to implement [navigation][navigation].
-
-### Mark occurrences
-
-Occurrences information is used by clients to highlight (or mark) all uses
-within a given file of a single identifier when the user selects one use of that
-identifier.
-
-If the server has subscribed for occurrences information in some set of files,
-then the plugin should send the information in an `analysis.occurrences`
-notification whenever the information needs to be updated.
-
-### Outline
-
-Outline information is typically used by clients to provide a tree indicating
-the nesting structure of declarations within the code.
-
-If the server has subscribed for outline information in some set of files, then
-the plugin should send the information in an `analysis.outline` notification
-whenever the information needs to be updated.
-
-### Folding
-
-Folding information is used to allow users to collapse regions of text.
-
-If the server has subscribed for folding information in some set of files, then
-the plugin should send the information in an `analysis.folding` notification
-whenever the information needs to be updated.
-
-### Code completion
-
-Code completion suggestions are used to provide possible completions at some
-point in the text.
-
-When the client request completion suggestions, the server will send a
-`completion.getSuggestions` request. The plugin should only send suggestions
-that would not also be returned by the server.
-
-There is a tutorial explaining how to implement [code completion][completion].
-
-### Fixes and assists
-
-Fixes and assists are a set of edits that users can choose to have applied to
-the code. They differ from a refactoring in that they cannot request additional
-information from the user. For example, a rename refactoring needs to know the
-new name, which requires prompting the user, and hence could not be implemented
-as either a fix or an assist.
-
-Fixes are associated with specific diagnostics, and hence should only be
-generated if the diagnostics with which they are associated have been generated.
-For example, if a diagnostic has been produced to indicate that a required
-semicolon is missing, a fix might be generated to insert a semicolon.
-
-The analysis server will request fixes by sending an `edit.getFixes` request.
-
-Plugins should provide fixes for as many of the diagnostics they generate as
-possible, but only when those fixes provide value to the user. (For example, a
-fix to insert a semicolon is arguably harder to use than simply typing the
-semicolon would be, and therefore is of questionable value.)
-
-There is a tutorial explaining how to implement [fixes][fixes].
-
-Assists are generally context-specific and hence should only be generated if the
-cursor is in the right context. For example, if there is an assist to convert an
-expression-style function body (one introduced by `=>`) into a block-style
-function body, it should only be generated if the cursor is within an
-expression-style function body.
-
-The analysis server will request assists by sending an `edit.getAssists`
-request.
-
-There is a tutorial explaining how to implement [assists][assists].
-
-[assists]: assists.md
-[completion]: completion.md
-[fixes]: fixes.md
-[navigation]: navigation.md
-[pluginapi]: https://htmlpreview.github.io/?https://github.com/dart-lang/sdk/blob/master/pkg/analyzer_plugin/doc/api.html
diff --git a/analyzer_plugin/doc/tutorial/kythe.md b/analyzer_plugin/doc/tutorial/kythe.md
deleted file mode 100644
index 58e1706..0000000
--- a/analyzer_plugin/doc/tutorial/kythe.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# Providing Kythe Data
-
-**Note:** Kythe support is experimental and might be removed or changed without
-notice.
-
-[Kythe][kythe] is, in their own words, "A pluggable, (mostly) language-agnostic
-ecosystem for building tools that work with code." The analysis server can be
-used to produce the data that should be sent to Kythe. In other words, the
-analysis server is (almost) a Kythe indexer. (The data needs to be converted
-from a Json representation to a protobuf format before being sent to Kythe.)
-
-## Implementation details
-
-When appropriate, the analysis server will send your plugin a
-`kythe.getKytheEntries` request. The request includes the `file` for which data
-should be generated. The data consists of a list of `KytheEntry`s.
-
-When a `kythe.getKytheEntries` request is received, the method
-`handleKytheGetKytheEntries` will be invoked. This method is responsible for
-returning a response that contains the entries to be sent to Kythe.
-
-The easiest way to implement this method is by adding the classes `EntryMixin`
-and `DartEntryMixin` (from `package:analyzer_plugin/plugin/kythe_mixin.dart`) to
-the list of mixins for your subclass of `ServerPlugin`. This will leave you with
-one abstract method that you need to implement: `getEntryContributors`. That
-method is responsible for returning a list of `EntryContributor`s. It is the
-entry contributors that produce the actual entries. (Most plugins will only need
-a single entry contributor.)
-
-To write an entry contributor, create a class that implements
-`EntryContributor`. The interface defines a single method named
-`computeEntries`. The method has two arguments: an `EntryRequest` that describes
-the file to be indexed and an `EntryCollector` through which entries are to be
-added.
-
-If you mix in the class `DartEntryMixin`, then the request will be an instance
-of `DartEntryRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `EntryContributor`, then implement the
-method `computeEntries`. This method is typically implemented by creating a
-visitor (such as an AstVisitor) that can visit the results of the analysis (such
-as a CompilationUnit) and extract the navigation information from the analysis
-result.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyEntryContributor implements EntryContributor {
- @override
- void computeEntries(EntryRequest request, EntryCollector collector) {
- if (request is DartEntryRequest) {
- EntryVisitor visitor = new EntryVisitor(collector);
- request.result.unit.accept(visitor);
- }
- }
-}
-
-class EntryVisitor extends RecursiveAstVisitor {
- final EntryCollector collector;
-
- EntryVisitor(this.collector);
-
- @override
- void visitSimpleIdentifier(SimpleIdentifier node) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with EntryMixin, DartEntryMixin {
- // ...
-
- @override
- List<EntryContributor> getEntryContributors(String path) {
- return <EntryContributor>[new MyEntryContributor()];
- }
-}
-```
-
-[kythe]: http://kythe.io/
diff --git a/analyzer_plugin/doc/tutorial/navigation.md b/analyzer_plugin/doc/tutorial/navigation.md
deleted file mode 100644
index f9c83a6..0000000
--- a/analyzer_plugin/doc/tutorial/navigation.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# Providing Navigation
-
-Navigation information is used by clients to allow users to navigate to the
-location at which an identifier is defined.
-
-## Implementation details
-
-Navigation information can be requested both by an `analysis.getNavigation`
-request and by a subscription. If the server has subscribed for navigation
-information in some set of files, the the plugin should send the information in
-an `analysis.navigation` notification whenever the information needs to be
-updated.
-
-When an `analysis.getNavigation` request is received, the method
-`handleAnalysisGetNavigation` will be invoked. This method is responsible for
-returning a response that contains the available navigation information.
-
-When a notification needs to be sent, the method `sendNavigationNotification`
-will be invoked. This method is responsible for sending the notification.
-
-The easiest way to add support for both the request and the notification is by
-adding the classes `NavigationMixin` and `DartNavigationMixin` (from
-`package:analyzer_plugin/plugin/navigation_mixin.dart`) to the list of mixins
-for your subclass of `ServerPlugin`. This will leave you with one abstract
-method that you need to implement: `getNavigationContributors`. That method is
-responsible for returning a list of `NavigationContributor`s. It is the
-navigation contributors that produce the actual navigation information. (Most
-plugins will only need a single navigation contributor.)
-
-To write a navigation contributor, create a class that implements
-`NavigationContributor`. The interface defines a single method named
-`computeNavigation`. The method has two arguments: a `NavigationRequest` that
-describes the region of the file for which navigation is being requested and a
-`NavigationCollector` through which navigation information is to be added.
-
-If you mix in the class `DartNavigationMixin`, then the request will be an
-instance of `DartNavigationRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `NavigationContributor`, then
-implement the method `computeNavigation`. This method is typically implemented
-by creating a visitor (such as an AstVisitor) that can visit the results of the
-analysis (such as a CompilationUnit) and extract the navigation information from
-the analysis result.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyNavigationContributor implements NavigationContributor {
- @override
- void computeNavigation(
- NavigationRequest request, NavigationCollector collector) {
- if (request is DartNavigationRequest) {
- NavigationVisitor visitor = new NavigationVisitor(collector);
- request.result.unit.accept(visitor);
- }
- }
-}
-
-class NavigationVisitor extends RecursiveAstVisitor {
- final NavigationCollector collector;
-
- NavigationVisitor(this.collector);
-
- @override
- void visitSimpleIdentifier(SimpleIdentifier node) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with NavigationMixin, DartNavigationMixin {
- // ...
-
- @override
- List<NavigationContributor> getNavigationContributors(String path) {
- return <NavigationContributor>[new MyNavigationContributor()];
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/occurrences.md b/analyzer_plugin/doc/tutorial/occurrences.md
deleted file mode 100644
index fffac7a..0000000
--- a/analyzer_plugin/doc/tutorial/occurrences.md
+++ /dev/null
@@ -1,81 +0,0 @@
-# Providing Occurrences Information
-
-Occurrences information is used by clients to help users identify all of the
-references to a single program element, such as a class, field, or local
-variable, within a single file.
-
-## Implementation details
-
-Occurrences information is available through a subscription. If the server has
-subscribed for occurrences information in some set of files, then the plugin
-should send the information in an `analysis.occurrences` notification whenever
-the information needs to be updated.
-
-When a notification needs to be sent, the method `sendOccurrencesNotification`
-will be invoked. This method is responsible for sending the notification.
-
-The easiest way to add support for this notification is by adding the classes
-`OccurrencesMixin` and `DartOccurrencesMixin` (from
-`package:analyzer_plugin/plugin/occurrences_mixin.dart`) to the list of mixins
-for your subclass of `ServerPlugin`. This will leave you with one abstract
-method that you need to implement: `getOccurrencesContributors`. That method is
-responsible for returning a list of `OccurrencesContributor`s. It is the
-occurrences contributors that produce the actual occurrences information. (Most
-plugins will only need a single occurrences contributor.)
-
-To write an occurrences contributor, create a class that implements
-`OccurrencesContributor`. The interface defines a single method named
-`computeOccurrences`. The method has two arguments: an `OccurrencesRequest` that
-describes the file for which occurrences information is being requested and an
-`OccurrencesCollector` through which occurrences information is to be added.
-
-If you mix in the class `DartOccurrencesMixin`, then the request will be an
-instance of `DartOccurrencesRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `OccurrencesContributor`, then
-implement the method `computeOccurrences`. This method is typically implemented
-by creating a visitor (such as an AstVisitor) that can visit the results of the
-analysis (such as a CompilationUnit) and extract the occurrences information
-from the analysis result.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyOccurrencesContributor implements OccurrencesContributor {
- @override
- void computeOccurrences(
- OccurrencesRequest request, OccurrencesCollector collector) {
- if (request is DartOccurrencesRequest) {
- OccurrencesVisitor visitor = new OccurrencesVisitor(collector);
- request.result.unit.accept(visitor);
- }
- }
-}
-
-class OccurrencesVisitor extends RecursiveAstVisitor {
- final OccurrencesCollector collector;
-
- OccurrencesVisitor(this.collector);
-
- @override
- void visitSimpleIdentifier(SimpleIdentifier node) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with OccurrencesMixin, DartOccurrencesMixin {
- // ...
-
- @override
- List<OccurrencesContributor> getOccurrencesContributors(String path) {
- return <OccurrencesContributor>[new MyOccurrencesContributor()];
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/outline.md b/analyzer_plugin/doc/tutorial/outline.md
deleted file mode 100644
index 61a42b9..0000000
--- a/analyzer_plugin/doc/tutorial/outline.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Providing Outlines
-
-Outline information is used by clients to allow users to see the structure of
-their code.
-
-## Implementation details
-
-Outline information is available through a subscription. If the server has
-subscribed for outline information in some set of files, then the plugin should
-send the information in an `analysis.outline` notification whenever the
-information needs to be updated.
-
-When a notification needs to be sent, the method `sendOutlineNotification` will
-be invoked. This method is responsible for sending the notification.
-
-The easiest way to add support for this notification is by adding the classes
-`OutlineMixin` and `DartOutlineMixin` (from
-`package:analyzer_plugin/plugin/outline_mixin.dart`) to the list of mixins
-for your subclass of `ServerPlugin`. This will leave you with one abstract
-method that you need to implement: `getOutlineContributors`. That method is
-responsible for returning a list of `OutlineContributor`s. It is the outline
-contributors that produce the actual outline information. (Most plugins will
-only need a single outline contributor.)
-
-To write an outline contributor, create a class that implements
-`OutlineContributor`. The interface defines a single method named
-`computeOutline`. The method has two arguments: an `OutlineRequest` that
-describes the file for which outline information is being requested and an
-`OutlineCollector` through which outline information is to be added.
-
-If you mix in the class `DartOutlineMixin`, then the request will be an instance
-of `DartOutlineRequest`, which also has analysis results.
-
-## Example
-
-Start by creating a class that implements `OutlineContributor`, then
-implement the method `computeOutline`. This method is typically implemented
-by creating a visitor (such as an AstVisitor) that can visit the results of the
-analysis (such as a CompilationUnit) and extract the outline information from
-the analysis result.
-
-For example, your contributor might look something like the following:
-
-```dart
-class MyOutlineContributor implements OutlineContributor {
- @override
- void computeOutline(
- OutlineRequest request, OutlineCollector collector) {
- if (request is DartOutlineRequest) {
- OutlineVisitor visitor = new OutlineVisitor(collector);
- request.result.unit.accept(visitor);
- }
- }
-}
-
-class OutlineVisitor extends RecursiveAstVisitor {
- final OutlineCollector collector;
-
- OutlineVisitor(this.collector);
-
- @override
- void visitClassDeclaration(ClassDeclaration node) {
- // ...
- }
-}
-```
-
-Given a contributor like the one above, you can implement your plugin similar to
-the following:
-
-```dart
-class MyPlugin extends ServerPlugin with OutlineMixin, DartOutlineMixin {
- // ...
-
- @override
- List<OutlineContributor> getOutlineContributors(String path) {
- return <OutlineContributor>[new MyOutlineContributor()];
- }
-}
-```
diff --git a/analyzer_plugin/doc/tutorial/package_structure.md b/analyzer_plugin/doc/tutorial/package_structure.md
deleted file mode 100644
index 9572ece..0000000
--- a/analyzer_plugin/doc/tutorial/package_structure.md
+++ /dev/null
@@ -1,93 +0,0 @@
-# Package Structure
-
-Plugins are used by tools that want to allow external contributions to the
-results being produced by that tool. At the moment, the analysis server is the
-only tool that supports plugins, but we intend to add plugin support to the
-command-line analyzer and possibly other tools as well. For that reason,
-throughout this document we will generically refer to the tool running the
-plugins as simply the _tool_.
-
-In order to describe the way tools use plugins, we need to refer to four
-different packages. In order to keep the discussion clear, we will refer to
-those packages as the target package, the host package, the bootstrap package,
-and the plugin package. (If you're not familiar will packages, you should read
-about the Dart [package manager][pub].)
-
-The _target package_ is the package for which the tool is producing analysis
-results. If the tool is the analysis server, this is a package that the user has
-opened in the client and is actively developing.
-
-The _host package_ is a package that contains the information necessary to find
-and run the plugin. Specifically, the host package contains the bootstrap
-package. In order for the tool to find and use the host package, the target
-package must have a dependency on the host package. This can be either a normal
-dependency or a dev dependency.
-
-The _bootstrap package_ is a small package embedded within the host package that
-is used to load the plugin package.
-
-The _plugin package_ is the package that contains the actual implementation of
-the plugin.
-
-While you could technically merge the bootstrap and plugin packages, we
-recommend this structure because it minimizes the number of additional files
-that need to be downloaded by users who do not choose to enable the hosted
-plugin.
-
-As a concrete example, the angular package has a plugin associated with it. In
-order to implement this, the angular package has a bootstrap package embedded
-within it. When a target package (a package implementing a web app) has a
-dependency on the angular package, it can list 'angular' as an approved host
-package and the angular plugin will be run.
-
-## Plugin Discovery
-
-Plugins are used by a tool to analyze the target package only if the tool is
-explicitly told to run them. Tools look for a list of approved host packages in
-the analysis options file (`analysis_options.yaml`) associated with the target
-package. The list has the form:
-
-```yaml
-analyzer:
- plugins:
- - host_package_1
- - host_package_2
-```
-
-If a listed host package can be found (via the `.packages` file associated with
-the target package), then the tool looks in the host package for the folder
-`<host_package>/tools/analysis_plugin`. If that directory exists and contains a
-valid bootstrap package, then the bootstrap package is run as a plugin.
-
-## Bootstrap Package Structure
-
-The other packages described above can have any valid package structure, but the
-bootstrap package is required to have two specific files.
-
-First, it must have a file named `tools/analyzer_plugin/pubspec.yaml` that can
-be used by the [`pub`][pub] command to produce a `.packages` file describing how
-to resolve the `package:` URIs found in it. Typically, the only dependency that
-needs to be included is a dependency on the plugin package.
-
-Second, it must have a file named `tools/analyzer_plugin/bin/plugin.dart` that
-contains the entry point for the plugin. Every plugin will be run in a separate
-isolate. As a result, the entry point must have the following signature:
-
-```dart
-void main(List<String> args, SendPort sendPort) {
- // Invoke the real main method in the plugin package.
-}
-```
-
-The body of `main` should typically be a single line that invokes a method or
-function within the plugin package that will create and start the plugin.
-
-## Plugin Execution
-
-When a bootstrap package is to be run, the contents of the directory containing
-the bootstrap package are copied to a temporary directory, the [`pub`][pub]
-command is run in that directory to produce a `.packages` file for the bootstrap
-package, and the file `tools/analysis_plugin/bin/plugin.dart` is run in its own
-isolate.
-
-[pub]:https://www.dartlang.org/tools/pub/get-started
diff --git a/analyzer_plugin/doc/tutorial/tutorial.md b/analyzer_plugin/doc/tutorial/tutorial.md
deleted file mode 100644
index 8d9fafb..0000000
--- a/analyzer_plugin/doc/tutorial/tutorial.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# Building a Plugin
-
-This is the table of contents for a set of pages that describe how to implement
-a plugin. You should probably read the [Introduction][introduction],
-[Package Structure][packageStructure] and [Getting Started][gettingStarted]
-pages first, but the remaining pages can be read when you decide to implement
-the described functionality.
-
-## Pages
-
-The following is a list of the pages available in this tutorial.
-
-[Introduction][introduction] -
-What is a plugin and what can it do?
-
-[Package Structure][packageStructure] -
-How the code for a plugin is structured into packages.
-
-[Getting Started][gettingStarted] -
-How to write a minimal plugin.
-
-[Creating Edits][creatingEdits] -
-How to compose the edits used in assists, fixes, and refactorings.
-
-[Providing Quick Assists][assists] -
-How to provide quick assists.
-
-[Providing Quick Fixes][fixes] -
-How to provide quick fixes associated with errors.
-
-[Providing Code Completions][completion] -
-How to provide code completion suggestions.
-
-[Providing Navigation Information][navigation] -
-How to provide navigation support.
-
-[Providing Occurrences Information][occurrences] -
-How to provide information for marking occurrences.
-
-[Providing Outline Information][outline] -
-How to provide the information to build outline structures.
-
-[Providing Folding Information][folding] -
-How to provide support for code folding.
-
-[Debugging Plugins][debugging] -
-How to debug a plugin.
-
-[assists]: assists.md
-[completion]: completion.md
-[creatingEdits]: creating_edits.md
-[debugging]: debugging.md
-[fixes]: fixes.md
-[folding]: folding.md
-[gettingStarted]: getting_started.md
-[introduction]: introduction.md
-[navigation]: navigation.md
-[occurrences]: occurrences.md
-[outline]: outline.md
-[packageStructure]: package_structure.md
diff --git a/analyzer_plugin/lib/channel/channel.dart b/analyzer_plugin/lib/channel/channel.dart
deleted file mode 100644
index 9126c94..0000000
--- a/analyzer_plugin/lib/channel/channel.dart
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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_plugin/protocol/protocol.dart';
-
-/**
- * A communication channel that allows a [ServerPlugin] to receive [Request]s
- * from, and to return both [Response]s and [Notification]s to, an analysis
- * server.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class PluginCommunicationChannel {
- /**
- * Close the communication channel.
- */
- void close();
-
- /**
- * Listen to the channel for requests. If a request is received, invoke the
- * [onRequest] function. If an error is encountered while trying to read from
- * the socket, invoke the [onError] function. If the socket is closed by the
- * client, invoke the [onDone] function. Only one listener is allowed per
- * channel.
- */
- void listen(void onRequest(Request request),
- {Function onError, void onDone()});
-
- /**
- * Send the given [notification] to the server.
- */
- void sendNotification(Notification notification);
-
- /**
- * Send the given [response] to the server.
- */
- void sendResponse(Response response);
-}
-
-/**
- * A communication channel that allows an analysis server to send [Request]s
- * to, and to receive both [Response]s and [Notification]s from, a plugin.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class ServerCommunicationChannel {
- /**
- * Close the communication channel.
- */
- void close();
-
- /**
- * Cause the plugin to terminate as soon as possible. This should only be used
- * when the plugin has failed to terminate after sending it a 'plugin.shutdown'
- * request.
- */
- void kill();
-
- /**
- * Listen to the channel for responses and notifications. If a response is
- * received, invoke the [onResponse] function. If a notification is received,
- * invoke the [onNotification] function. If an error is encountered while
- * trying to read from the socket, invoke the [onError] function. If the
- * socket is closed by the plugin, invoke the [onDone] function. Only one
- * listener is allowed per channel.
- */
- void listen(void onResponse(Response response),
- void onNotification(Notification notification),
- {void onError(dynamic error), void onDone()});
-
- /**
- * Send the given [request] to the plugin.
- */
- void sendRequest(Request request);
-}
diff --git a/analyzer_plugin/lib/plugin/assist_mixin.dart b/analyzer_plugin/lib/plugin/assist_mixin.dart
deleted file mode 100644
index d17d4cd..0000000
--- a/analyzer_plugin/lib/plugin/assist_mixin.dart
+++ /dev/null
@@ -1,74 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/assist/assist.dart';
-import 'package:analyzer_plugin/utilities/assist/assist.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for handling assist requests.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin AssistsMixin implements ServerPlugin {
- /**
- * Return a list containing the assist contributors that should be used to
- * create assists for the file with the given [path].
- */
- List<AssistContributor> getAssistContributors(String path);
-
- /**
- * Return the assist request that should be passes to the contributors
- * returned from [getAssistContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<AssistRequest> getAssistRequest(EditGetAssistsParams parameters);
-
- @override
- Future<EditGetAssistsResult> handleEditGetAssists(
- EditGetAssistsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- AssistRequest request = await getAssistRequest(parameters);
- AssistGenerator generator =
- new AssistGenerator(getAssistContributors(path));
- GeneratorResult<EditGetAssistsResult> result =
- generator.generateAssistsResponse(request);
- result.sendNotifications(channel);
- return result.result;
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [AssistsMixin]. This implements the creation of the assists request
- * based on the assumption that the driver being created is an [AnalysisDriver].
- *
- * Clients may not extend or implement this class, but are allowed to use it as
- * a mix-in when creating a subclass of [ServerPlugin] that also uses
- * [AssistsMixin] as a mix-in.
- */
-abstract class DartAssistsMixin implements AssistsMixin {
- @override
- Future<AssistRequest> getAssistRequest(
- EditGetAssistsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartAssistRequestImpl(
- resourceProvider, parameters.offset, parameters.length, result);
- }
-}
diff --git a/analyzer_plugin/lib/plugin/completion_mixin.dart b/analyzer_plugin/lib/plugin/completion_mixin.dart
deleted file mode 100644
index a8aa3b8..0000000
--- a/analyzer_plugin/lib/plugin/completion_mixin.dart
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/completion/completion_core.dart';
-import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for handling code completion requests.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin CompletionMixin implements ServerPlugin {
- /**
- * Return a list containing the completion contributors that should be used to
- * create completion suggestions for the file with the given [path].
- */
- List<CompletionContributor> getCompletionContributors(String path);
-
- /**
- * Return the completion request that should be passes to the contributors
- * returned from [getCompletionContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<CompletionRequest> getCompletionRequest(
- CompletionGetSuggestionsParams parameters);
-
- @override
- Future<CompletionGetSuggestionsResult> handleCompletionGetSuggestions(
- CompletionGetSuggestionsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- CompletionRequest request = await getCompletionRequest(parameters);
- CompletionGenerator generator =
- new CompletionGenerator(getCompletionContributors(path));
- GeneratorResult<CompletionGetSuggestionsResult> result =
- await generator.generateCompletionResponse(request);
- result.sendNotifications(channel);
- return result.result;
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [CompletionMixin]. This implements the creation of the completion
- * request based on the assumption that the driver being created is an
- * [AnalysisDriver].
- *
- * Clients may not extend or implement this class, but are allowed to use it as
- * a mix-in when creating a subclass of [ServerPlugin] that also uses
- * [CompletionMixin] as a mix-in.
- */
-abstract class DartCompletionMixin implements CompletionMixin {
- @override
- Future<CompletionRequest> getCompletionRequest(
- CompletionGetSuggestionsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- ResolvedUnitResult result = await getResolvedUnitResult(parameters.file);
- return new DartCompletionRequestImpl(
- resourceProvider, parameters.offset, result);
- }
-}
diff --git a/analyzer_plugin/lib/plugin/fix_mixin.dart b/analyzer_plugin/lib/plugin/fix_mixin.dart
deleted file mode 100644
index a4a113d..0000000
--- a/analyzer_plugin/lib/plugin/fix_mixin.dart
+++ /dev/null
@@ -1,84 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/error/error.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/fixes/fixes.dart';
-import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [FixesMixin]. This implements the creation of the fixes request
- * based on the assumption that the driver being created is an [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [FixesMixin] as a
- * mix-in.
- */
-mixin DartFixesMixin implements FixesMixin {
- @override
- Future<FixesRequest> getFixesRequest(EditGetFixesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- int offset = parameters.offset;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartFixesRequestImpl(
- resourceProvider, offset, _getErrors(offset, result), result);
- }
-
- List<AnalysisError> _getErrors(int offset, ResolvedUnitResult result) {
- LineInfo lineInfo = result.lineInfo;
- int offsetLine = lineInfo.getLocation(offset).lineNumber;
- return result.errors.where((AnalysisError error) {
- int errorLine = lineInfo.getLocation(error.offset).lineNumber;
- return errorLine == offsetLine;
- }).toList();
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for handling fix requests.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin FixesMixin implements ServerPlugin {
- /**
- * Return a list containing the fix contributors that should be used to create
- * fixes for the file with the given [path].
- */
- List<FixContributor> getFixContributors(String path);
-
- /**
- * Return the fixes request that should be passes to the contributors
- * returned from [getFixContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<FixesRequest> getFixesRequest(EditGetFixesParams parameters);
-
- @override
- Future<EditGetFixesResult> handleEditGetFixes(
- EditGetFixesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- FixesRequest request = await getFixesRequest(parameters);
- FixGenerator generator = new FixGenerator(getFixContributors(path));
- GeneratorResult<EditGetFixesResult> result =
- generator.generateFixesResponse(request);
- result.sendNotifications(channel);
- return result.result;
- }
-}
diff --git a/analyzer_plugin/lib/plugin/folding_mixin.dart b/analyzer_plugin/lib/plugin/folding_mixin.dart
deleted file mode 100644
index 1ca0f81..0000000
--- a/analyzer_plugin/lib/plugin/folding_mixin.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/utilities/folding/folding.dart';
-import 'package:analyzer_plugin/utilities/folding/folding.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [FoldingMixin]. This implements the creation of the folding
- * request based on the assumption that the driver being created is an
- * [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [FoldingMixin] as a
- * mix-in.
- */
-mixin DartFoldingMixin implements FoldingMixin {
- @override
- Future<FoldingRequest> getFoldingRequest(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartFoldingRequestImpl(resourceProvider, result);
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for producing folding notifications.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin FoldingMixin implements ServerPlugin {
- /**
- * Return a list containing the folding contributors that should be used
- * to create folding regions for the file with the given [path].
- */
- List<FoldingContributor> getFoldingContributors(String path);
-
- /**
- * Return the folding request that should be passes to the contributors
- * returned from [getFoldingContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<FoldingRequest> getFoldingRequest(String path);
-
- @override
- Future<void> sendFoldingNotification(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- try {
- FoldingRequest request = await getFoldingRequest(path);
- FoldingGenerator generator =
- new FoldingGenerator(getFoldingContributors(path));
- GeneratorResult generatorResult =
- generator.generateFoldingNotification(request);
- generatorResult.sendNotifications(channel);
- } on RequestFailure {
- // If we couldn't analyze the file, then don't send a notification.
- }
- }
-}
diff --git a/analyzer_plugin/lib/plugin/highlights_mixin.dart b/analyzer_plugin/lib/plugin/highlights_mixin.dart
deleted file mode 100644
index 20748c9..0000000
--- a/analyzer_plugin/lib/plugin/highlights_mixin.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/utilities/highlights/highlights.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-import 'package:analyzer_plugin/utilities/highlights/highlights.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [HighlightsMixin]. This implements the creation of the
- * highlighting request based on the assumption that the driver being created is
- * an [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [HighlightsMixin]
- * as a mix-in.
- */
-mixin DartHighlightsMixin implements HighlightsMixin {
- @override
- Future<HighlightsRequest> getHighlightsRequest(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartHighlightsRequestImpl(resourceProvider, result);
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for producing highlighting notifications.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin HighlightsMixin implements ServerPlugin {
- /**
- * Return a list containing the highlighting contributors that should be used
- * to create highlighting information for the file with the given [path].
- */
- List<HighlightsContributor> getHighlightsContributors(String path);
-
- /**
- * Return the highlighting request that should be passes to the contributors
- * returned from [getHighlightsContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<HighlightsRequest> getHighlightsRequest(String path);
-
- @override
- Future<void> sendHighlightsNotification(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- try {
- HighlightsRequest request = await getHighlightsRequest(path);
- HighlightsGenerator generator =
- new HighlightsGenerator(getHighlightsContributors(path));
- GeneratorResult generatorResult =
- generator.generateHighlightsNotification(request);
- generatorResult.sendNotifications(channel);
- } on RequestFailure {
- // If we couldn't analyze the file, then don't send a notification.
- }
- }
-}
diff --git a/analyzer_plugin/lib/plugin/kythe_mixin.dart b/analyzer_plugin/lib/plugin/kythe_mixin.dart
deleted file mode 100644
index be89c6c..0000000
--- a/analyzer_plugin/lib/plugin/kythe_mixin.dart
+++ /dev/null
@@ -1,73 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/kythe/entries.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-import 'package:analyzer_plugin/utilities/kythe/entries.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [KytheMixin]. This implements the creation of the kythe.getEntries
- * request based on the assumption that the driver being created is an
- * [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [KytheMixin] as a
- * mix-in.
- */
-mixin DartEntryMixin implements EntryMixin {
- @override
- Future<EntryRequest> getEntryRequest(
- KytheGetKytheEntriesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartEntryRequestImpl(resourceProvider, result);
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for handling kythe.getEntries requests.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin EntryMixin implements ServerPlugin {
- /**
- * Return a list containing the entry contributors that should be used to
- * create entries for the file with the given [path]
- */
- List<EntryContributor> getEntryContributors(String path);
-
- /**
- * Return the entries request that should be passes to the contributors
- * returned from [getEntryContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<EntryRequest> getEntryRequest(KytheGetKytheEntriesParams parameters);
-
- @override
- Future<KytheGetKytheEntriesResult> handleKytheGetKytheEntries(
- KytheGetKytheEntriesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- EntryRequest request = await getEntryRequest(parameters);
- EntryGenerator generator = new EntryGenerator(getEntryContributors(path));
- GeneratorResult<KytheGetKytheEntriesResult> result =
- generator.generateGetEntriesResponse(request);
- result.sendNotifications(channel);
- return result.result;
- }
-}
diff --git a/analyzer_plugin/lib/plugin/navigation_mixin.dart b/analyzer_plugin/lib/plugin/navigation_mixin.dart
deleted file mode 100644
index 96bfdc5..0000000
--- a/analyzer_plugin/lib/plugin/navigation_mixin.dart
+++ /dev/null
@@ -1,103 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/navigation/navigation.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-import 'package:analyzer_plugin/utilities/navigation/navigation.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [NavigationMixin]. This implements the creation of the navigation
- * request based on the assumption that the driver being created is an
- * [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [NavigationMixin]
- * as a mix-in.
- */
-mixin DartNavigationMixin implements NavigationMixin {
- @override
- Future<NavigationRequest> getNavigationRequest(
- AnalysisGetNavigationParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- int offset = parameters.offset;
- int length = parameters.length;
- if (offset < 0 && length < 0) {
- offset = 0;
- length = result.content.length;
- }
- return new DartNavigationRequestImpl(
- resourceProvider, offset, length, result);
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for handling navigation requests.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin NavigationMixin implements ServerPlugin {
- /**
- * Return a list containing the navigation contributors that should be used to
- * create navigation information for the file with the given [path]
- */
- List<NavigationContributor> getNavigationContributors(String path);
-
- /**
- * Return the navigation request that should be passes to the contributors
- * returned from [getNavigationContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<NavigationRequest> getNavigationRequest(
- AnalysisGetNavigationParams parameters);
-
- @override
- Future<AnalysisGetNavigationResult> handleAnalysisGetNavigation(
- AnalysisGetNavigationParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String path = parameters.file;
- NavigationRequest request = await getNavigationRequest(parameters);
- NavigationGenerator generator =
- new NavigationGenerator(getNavigationContributors(path));
- GeneratorResult<AnalysisGetNavigationResult> result =
- generator.generateNavigationResponse(request);
- result.sendNotifications(channel);
- return result.result;
- }
-
- /**
- * Send a navigation notification for the file with the given [path] to the
- * server.
- */
- @override
- Future<void> sendNavigationNotification(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- try {
- NavigationRequest request = await getNavigationRequest(
- new AnalysisGetNavigationParams(path, -1, -1));
- NavigationGenerator generator =
- new NavigationGenerator(getNavigationContributors(path));
- GeneratorResult generatorResult =
- generator.generateNavigationNotification(request);
- generatorResult.sendNotifications(channel);
- } on RequestFailure {
- // If we couldn't analyze the file, then don't send a notification.
- }
- }
-}
diff --git a/analyzer_plugin/lib/plugin/occurrences_mixin.dart b/analyzer_plugin/lib/plugin/occurrences_mixin.dart
deleted file mode 100644
index 8547779..0000000
--- a/analyzer_plugin/lib/plugin/occurrences_mixin.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/utilities/occurrences/occurrences.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-import 'package:analyzer_plugin/utilities/occurrences/occurrences.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [OccurrencesMixin]. This implements the creation of the occurrences
- * request based on the assumption that the driver being created is an
- * [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [OccurrencesMixin]
- * as a mix-in.
- */
-mixin DartOccurrencesMixin implements OccurrencesMixin {
- @override
- Future<OccurrencesRequest> getOccurrencesRequest(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartOccurrencesRequestImpl(resourceProvider, result);
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for producing occurrences notifications.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin OccurrencesMixin implements ServerPlugin {
- /**
- * Return a list containing the occurrences contributors that should be used
- * to create occurrences information for the file with the given [path].
- */
- List<OccurrencesContributor> getOccurrencesContributors(String path);
-
- /**
- * Return the occurrences request that should be passes to the contributors
- * returned from [getOccurrencesContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<OccurrencesRequest> getOccurrencesRequest(String path);
-
- @override
- Future<void> sendOccurrencesNotification(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- try {
- OccurrencesRequest request = await getOccurrencesRequest(path);
- OccurrencesGenerator generator =
- new OccurrencesGenerator(getOccurrencesContributors(path));
- GeneratorResult generatorResult =
- generator.generateOccurrencesNotification(request);
- generatorResult.sendNotifications(channel);
- } on RequestFailure {
- // If we couldn't analyze the file, then don't send a notification.
- }
- }
-}
diff --git a/analyzer_plugin/lib/plugin/outline_mixin.dart b/analyzer_plugin/lib/plugin/outline_mixin.dart
deleted file mode 100644
index 4207a25..0000000
--- a/analyzer_plugin/lib/plugin/outline_mixin.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/utilities/outline/outline.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-import 'package:analyzer_plugin/utilities/outline/outline.dart';
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] and
- * mixing in [OutlineMixin]. This implements the creation of the outline
- * request based on the assumption that the driver being created is an
- * [AnalysisDriver].
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin] that also uses [OutlineMixin] as a
- * mix-in.
- */
-mixin DartOutlineMixin implements OutlineMixin {
- @override
- Future<OutlineRequest> getOutlineRequest(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- ResolvedUnitResult result = await getResolvedUnitResult(path);
- return new DartOutlineRequestImpl(resourceProvider, result);
- }
-}
-
-/**
- * A mixin that can be used when creating a subclass of [ServerPlugin] to
- * provide most of the implementation for producing outline notifications.
- *
- * Clients may not implement this mixin, but are allowed to use it as a mix-in
- * when creating a subclass of [ServerPlugin].
- */
-mixin OutlineMixin implements ServerPlugin {
- /**
- * Return a list containing the outline contributors that should be used to
- * create outline information for the file with the given [path].
- */
- List<OutlineContributor> getOutlineContributors(String path);
-
- /**
- * Return the outline request that should be passes to the contributors
- * returned from [getOutlineContributors].
- *
- * Throw a [RequestFailure] if the request could not be created.
- */
- Future<OutlineRequest> getOutlineRequest(String path);
-
- @override
- Future<void> sendOutlineNotification(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- try {
- OutlineRequest request = await getOutlineRequest(path);
- OutlineGenerator generator =
- new OutlineGenerator(getOutlineContributors(path));
- GeneratorResult generatorResult =
- generator.generateOutlineNotification(request);
- generatorResult.sendNotifications(channel);
- } on RequestFailure {
- // If we couldn't analyze the file, then don't send a notification.
- }
- }
-}
diff --git a/analyzer_plugin/lib/plugin/plugin.dart b/analyzer_plugin/lib/plugin/plugin.dart
deleted file mode 100644
index 44ad8e9..0000000
--- a/analyzer_plugin/lib/plugin/plugin.dart
+++ /dev/null
@@ -1,757 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/file_system/physical_file_system.dart';
-import 'package:analyzer/src/dart/analysis/byte_store.dart';
-import 'package:analyzer/src/dart/analysis/driver.dart'
- show AnalysisDriver, AnalysisDriverGeneric, AnalysisDriverScheduler;
-import 'package:analyzer/src/dart/analysis/file_byte_store.dart';
-import 'package:analyzer/src/dart/analysis/file_state.dart';
-import 'package:analyzer/src/dart/analysis/performance_logger.dart';
-import 'package:analyzer/src/generated/sdk.dart';
-import 'package:analyzer_plugin/channel/channel.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/protocol/protocol_constants.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart';
-import 'package:analyzer_plugin/src/utilities/null_string_sink.dart';
-import 'package:analyzer_plugin/utilities/subscriptions/subscription_manager.dart';
-import 'package:path/src/context.dart';
-import 'package:pub_semver/pub_semver.dart';
-
-/**
- * The abstract superclass of any class implementing a plugin for the analysis
- * server.
- *
- * Clients may not implement or mix-in this class, but are expected to extend
- * it.
- */
-abstract class ServerPlugin {
- /**
- * A megabyte.
- */
- static const int M = 1024 * 1024;
-
- /**
- * The communication channel being used to communicate with the analysis
- * server.
- */
- PluginCommunicationChannel _channel;
-
- /**
- * The resource provider used to access the file system.
- */
- final ResourceProvider resourceProvider;
-
- /**
- * The object used to manage analysis subscriptions.
- */
- final SubscriptionManager subscriptionManager = new SubscriptionManager();
-
- /**
- * The scheduler used by any analysis drivers that are created.
- */
- AnalysisDriverScheduler analysisDriverScheduler;
-
- /**
- * A table mapping the current context roots to the analysis driver created
- * for that root.
- */
- final Map<ContextRoot, AnalysisDriverGeneric> driverMap =
- <ContextRoot, AnalysisDriverGeneric>{};
-
- /**
- * The performance log used by any analysis drivers that are created.
- */
- final PerformanceLog performanceLog =
- new PerformanceLog(new NullStringSink());
-
- /**
- * The byte store used by any analysis drivers that are created, or `null` if
- * the cache location isn't known because the 'plugin.version' request has not
- * yet been received.
- */
- ByteStore _byteStore;
-
- /**
- * The SDK manager used to manage SDKs.
- */
- DartSdkManager _sdkManager;
-
- /**
- * The file content overlay used by any analysis drivers that are created.
- */
- final FileContentOverlay fileContentOverlay = new FileContentOverlay();
-
- /**
- * Initialize a newly created analysis server plugin. If a resource [provider]
- * is given, then it will be used to access the file system. Otherwise a
- * resource provider that accesses the physical file system will be used.
- */
- ServerPlugin(ResourceProvider provider)
- : resourceProvider = provider ?? PhysicalResourceProvider.INSTANCE {
- analysisDriverScheduler = new AnalysisDriverScheduler(performanceLog);
- analysisDriverScheduler.start();
- }
-
- /**
- * Return the byte store used by any analysis drivers that are created, or
- * `null` if the cache location isn't known because the 'plugin.version'
- * request has not yet been received.
- */
- ByteStore get byteStore => _byteStore;
-
- /**
- * Return the communication channel being used to communicate with the
- * analysis server, or `null` if the plugin has not been started.
- */
- PluginCommunicationChannel get channel => _channel;
-
- /**
- * Return the user visible information about how to contact the plugin authors
- * with any problems that are found, or `null` if there is no contact info.
- */
- String get contactInfo => null;
-
- /**
- * Return a list of glob patterns selecting the files that this plugin is
- * interested in analyzing.
- */
- List<String> get fileGlobsToAnalyze;
-
- /**
- * Return the user visible name of this plugin.
- */
- String get name;
-
- /**
- * Return the SDK manager used to manage SDKs.
- */
- DartSdkManager get sdkManager => _sdkManager;
-
- /**
- * Return the version number of this plugin, encoded as a string.
- */
- String get version;
-
- /**
- * Handle the fact that the file with the given [path] has been modified.
- */
- void contentChanged(String path) {
- // Ignore changes to files.
- }
-
- /**
- * Return the context root containing the file at the given [filePath].
- */
- ContextRoot contextRootContaining(String filePath) {
- Context pathContext = resourceProvider.pathContext;
-
- /**
- * Return `true` if the given [child] is either the same as or within the
- * given [parent].
- */
- bool isOrWithin(String parent, String child) {
- return parent == child || pathContext.isWithin(parent, child);
- }
-
- /**
- * Return `true` if the given context [root] contains the target [file].
- */
- bool ownsFile(ContextRoot root) {
- if (isOrWithin(root.root, filePath)) {
- List<String> excludedPaths = root.exclude;
- for (String excludedPath in excludedPaths) {
- if (isOrWithin(excludedPath, filePath)) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
- for (ContextRoot root in driverMap.keys) {
- if (ownsFile(root)) {
- return root;
- }
- }
- return null;
- }
-
- /**
- * Create an analysis driver that can analyze the files within the given
- * [contextRoot].
- */
- AnalysisDriverGeneric createAnalysisDriver(ContextRoot contextRoot);
-
- /**
- * Return the driver being used to analyze the file with the given [path].
- */
- AnalysisDriverGeneric driverForPath(String path) {
- ContextRoot contextRoot = contextRootContaining(path);
- if (contextRoot == null) {
- return null;
- }
- return driverMap[contextRoot];
- }
-
- /**
- * Return the result of analyzing the file with the given [path].
- *
- * Throw a [RequestFailure] is the file cannot be analyzed or if the driver
- * associated with the file is not an [AnalysisDriver].
- */
- Future<ResolvedUnitResult> getResolvedUnitResult(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- AnalysisDriverGeneric driver = driverForPath(path);
- if (driver is! AnalysisDriver) {
- // Return an error from the request.
- throw new RequestFailure(
- RequestErrorFactory.pluginError('Failed to analyze $path', null));
- }
- ResolvedUnitResult result =
- await (driver as AnalysisDriver).getResult(path);
- ResultState state = result.state;
- if (state != ResultState.VALID) {
- // Return an error from the request.
- throw new RequestFailure(
- RequestErrorFactory.pluginError('Failed to analyze $path', null));
- }
- return result;
- }
-
- /**
- * Return the result of analyzing the file with the given [path].
- *
- * Throw a [RequestFailure] is the file cannot be analyzed or if the driver
- * associated with the file is not an [AnalysisDriver].
- */
- @deprecated
- Future<ResolveResult> getResolveResult(String path) =>
- getResolvedUnitResult(path);
-
- /**
- * Handle an 'analysis.getNavigation' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<AnalysisGetNavigationResult> handleAnalysisGetNavigation(
- AnalysisGetNavigationParams params) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new AnalysisGetNavigationResult(
- <String>[], <NavigationTarget>[], <NavigationRegion>[]);
- }
-
- /**
- * Handle an 'analysis.handleWatchEvents' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<AnalysisHandleWatchEventsResult> handleAnalysisHandleWatchEvents(
- AnalysisHandleWatchEventsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- for (WatchEvent event in parameters.events) {
- switch (event.type) {
- case WatchEventType.ADD:
- // TODO(brianwilkerson) Handle the event.
- break;
- case WatchEventType.MODIFY:
- contentChanged(event.path);
- break;
- case WatchEventType.REMOVE:
- // TODO(brianwilkerson) Handle the event.
- break;
- default:
- // Ignore unhandled watch event types.
- break;
- }
- }
- return new AnalysisHandleWatchEventsResult();
- }
-
- /**
- * Handle an 'analysis.setContextRoots' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<AnalysisSetContextRootsResult> handleAnalysisSetContextRoots(
- AnalysisSetContextRootsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- List<ContextRoot> contextRoots = parameters.roots;
- List<ContextRoot> oldRoots = driverMap.keys.toList();
- for (ContextRoot contextRoot in contextRoots) {
- if (!oldRoots.remove(contextRoot)) {
- // The context is new, so we create a driver for it. Creating the driver
- // has the side-effect of adding it to the analysis driver scheduler.
- AnalysisDriverGeneric driver = createAnalysisDriver(contextRoot);
- driverMap[contextRoot] = driver;
- _addFilesToDriver(
- driver,
- resourceProvider.getResource(contextRoot.root),
- contextRoot.exclude);
- }
- }
- for (ContextRoot contextRoot in oldRoots) {
- // The context has been removed, so we remove its driver.
- AnalysisDriverGeneric driver = driverMap.remove(contextRoot);
- // The `dispose` method has the side-effect of removing the driver from
- // the analysis driver scheduler.
- driver.dispose();
- }
- return new AnalysisSetContextRootsResult();
- }
-
- /**
- * Handle an 'analysis.setPriorityFiles' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<AnalysisSetPriorityFilesResult> handleAnalysisSetPriorityFiles(
- AnalysisSetPriorityFilesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- List<String> files = parameters.files;
- Map<AnalysisDriverGeneric, List<String>> filesByDriver =
- <AnalysisDriverGeneric, List<String>>{};
- for (String file in files) {
- ContextRoot contextRoot = contextRootContaining(file);
- if (contextRoot != null) {
- // TODO(brianwilkerson) Which driver should we use if there is no context root?
- AnalysisDriverGeneric driver = driverMap[contextRoot];
- filesByDriver.putIfAbsent(driver, () => <String>[]).add(file);
- }
- }
- filesByDriver.forEach((AnalysisDriverGeneric driver, List<String> files) {
- driver.priorityFiles = files;
- });
- return new AnalysisSetPriorityFilesResult();
- }
-
- /**
- * Handle an 'analysis.setSubscriptions' request. Most subclasses should not
- * override this method, but should instead use the [subscriptionManager] to
- * access the list of subscriptions for any given file.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<AnalysisSetSubscriptionsResult> handleAnalysisSetSubscriptions(
- AnalysisSetSubscriptionsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- Map<AnalysisService, List<String>> subscriptions = parameters.subscriptions;
- Map<String, List<AnalysisService>> newSubscriptions =
- subscriptionManager.setSubscriptions(subscriptions);
- sendNotificationsForSubscriptions(newSubscriptions);
- return new AnalysisSetSubscriptionsResult();
- }
-
- /**
- * Handle an 'analysis.updateContent' request. Most subclasses should not
- * override this method, but should instead use the [contentCache] to access
- * the current content of overlaid files.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<AnalysisUpdateContentResult> handleAnalysisUpdateContent(
- AnalysisUpdateContentParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- Map<String, Object> files = parameters.files;
- files.forEach((String filePath, Object overlay) {
- if (overlay is AddContentOverlay) {
- fileContentOverlay[filePath] = overlay.content;
- } else if (overlay is ChangeContentOverlay) {
- String oldContents = fileContentOverlay[filePath];
- String newContents;
- if (oldContents == null) {
- // The server should only send a ChangeContentOverlay if there is
- // already an existing overlay for the source.
- throw new RequestFailure(
- RequestErrorFactory.invalidOverlayChangeNoContent());
- }
- try {
- newContents = SourceEdit.applySequence(oldContents, overlay.edits);
- } on RangeError {
- throw new RequestFailure(
- RequestErrorFactory.invalidOverlayChangeInvalidEdit());
- }
- fileContentOverlay[filePath] = newContents;
- } else if (overlay is RemoveContentOverlay) {
- fileContentOverlay[filePath] = null;
- }
- contentChanged(filePath);
- });
- return new AnalysisUpdateContentResult();
- }
-
- /**
- * Handle a 'completion.getSuggestions' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<CompletionGetSuggestionsResult> handleCompletionGetSuggestions(
- CompletionGetSuggestionsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new CompletionGetSuggestionsResult(
- -1, -1, const <CompletionSuggestion>[]);
- }
-
- /**
- * Handle an 'edit.getAssists' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<EditGetAssistsResult> handleEditGetAssists(
- EditGetAssistsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new EditGetAssistsResult(const <PrioritizedSourceChange>[]);
- }
-
- /**
- * Handle an 'edit.getAvailableRefactorings' request. Subclasses that override
- * this method in order to participate in refactorings must also override the
- * method [handleEditGetRefactoring].
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<EditGetAvailableRefactoringsResult> handleEditGetAvailableRefactorings(
- EditGetAvailableRefactoringsParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new EditGetAvailableRefactoringsResult(const <RefactoringKind>[]);
- }
-
- /**
- * Handle an 'edit.getFixes' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<EditGetFixesResult> handleEditGetFixes(
- EditGetFixesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new EditGetFixesResult(const <AnalysisErrorFixes>[]);
- }
-
- /**
- * Handle an 'edit.getRefactoring' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<EditGetRefactoringResult> handleEditGetRefactoring(
- EditGetRefactoringParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- return await null;
- }
-
- /**
- * Handle a 'kythe.getKytheEntries' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<KytheGetKytheEntriesResult> handleKytheGetKytheEntries(
- KytheGetKytheEntriesParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- return await null;
- }
-
- /**
- * Handle a 'plugin.shutdown' request. Subclasses can override this method to
- * perform any required clean-up, but cannot prevent the plugin from shutting
- * down.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<PluginShutdownResult> handlePluginShutdown(
- PluginShutdownParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new PluginShutdownResult();
- }
-
- /**
- * Handle a 'plugin.versionCheck' request.
- *
- * Throw a [RequestFailure] if the request could not be handled.
- */
- Future<PluginVersionCheckResult> handlePluginVersionCheck(
- PluginVersionCheckParams parameters) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- String byteStorePath = parameters.byteStorePath;
- String sdkPath = parameters.sdkPath;
- String versionString = parameters.version;
- Version serverVersion = new Version.parse(versionString);
- _byteStore = new MemoryCachingByteStore(
- new FileByteStore(byteStorePath,
- tempNameSuffix:
- new DateTime.now().millisecondsSinceEpoch.toString()),
- 64 * M);
- _sdkManager = new DartSdkManager(sdkPath, true);
- return new PluginVersionCheckResult(
- isCompatibleWith(serverVersion), name, version, fileGlobsToAnalyze,
- contactInfo: contactInfo);
- }
-
- /**
- * Return `true` if this plugin is compatible with an analysis server that is
- * using the given version of the plugin API.
- */
- bool isCompatibleWith(Version serverVersion) =>
- serverVersion <= new Version.parse(version);
-
- /**
- * The method that is called when the analysis server closes the communication
- * channel. This method will not be invoked under normal conditions because
- * the server will send a shutdown request and the plugin will stop listening
- * to the channel before the server closes the channel.
- */
- void onDone() {}
-
- /**
- * The method that is called when an error has occurred in the analysis
- * server. This method will not be invoked under normal conditions.
- */
- void onError(Object exception, StackTrace stackTrace) {}
-
- /**
- * If the plugin provides folding information, send a folding notification
- * for the file with the given [path] to the server.
- */
- Future<void> sendFoldingNotification(String path) {
- return new Future.value();
- }
-
- /**
- * If the plugin provides highlighting information, send a highlights
- * notification for the file with the given [path] to the server.
- */
- Future<void> sendHighlightsNotification(String path) {
- return new Future.value();
- }
-
- /**
- * If the plugin provides navigation information, send a navigation
- * notification for the file with the given [path] to the server.
- */
- Future<void> sendNavigationNotification(String path) {
- return new Future.value();
- }
-
- /**
- * Send notifications for the services subscribed to for the file with the
- * given [path].
- *
- * This is a convenience method that subclasses can use to send notifications
- * after analysis has been performed on a file.
- */
- void sendNotificationsForFile(String path) {
- for (AnalysisService service in subscriptionManager.servicesForFile(path)) {
- _sendNotificationForFile(path, service);
- }
- }
-
- /**
- * Send notifications corresponding to the given description of
- * [subscriptions]. The map is keyed by the path of each file for which
- * notifications should be sent and has values representing the list of
- * services associated with the notifications to send.
- *
- * This method is used when the set of subscribed notifications has been
- * changed and notifications need to be sent even when the specified files
- * have already been analyzed.
- */
- void sendNotificationsForSubscriptions(
- Map<String, List<AnalysisService>> subscriptions) {
- subscriptions.forEach((String path, List<AnalysisService> services) {
- for (AnalysisService service in services) {
- _sendNotificationForFile(path, service);
- }
- });
- }
-
- /**
- * If the plugin provides occurrences information, send an occurrences
- * notification for the file with the given [path] to the server.
- */
- Future<void> sendOccurrencesNotification(String path) {
- return new Future.value();
- }
-
- /**
- * If the plugin provides outline information, send an outline notification
- * for the file with the given [path] to the server.
- */
- Future<void> sendOutlineNotification(String path) {
- return new Future.value();
- }
-
- /**
- * Start this plugin by listening to the given communication [channel].
- */
- void start(PluginCommunicationChannel channel) {
- _channel = channel;
- _channel.listen(_onRequest, onError: onError, onDone: onDone);
- }
-
- /**
- * Add all of the files contained in the given [resource] that are not in the
- * list of [excluded] resources to the given [driver].
- */
- void _addFilesToDriver(
- AnalysisDriverGeneric driver, Resource resource, List<String> excluded) {
- String path = resource.path;
- if (excluded.contains(path)) {
- return;
- }
- if (resource is File) {
- driver.addFile(path);
- } else if (resource is Folder) {
- try {
- for (Resource child in resource.getChildren()) {
- _addFilesToDriver(driver, child, excluded);
- }
- } on FileSystemException {
- // The folder does not exist, so ignore it.
- }
- }
- }
-
- /**
- * Compute the response that should be returned for the given [request], or
- * `null` if the response has already been sent.
- */
- Future<Response> _getResponse(Request request, int requestTime) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- ResponseResult result = null;
- switch (request.method) {
- case ANALYSIS_REQUEST_GET_NAVIGATION:
- var params = new AnalysisGetNavigationParams.fromRequest(request);
- result = await handleAnalysisGetNavigation(params);
- break;
- case ANALYSIS_REQUEST_HANDLE_WATCH_EVENTS:
- var params = new AnalysisHandleWatchEventsParams.fromRequest(request);
- result = await handleAnalysisHandleWatchEvents(params);
- break;
- case ANALYSIS_REQUEST_SET_CONTEXT_ROOTS:
- var params = new AnalysisSetContextRootsParams.fromRequest(request);
- result = await handleAnalysisSetContextRoots(params);
- break;
- case ANALYSIS_REQUEST_SET_PRIORITY_FILES:
- var params = new AnalysisSetPriorityFilesParams.fromRequest(request);
- result = await handleAnalysisSetPriorityFiles(params);
- break;
- case ANALYSIS_REQUEST_SET_SUBSCRIPTIONS:
- var params = new AnalysisSetSubscriptionsParams.fromRequest(request);
- result = await handleAnalysisSetSubscriptions(params);
- break;
- case ANALYSIS_REQUEST_UPDATE_CONTENT:
- var params = new AnalysisUpdateContentParams.fromRequest(request);
- result = await handleAnalysisUpdateContent(params);
- break;
- case COMPLETION_REQUEST_GET_SUGGESTIONS:
- var params = new CompletionGetSuggestionsParams.fromRequest(request);
- result = await handleCompletionGetSuggestions(params);
- break;
- case EDIT_REQUEST_GET_ASSISTS:
- var params = new EditGetAssistsParams.fromRequest(request);
- result = await handleEditGetAssists(params);
- break;
- case EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS:
- var params =
- new EditGetAvailableRefactoringsParams.fromRequest(request);
- result = await handleEditGetAvailableRefactorings(params);
- break;
- case EDIT_REQUEST_GET_FIXES:
- var params = new EditGetFixesParams.fromRequest(request);
- result = await handleEditGetFixes(params);
- break;
- case EDIT_REQUEST_GET_REFACTORING:
- var params = new EditGetRefactoringParams.fromRequest(request);
- result = await handleEditGetRefactoring(params);
- break;
- case KYTHE_REQUEST_GET_KYTHE_ENTRIES:
- var params = new KytheGetKytheEntriesParams.fromRequest(request);
- result = await handleKytheGetKytheEntries(params);
- break;
- case PLUGIN_REQUEST_SHUTDOWN:
- var params = new PluginShutdownParams();
- result = await handlePluginShutdown(params);
- _channel.sendResponse(result.toResponse(request.id, requestTime));
- _channel.close();
- return null;
- case PLUGIN_REQUEST_VERSION_CHECK:
- var params = new PluginVersionCheckParams.fromRequest(request);
- result = await handlePluginVersionCheck(params);
- break;
- }
- if (result == null) {
- return new Response(request.id, requestTime,
- error: RequestErrorFactory.unknownRequest(request.method));
- }
- return result.toResponse(request.id, requestTime);
- }
-
- /**
- * The method that is called when a [request] is received from the analysis
- * server.
- */
- Future<void> _onRequest(Request request) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- int requestTime = new DateTime.now().millisecondsSinceEpoch;
- String id = request.id;
- Response response;
- try {
- response = await _getResponse(request, requestTime);
- } on RequestFailure catch (exception) {
- response = new Response(id, requestTime, error: exception.error);
- } catch (exception, stackTrace) {
- response = new Response(id, requestTime,
- error: new RequestError(
- RequestErrorCode.PLUGIN_ERROR, exception.toString(),
- stackTrace: stackTrace.toString()));
- }
- if (response != null) {
- _channel.sendResponse(response);
- }
- }
-
- /**
- * Send a notification for the file at the given [path] corresponding to the
- * given [service].
- */
- void _sendNotificationForFile(String path, AnalysisService service) {
- switch (service) {
- case AnalysisService.FOLDING:
- sendFoldingNotification(path);
- break;
- case AnalysisService.HIGHLIGHTS:
- sendHighlightsNotification(path);
- break;
- case AnalysisService.NAVIGATION:
- sendNavigationNotification(path);
- break;
- case AnalysisService.OCCURRENCES:
- sendOccurrencesNotification(path);
- break;
- case AnalysisService.OUTLINE:
- sendOutlineNotification(path);
- break;
- }
- }
-}
diff --git a/analyzer_plugin/lib/protocol/protocol.dart b/analyzer_plugin/lib/protocol/protocol.dart
deleted file mode 100644
index 98c667a..0000000
--- a/analyzer_plugin/lib/protocol/protocol.dart
+++ /dev/null
@@ -1,444 +0,0 @@
-// 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_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart';
-
-/**
- * An interface for enumerated types in the protocol.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class Enum {
- /**
- * The name of the enumerated value. This should match the name of the static
- * getter which provides access to this enumerated value.
- */
- String get name;
-}
-
-/**
- * A notification that can be sent to the server about an event that occurred.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Notification {
- /**
- * The name of the JSON attribute containing the name of the event that
- * triggered the notification.
- */
- static const String EVENT = 'event';
-
- /**
- * The name of the JSON attribute containing the result values.
- */
- static const String PARAMS = 'params';
-
- /**
- * The name of the event that triggered the notification.
- */
- final String event;
-
- /**
- * A table mapping the names of notification parameters to their values, or
- * `null` if there are no notification parameters.
- */
- final Map<String, Object> params;
-
- /**
- * Initialize a newly created [Notification] to have the given [event] name.
- * If [params] is provided, it will be used as the params; otherwise no
- * params will be used.
- */
- Notification(this.event, [this.params]);
-
- /**
- * Initialize a newly created instance based on the given JSON data.
- */
- factory Notification.fromJson(Map json) {
- return new Notification(json[Notification.EVENT] as String,
- json[Notification.PARAMS] as Map<String, Object>);
- }
-
- /**
- * Return a table representing the structure of the Json object that will be
- * sent to the client to represent this response.
- */
- Map<String, Object> toJson() {
- Map<String, Object> jsonObject = {};
- jsonObject[EVENT] = event;
- if (params != null) {
- jsonObject[PARAMS] = params;
- }
- return jsonObject;
- }
-}
-
-/**
- * A request that was received from the server.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Request {
- /**
- * The name of the JSON attribute containing the id of the request.
- */
- static const String ID = 'id';
-
- /**
- * The name of the JSON attribute containing the name of the request.
- */
- static const String METHOD = 'method';
-
- /**
- * The name of the JSON attribute containing the request parameters.
- */
- static const String PARAMS = 'params';
-
- /**
- * The name of the optional JSON attribute indicating the time (milliseconds
- * since epoch) at which the server made the request.
- */
- static const String SERVER_REQUEST_TIME = 'serverRequestTime';
-
- /**
- * The unique identifier used to identify this request.
- */
- final String id;
-
- /**
- * The method being requested.
- */
- final String method;
-
- /**
- * A table mapping the names of request parameters to their values.
- */
- final Map<String, Object> params;
-
- /**
- * The time (milliseconds since epoch) at which the server made the request,
- * or `null` if this information is not provided by the server.
- */
- final int serverRequestTime;
-
- /**
- * Initialize a newly created [Request] to have the given [id] and [method]
- * name. If [params] is supplied, it is used as the "params" map for the
- * request. Otherwise an empty "params" map is allocated.
- */
- Request(this.id, this.method,
- [Map<String, Object> params, this.serverRequestTime])
- : params = params ?? <String, Object>{};
-
- /**
- * Return a request parsed from the given json, or `null` if the [data] is
- * not a valid json representation of a request. The [data] is expected to
- * have the following format:
- *
- * {
- * 'clientRequestTime': millisecondsSinceEpoch
- * 'id': String,
- * 'method': methodName,
- * 'params': {
- * paramter_name: value
- * }
- * }
- *
- * where both the parameters and clientRequestTime are optional.
- *
- * The parameters can contain any number of name/value pairs. The
- * clientRequestTime must be an int representing the time at which the client
- * issued the request (milliseconds since epoch).
- */
- factory Request.fromJson(Map<String, Object> result) {
- var id = result[Request.ID];
- var method = result[Request.METHOD];
- if (id is! String || method is! String) {
- return null;
- }
- var time = result[Request.SERVER_REQUEST_TIME];
- if (time != null && time is! int) {
- return null;
- }
- var params = result[Request.PARAMS];
- if (params is Map || params == null) {
- return new Request(id as String, method as String,
- params as Map<String, Object>, time as int);
- } else {
- return null;
- }
- }
-
- @override
- int get hashCode {
- return id.hashCode;
- }
-
- @override
- bool operator ==(Object other) {
- return other is Request &&
- id == other.id &&
- method == other.method &&
- serverRequestTime == other.serverRequestTime &&
- _equalMaps(params, other.params);
- }
-
- /**
- * Return a table representing the structure of the Json object that will be
- * sent to the server to represent this response.
- */
- Map<String, Object> toJson() {
- Map<String, Object> jsonObject = <String, Object>{};
- jsonObject[ID] = id;
- jsonObject[METHOD] = method;
- if (params.isNotEmpty) {
- jsonObject[PARAMS] = params;
- }
- if (serverRequestTime != null) {
- jsonObject[SERVER_REQUEST_TIME] = serverRequestTime;
- }
- return jsonObject;
- }
-
- bool _equalLists(List first, List second) {
- if (first == null) {
- return second == null;
- }
- if (second == null) {
- return false;
- }
- int length = first.length;
- if (length != second.length) {
- return false;
- }
- for (int i = 0; i < length; i++) {
- if (!_equalObjects(first[i], second[i])) {
- return false;
- }
- }
- return true;
- }
-
- bool _equalMaps(Map first, Map second) {
- if (first == null) {
- return second == null;
- }
- if (second == null) {
- return false;
- }
- if (first.length != second.length) {
- return false;
- }
- for (var key in first.keys) {
- if (!second.containsKey(key)) {
- return false;
- }
- if (!_equalObjects(first[key], second[key])) {
- return false;
- }
- }
- return true;
- }
-
- bool _equalObjects(Object first, Object second) {
- if (first == null) {
- return second == null;
- }
- if (second == null) {
- return false;
- }
- if (first is Map) {
- if (second is Map) {
- return _equalMaps(first, second);
- }
- return false;
- }
- if (first is List) {
- if (second is List) {
- return _equalLists(first, second);
- }
- return false;
- }
- return first == second;
- }
-}
-
-/**
- * A collection of utility methods that create instances of the generated class
- * [RequestError].
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RequestErrorFactory {
- /**
- * Return a request error representing an error condition caused by a
- * [request] that had an invalid edit object.
- */
- static RequestError invalidOverlayChangeInvalidEdit() => new RequestError(
- RequestErrorCode.INVALID_OVERLAY_CHANGE,
- 'Invalid overlay change: invalid edit');
-
- /**
- * Return a request error representing an error condition caused by a
- * [request] that attempted to change an existing overlay when no overlay
- * existed.
- */
- static RequestError invalidOverlayChangeNoContent() => new RequestError(
- RequestErrorCode.INVALID_OVERLAY_CHANGE,
- 'Invalid overlay change: no content to change');
-
- /**
- * Return a request error representing an error condition caused by a request
- * that had an invalid parameter. The [path] is the path to the invalid
- * parameter, in Javascript notation (e.g. "foo.bar" means that the parameter
- * "foo" contained a key "bar" whose value was the wrong type). The
- * [expectation] is a description of the type of data that was expected.
- */
- static RequestError invalidParameter(String path, String expectation) =>
- new RequestError(RequestErrorCode.INVALID_PARAMETER,
- "Invalid parameter '$path'. $expectation.");
-
- /**
- * Return a request error representing an error that occurred in the plugin.
- */
- static RequestError pluginError(dynamic exception, String stackTrace) =>
- new RequestError(RequestErrorCode.PLUGIN_ERROR, exception.toString(),
- stackTrace: stackTrace);
-
- /**
- * Return a request error representing an error condition caused by a request
- * with the given [method] that cannot be handled by any known handlers.
- */
- static RequestError unknownRequest(String method) => new RequestError(
- RequestErrorCode.UNKNOWN_REQUEST, 'Unknown request: $method');
-}
-
-/**
- * An exception that occurred during the handling of a request that requires
- * that an error be returned to the server.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RequestFailure implements Exception {
- /**
- * A description of the error that was encountered.
- */
- final RequestError error;
-
- /**
- * Initialize a newly created exception to return a response with the given
- * [error].
- */
- RequestFailure(this.error);
-}
-
-/**
- * A response to the server.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Response {
- /**
- * The name of the JSON attribute containing the id of the request for which
- * this is a response.
- */
- static const String ID = 'id';
-
- /**
- * The name of the JSON attribute containing the error message.
- */
- static const String ERROR = 'error';
-
- /**
- * The name of the JSON attribute containing the time at which the request was
- * handled by the plugin.
- */
- static const String REQUEST_TIME = 'requestTime';
-
- /**
- * The name of the JSON attribute containing the result values.
- */
- static const String RESULT = 'result';
-
- /**
- * The unique identifier used to identify the request that this response is
- * associated with.
- */
- final String id;
-
- /**
- * The error that was caused by attempting to handle the request, or `null` if
- * there was no error.
- */
- final RequestError error;
-
- /**
- * The time at which the request was handled by the plugin.
- */
- final int requestTime;
-
- /**
- * A table mapping the names of result fields to their values. Should be
- * `null` if there is no result to send.
- */
- Map<String, Object> result;
-
- /**
- * Initialize a newly created instance to represent a response to a request
- * with the given [id]. If [_result] is provided, it will be used as the
- * result; otherwise an empty result will be used. If an [error] is provided
- * then the response will represent an error condition.
- */
- Response(this.id, this.requestTime, {this.error, Map<String, Object> result})
- : result = result;
-
- /**
- * Initialize a newly created instance based on the given JSON data.
- */
- factory Response.fromJson(Map json) {
- try {
- Object id = json[ID];
- if (id is! String) {
- return null;
- }
- Object error = json[ERROR];
- RequestError decodedError;
- if (error is Map) {
- decodedError = new RequestError.fromJson(
- new ResponseDecoder(null), '.error', error);
- }
- Object requestTime = json[REQUEST_TIME];
- if (requestTime is! int) {
- return null;
- }
- Object result = json[RESULT];
- Map<String, Object> decodedResult;
- if (result is Map) {
- decodedResult = result as Map<String, Object>;
- }
- return new Response(id as String, requestTime as int,
- error: decodedError, result: decodedResult);
- } catch (exception) {
- return null;
- }
- }
-
- /**
- * Return a table representing the structure of the Json object that will be
- * sent to the client to represent this response.
- */
- Map<String, Object> toJson() {
- Map<String, Object> jsonObject = <String, Object>{};
- jsonObject[ID] = id;
- if (error != null) {
- jsonObject[ERROR] = error.toJson();
- }
- jsonObject[REQUEST_TIME] = requestTime;
- if (result != null) {
- jsonObject[RESULT] = result;
- }
- return jsonObject;
- }
-}
diff --git a/analyzer_plugin/lib/protocol/protocol_common.dart b/analyzer_plugin/lib/protocol/protocol_common.dart
deleted file mode 100644
index 75ea664..0000000
--- a/analyzer_plugin/lib/protocol/protocol_common.dart
+++ /dev/null
@@ -1,6262 +0,0 @@
-// 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.
-//
-// This file has been automatically generated. Please do not edit it manually.
-// To regenerate the file, use the script
-// "pkg/analysis_server/tool/spec/generate_files".
-
-import 'dart:convert' hide JsonDecoder;
-
-import 'package:analyzer/src/generated/utilities_general.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart';
-
-/**
- * AddContentOverlay
- *
- * {
- * "type": "add"
- * "content": String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AddContentOverlay implements HasToJson {
- String _content;
-
- /**
- * The new content of the file.
- */
- String get content => _content;
-
- /**
- * The new content of the file.
- */
- set content(String value) {
- assert(value != null);
- this._content = value;
- }
-
- AddContentOverlay(String content) {
- this.content = content;
- }
-
- factory AddContentOverlay.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- if (json["type"] != "add") {
- throw jsonDecoder.mismatch(jsonPath, "equal " + "add", json);
- }
- String content;
- if (json.containsKey("content")) {
- content =
- jsonDecoder.decodeString(jsonPath + ".content", json["content"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "content");
- }
- return new AddContentOverlay(content);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "AddContentOverlay", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["type"] = "add";
- result["content"] = content;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AddContentOverlay) {
- return content == other.content;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, 704418402);
- hash = JenkinsSmiHash.combine(hash, content.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * AnalysisError
- *
- * {
- * "severity": AnalysisErrorSeverity
- * "type": AnalysisErrorType
- * "location": Location
- * "message": String
- * "correction": optional String
- * "code": String
- * "url": optional String
- * "contextMessages": optional List<DiagnosticMessage>
- * "hasFix": optional bool
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisError implements HasToJson {
- AnalysisErrorSeverity _severity;
-
- AnalysisErrorType _type;
-
- Location _location;
-
- String _message;
-
- String _correction;
-
- String _code;
-
- String _url;
-
- List<DiagnosticMessage> _contextMessages;
-
- bool _hasFix;
-
- /**
- * The severity of the error.
- */
- AnalysisErrorSeverity get severity => _severity;
-
- /**
- * The severity of the error.
- */
- set severity(AnalysisErrorSeverity value) {
- assert(value != null);
- this._severity = value;
- }
-
- /**
- * The type of the error.
- */
- AnalysisErrorType get type => _type;
-
- /**
- * The type of the error.
- */
- set type(AnalysisErrorType value) {
- assert(value != null);
- this._type = value;
- }
-
- /**
- * The location associated with the error.
- */
- Location get location => _location;
-
- /**
- * The location associated with the error.
- */
- set location(Location value) {
- assert(value != null);
- this._location = value;
- }
-
- /**
- * The message to be displayed for this error. The message should indicate
- * what is wrong with the code and why it is wrong.
- */
- String get message => _message;
-
- /**
- * The message to be displayed for this error. The message should indicate
- * what is wrong with the code and why it is wrong.
- */
- set message(String value) {
- assert(value != null);
- this._message = value;
- }
-
- /**
- * The correction message to be displayed for this error. The correction
- * message should indicate how the user can fix the error. The field is
- * omitted if there is no correction message associated with the error code.
- */
- String get correction => _correction;
-
- /**
- * The correction message to be displayed for this error. The correction
- * message should indicate how the user can fix the error. The field is
- * omitted if there is no correction message associated with the error code.
- */
- set correction(String value) {
- this._correction = value;
- }
-
- /**
- * The name, as a string, of the error code associated with this error.
- */
- String get code => _code;
-
- /**
- * The name, as a string, of the error code associated with this error.
- */
- set code(String value) {
- assert(value != null);
- this._code = value;
- }
-
- /**
- * The URL of a page containing documentation associated with this error.
- */
- String get url => _url;
-
- /**
- * The URL of a page containing documentation associated with this error.
- */
- set url(String value) {
- this._url = value;
- }
-
- /**
- * Additional messages associated with this diagnostic that provide context
- * to help the user understand the diagnostic.
- */
- List<DiagnosticMessage> get contextMessages => _contextMessages;
-
- /**
- * Additional messages associated with this diagnostic that provide context
- * to help the user understand the diagnostic.
- */
- set contextMessages(List<DiagnosticMessage> value) {
- this._contextMessages = value;
- }
-
- /**
- * A hint to indicate to interested clients that this error has an associated
- * fix (or fixes). The absence of this field implies there are not known to
- * be fixes. Note that since the operation to calculate whether fixes apply
- * needs to be performant it is possible that complicated tests will be
- * skipped and a false negative returned. For this reason, this attribute
- * should be treated as a "hint". Despite the possibility of false negatives,
- * no false positives should be returned. If a client sees this flag set they
- * can proceed with the confidence that there are in fact associated fixes.
- */
- bool get hasFix => _hasFix;
-
- /**
- * A hint to indicate to interested clients that this error has an associated
- * fix (or fixes). The absence of this field implies there are not known to
- * be fixes. Note that since the operation to calculate whether fixes apply
- * needs to be performant it is possible that complicated tests will be
- * skipped and a false negative returned. For this reason, this attribute
- * should be treated as a "hint". Despite the possibility of false negatives,
- * no false positives should be returned. If a client sees this flag set they
- * can proceed with the confidence that there are in fact associated fixes.
- */
- set hasFix(bool value) {
- this._hasFix = value;
- }
-
- AnalysisError(AnalysisErrorSeverity severity, AnalysisErrorType type,
- Location location, String message, String code,
- {String correction,
- String url,
- List<DiagnosticMessage> contextMessages,
- bool hasFix}) {
- this.severity = severity;
- this.type = type;
- this.location = location;
- this.message = message;
- this.correction = correction;
- this.code = code;
- this.url = url;
- this.contextMessages = contextMessages;
- this.hasFix = hasFix;
- }
-
- factory AnalysisError.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- AnalysisErrorSeverity severity;
- if (json.containsKey("severity")) {
- severity = new AnalysisErrorSeverity.fromJson(
- jsonDecoder, jsonPath + ".severity", json["severity"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "severity");
- }
- AnalysisErrorType type;
- if (json.containsKey("type")) {
- type = new AnalysisErrorType.fromJson(
- jsonDecoder, jsonPath + ".type", json["type"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "type");
- }
- Location location;
- if (json.containsKey("location")) {
- location = new Location.fromJson(
- jsonDecoder, jsonPath + ".location", json["location"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "location");
- }
- String message;
- if (json.containsKey("message")) {
- message =
- jsonDecoder.decodeString(jsonPath + ".message", json["message"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "message");
- }
- String correction;
- if (json.containsKey("correction")) {
- correction = jsonDecoder.decodeString(
- jsonPath + ".correction", json["correction"]);
- }
- String code;
- if (json.containsKey("code")) {
- code = jsonDecoder.decodeString(jsonPath + ".code", json["code"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "code");
- }
- String url;
- if (json.containsKey("url")) {
- url = jsonDecoder.decodeString(jsonPath + ".url", json["url"]);
- }
- List<DiagnosticMessage> contextMessages;
- if (json.containsKey("contextMessages")) {
- contextMessages = jsonDecoder.decodeList(
- jsonPath + ".contextMessages",
- json["contextMessages"],
- (String jsonPath, Object json) =>
- new DiagnosticMessage.fromJson(jsonDecoder, jsonPath, json));
- }
- bool hasFix;
- if (json.containsKey("hasFix")) {
- hasFix = jsonDecoder.decodeBool(jsonPath + ".hasFix", json["hasFix"]);
- }
- return new AnalysisError(severity, type, location, message, code,
- correction: correction,
- url: url,
- contextMessages: contextMessages,
- hasFix: hasFix);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "AnalysisError", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["severity"] = severity.toJson();
- result["type"] = type.toJson();
- result["location"] = location.toJson();
- result["message"] = message;
- if (correction != null) {
- result["correction"] = correction;
- }
- result["code"] = code;
- if (url != null) {
- result["url"] = url;
- }
- if (contextMessages != null) {
- result["contextMessages"] = contextMessages
- .map((DiagnosticMessage value) => value.toJson())
- .toList();
- }
- if (hasFix != null) {
- result["hasFix"] = hasFix;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisError) {
- return severity == other.severity &&
- type == other.type &&
- location == other.location &&
- message == other.message &&
- correction == other.correction &&
- code == other.code &&
- url == other.url &&
- listEqual(contextMessages, other.contextMessages,
- (DiagnosticMessage a, DiagnosticMessage b) => a == b) &&
- hasFix == other.hasFix;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, severity.hashCode);
- hash = JenkinsSmiHash.combine(hash, type.hashCode);
- hash = JenkinsSmiHash.combine(hash, location.hashCode);
- hash = JenkinsSmiHash.combine(hash, message.hashCode);
- hash = JenkinsSmiHash.combine(hash, correction.hashCode);
- hash = JenkinsSmiHash.combine(hash, code.hashCode);
- hash = JenkinsSmiHash.combine(hash, url.hashCode);
- hash = JenkinsSmiHash.combine(hash, contextMessages.hashCode);
- hash = JenkinsSmiHash.combine(hash, hasFix.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * AnalysisErrorSeverity
- *
- * enum {
- * INFO
- * WARNING
- * ERROR
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisErrorSeverity implements Enum {
- static const AnalysisErrorSeverity INFO =
- const AnalysisErrorSeverity._("INFO");
-
- static const AnalysisErrorSeverity WARNING =
- const AnalysisErrorSeverity._("WARNING");
-
- static const AnalysisErrorSeverity ERROR =
- const AnalysisErrorSeverity._("ERROR");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<AnalysisErrorSeverity> VALUES =
- const <AnalysisErrorSeverity>[INFO, WARNING, ERROR];
-
- @override
- final String name;
-
- const AnalysisErrorSeverity._(this.name);
-
- factory AnalysisErrorSeverity(String name) {
- switch (name) {
- case "INFO":
- return INFO;
- case "WARNING":
- return WARNING;
- case "ERROR":
- return ERROR;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory AnalysisErrorSeverity.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new AnalysisErrorSeverity(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "AnalysisErrorSeverity", json);
- }
-
- @override
- String toString() => "AnalysisErrorSeverity.$name";
-
- String toJson() => name;
-}
-
-/**
- * AnalysisErrorType
- *
- * enum {
- * CHECKED_MODE_COMPILE_TIME_ERROR
- * COMPILE_TIME_ERROR
- * HINT
- * LINT
- * STATIC_TYPE_WARNING
- * STATIC_WARNING
- * SYNTACTIC_ERROR
- * TODO
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisErrorType implements Enum {
- static const AnalysisErrorType CHECKED_MODE_COMPILE_TIME_ERROR =
- const AnalysisErrorType._("CHECKED_MODE_COMPILE_TIME_ERROR");
-
- static const AnalysisErrorType COMPILE_TIME_ERROR =
- const AnalysisErrorType._("COMPILE_TIME_ERROR");
-
- static const AnalysisErrorType HINT = const AnalysisErrorType._("HINT");
-
- static const AnalysisErrorType LINT = const AnalysisErrorType._("LINT");
-
- static const AnalysisErrorType STATIC_TYPE_WARNING =
- const AnalysisErrorType._("STATIC_TYPE_WARNING");
-
- static const AnalysisErrorType STATIC_WARNING =
- const AnalysisErrorType._("STATIC_WARNING");
-
- static const AnalysisErrorType SYNTACTIC_ERROR =
- const AnalysisErrorType._("SYNTACTIC_ERROR");
-
- static const AnalysisErrorType TODO = const AnalysisErrorType._("TODO");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<AnalysisErrorType> VALUES = const <AnalysisErrorType>[
- CHECKED_MODE_COMPILE_TIME_ERROR,
- COMPILE_TIME_ERROR,
- HINT,
- LINT,
- STATIC_TYPE_WARNING,
- STATIC_WARNING,
- SYNTACTIC_ERROR,
- TODO
- ];
-
- @override
- final String name;
-
- const AnalysisErrorType._(this.name);
-
- factory AnalysisErrorType(String name) {
- switch (name) {
- case "CHECKED_MODE_COMPILE_TIME_ERROR":
- return CHECKED_MODE_COMPILE_TIME_ERROR;
- case "COMPILE_TIME_ERROR":
- return COMPILE_TIME_ERROR;
- case "HINT":
- return HINT;
- case "LINT":
- return LINT;
- case "STATIC_TYPE_WARNING":
- return STATIC_TYPE_WARNING;
- case "STATIC_WARNING":
- return STATIC_WARNING;
- case "SYNTACTIC_ERROR":
- return SYNTACTIC_ERROR;
- case "TODO":
- return TODO;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory AnalysisErrorType.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new AnalysisErrorType(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "AnalysisErrorType", json);
- }
-
- @override
- String toString() => "AnalysisErrorType.$name";
-
- String toJson() => name;
-}
-
-/**
- * ChangeContentOverlay
- *
- * {
- * "type": "change"
- * "edits": List<SourceEdit>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ChangeContentOverlay implements HasToJson {
- List<SourceEdit> _edits;
-
- /**
- * The edits to be applied to the file.
- */
- List<SourceEdit> get edits => _edits;
-
- /**
- * The edits to be applied to the file.
- */
- set edits(List<SourceEdit> value) {
- assert(value != null);
- this._edits = value;
- }
-
- ChangeContentOverlay(List<SourceEdit> edits) {
- this.edits = edits;
- }
-
- factory ChangeContentOverlay.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- if (json["type"] != "change") {
- throw jsonDecoder.mismatch(jsonPath, "equal " + "change", json);
- }
- List<SourceEdit> edits;
- if (json.containsKey("edits")) {
- edits = jsonDecoder.decodeList(
- jsonPath + ".edits",
- json["edits"],
- (String jsonPath, Object json) =>
- new SourceEdit.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edits");
- }
- return new ChangeContentOverlay(edits);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "ChangeContentOverlay", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["type"] = "change";
- result["edits"] = edits.map((SourceEdit value) => value.toJson()).toList();
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ChangeContentOverlay) {
- return listEqual(
- edits, other.edits, (SourceEdit a, SourceEdit b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, 873118866);
- hash = JenkinsSmiHash.combine(hash, edits.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * CompletionSuggestion
- *
- * {
- * "kind": CompletionSuggestionKind
- * "relevance": int
- * "completion": String
- * "displayText": optional String
- * "selectionOffset": int
- * "selectionLength": int
- * "isDeprecated": bool
- * "isPotential": bool
- * "docSummary": optional String
- * "docComplete": optional String
- * "declaringType": optional String
- * "defaultArgumentListString": optional String
- * "defaultArgumentListTextRanges": optional List<int>
- * "element": optional Element
- * "returnType": optional String
- * "parameterNames": optional List<String>
- * "parameterTypes": optional List<String>
- * "requiredParameterCount": optional int
- * "hasNamedParameters": optional bool
- * "parameterName": optional String
- * "parameterType": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class CompletionSuggestion implements HasToJson {
- CompletionSuggestionKind _kind;
-
- int _relevance;
-
- String _completion;
-
- String _displayText;
-
- int _selectionOffset;
-
- int _selectionLength;
-
- bool _isDeprecated;
-
- bool _isPotential;
-
- String _docSummary;
-
- String _docComplete;
-
- String _declaringType;
-
- String _defaultArgumentListString;
-
- List<int> _defaultArgumentListTextRanges;
-
- Element _element;
-
- String _returnType;
-
- List<String> _parameterNames;
-
- List<String> _parameterTypes;
-
- int _requiredParameterCount;
-
- bool _hasNamedParameters;
-
- String _parameterName;
-
- String _parameterType;
-
- /**
- * The kind of element being suggested.
- */
- CompletionSuggestionKind get kind => _kind;
-
- /**
- * The kind of element being suggested.
- */
- set kind(CompletionSuggestionKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The relevance of this completion suggestion where a higher number
- * indicates a higher relevance.
- */
- int get relevance => _relevance;
-
- /**
- * The relevance of this completion suggestion where a higher number
- * indicates a higher relevance.
- */
- set relevance(int value) {
- assert(value != null);
- this._relevance = value;
- }
-
- /**
- * The identifier to be inserted if the suggestion is selected. If the
- * suggestion is for a method or function, the client might want to
- * additionally insert a template for the parameters. The information
- * required in order to do so is contained in other fields.
- */
- String get completion => _completion;
-
- /**
- * The identifier to be inserted if the suggestion is selected. If the
- * suggestion is for a method or function, the client might want to
- * additionally insert a template for the parameters. The information
- * required in order to do so is contained in other fields.
- */
- set completion(String value) {
- assert(value != null);
- this._completion = value;
- }
-
- /**
- * Text to be displayed in, for example, a completion pop-up. This field is
- * only defined if the displayed text should be different than the
- * completion. Otherwise it is omitted.
- */
- String get displayText => _displayText;
-
- /**
- * Text to be displayed in, for example, a completion pop-up. This field is
- * only defined if the displayed text should be different than the
- * completion. Otherwise it is omitted.
- */
- set displayText(String value) {
- this._displayText = value;
- }
-
- /**
- * The offset, relative to the beginning of the completion, of where the
- * selection should be placed after insertion.
- */
- int get selectionOffset => _selectionOffset;
-
- /**
- * The offset, relative to the beginning of the completion, of where the
- * selection should be placed after insertion.
- */
- set selectionOffset(int value) {
- assert(value != null);
- this._selectionOffset = value;
- }
-
- /**
- * The number of characters that should be selected after insertion.
- */
- int get selectionLength => _selectionLength;
-
- /**
- * The number of characters that should be selected after insertion.
- */
- set selectionLength(int value) {
- assert(value != null);
- this._selectionLength = value;
- }
-
- /**
- * True if the suggested element is deprecated.
- */
- bool get isDeprecated => _isDeprecated;
-
- /**
- * True if the suggested element is deprecated.
- */
- set isDeprecated(bool value) {
- assert(value != null);
- this._isDeprecated = value;
- }
-
- /**
- * True if the element is not known to be valid for the target. This happens
- * if the type of the target is dynamic.
- */
- bool get isPotential => _isPotential;
-
- /**
- * True if the element is not known to be valid for the target. This happens
- * if the type of the target is dynamic.
- */
- set isPotential(bool value) {
- assert(value != null);
- this._isPotential = value;
- }
-
- /**
- * An abbreviated version of the Dartdoc associated with the element being
- * suggested. This field is omitted if there is no Dartdoc associated with
- * the element.
- */
- String get docSummary => _docSummary;
-
- /**
- * An abbreviated version of the Dartdoc associated with the element being
- * suggested. This field is omitted if there is no Dartdoc associated with
- * the element.
- */
- set docSummary(String value) {
- this._docSummary = value;
- }
-
- /**
- * The Dartdoc associated with the element being suggested. This field is
- * omitted if there is no Dartdoc associated with the element.
- */
- String get docComplete => _docComplete;
-
- /**
- * The Dartdoc associated with the element being suggested. This field is
- * omitted if there is no Dartdoc associated with the element.
- */
- set docComplete(String value) {
- this._docComplete = value;
- }
-
- /**
- * The class that declares the element being suggested. This field is omitted
- * if the suggested element is not a member of a class.
- */
- String get declaringType => _declaringType;
-
- /**
- * The class that declares the element being suggested. This field is omitted
- * if the suggested element is not a member of a class.
- */
- set declaringType(String value) {
- this._declaringType = value;
- }
-
- /**
- * A default String for use in generating argument list source contents on
- * the client side.
- */
- String get defaultArgumentListString => _defaultArgumentListString;
-
- /**
- * A default String for use in generating argument list source contents on
- * the client side.
- */
- set defaultArgumentListString(String value) {
- this._defaultArgumentListString = value;
- }
-
- /**
- * Pairs of offsets and lengths describing 'defaultArgumentListString' text
- * ranges suitable for use by clients to set up linked edits of default
- * argument source contents. For example, given an argument list string 'x,
- * y', the corresponding text range [0, 1, 3, 1], indicates two text ranges
- * of length 1, starting at offsets 0 and 3. Clients can use these ranges to
- * treat the 'x' and 'y' values specially for linked edits.
- */
- List<int> get defaultArgumentListTextRanges => _defaultArgumentListTextRanges;
-
- /**
- * Pairs of offsets and lengths describing 'defaultArgumentListString' text
- * ranges suitable for use by clients to set up linked edits of default
- * argument source contents. For example, given an argument list string 'x,
- * y', the corresponding text range [0, 1, 3, 1], indicates two text ranges
- * of length 1, starting at offsets 0 and 3. Clients can use these ranges to
- * treat the 'x' and 'y' values specially for linked edits.
- */
- set defaultArgumentListTextRanges(List<int> value) {
- this._defaultArgumentListTextRanges = value;
- }
-
- /**
- * Information about the element reference being suggested.
- */
- Element get element => _element;
-
- /**
- * Information about the element reference being suggested.
- */
- set element(Element value) {
- this._element = value;
- }
-
- /**
- * The return type of the getter, function or method or the type of the field
- * being suggested. This field is omitted if the suggested element is not a
- * getter, function or method.
- */
- String get returnType => _returnType;
-
- /**
- * The return type of the getter, function or method or the type of the field
- * being suggested. This field is omitted if the suggested element is not a
- * getter, function or method.
- */
- set returnType(String value) {
- this._returnType = value;
- }
-
- /**
- * The names of the parameters of the function or method being suggested.
- * This field is omitted if the suggested element is not a setter, function
- * or method.
- */
- List<String> get parameterNames => _parameterNames;
-
- /**
- * The names of the parameters of the function or method being suggested.
- * This field is omitted if the suggested element is not a setter, function
- * or method.
- */
- set parameterNames(List<String> value) {
- this._parameterNames = value;
- }
-
- /**
- * The types of the parameters of the function or method being suggested.
- * This field is omitted if the parameterNames field is omitted.
- */
- List<String> get parameterTypes => _parameterTypes;
-
- /**
- * The types of the parameters of the function or method being suggested.
- * This field is omitted if the parameterNames field is omitted.
- */
- set parameterTypes(List<String> value) {
- this._parameterTypes = value;
- }
-
- /**
- * The number of required parameters for the function or method being
- * suggested. This field is omitted if the parameterNames field is omitted.
- */
- int get requiredParameterCount => _requiredParameterCount;
-
- /**
- * The number of required parameters for the function or method being
- * suggested. This field is omitted if the parameterNames field is omitted.
- */
- set requiredParameterCount(int value) {
- this._requiredParameterCount = value;
- }
-
- /**
- * True if the function or method being suggested has at least one named
- * parameter. This field is omitted if the parameterNames field is omitted.
- */
- bool get hasNamedParameters => _hasNamedParameters;
-
- /**
- * True if the function or method being suggested has at least one named
- * parameter. This field is omitted if the parameterNames field is omitted.
- */
- set hasNamedParameters(bool value) {
- this._hasNamedParameters = value;
- }
-
- /**
- * The name of the optional parameter being suggested. This field is omitted
- * if the suggestion is not the addition of an optional argument within an
- * argument list.
- */
- String get parameterName => _parameterName;
-
- /**
- * The name of the optional parameter being suggested. This field is omitted
- * if the suggestion is not the addition of an optional argument within an
- * argument list.
- */
- set parameterName(String value) {
- this._parameterName = value;
- }
-
- /**
- * The type of the options parameter being suggested. This field is omitted
- * if the parameterName field is omitted.
- */
- String get parameterType => _parameterType;
-
- /**
- * The type of the options parameter being suggested. This field is omitted
- * if the parameterName field is omitted.
- */
- set parameterType(String value) {
- this._parameterType = value;
- }
-
- CompletionSuggestion(
- CompletionSuggestionKind kind,
- int relevance,
- String completion,
- int selectionOffset,
- int selectionLength,
- bool isDeprecated,
- bool isPotential,
- {String displayText,
- String docSummary,
- String docComplete,
- String declaringType,
- String defaultArgumentListString,
- List<int> defaultArgumentListTextRanges,
- Element element,
- String returnType,
- List<String> parameterNames,
- List<String> parameterTypes,
- int requiredParameterCount,
- bool hasNamedParameters,
- String parameterName,
- String parameterType}) {
- this.kind = kind;
- this.relevance = relevance;
- this.completion = completion;
- this.displayText = displayText;
- this.selectionOffset = selectionOffset;
- this.selectionLength = selectionLength;
- this.isDeprecated = isDeprecated;
- this.isPotential = isPotential;
- this.docSummary = docSummary;
- this.docComplete = docComplete;
- this.declaringType = declaringType;
- this.defaultArgumentListString = defaultArgumentListString;
- this.defaultArgumentListTextRanges = defaultArgumentListTextRanges;
- this.element = element;
- this.returnType = returnType;
- this.parameterNames = parameterNames;
- this.parameterTypes = parameterTypes;
- this.requiredParameterCount = requiredParameterCount;
- this.hasNamedParameters = hasNamedParameters;
- this.parameterName = parameterName;
- this.parameterType = parameterType;
- }
-
- factory CompletionSuggestion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- CompletionSuggestionKind kind;
- if (json.containsKey("kind")) {
- kind = new CompletionSuggestionKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- int relevance;
- if (json.containsKey("relevance")) {
- relevance =
- jsonDecoder.decodeInt(jsonPath + ".relevance", json["relevance"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "relevance");
- }
- String completion;
- if (json.containsKey("completion")) {
- completion = jsonDecoder.decodeString(
- jsonPath + ".completion", json["completion"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "completion");
- }
- String displayText;
- if (json.containsKey("displayText")) {
- displayText = jsonDecoder.decodeString(
- jsonPath + ".displayText", json["displayText"]);
- }
- int selectionOffset;
- if (json.containsKey("selectionOffset")) {
- selectionOffset = jsonDecoder.decodeInt(
- jsonPath + ".selectionOffset", json["selectionOffset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "selectionOffset");
- }
- int selectionLength;
- if (json.containsKey("selectionLength")) {
- selectionLength = jsonDecoder.decodeInt(
- jsonPath + ".selectionLength", json["selectionLength"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "selectionLength");
- }
- bool isDeprecated;
- if (json.containsKey("isDeprecated")) {
- isDeprecated = jsonDecoder.decodeBool(
- jsonPath + ".isDeprecated", json["isDeprecated"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "isDeprecated");
- }
- bool isPotential;
- if (json.containsKey("isPotential")) {
- isPotential = jsonDecoder.decodeBool(
- jsonPath + ".isPotential", json["isPotential"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "isPotential");
- }
- String docSummary;
- if (json.containsKey("docSummary")) {
- docSummary = jsonDecoder.decodeString(
- jsonPath + ".docSummary", json["docSummary"]);
- }
- String docComplete;
- if (json.containsKey("docComplete")) {
- docComplete = jsonDecoder.decodeString(
- jsonPath + ".docComplete", json["docComplete"]);
- }
- String declaringType;
- if (json.containsKey("declaringType")) {
- declaringType = jsonDecoder.decodeString(
- jsonPath + ".declaringType", json["declaringType"]);
- }
- String defaultArgumentListString;
- if (json.containsKey("defaultArgumentListString")) {
- defaultArgumentListString = jsonDecoder.decodeString(
- jsonPath + ".defaultArgumentListString",
- json["defaultArgumentListString"]);
- }
- List<int> defaultArgumentListTextRanges;
- if (json.containsKey("defaultArgumentListTextRanges")) {
- defaultArgumentListTextRanges = jsonDecoder.decodeList(
- jsonPath + ".defaultArgumentListTextRanges",
- json["defaultArgumentListTextRanges"],
- jsonDecoder.decodeInt);
- }
- Element element;
- if (json.containsKey("element")) {
- element = new Element.fromJson(
- jsonDecoder, jsonPath + ".element", json["element"]);
- }
- String returnType;
- if (json.containsKey("returnType")) {
- returnType = jsonDecoder.decodeString(
- jsonPath + ".returnType", json["returnType"]);
- }
- List<String> parameterNames;
- if (json.containsKey("parameterNames")) {
- parameterNames = jsonDecoder.decodeList(jsonPath + ".parameterNames",
- json["parameterNames"], jsonDecoder.decodeString);
- }
- List<String> parameterTypes;
- if (json.containsKey("parameterTypes")) {
- parameterTypes = jsonDecoder.decodeList(jsonPath + ".parameterTypes",
- json["parameterTypes"], jsonDecoder.decodeString);
- }
- int requiredParameterCount;
- if (json.containsKey("requiredParameterCount")) {
- requiredParameterCount = jsonDecoder.decodeInt(
- jsonPath + ".requiredParameterCount",
- json["requiredParameterCount"]);
- }
- bool hasNamedParameters;
- if (json.containsKey("hasNamedParameters")) {
- hasNamedParameters = jsonDecoder.decodeBool(
- jsonPath + ".hasNamedParameters", json["hasNamedParameters"]);
- }
- String parameterName;
- if (json.containsKey("parameterName")) {
- parameterName = jsonDecoder.decodeString(
- jsonPath + ".parameterName", json["parameterName"]);
- }
- String parameterType;
- if (json.containsKey("parameterType")) {
- parameterType = jsonDecoder.decodeString(
- jsonPath + ".parameterType", json["parameterType"]);
- }
- return new CompletionSuggestion(kind, relevance, completion,
- selectionOffset, selectionLength, isDeprecated, isPotential,
- displayText: displayText,
- docSummary: docSummary,
- docComplete: docComplete,
- declaringType: declaringType,
- defaultArgumentListString: defaultArgumentListString,
- defaultArgumentListTextRanges: defaultArgumentListTextRanges,
- element: element,
- returnType: returnType,
- parameterNames: parameterNames,
- parameterTypes: parameterTypes,
- requiredParameterCount: requiredParameterCount,
- hasNamedParameters: hasNamedParameters,
- parameterName: parameterName,
- parameterType: parameterType);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "CompletionSuggestion", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kind"] = kind.toJson();
- result["relevance"] = relevance;
- result["completion"] = completion;
- if (displayText != null) {
- result["displayText"] = displayText;
- }
- result["selectionOffset"] = selectionOffset;
- result["selectionLength"] = selectionLength;
- result["isDeprecated"] = isDeprecated;
- result["isPotential"] = isPotential;
- if (docSummary != null) {
- result["docSummary"] = docSummary;
- }
- if (docComplete != null) {
- result["docComplete"] = docComplete;
- }
- if (declaringType != null) {
- result["declaringType"] = declaringType;
- }
- if (defaultArgumentListString != null) {
- result["defaultArgumentListString"] = defaultArgumentListString;
- }
- if (defaultArgumentListTextRanges != null) {
- result["defaultArgumentListTextRanges"] = defaultArgumentListTextRanges;
- }
- if (element != null) {
- result["element"] = element.toJson();
- }
- if (returnType != null) {
- result["returnType"] = returnType;
- }
- if (parameterNames != null) {
- result["parameterNames"] = parameterNames;
- }
- if (parameterTypes != null) {
- result["parameterTypes"] = parameterTypes;
- }
- if (requiredParameterCount != null) {
- result["requiredParameterCount"] = requiredParameterCount;
- }
- if (hasNamedParameters != null) {
- result["hasNamedParameters"] = hasNamedParameters;
- }
- if (parameterName != null) {
- result["parameterName"] = parameterName;
- }
- if (parameterType != null) {
- result["parameterType"] = parameterType;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is CompletionSuggestion) {
- return kind == other.kind &&
- relevance == other.relevance &&
- completion == other.completion &&
- displayText == other.displayText &&
- selectionOffset == other.selectionOffset &&
- selectionLength == other.selectionLength &&
- isDeprecated == other.isDeprecated &&
- isPotential == other.isPotential &&
- docSummary == other.docSummary &&
- docComplete == other.docComplete &&
- declaringType == other.declaringType &&
- defaultArgumentListString == other.defaultArgumentListString &&
- listEqual(defaultArgumentListTextRanges,
- other.defaultArgumentListTextRanges, (int a, int b) => a == b) &&
- element == other.element &&
- returnType == other.returnType &&
- listEqual(parameterNames, other.parameterNames,
- (String a, String b) => a == b) &&
- listEqual(parameterTypes, other.parameterTypes,
- (String a, String b) => a == b) &&
- requiredParameterCount == other.requiredParameterCount &&
- hasNamedParameters == other.hasNamedParameters &&
- parameterName == other.parameterName &&
- parameterType == other.parameterType;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, relevance.hashCode);
- hash = JenkinsSmiHash.combine(hash, completion.hashCode);
- hash = JenkinsSmiHash.combine(hash, displayText.hashCode);
- hash = JenkinsSmiHash.combine(hash, selectionOffset.hashCode);
- hash = JenkinsSmiHash.combine(hash, selectionLength.hashCode);
- hash = JenkinsSmiHash.combine(hash, isDeprecated.hashCode);
- hash = JenkinsSmiHash.combine(hash, isPotential.hashCode);
- hash = JenkinsSmiHash.combine(hash, docSummary.hashCode);
- hash = JenkinsSmiHash.combine(hash, docComplete.hashCode);
- hash = JenkinsSmiHash.combine(hash, declaringType.hashCode);
- hash = JenkinsSmiHash.combine(hash, defaultArgumentListString.hashCode);
- hash = JenkinsSmiHash.combine(hash, defaultArgumentListTextRanges.hashCode);
- hash = JenkinsSmiHash.combine(hash, element.hashCode);
- hash = JenkinsSmiHash.combine(hash, returnType.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameterNames.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameterTypes.hashCode);
- hash = JenkinsSmiHash.combine(hash, requiredParameterCount.hashCode);
- hash = JenkinsSmiHash.combine(hash, hasNamedParameters.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameterName.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameterType.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * CompletionSuggestionKind
- *
- * enum {
- * ARGUMENT_LIST
- * IMPORT
- * IDENTIFIER
- * INVOCATION
- * KEYWORD
- * NAMED_ARGUMENT
- * OPTIONAL_ARGUMENT
- * OVERRIDE
- * PARAMETER
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class CompletionSuggestionKind implements Enum {
- /**
- * A list of arguments for the method or function that is being invoked. For
- * this suggestion kind, the completion field is a textual representation of
- * the invocation and the parameterNames, parameterTypes, and
- * requiredParameterCount attributes are defined.
- */
- static const CompletionSuggestionKind ARGUMENT_LIST =
- const CompletionSuggestionKind._("ARGUMENT_LIST");
-
- static const CompletionSuggestionKind IMPORT =
- const CompletionSuggestionKind._("IMPORT");
-
- /**
- * The element identifier should be inserted at the completion location. For
- * example "someMethod" in import 'myLib.dart' show someMethod;. For
- * suggestions of this kind, the element attribute is defined and the
- * completion field is the element's identifier.
- */
- static const CompletionSuggestionKind IDENTIFIER =
- const CompletionSuggestionKind._("IDENTIFIER");
-
- /**
- * The element is being invoked at the completion location. For example,
- * 'someMethod' in x.someMethod();. For suggestions of this kind, the element
- * attribute is defined and the completion field is the element's identifier.
- */
- static const CompletionSuggestionKind INVOCATION =
- const CompletionSuggestionKind._("INVOCATION");
-
- /**
- * A keyword is being suggested. For suggestions of this kind, the completion
- * is the keyword.
- */
- static const CompletionSuggestionKind KEYWORD =
- const CompletionSuggestionKind._("KEYWORD");
-
- /**
- * A named argument for the current call site is being suggested. For
- * suggestions of this kind, the completion is the named argument identifier
- * including a trailing ':' and a space.
- */
- static const CompletionSuggestionKind NAMED_ARGUMENT =
- const CompletionSuggestionKind._("NAMED_ARGUMENT");
-
- static const CompletionSuggestionKind OPTIONAL_ARGUMENT =
- const CompletionSuggestionKind._("OPTIONAL_ARGUMENT");
-
- /**
- * An overriding implementation of a class member is being suggested.
- */
- static const CompletionSuggestionKind OVERRIDE =
- const CompletionSuggestionKind._("OVERRIDE");
-
- static const CompletionSuggestionKind PARAMETER =
- const CompletionSuggestionKind._("PARAMETER");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<CompletionSuggestionKind> VALUES =
- const <CompletionSuggestionKind>[
- ARGUMENT_LIST,
- IMPORT,
- IDENTIFIER,
- INVOCATION,
- KEYWORD,
- NAMED_ARGUMENT,
- OPTIONAL_ARGUMENT,
- OVERRIDE,
- PARAMETER
- ];
-
- @override
- final String name;
-
- const CompletionSuggestionKind._(this.name);
-
- factory CompletionSuggestionKind(String name) {
- switch (name) {
- case "ARGUMENT_LIST":
- return ARGUMENT_LIST;
- case "IMPORT":
- return IMPORT;
- case "IDENTIFIER":
- return IDENTIFIER;
- case "INVOCATION":
- return INVOCATION;
- case "KEYWORD":
- return KEYWORD;
- case "NAMED_ARGUMENT":
- return NAMED_ARGUMENT;
- case "OPTIONAL_ARGUMENT":
- return OPTIONAL_ARGUMENT;
- case "OVERRIDE":
- return OVERRIDE;
- case "PARAMETER":
- return PARAMETER;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory CompletionSuggestionKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new CompletionSuggestionKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "CompletionSuggestionKind", json);
- }
-
- @override
- String toString() => "CompletionSuggestionKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * DiagnosticMessage
- *
- * {
- * "message": String
- * "location": Location
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class DiagnosticMessage implements HasToJson {
- String _message;
-
- Location _location;
-
- /**
- * The message to be displayed to the user.
- */
- String get message => _message;
-
- /**
- * The message to be displayed to the user.
- */
- set message(String value) {
- assert(value != null);
- this._message = value;
- }
-
- /**
- * The location associated with or referenced by the message. Clients should
- * provide the ability to navigate to the location.
- */
- Location get location => _location;
-
- /**
- * The location associated with or referenced by the message. Clients should
- * provide the ability to navigate to the location.
- */
- set location(Location value) {
- assert(value != null);
- this._location = value;
- }
-
- DiagnosticMessage(String message, Location location) {
- this.message = message;
- this.location = location;
- }
-
- factory DiagnosticMessage.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String message;
- if (json.containsKey("message")) {
- message =
- jsonDecoder.decodeString(jsonPath + ".message", json["message"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "message");
- }
- Location location;
- if (json.containsKey("location")) {
- location = new Location.fromJson(
- jsonDecoder, jsonPath + ".location", json["location"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "location");
- }
- return new DiagnosticMessage(message, location);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "DiagnosticMessage", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["message"] = message;
- result["location"] = location.toJson();
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is DiagnosticMessage) {
- return message == other.message && location == other.location;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, message.hashCode);
- hash = JenkinsSmiHash.combine(hash, location.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * Element
- *
- * {
- * "kind": ElementKind
- * "name": String
- * "location": optional Location
- * "flags": int
- * "parameters": optional String
- * "returnType": optional String
- * "typeParameters": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Element implements HasToJson {
- static const int FLAG_ABSTRACT = 0x01;
- static const int FLAG_CONST = 0x02;
- static const int FLAG_FINAL = 0x04;
- static const int FLAG_STATIC = 0x08;
- static const int FLAG_PRIVATE = 0x10;
- static const int FLAG_DEPRECATED = 0x20;
-
- static int makeFlags(
- {bool isAbstract: false,
- bool isConst: false,
- bool isFinal: false,
- bool isStatic: false,
- bool isPrivate: false,
- bool isDeprecated: false}) {
- int flags = 0;
- if (isAbstract) flags |= FLAG_ABSTRACT;
- if (isConst) flags |= FLAG_CONST;
- if (isFinal) flags |= FLAG_FINAL;
- if (isStatic) flags |= FLAG_STATIC;
- if (isPrivate) flags |= FLAG_PRIVATE;
- if (isDeprecated) flags |= FLAG_DEPRECATED;
- return flags;
- }
-
- ElementKind _kind;
-
- String _name;
-
- Location _location;
-
- int _flags;
-
- String _parameters;
-
- String _returnType;
-
- String _typeParameters;
-
- /**
- * The kind of the element.
- */
- ElementKind get kind => _kind;
-
- /**
- * The kind of the element.
- */
- set kind(ElementKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The name of the element. This is typically used as the label in the
- * outline.
- */
- String get name => _name;
-
- /**
- * The name of the element. This is typically used as the label in the
- * outline.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * The location of the name in the declaration of the element.
- */
- Location get location => _location;
-
- /**
- * The location of the name in the declaration of the element.
- */
- set location(Location value) {
- this._location = value;
- }
-
- /**
- * A bit-map containing the following flags:
- *
- * - 0x01 - set if the element is explicitly or implicitly abstract
- * - 0x02 - set if the element was declared to be ‘const’
- * - 0x04 - set if the element was declared to be ‘final’
- * - 0x08 - set if the element is a static member of a class or is a
- * top-level function or field
- * - 0x10 - set if the element is private
- * - 0x20 - set if the element is deprecated
- */
- int get flags => _flags;
-
- /**
- * A bit-map containing the following flags:
- *
- * - 0x01 - set if the element is explicitly or implicitly abstract
- * - 0x02 - set if the element was declared to be ‘const’
- * - 0x04 - set if the element was declared to be ‘final’
- * - 0x08 - set if the element is a static member of a class or is a
- * top-level function or field
- * - 0x10 - set if the element is private
- * - 0x20 - set if the element is deprecated
- */
- set flags(int value) {
- assert(value != null);
- this._flags = value;
- }
-
- /**
- * The parameter list for the element. If the element is not a method or
- * function this field will not be defined. If the element doesn't have
- * parameters (e.g. getter), this field will not be defined. If the element
- * has zero parameters, this field will have a value of "()".
- */
- String get parameters => _parameters;
-
- /**
- * The parameter list for the element. If the element is not a method or
- * function this field will not be defined. If the element doesn't have
- * parameters (e.g. getter), this field will not be defined. If the element
- * has zero parameters, this field will have a value of "()".
- */
- set parameters(String value) {
- this._parameters = value;
- }
-
- /**
- * The return type of the element. If the element is not a method or function
- * this field will not be defined. If the element does not have a declared
- * return type, this field will contain an empty string.
- */
- String get returnType => _returnType;
-
- /**
- * The return type of the element. If the element is not a method or function
- * this field will not be defined. If the element does not have a declared
- * return type, this field will contain an empty string.
- */
- set returnType(String value) {
- this._returnType = value;
- }
-
- /**
- * The type parameter list for the element. If the element doesn't have type
- * parameters, this field will not be defined.
- */
- String get typeParameters => _typeParameters;
-
- /**
- * The type parameter list for the element. If the element doesn't have type
- * parameters, this field will not be defined.
- */
- set typeParameters(String value) {
- this._typeParameters = value;
- }
-
- Element(ElementKind kind, String name, int flags,
- {Location location,
- String parameters,
- String returnType,
- String typeParameters}) {
- this.kind = kind;
- this.name = name;
- this.location = location;
- this.flags = flags;
- this.parameters = parameters;
- this.returnType = returnType;
- this.typeParameters = typeParameters;
- }
-
- factory Element.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- ElementKind kind;
- if (json.containsKey("kind")) {
- kind = new ElementKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- Location location;
- if (json.containsKey("location")) {
- location = new Location.fromJson(
- jsonDecoder, jsonPath + ".location", json["location"]);
- }
- int flags;
- if (json.containsKey("flags")) {
- flags = jsonDecoder.decodeInt(jsonPath + ".flags", json["flags"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "flags");
- }
- String parameters;
- if (json.containsKey("parameters")) {
- parameters = jsonDecoder.decodeString(
- jsonPath + ".parameters", json["parameters"]);
- }
- String returnType;
- if (json.containsKey("returnType")) {
- returnType = jsonDecoder.decodeString(
- jsonPath + ".returnType", json["returnType"]);
- }
- String typeParameters;
- if (json.containsKey("typeParameters")) {
- typeParameters = jsonDecoder.decodeString(
- jsonPath + ".typeParameters", json["typeParameters"]);
- }
- return new Element(kind, name, flags,
- location: location,
- parameters: parameters,
- returnType: returnType,
- typeParameters: typeParameters);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "Element", json);
- }
- }
-
- bool get isAbstract => (flags & FLAG_ABSTRACT) != 0;
- bool get isConst => (flags & FLAG_CONST) != 0;
- bool get isFinal => (flags & FLAG_FINAL) != 0;
- bool get isStatic => (flags & FLAG_STATIC) != 0;
- bool get isPrivate => (flags & FLAG_PRIVATE) != 0;
- bool get isDeprecated => (flags & FLAG_DEPRECATED) != 0;
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kind"] = kind.toJson();
- result["name"] = name;
- if (location != null) {
- result["location"] = location.toJson();
- }
- result["flags"] = flags;
- if (parameters != null) {
- result["parameters"] = parameters;
- }
- if (returnType != null) {
- result["returnType"] = returnType;
- }
- if (typeParameters != null) {
- result["typeParameters"] = typeParameters;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is Element) {
- return kind == other.kind &&
- name == other.name &&
- location == other.location &&
- flags == other.flags &&
- parameters == other.parameters &&
- returnType == other.returnType &&
- typeParameters == other.typeParameters;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, location.hashCode);
- hash = JenkinsSmiHash.combine(hash, flags.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameters.hashCode);
- hash = JenkinsSmiHash.combine(hash, returnType.hashCode);
- hash = JenkinsSmiHash.combine(hash, typeParameters.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * ElementKind
- *
- * enum {
- * CLASS
- * CLASS_TYPE_ALIAS
- * COMPILATION_UNIT
- * CONSTRUCTOR
- * CONSTRUCTOR_INVOCATION
- * ENUM
- * ENUM_CONSTANT
- * EXTENSION
- * FIELD
- * FILE
- * FUNCTION
- * FUNCTION_INVOCATION
- * FUNCTION_TYPE_ALIAS
- * GETTER
- * LABEL
- * LIBRARY
- * LOCAL_VARIABLE
- * METHOD
- * MIXIN
- * PARAMETER
- * PREFIX
- * SETTER
- * TOP_LEVEL_VARIABLE
- * TYPE_PARAMETER
- * UNIT_TEST_GROUP
- * UNIT_TEST_TEST
- * UNKNOWN
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ElementKind implements Enum {
- static const ElementKind CLASS = const ElementKind._("CLASS");
-
- static const ElementKind CLASS_TYPE_ALIAS =
- const ElementKind._("CLASS_TYPE_ALIAS");
-
- static const ElementKind COMPILATION_UNIT =
- const ElementKind._("COMPILATION_UNIT");
-
- static const ElementKind CONSTRUCTOR = const ElementKind._("CONSTRUCTOR");
-
- static const ElementKind CONSTRUCTOR_INVOCATION =
- const ElementKind._("CONSTRUCTOR_INVOCATION");
-
- static const ElementKind ENUM = const ElementKind._("ENUM");
-
- static const ElementKind ENUM_CONSTANT = const ElementKind._("ENUM_CONSTANT");
-
- static const ElementKind EXTENSION = const ElementKind._("EXTENSION");
-
- static const ElementKind FIELD = const ElementKind._("FIELD");
-
- static const ElementKind FILE = const ElementKind._("FILE");
-
- static const ElementKind FUNCTION = const ElementKind._("FUNCTION");
-
- static const ElementKind FUNCTION_INVOCATION =
- const ElementKind._("FUNCTION_INVOCATION");
-
- static const ElementKind FUNCTION_TYPE_ALIAS =
- const ElementKind._("FUNCTION_TYPE_ALIAS");
-
- static const ElementKind GETTER = const ElementKind._("GETTER");
-
- static const ElementKind LABEL = const ElementKind._("LABEL");
-
- static const ElementKind LIBRARY = const ElementKind._("LIBRARY");
-
- static const ElementKind LOCAL_VARIABLE =
- const ElementKind._("LOCAL_VARIABLE");
-
- static const ElementKind METHOD = const ElementKind._("METHOD");
-
- static const ElementKind MIXIN = const ElementKind._("MIXIN");
-
- static const ElementKind PARAMETER = const ElementKind._("PARAMETER");
-
- static const ElementKind PREFIX = const ElementKind._("PREFIX");
-
- static const ElementKind SETTER = const ElementKind._("SETTER");
-
- static const ElementKind TOP_LEVEL_VARIABLE =
- const ElementKind._("TOP_LEVEL_VARIABLE");
-
- static const ElementKind TYPE_PARAMETER =
- const ElementKind._("TYPE_PARAMETER");
-
- static const ElementKind UNIT_TEST_GROUP =
- const ElementKind._("UNIT_TEST_GROUP");
-
- static const ElementKind UNIT_TEST_TEST =
- const ElementKind._("UNIT_TEST_TEST");
-
- static const ElementKind UNKNOWN = const ElementKind._("UNKNOWN");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<ElementKind> VALUES = const <ElementKind>[
- CLASS,
- CLASS_TYPE_ALIAS,
- COMPILATION_UNIT,
- CONSTRUCTOR,
- CONSTRUCTOR_INVOCATION,
- ENUM,
- ENUM_CONSTANT,
- EXTENSION,
- FIELD,
- FILE,
- FUNCTION,
- FUNCTION_INVOCATION,
- FUNCTION_TYPE_ALIAS,
- GETTER,
- LABEL,
- LIBRARY,
- LOCAL_VARIABLE,
- METHOD,
- MIXIN,
- PARAMETER,
- PREFIX,
- SETTER,
- TOP_LEVEL_VARIABLE,
- TYPE_PARAMETER,
- UNIT_TEST_GROUP,
- UNIT_TEST_TEST,
- UNKNOWN
- ];
-
- @override
- final String name;
-
- const ElementKind._(this.name);
-
- factory ElementKind(String name) {
- switch (name) {
- case "CLASS":
- return CLASS;
- case "CLASS_TYPE_ALIAS":
- return CLASS_TYPE_ALIAS;
- case "COMPILATION_UNIT":
- return COMPILATION_UNIT;
- case "CONSTRUCTOR":
- return CONSTRUCTOR;
- case "CONSTRUCTOR_INVOCATION":
- return CONSTRUCTOR_INVOCATION;
- case "ENUM":
- return ENUM;
- case "ENUM_CONSTANT":
- return ENUM_CONSTANT;
- case "EXTENSION":
- return EXTENSION;
- case "FIELD":
- return FIELD;
- case "FILE":
- return FILE;
- case "FUNCTION":
- return FUNCTION;
- case "FUNCTION_INVOCATION":
- return FUNCTION_INVOCATION;
- case "FUNCTION_TYPE_ALIAS":
- return FUNCTION_TYPE_ALIAS;
- case "GETTER":
- return GETTER;
- case "LABEL":
- return LABEL;
- case "LIBRARY":
- return LIBRARY;
- case "LOCAL_VARIABLE":
- return LOCAL_VARIABLE;
- case "METHOD":
- return METHOD;
- case "MIXIN":
- return MIXIN;
- case "PARAMETER":
- return PARAMETER;
- case "PREFIX":
- return PREFIX;
- case "SETTER":
- return SETTER;
- case "TOP_LEVEL_VARIABLE":
- return TOP_LEVEL_VARIABLE;
- case "TYPE_PARAMETER":
- return TYPE_PARAMETER;
- case "UNIT_TEST_GROUP":
- return UNIT_TEST_GROUP;
- case "UNIT_TEST_TEST":
- return UNIT_TEST_TEST;
- case "UNKNOWN":
- return UNKNOWN;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory ElementKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new ElementKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "ElementKind", json);
- }
-
- @override
- String toString() => "ElementKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * FoldingKind
- *
- * enum {
- * ANNOTATIONS
- * CLASS_BODY
- * DIRECTIVES
- * DOCUMENTATION_COMMENT
- * FILE_HEADER
- * FUNCTION_BODY
- * INVOCATION
- * LITERAL
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class FoldingKind implements Enum {
- static const FoldingKind ANNOTATIONS = const FoldingKind._("ANNOTATIONS");
-
- static const FoldingKind CLASS_BODY = const FoldingKind._("CLASS_BODY");
-
- static const FoldingKind DIRECTIVES = const FoldingKind._("DIRECTIVES");
-
- static const FoldingKind DOCUMENTATION_COMMENT =
- const FoldingKind._("DOCUMENTATION_COMMENT");
-
- static const FoldingKind FILE_HEADER = const FoldingKind._("FILE_HEADER");
-
- static const FoldingKind FUNCTION_BODY = const FoldingKind._("FUNCTION_BODY");
-
- static const FoldingKind INVOCATION = const FoldingKind._("INVOCATION");
-
- static const FoldingKind LITERAL = const FoldingKind._("LITERAL");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<FoldingKind> VALUES = const <FoldingKind>[
- ANNOTATIONS,
- CLASS_BODY,
- DIRECTIVES,
- DOCUMENTATION_COMMENT,
- FILE_HEADER,
- FUNCTION_BODY,
- INVOCATION,
- LITERAL
- ];
-
- @override
- final String name;
-
- const FoldingKind._(this.name);
-
- factory FoldingKind(String name) {
- switch (name) {
- case "ANNOTATIONS":
- return ANNOTATIONS;
- case "CLASS_BODY":
- return CLASS_BODY;
- case "DIRECTIVES":
- return DIRECTIVES;
- case "DOCUMENTATION_COMMENT":
- return DOCUMENTATION_COMMENT;
- case "FILE_HEADER":
- return FILE_HEADER;
- case "FUNCTION_BODY":
- return FUNCTION_BODY;
- case "INVOCATION":
- return INVOCATION;
- case "LITERAL":
- return LITERAL;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory FoldingKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new FoldingKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "FoldingKind", json);
- }
-
- @override
- String toString() => "FoldingKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * FoldingRegion
- *
- * {
- * "kind": FoldingKind
- * "offset": int
- * "length": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class FoldingRegion implements HasToJson {
- FoldingKind _kind;
-
- int _offset;
-
- int _length;
-
- /**
- * The kind of the region.
- */
- FoldingKind get kind => _kind;
-
- /**
- * The kind of the region.
- */
- set kind(FoldingKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The offset of the region to be folded.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region to be folded.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region to be folded.
- */
- int get length => _length;
-
- /**
- * The length of the region to be folded.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- FoldingRegion(FoldingKind kind, int offset, int length) {
- this.kind = kind;
- this.offset = offset;
- this.length = length;
- }
-
- factory FoldingRegion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- FoldingKind kind;
- if (json.containsKey("kind")) {
- kind = new FoldingKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- return new FoldingRegion(kind, offset, length);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "FoldingRegion", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kind"] = kind.toJson();
- result["offset"] = offset;
- result["length"] = length;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is FoldingRegion) {
- return kind == other.kind &&
- offset == other.offset &&
- length == other.length;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * HighlightRegion
- *
- * {
- * "type": HighlightRegionType
- * "offset": int
- * "length": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class HighlightRegion implements HasToJson {
- HighlightRegionType _type;
-
- int _offset;
-
- int _length;
-
- /**
- * The type of highlight associated with the region.
- */
- HighlightRegionType get type => _type;
-
- /**
- * The type of highlight associated with the region.
- */
- set type(HighlightRegionType value) {
- assert(value != null);
- this._type = value;
- }
-
- /**
- * The offset of the region to be highlighted.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region to be highlighted.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region to be highlighted.
- */
- int get length => _length;
-
- /**
- * The length of the region to be highlighted.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- HighlightRegion(HighlightRegionType type, int offset, int length) {
- this.type = type;
- this.offset = offset;
- this.length = length;
- }
-
- factory HighlightRegion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- HighlightRegionType type;
- if (json.containsKey("type")) {
- type = new HighlightRegionType.fromJson(
- jsonDecoder, jsonPath + ".type", json["type"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "type");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- return new HighlightRegion(type, offset, length);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "HighlightRegion", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["type"] = type.toJson();
- result["offset"] = offset;
- result["length"] = length;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is HighlightRegion) {
- return type == other.type &&
- offset == other.offset &&
- length == other.length;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, type.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * HighlightRegionType
- *
- * enum {
- * ANNOTATION
- * BUILT_IN
- * CLASS
- * COMMENT_BLOCK
- * COMMENT_DOCUMENTATION
- * COMMENT_END_OF_LINE
- * CONSTRUCTOR
- * DIRECTIVE
- * DYNAMIC_TYPE
- * DYNAMIC_LOCAL_VARIABLE_DECLARATION
- * DYNAMIC_LOCAL_VARIABLE_REFERENCE
- * DYNAMIC_PARAMETER_DECLARATION
- * DYNAMIC_PARAMETER_REFERENCE
- * ENUM
- * ENUM_CONSTANT
- * FIELD
- * FIELD_STATIC
- * FUNCTION
- * FUNCTION_DECLARATION
- * FUNCTION_TYPE_ALIAS
- * GETTER_DECLARATION
- * IDENTIFIER_DEFAULT
- * IMPORT_PREFIX
- * INSTANCE_FIELD_DECLARATION
- * INSTANCE_FIELD_REFERENCE
- * INSTANCE_GETTER_DECLARATION
- * INSTANCE_GETTER_REFERENCE
- * INSTANCE_METHOD_DECLARATION
- * INSTANCE_METHOD_REFERENCE
- * INSTANCE_SETTER_DECLARATION
- * INSTANCE_SETTER_REFERENCE
- * INVALID_STRING_ESCAPE
- * KEYWORD
- * LABEL
- * LIBRARY_NAME
- * LITERAL_BOOLEAN
- * LITERAL_DOUBLE
- * LITERAL_INTEGER
- * LITERAL_LIST
- * LITERAL_MAP
- * LITERAL_STRING
- * LOCAL_FUNCTION_DECLARATION
- * LOCAL_FUNCTION_REFERENCE
- * LOCAL_VARIABLE
- * LOCAL_VARIABLE_DECLARATION
- * LOCAL_VARIABLE_REFERENCE
- * METHOD
- * METHOD_DECLARATION
- * METHOD_DECLARATION_STATIC
- * METHOD_STATIC
- * PARAMETER
- * SETTER_DECLARATION
- * TOP_LEVEL_VARIABLE
- * PARAMETER_DECLARATION
- * PARAMETER_REFERENCE
- * STATIC_FIELD_DECLARATION
- * STATIC_GETTER_DECLARATION
- * STATIC_GETTER_REFERENCE
- * STATIC_METHOD_DECLARATION
- * STATIC_METHOD_REFERENCE
- * STATIC_SETTER_DECLARATION
- * STATIC_SETTER_REFERENCE
- * TOP_LEVEL_FUNCTION_DECLARATION
- * TOP_LEVEL_FUNCTION_REFERENCE
- * TOP_LEVEL_GETTER_DECLARATION
- * TOP_LEVEL_GETTER_REFERENCE
- * TOP_LEVEL_SETTER_DECLARATION
- * TOP_LEVEL_SETTER_REFERENCE
- * TOP_LEVEL_VARIABLE_DECLARATION
- * TYPE_NAME_DYNAMIC
- * TYPE_PARAMETER
- * UNRESOLVED_INSTANCE_MEMBER_REFERENCE
- * VALID_STRING_ESCAPE
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class HighlightRegionType implements Enum {
- static const HighlightRegionType ANNOTATION =
- const HighlightRegionType._("ANNOTATION");
-
- static const HighlightRegionType BUILT_IN =
- const HighlightRegionType._("BUILT_IN");
-
- static const HighlightRegionType CLASS = const HighlightRegionType._("CLASS");
-
- static const HighlightRegionType COMMENT_BLOCK =
- const HighlightRegionType._("COMMENT_BLOCK");
-
- static const HighlightRegionType COMMENT_DOCUMENTATION =
- const HighlightRegionType._("COMMENT_DOCUMENTATION");
-
- static const HighlightRegionType COMMENT_END_OF_LINE =
- const HighlightRegionType._("COMMENT_END_OF_LINE");
-
- static const HighlightRegionType CONSTRUCTOR =
- const HighlightRegionType._("CONSTRUCTOR");
-
- static const HighlightRegionType DIRECTIVE =
- const HighlightRegionType._("DIRECTIVE");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType DYNAMIC_TYPE =
- const HighlightRegionType._("DYNAMIC_TYPE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType DYNAMIC_LOCAL_VARIABLE_DECLARATION =
- const HighlightRegionType._("DYNAMIC_LOCAL_VARIABLE_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType DYNAMIC_LOCAL_VARIABLE_REFERENCE =
- const HighlightRegionType._("DYNAMIC_LOCAL_VARIABLE_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType DYNAMIC_PARAMETER_DECLARATION =
- const HighlightRegionType._("DYNAMIC_PARAMETER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType DYNAMIC_PARAMETER_REFERENCE =
- const HighlightRegionType._("DYNAMIC_PARAMETER_REFERENCE");
-
- static const HighlightRegionType ENUM = const HighlightRegionType._("ENUM");
-
- static const HighlightRegionType ENUM_CONSTANT =
- const HighlightRegionType._("ENUM_CONSTANT");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType FIELD = const HighlightRegionType._("FIELD");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType FIELD_STATIC =
- const HighlightRegionType._("FIELD_STATIC");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType FUNCTION =
- const HighlightRegionType._("FUNCTION");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType FUNCTION_DECLARATION =
- const HighlightRegionType._("FUNCTION_DECLARATION");
-
- static const HighlightRegionType FUNCTION_TYPE_ALIAS =
- const HighlightRegionType._("FUNCTION_TYPE_ALIAS");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType GETTER_DECLARATION =
- const HighlightRegionType._("GETTER_DECLARATION");
-
- static const HighlightRegionType IDENTIFIER_DEFAULT =
- const HighlightRegionType._("IDENTIFIER_DEFAULT");
-
- static const HighlightRegionType IMPORT_PREFIX =
- const HighlightRegionType._("IMPORT_PREFIX");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_FIELD_DECLARATION =
- const HighlightRegionType._("INSTANCE_FIELD_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_FIELD_REFERENCE =
- const HighlightRegionType._("INSTANCE_FIELD_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_GETTER_DECLARATION =
- const HighlightRegionType._("INSTANCE_GETTER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_GETTER_REFERENCE =
- const HighlightRegionType._("INSTANCE_GETTER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_METHOD_DECLARATION =
- const HighlightRegionType._("INSTANCE_METHOD_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_METHOD_REFERENCE =
- const HighlightRegionType._("INSTANCE_METHOD_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_SETTER_DECLARATION =
- const HighlightRegionType._("INSTANCE_SETTER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INSTANCE_SETTER_REFERENCE =
- const HighlightRegionType._("INSTANCE_SETTER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType INVALID_STRING_ESCAPE =
- const HighlightRegionType._("INVALID_STRING_ESCAPE");
-
- static const HighlightRegionType KEYWORD =
- const HighlightRegionType._("KEYWORD");
-
- static const HighlightRegionType LABEL = const HighlightRegionType._("LABEL");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType LIBRARY_NAME =
- const HighlightRegionType._("LIBRARY_NAME");
-
- static const HighlightRegionType LITERAL_BOOLEAN =
- const HighlightRegionType._("LITERAL_BOOLEAN");
-
- static const HighlightRegionType LITERAL_DOUBLE =
- const HighlightRegionType._("LITERAL_DOUBLE");
-
- static const HighlightRegionType LITERAL_INTEGER =
- const HighlightRegionType._("LITERAL_INTEGER");
-
- static const HighlightRegionType LITERAL_LIST =
- const HighlightRegionType._("LITERAL_LIST");
-
- static const HighlightRegionType LITERAL_MAP =
- const HighlightRegionType._("LITERAL_MAP");
-
- static const HighlightRegionType LITERAL_STRING =
- const HighlightRegionType._("LITERAL_STRING");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType LOCAL_FUNCTION_DECLARATION =
- const HighlightRegionType._("LOCAL_FUNCTION_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType LOCAL_FUNCTION_REFERENCE =
- const HighlightRegionType._("LOCAL_FUNCTION_REFERENCE");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType LOCAL_VARIABLE =
- const HighlightRegionType._("LOCAL_VARIABLE");
-
- static const HighlightRegionType LOCAL_VARIABLE_DECLARATION =
- const HighlightRegionType._("LOCAL_VARIABLE_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType LOCAL_VARIABLE_REFERENCE =
- const HighlightRegionType._("LOCAL_VARIABLE_REFERENCE");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType METHOD =
- const HighlightRegionType._("METHOD");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType METHOD_DECLARATION =
- const HighlightRegionType._("METHOD_DECLARATION");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType METHOD_DECLARATION_STATIC =
- const HighlightRegionType._("METHOD_DECLARATION_STATIC");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType METHOD_STATIC =
- const HighlightRegionType._("METHOD_STATIC");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType PARAMETER =
- const HighlightRegionType._("PARAMETER");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType SETTER_DECLARATION =
- const HighlightRegionType._("SETTER_DECLARATION");
-
- /**
- * Only for version 1 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_VARIABLE =
- const HighlightRegionType._("TOP_LEVEL_VARIABLE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType PARAMETER_DECLARATION =
- const HighlightRegionType._("PARAMETER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType PARAMETER_REFERENCE =
- const HighlightRegionType._("PARAMETER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_FIELD_DECLARATION =
- const HighlightRegionType._("STATIC_FIELD_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_GETTER_DECLARATION =
- const HighlightRegionType._("STATIC_GETTER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_GETTER_REFERENCE =
- const HighlightRegionType._("STATIC_GETTER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_METHOD_DECLARATION =
- const HighlightRegionType._("STATIC_METHOD_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_METHOD_REFERENCE =
- const HighlightRegionType._("STATIC_METHOD_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_SETTER_DECLARATION =
- const HighlightRegionType._("STATIC_SETTER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType STATIC_SETTER_REFERENCE =
- const HighlightRegionType._("STATIC_SETTER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_FUNCTION_DECLARATION =
- const HighlightRegionType._("TOP_LEVEL_FUNCTION_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_FUNCTION_REFERENCE =
- const HighlightRegionType._("TOP_LEVEL_FUNCTION_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_GETTER_DECLARATION =
- const HighlightRegionType._("TOP_LEVEL_GETTER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_GETTER_REFERENCE =
- const HighlightRegionType._("TOP_LEVEL_GETTER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_SETTER_DECLARATION =
- const HighlightRegionType._("TOP_LEVEL_SETTER_DECLARATION");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_SETTER_REFERENCE =
- const HighlightRegionType._("TOP_LEVEL_SETTER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType TOP_LEVEL_VARIABLE_DECLARATION =
- const HighlightRegionType._("TOP_LEVEL_VARIABLE_DECLARATION");
-
- static const HighlightRegionType TYPE_NAME_DYNAMIC =
- const HighlightRegionType._("TYPE_NAME_DYNAMIC");
-
- static const HighlightRegionType TYPE_PARAMETER =
- const HighlightRegionType._("TYPE_PARAMETER");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType UNRESOLVED_INSTANCE_MEMBER_REFERENCE =
- const HighlightRegionType._("UNRESOLVED_INSTANCE_MEMBER_REFERENCE");
-
- /**
- * Only for version 2 of highlight.
- */
- static const HighlightRegionType VALID_STRING_ESCAPE =
- const HighlightRegionType._("VALID_STRING_ESCAPE");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<HighlightRegionType> VALUES = const <HighlightRegionType>[
- ANNOTATION,
- BUILT_IN,
- CLASS,
- COMMENT_BLOCK,
- COMMENT_DOCUMENTATION,
- COMMENT_END_OF_LINE,
- CONSTRUCTOR,
- DIRECTIVE,
- DYNAMIC_TYPE,
- DYNAMIC_LOCAL_VARIABLE_DECLARATION,
- DYNAMIC_LOCAL_VARIABLE_REFERENCE,
- DYNAMIC_PARAMETER_DECLARATION,
- DYNAMIC_PARAMETER_REFERENCE,
- ENUM,
- ENUM_CONSTANT,
- FIELD,
- FIELD_STATIC,
- FUNCTION,
- FUNCTION_DECLARATION,
- FUNCTION_TYPE_ALIAS,
- GETTER_DECLARATION,
- IDENTIFIER_DEFAULT,
- IMPORT_PREFIX,
- INSTANCE_FIELD_DECLARATION,
- INSTANCE_FIELD_REFERENCE,
- INSTANCE_GETTER_DECLARATION,
- INSTANCE_GETTER_REFERENCE,
- INSTANCE_METHOD_DECLARATION,
- INSTANCE_METHOD_REFERENCE,
- INSTANCE_SETTER_DECLARATION,
- INSTANCE_SETTER_REFERENCE,
- INVALID_STRING_ESCAPE,
- KEYWORD,
- LABEL,
- LIBRARY_NAME,
- LITERAL_BOOLEAN,
- LITERAL_DOUBLE,
- LITERAL_INTEGER,
- LITERAL_LIST,
- LITERAL_MAP,
- LITERAL_STRING,
- LOCAL_FUNCTION_DECLARATION,
- LOCAL_FUNCTION_REFERENCE,
- LOCAL_VARIABLE,
- LOCAL_VARIABLE_DECLARATION,
- LOCAL_VARIABLE_REFERENCE,
- METHOD,
- METHOD_DECLARATION,
- METHOD_DECLARATION_STATIC,
- METHOD_STATIC,
- PARAMETER,
- SETTER_DECLARATION,
- TOP_LEVEL_VARIABLE,
- PARAMETER_DECLARATION,
- PARAMETER_REFERENCE,
- STATIC_FIELD_DECLARATION,
- STATIC_GETTER_DECLARATION,
- STATIC_GETTER_REFERENCE,
- STATIC_METHOD_DECLARATION,
- STATIC_METHOD_REFERENCE,
- STATIC_SETTER_DECLARATION,
- STATIC_SETTER_REFERENCE,
- TOP_LEVEL_FUNCTION_DECLARATION,
- TOP_LEVEL_FUNCTION_REFERENCE,
- TOP_LEVEL_GETTER_DECLARATION,
- TOP_LEVEL_GETTER_REFERENCE,
- TOP_LEVEL_SETTER_DECLARATION,
- TOP_LEVEL_SETTER_REFERENCE,
- TOP_LEVEL_VARIABLE_DECLARATION,
- TYPE_NAME_DYNAMIC,
- TYPE_PARAMETER,
- UNRESOLVED_INSTANCE_MEMBER_REFERENCE,
- VALID_STRING_ESCAPE
- ];
-
- @override
- final String name;
-
- const HighlightRegionType._(this.name);
-
- factory HighlightRegionType(String name) {
- switch (name) {
- case "ANNOTATION":
- return ANNOTATION;
- case "BUILT_IN":
- return BUILT_IN;
- case "CLASS":
- return CLASS;
- case "COMMENT_BLOCK":
- return COMMENT_BLOCK;
- case "COMMENT_DOCUMENTATION":
- return COMMENT_DOCUMENTATION;
- case "COMMENT_END_OF_LINE":
- return COMMENT_END_OF_LINE;
- case "CONSTRUCTOR":
- return CONSTRUCTOR;
- case "DIRECTIVE":
- return DIRECTIVE;
- case "DYNAMIC_TYPE":
- return DYNAMIC_TYPE;
- case "DYNAMIC_LOCAL_VARIABLE_DECLARATION":
- return DYNAMIC_LOCAL_VARIABLE_DECLARATION;
- case "DYNAMIC_LOCAL_VARIABLE_REFERENCE":
- return DYNAMIC_LOCAL_VARIABLE_REFERENCE;
- case "DYNAMIC_PARAMETER_DECLARATION":
- return DYNAMIC_PARAMETER_DECLARATION;
- case "DYNAMIC_PARAMETER_REFERENCE":
- return DYNAMIC_PARAMETER_REFERENCE;
- case "ENUM":
- return ENUM;
- case "ENUM_CONSTANT":
- return ENUM_CONSTANT;
- case "FIELD":
- return FIELD;
- case "FIELD_STATIC":
- return FIELD_STATIC;
- case "FUNCTION":
- return FUNCTION;
- case "FUNCTION_DECLARATION":
- return FUNCTION_DECLARATION;
- case "FUNCTION_TYPE_ALIAS":
- return FUNCTION_TYPE_ALIAS;
- case "GETTER_DECLARATION":
- return GETTER_DECLARATION;
- case "IDENTIFIER_DEFAULT":
- return IDENTIFIER_DEFAULT;
- case "IMPORT_PREFIX":
- return IMPORT_PREFIX;
- case "INSTANCE_FIELD_DECLARATION":
- return INSTANCE_FIELD_DECLARATION;
- case "INSTANCE_FIELD_REFERENCE":
- return INSTANCE_FIELD_REFERENCE;
- case "INSTANCE_GETTER_DECLARATION":
- return INSTANCE_GETTER_DECLARATION;
- case "INSTANCE_GETTER_REFERENCE":
- return INSTANCE_GETTER_REFERENCE;
- case "INSTANCE_METHOD_DECLARATION":
- return INSTANCE_METHOD_DECLARATION;
- case "INSTANCE_METHOD_REFERENCE":
- return INSTANCE_METHOD_REFERENCE;
- case "INSTANCE_SETTER_DECLARATION":
- return INSTANCE_SETTER_DECLARATION;
- case "INSTANCE_SETTER_REFERENCE":
- return INSTANCE_SETTER_REFERENCE;
- case "INVALID_STRING_ESCAPE":
- return INVALID_STRING_ESCAPE;
- case "KEYWORD":
- return KEYWORD;
- case "LABEL":
- return LABEL;
- case "LIBRARY_NAME":
- return LIBRARY_NAME;
- case "LITERAL_BOOLEAN":
- return LITERAL_BOOLEAN;
- case "LITERAL_DOUBLE":
- return LITERAL_DOUBLE;
- case "LITERAL_INTEGER":
- return LITERAL_INTEGER;
- case "LITERAL_LIST":
- return LITERAL_LIST;
- case "LITERAL_MAP":
- return LITERAL_MAP;
- case "LITERAL_STRING":
- return LITERAL_STRING;
- case "LOCAL_FUNCTION_DECLARATION":
- return LOCAL_FUNCTION_DECLARATION;
- case "LOCAL_FUNCTION_REFERENCE":
- return LOCAL_FUNCTION_REFERENCE;
- case "LOCAL_VARIABLE":
- return LOCAL_VARIABLE;
- case "LOCAL_VARIABLE_DECLARATION":
- return LOCAL_VARIABLE_DECLARATION;
- case "LOCAL_VARIABLE_REFERENCE":
- return LOCAL_VARIABLE_REFERENCE;
- case "METHOD":
- return METHOD;
- case "METHOD_DECLARATION":
- return METHOD_DECLARATION;
- case "METHOD_DECLARATION_STATIC":
- return METHOD_DECLARATION_STATIC;
- case "METHOD_STATIC":
- return METHOD_STATIC;
- case "PARAMETER":
- return PARAMETER;
- case "SETTER_DECLARATION":
- return SETTER_DECLARATION;
- case "TOP_LEVEL_VARIABLE":
- return TOP_LEVEL_VARIABLE;
- case "PARAMETER_DECLARATION":
- return PARAMETER_DECLARATION;
- case "PARAMETER_REFERENCE":
- return PARAMETER_REFERENCE;
- case "STATIC_FIELD_DECLARATION":
- return STATIC_FIELD_DECLARATION;
- case "STATIC_GETTER_DECLARATION":
- return STATIC_GETTER_DECLARATION;
- case "STATIC_GETTER_REFERENCE":
- return STATIC_GETTER_REFERENCE;
- case "STATIC_METHOD_DECLARATION":
- return STATIC_METHOD_DECLARATION;
- case "STATIC_METHOD_REFERENCE":
- return STATIC_METHOD_REFERENCE;
- case "STATIC_SETTER_DECLARATION":
- return STATIC_SETTER_DECLARATION;
- case "STATIC_SETTER_REFERENCE":
- return STATIC_SETTER_REFERENCE;
- case "TOP_LEVEL_FUNCTION_DECLARATION":
- return TOP_LEVEL_FUNCTION_DECLARATION;
- case "TOP_LEVEL_FUNCTION_REFERENCE":
- return TOP_LEVEL_FUNCTION_REFERENCE;
- case "TOP_LEVEL_GETTER_DECLARATION":
- return TOP_LEVEL_GETTER_DECLARATION;
- case "TOP_LEVEL_GETTER_REFERENCE":
- return TOP_LEVEL_GETTER_REFERENCE;
- case "TOP_LEVEL_SETTER_DECLARATION":
- return TOP_LEVEL_SETTER_DECLARATION;
- case "TOP_LEVEL_SETTER_REFERENCE":
- return TOP_LEVEL_SETTER_REFERENCE;
- case "TOP_LEVEL_VARIABLE_DECLARATION":
- return TOP_LEVEL_VARIABLE_DECLARATION;
- case "TYPE_NAME_DYNAMIC":
- return TYPE_NAME_DYNAMIC;
- case "TYPE_PARAMETER":
- return TYPE_PARAMETER;
- case "UNRESOLVED_INSTANCE_MEMBER_REFERENCE":
- return UNRESOLVED_INSTANCE_MEMBER_REFERENCE;
- case "VALID_STRING_ESCAPE":
- return VALID_STRING_ESCAPE;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory HighlightRegionType.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new HighlightRegionType(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "HighlightRegionType", json);
- }
-
- @override
- String toString() => "HighlightRegionType.$name";
-
- String toJson() => name;
-}
-
-/**
- * KytheEntry
- *
- * {
- * "source": KytheVName
- * "kind": optional String
- * "target": optional KytheVName
- * "fact": String
- * "value": optional List<int>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class KytheEntry implements HasToJson {
- KytheVName _source;
-
- String _kind;
-
- KytheVName _target;
-
- String _fact;
-
- List<int> _value;
-
- /**
- * The ticket of the source node.
- */
- KytheVName get source => _source;
-
- /**
- * The ticket of the source node.
- */
- set source(KytheVName value) {
- assert(value != null);
- this._source = value;
- }
-
- /**
- * An edge label. The schema defines which labels are meaningful.
- */
- String get kind => _kind;
-
- /**
- * An edge label. The schema defines which labels are meaningful.
- */
- set kind(String value) {
- this._kind = value;
- }
-
- /**
- * The ticket of the target node.
- */
- KytheVName get target => _target;
-
- /**
- * The ticket of the target node.
- */
- set target(KytheVName value) {
- this._target = value;
- }
-
- /**
- * A fact label. The schema defines which fact labels are meaningful.
- */
- String get fact => _fact;
-
- /**
- * A fact label. The schema defines which fact labels are meaningful.
- */
- set fact(String value) {
- assert(value != null);
- this._fact = value;
- }
-
- /**
- * The String value of the fact.
- */
- List<int> get value => _value;
-
- /**
- * The String value of the fact.
- */
- set value(List<int> value) {
- this._value = value;
- }
-
- KytheEntry(KytheVName source, String fact,
- {String kind, KytheVName target, List<int> value}) {
- this.source = source;
- this.kind = kind;
- this.target = target;
- this.fact = fact;
- this.value = value;
- }
-
- factory KytheEntry.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- KytheVName source;
- if (json.containsKey("source")) {
- source = new KytheVName.fromJson(
- jsonDecoder, jsonPath + ".source", json["source"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "source");
- }
- String kind;
- if (json.containsKey("kind")) {
- kind = jsonDecoder.decodeString(jsonPath + ".kind", json["kind"]);
- }
- KytheVName target;
- if (json.containsKey("target")) {
- target = new KytheVName.fromJson(
- jsonDecoder, jsonPath + ".target", json["target"]);
- }
- String fact;
- if (json.containsKey("fact")) {
- fact = jsonDecoder.decodeString(jsonPath + ".fact", json["fact"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "fact");
- }
- List<int> value;
- if (json.containsKey("value")) {
- value = jsonDecoder.decodeList(
- jsonPath + ".value", json["value"], jsonDecoder.decodeInt);
- }
- return new KytheEntry(source, fact,
- kind: kind, target: target, value: value);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "KytheEntry", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["source"] = source.toJson();
- if (kind != null) {
- result["kind"] = kind;
- }
- if (target != null) {
- result["target"] = target.toJson();
- }
- result["fact"] = fact;
- if (value != null) {
- result["value"] = value;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is KytheEntry) {
- return source == other.source &&
- kind == other.kind &&
- target == other.target &&
- fact == other.fact &&
- listEqual(value, other.value, (int a, int b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, source.hashCode);
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, target.hashCode);
- hash = JenkinsSmiHash.combine(hash, fact.hashCode);
- hash = JenkinsSmiHash.combine(hash, value.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * KytheVName
- *
- * {
- * "signature": String
- * "corpus": String
- * "root": String
- * "path": String
- * "language": String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class KytheVName implements HasToJson {
- String _signature;
-
- String _corpus;
-
- String _root;
-
- String _path;
-
- String _language;
-
- /**
- * An opaque signature generated by the analyzer.
- */
- String get signature => _signature;
-
- /**
- * An opaque signature generated by the analyzer.
- */
- set signature(String value) {
- assert(value != null);
- this._signature = value;
- }
-
- /**
- * The corpus of source code this KytheVName belongs to. Loosely, a corpus is
- * a collection of related files, such as the contents of a given source
- * repository.
- */
- String get corpus => _corpus;
-
- /**
- * The corpus of source code this KytheVName belongs to. Loosely, a corpus is
- * a collection of related files, such as the contents of a given source
- * repository.
- */
- set corpus(String value) {
- assert(value != null);
- this._corpus = value;
- }
-
- /**
- * A corpus-specific root label, typically a directory path or project
- * identifier, denoting a distinct subset of the corpus. This may also be
- * used to designate virtual collections like generated files.
- */
- String get root => _root;
-
- /**
- * A corpus-specific root label, typically a directory path or project
- * identifier, denoting a distinct subset of the corpus. This may also be
- * used to designate virtual collections like generated files.
- */
- set root(String value) {
- assert(value != null);
- this._root = value;
- }
-
- /**
- * A path-structured label describing the “location” of the named object
- * relative to the corpus and the root.
- */
- String get path => _path;
-
- /**
- * A path-structured label describing the “location” of the named object
- * relative to the corpus and the root.
- */
- set path(String value) {
- assert(value != null);
- this._path = value;
- }
-
- /**
- * The language this name belongs to.
- */
- String get language => _language;
-
- /**
- * The language this name belongs to.
- */
- set language(String value) {
- assert(value != null);
- this._language = value;
- }
-
- KytheVName(String signature, String corpus, String root, String path,
- String language) {
- this.signature = signature;
- this.corpus = corpus;
- this.root = root;
- this.path = path;
- this.language = language;
- }
-
- factory KytheVName.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String signature;
- if (json.containsKey("signature")) {
- signature = jsonDecoder.decodeString(
- jsonPath + ".signature", json["signature"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "signature");
- }
- String corpus;
- if (json.containsKey("corpus")) {
- corpus = jsonDecoder.decodeString(jsonPath + ".corpus", json["corpus"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "corpus");
- }
- String root;
- if (json.containsKey("root")) {
- root = jsonDecoder.decodeString(jsonPath + ".root", json["root"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "root");
- }
- String path;
- if (json.containsKey("path")) {
- path = jsonDecoder.decodeString(jsonPath + ".path", json["path"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "path");
- }
- String language;
- if (json.containsKey("language")) {
- language =
- jsonDecoder.decodeString(jsonPath + ".language", json["language"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "language");
- }
- return new KytheVName(signature, corpus, root, path, language);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "KytheVName", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["signature"] = signature;
- result["corpus"] = corpus;
- result["root"] = root;
- result["path"] = path;
- result["language"] = language;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is KytheVName) {
- return signature == other.signature &&
- corpus == other.corpus &&
- root == other.root &&
- path == other.path &&
- language == other.language;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, signature.hashCode);
- hash = JenkinsSmiHash.combine(hash, corpus.hashCode);
- hash = JenkinsSmiHash.combine(hash, root.hashCode);
- hash = JenkinsSmiHash.combine(hash, path.hashCode);
- hash = JenkinsSmiHash.combine(hash, language.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * LinkedEditGroup
- *
- * {
- * "positions": List<Position>
- * "length": int
- * "suggestions": List<LinkedEditSuggestion>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class LinkedEditGroup implements HasToJson {
- List<Position> _positions;
-
- int _length;
-
- List<LinkedEditSuggestion> _suggestions;
-
- /**
- * The positions of the regions that should be edited simultaneously.
- */
- List<Position> get positions => _positions;
-
- /**
- * The positions of the regions that should be edited simultaneously.
- */
- set positions(List<Position> value) {
- assert(value != null);
- this._positions = value;
- }
-
- /**
- * The length of the regions that should be edited simultaneously.
- */
- int get length => _length;
-
- /**
- * The length of the regions that should be edited simultaneously.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * Pre-computed suggestions for what every region might want to be changed
- * to.
- */
- List<LinkedEditSuggestion> get suggestions => _suggestions;
-
- /**
- * Pre-computed suggestions for what every region might want to be changed
- * to.
- */
- set suggestions(List<LinkedEditSuggestion> value) {
- assert(value != null);
- this._suggestions = value;
- }
-
- LinkedEditGroup(List<Position> positions, int length,
- List<LinkedEditSuggestion> suggestions) {
- this.positions = positions;
- this.length = length;
- this.suggestions = suggestions;
- }
-
- factory LinkedEditGroup.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<Position> positions;
- if (json.containsKey("positions")) {
- positions = jsonDecoder.decodeList(
- jsonPath + ".positions",
- json["positions"],
- (String jsonPath, Object json) =>
- new Position.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "positions");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- List<LinkedEditSuggestion> suggestions;
- if (json.containsKey("suggestions")) {
- suggestions = jsonDecoder.decodeList(
- jsonPath + ".suggestions",
- json["suggestions"],
- (String jsonPath, Object json) =>
- new LinkedEditSuggestion.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "suggestions");
- }
- return new LinkedEditGroup(positions, length, suggestions);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "LinkedEditGroup", json);
- }
- }
-
- /**
- * Construct an empty LinkedEditGroup.
- */
- LinkedEditGroup.empty() : this(<Position>[], 0, <LinkedEditSuggestion>[]);
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["positions"] =
- positions.map((Position value) => value.toJson()).toList();
- result["length"] = length;
- result["suggestions"] = suggestions
- .map((LinkedEditSuggestion value) => value.toJson())
- .toList();
- return result;
- }
-
- /**
- * Add a new position and change the length.
- */
- void addPosition(Position position, int length) {
- positions.add(position);
- this.length = length;
- }
-
- /**
- * Add a new suggestion.
- */
- void addSuggestion(LinkedEditSuggestion suggestion) {
- suggestions.add(suggestion);
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is LinkedEditGroup) {
- return listEqual(
- positions, other.positions, (Position a, Position b) => a == b) &&
- length == other.length &&
- listEqual(suggestions, other.suggestions,
- (LinkedEditSuggestion a, LinkedEditSuggestion b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, positions.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, suggestions.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * LinkedEditSuggestion
- *
- * {
- * "value": String
- * "kind": LinkedEditSuggestionKind
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class LinkedEditSuggestion implements HasToJson {
- String _value;
-
- LinkedEditSuggestionKind _kind;
-
- /**
- * The value that could be used to replace all of the linked edit regions.
- */
- String get value => _value;
-
- /**
- * The value that could be used to replace all of the linked edit regions.
- */
- set value(String value) {
- assert(value != null);
- this._value = value;
- }
-
- /**
- * The kind of value being proposed.
- */
- LinkedEditSuggestionKind get kind => _kind;
-
- /**
- * The kind of value being proposed.
- */
- set kind(LinkedEditSuggestionKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- LinkedEditSuggestion(String value, LinkedEditSuggestionKind kind) {
- this.value = value;
- this.kind = kind;
- }
-
- factory LinkedEditSuggestion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String value;
- if (json.containsKey("value")) {
- value = jsonDecoder.decodeString(jsonPath + ".value", json["value"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "value");
- }
- LinkedEditSuggestionKind kind;
- if (json.containsKey("kind")) {
- kind = new LinkedEditSuggestionKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- return new LinkedEditSuggestion(value, kind);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "LinkedEditSuggestion", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["value"] = value;
- result["kind"] = kind.toJson();
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is LinkedEditSuggestion) {
- return value == other.value && kind == other.kind;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, value.hashCode);
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * LinkedEditSuggestionKind
- *
- * enum {
- * METHOD
- * PARAMETER
- * TYPE
- * VARIABLE
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class LinkedEditSuggestionKind implements Enum {
- static const LinkedEditSuggestionKind METHOD =
- const LinkedEditSuggestionKind._("METHOD");
-
- static const LinkedEditSuggestionKind PARAMETER =
- const LinkedEditSuggestionKind._("PARAMETER");
-
- static const LinkedEditSuggestionKind TYPE =
- const LinkedEditSuggestionKind._("TYPE");
-
- static const LinkedEditSuggestionKind VARIABLE =
- const LinkedEditSuggestionKind._("VARIABLE");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<LinkedEditSuggestionKind> VALUES =
- const <LinkedEditSuggestionKind>[METHOD, PARAMETER, TYPE, VARIABLE];
-
- @override
- final String name;
-
- const LinkedEditSuggestionKind._(this.name);
-
- factory LinkedEditSuggestionKind(String name) {
- switch (name) {
- case "METHOD":
- return METHOD;
- case "PARAMETER":
- return PARAMETER;
- case "TYPE":
- return TYPE;
- case "VARIABLE":
- return VARIABLE;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory LinkedEditSuggestionKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new LinkedEditSuggestionKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "LinkedEditSuggestionKind", json);
- }
-
- @override
- String toString() => "LinkedEditSuggestionKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * Location
- *
- * {
- * "file": FilePath
- * "offset": int
- * "length": int
- * "startLine": int
- * "startColumn": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Location implements HasToJson {
- String _file;
-
- int _offset;
-
- int _length;
-
- int _startLine;
-
- int _startColumn;
-
- /**
- * The file containing the range.
- */
- String get file => _file;
-
- /**
- * The file containing the range.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset of the range.
- */
- int get offset => _offset;
-
- /**
- * The offset of the range.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the range.
- */
- int get length => _length;
-
- /**
- * The length of the range.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The one-based index of the line containing the first character of the
- * range.
- */
- int get startLine => _startLine;
-
- /**
- * The one-based index of the line containing the first character of the
- * range.
- */
- set startLine(int value) {
- assert(value != null);
- this._startLine = value;
- }
-
- /**
- * The one-based index of the column containing the first character of the
- * range.
- */
- int get startColumn => _startColumn;
-
- /**
- * The one-based index of the column containing the first character of the
- * range.
- */
- set startColumn(int value) {
- assert(value != null);
- this._startColumn = value;
- }
-
- Location(
- String file, int offset, int length, int startLine, int startColumn) {
- this.file = file;
- this.offset = offset;
- this.length = length;
- this.startLine = startLine;
- this.startColumn = startColumn;
- }
-
- factory Location.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- int startLine;
- if (json.containsKey("startLine")) {
- startLine =
- jsonDecoder.decodeInt(jsonPath + ".startLine", json["startLine"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "startLine");
- }
- int startColumn;
- if (json.containsKey("startColumn")) {
- startColumn = jsonDecoder.decodeInt(
- jsonPath + ".startColumn", json["startColumn"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "startColumn");
- }
- return new Location(file, offset, length, startLine, startColumn);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "Location", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- result["length"] = length;
- result["startLine"] = startLine;
- result["startColumn"] = startColumn;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is Location) {
- return file == other.file &&
- offset == other.offset &&
- length == other.length &&
- startLine == other.startLine &&
- startColumn == other.startColumn;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, startLine.hashCode);
- hash = JenkinsSmiHash.combine(hash, startColumn.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * NavigationRegion
- *
- * {
- * "offset": int
- * "length": int
- * "targets": List<int>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class NavigationRegion implements HasToJson {
- int _offset;
-
- int _length;
-
- List<int> _targets;
-
- /**
- * The offset of the region from which the user can navigate.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region from which the user can navigate.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region from which the user can navigate.
- */
- int get length => _length;
-
- /**
- * The length of the region from which the user can navigate.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The indexes of the targets (in the enclosing navigation response) to which
- * the given region is bound. By opening the target, clients can implement
- * one form of navigation. This list cannot be empty.
- */
- List<int> get targets => _targets;
-
- /**
- * The indexes of the targets (in the enclosing navigation response) to which
- * the given region is bound. By opening the target, clients can implement
- * one form of navigation. This list cannot be empty.
- */
- set targets(List<int> value) {
- assert(value != null);
- this._targets = value;
- }
-
- NavigationRegion(int offset, int length, List<int> targets) {
- this.offset = offset;
- this.length = length;
- this.targets = targets;
- }
-
- factory NavigationRegion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- List<int> targets;
- if (json.containsKey("targets")) {
- targets = jsonDecoder.decodeList(
- jsonPath + ".targets", json["targets"], jsonDecoder.decodeInt);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "targets");
- }
- return new NavigationRegion(offset, length, targets);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "NavigationRegion", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["offset"] = offset;
- result["length"] = length;
- result["targets"] = targets;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is NavigationRegion) {
- return offset == other.offset &&
- length == other.length &&
- listEqual(targets, other.targets, (int a, int b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, targets.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * NavigationTarget
- *
- * {
- * "kind": ElementKind
- * "fileIndex": int
- * "offset": int
- * "length": int
- * "startLine": int
- * "startColumn": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class NavigationTarget implements HasToJson {
- ElementKind _kind;
-
- int _fileIndex;
-
- int _offset;
-
- int _length;
-
- int _startLine;
-
- int _startColumn;
-
- /**
- * The kind of the element.
- */
- ElementKind get kind => _kind;
-
- /**
- * The kind of the element.
- */
- set kind(ElementKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The index of the file (in the enclosing navigation response) to navigate
- * to.
- */
- int get fileIndex => _fileIndex;
-
- /**
- * The index of the file (in the enclosing navigation response) to navigate
- * to.
- */
- set fileIndex(int value) {
- assert(value != null);
- this._fileIndex = value;
- }
-
- /**
- * The offset of the region to which the user can navigate.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region to which the user can navigate.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region to which the user can navigate.
- */
- int get length => _length;
-
- /**
- * The length of the region to which the user can navigate.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The one-based index of the line containing the first character of the
- * region.
- */
- int get startLine => _startLine;
-
- /**
- * The one-based index of the line containing the first character of the
- * region.
- */
- set startLine(int value) {
- assert(value != null);
- this._startLine = value;
- }
-
- /**
- * The one-based index of the column containing the first character of the
- * region.
- */
- int get startColumn => _startColumn;
-
- /**
- * The one-based index of the column containing the first character of the
- * region.
- */
- set startColumn(int value) {
- assert(value != null);
- this._startColumn = value;
- }
-
- NavigationTarget(ElementKind kind, int fileIndex, int offset, int length,
- int startLine, int startColumn) {
- this.kind = kind;
- this.fileIndex = fileIndex;
- this.offset = offset;
- this.length = length;
- this.startLine = startLine;
- this.startColumn = startColumn;
- }
-
- factory NavigationTarget.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- ElementKind kind;
- if (json.containsKey("kind")) {
- kind = new ElementKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- int fileIndex;
- if (json.containsKey("fileIndex")) {
- fileIndex =
- jsonDecoder.decodeInt(jsonPath + ".fileIndex", json["fileIndex"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "fileIndex");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- int startLine;
- if (json.containsKey("startLine")) {
- startLine =
- jsonDecoder.decodeInt(jsonPath + ".startLine", json["startLine"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "startLine");
- }
- int startColumn;
- if (json.containsKey("startColumn")) {
- startColumn = jsonDecoder.decodeInt(
- jsonPath + ".startColumn", json["startColumn"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "startColumn");
- }
- return new NavigationTarget(
- kind, fileIndex, offset, length, startLine, startColumn);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "NavigationTarget", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kind"] = kind.toJson();
- result["fileIndex"] = fileIndex;
- result["offset"] = offset;
- result["length"] = length;
- result["startLine"] = startLine;
- result["startColumn"] = startColumn;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is NavigationTarget) {
- return kind == other.kind &&
- fileIndex == other.fileIndex &&
- offset == other.offset &&
- length == other.length &&
- startLine == other.startLine &&
- startColumn == other.startColumn;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, fileIndex.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, startLine.hashCode);
- hash = JenkinsSmiHash.combine(hash, startColumn.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * Occurrences
- *
- * {
- * "element": Element
- * "offsets": List<int>
- * "length": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Occurrences implements HasToJson {
- Element _element;
-
- List<int> _offsets;
-
- int _length;
-
- /**
- * The element that was referenced.
- */
- Element get element => _element;
-
- /**
- * The element that was referenced.
- */
- set element(Element value) {
- assert(value != null);
- this._element = value;
- }
-
- /**
- * The offsets of the name of the referenced element within the file.
- */
- List<int> get offsets => _offsets;
-
- /**
- * The offsets of the name of the referenced element within the file.
- */
- set offsets(List<int> value) {
- assert(value != null);
- this._offsets = value;
- }
-
- /**
- * The length of the name of the referenced element.
- */
- int get length => _length;
-
- /**
- * The length of the name of the referenced element.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- Occurrences(Element element, List<int> offsets, int length) {
- this.element = element;
- this.offsets = offsets;
- this.length = length;
- }
-
- factory Occurrences.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- Element element;
- if (json.containsKey("element")) {
- element = new Element.fromJson(
- jsonDecoder, jsonPath + ".element", json["element"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "element");
- }
- List<int> offsets;
- if (json.containsKey("offsets")) {
- offsets = jsonDecoder.decodeList(
- jsonPath + ".offsets", json["offsets"], jsonDecoder.decodeInt);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offsets");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- return new Occurrences(element, offsets, length);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "Occurrences", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["element"] = element.toJson();
- result["offsets"] = offsets;
- result["length"] = length;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is Occurrences) {
- return element == other.element &&
- listEqual(offsets, other.offsets, (int a, int b) => a == b) &&
- length == other.length;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, element.hashCode);
- hash = JenkinsSmiHash.combine(hash, offsets.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * Outline
- *
- * {
- * "element": Element
- * "offset": int
- * "length": int
- * "codeOffset": int
- * "codeLength": int
- * "children": optional List<Outline>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Outline implements HasToJson {
- Element _element;
-
- int _offset;
-
- int _length;
-
- int _codeOffset;
-
- int _codeLength;
-
- List<Outline> _children;
-
- /**
- * A description of the element represented by this node.
- */
- Element get element => _element;
-
- /**
- * A description of the element represented by this node.
- */
- set element(Element value) {
- assert(value != null);
- this._element = value;
- }
-
- /**
- * The offset of the first character of the element. This is different than
- * the offset in the Element, which is the offset of the name of the element.
- * It can be used, for example, to map locations in the file back to an
- * outline.
- */
- int get offset => _offset;
-
- /**
- * The offset of the first character of the element. This is different than
- * the offset in the Element, which is the offset of the name of the element.
- * It can be used, for example, to map locations in the file back to an
- * outline.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the element.
- */
- int get length => _length;
-
- /**
- * The length of the element.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The offset of the first character of the element code, which is neither
- * documentation, nor annotation.
- */
- int get codeOffset => _codeOffset;
-
- /**
- * The offset of the first character of the element code, which is neither
- * documentation, nor annotation.
- */
- set codeOffset(int value) {
- assert(value != null);
- this._codeOffset = value;
- }
-
- /**
- * The length of the element code.
- */
- int get codeLength => _codeLength;
-
- /**
- * The length of the element code.
- */
- set codeLength(int value) {
- assert(value != null);
- this._codeLength = value;
- }
-
- /**
- * The children of the node. The field will be omitted if the node has no
- * children. Children are sorted by offset.
- */
- List<Outline> get children => _children;
-
- /**
- * The children of the node. The field will be omitted if the node has no
- * children. Children are sorted by offset.
- */
- set children(List<Outline> value) {
- this._children = value;
- }
-
- Outline(
- Element element, int offset, int length, int codeOffset, int codeLength,
- {List<Outline> children}) {
- this.element = element;
- this.offset = offset;
- this.length = length;
- this.codeOffset = codeOffset;
- this.codeLength = codeLength;
- this.children = children;
- }
-
- factory Outline.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- Element element;
- if (json.containsKey("element")) {
- element = new Element.fromJson(
- jsonDecoder, jsonPath + ".element", json["element"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "element");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- int codeOffset;
- if (json.containsKey("codeOffset")) {
- codeOffset =
- jsonDecoder.decodeInt(jsonPath + ".codeOffset", json["codeOffset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "codeOffset");
- }
- int codeLength;
- if (json.containsKey("codeLength")) {
- codeLength =
- jsonDecoder.decodeInt(jsonPath + ".codeLength", json["codeLength"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "codeLength");
- }
- List<Outline> children;
- if (json.containsKey("children")) {
- children = jsonDecoder.decodeList(
- jsonPath + ".children",
- json["children"],
- (String jsonPath, Object json) =>
- new Outline.fromJson(jsonDecoder, jsonPath, json));
- }
- return new Outline(element, offset, length, codeOffset, codeLength,
- children: children);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "Outline", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["element"] = element.toJson();
- result["offset"] = offset;
- result["length"] = length;
- result["codeOffset"] = codeOffset;
- result["codeLength"] = codeLength;
- if (children != null) {
- result["children"] =
- children.map((Outline value) => value.toJson()).toList();
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is Outline) {
- return element == other.element &&
- offset == other.offset &&
- length == other.length &&
- codeOffset == other.codeOffset &&
- codeLength == other.codeLength &&
- listEqual(children, other.children, (Outline a, Outline b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, element.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, codeOffset.hashCode);
- hash = JenkinsSmiHash.combine(hash, codeLength.hashCode);
- hash = JenkinsSmiHash.combine(hash, children.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * ParameterInfo
- *
- * {
- * "kind": ParameterKind
- * "name": String
- * "type": String
- * "defaultValue": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ParameterInfo implements HasToJson {
- ParameterKind _kind;
-
- String _name;
-
- String _type;
-
- String _defaultValue;
-
- /**
- * The kind of the parameter.
- */
- ParameterKind get kind => _kind;
-
- /**
- * The kind of the parameter.
- */
- set kind(ParameterKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The name of the parameter.
- */
- String get name => _name;
-
- /**
- * The name of the parameter.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * The type of the parameter.
- */
- String get type => _type;
-
- /**
- * The type of the parameter.
- */
- set type(String value) {
- assert(value != null);
- this._type = value;
- }
-
- /**
- * The default value for this parameter. This value will be omitted if the
- * parameter does not have a default value.
- */
- String get defaultValue => _defaultValue;
-
- /**
- * The default value for this parameter. This value will be omitted if the
- * parameter does not have a default value.
- */
- set defaultValue(String value) {
- this._defaultValue = value;
- }
-
- ParameterInfo(ParameterKind kind, String name, String type,
- {String defaultValue}) {
- this.kind = kind;
- this.name = name;
- this.type = type;
- this.defaultValue = defaultValue;
- }
-
- factory ParameterInfo.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- ParameterKind kind;
- if (json.containsKey("kind")) {
- kind = new ParameterKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- String type;
- if (json.containsKey("type")) {
- type = jsonDecoder.decodeString(jsonPath + ".type", json["type"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "type");
- }
- String defaultValue;
- if (json.containsKey("defaultValue")) {
- defaultValue = jsonDecoder.decodeString(
- jsonPath + ".defaultValue", json["defaultValue"]);
- }
- return new ParameterInfo(kind, name, type, defaultValue: defaultValue);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "ParameterInfo", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kind"] = kind.toJson();
- result["name"] = name;
- result["type"] = type;
- if (defaultValue != null) {
- result["defaultValue"] = defaultValue;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ParameterInfo) {
- return kind == other.kind &&
- name == other.name &&
- type == other.type &&
- defaultValue == other.defaultValue;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, type.hashCode);
- hash = JenkinsSmiHash.combine(hash, defaultValue.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * ParameterKind
- *
- * enum {
- * NAMED
- * OPTIONAL
- * REQUIRED
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ParameterKind implements Enum {
- /**
- * A named parameter.
- */
- static const ParameterKind NAMED = const ParameterKind._("NAMED");
-
- /**
- * An optional parameter.
- */
- static const ParameterKind OPTIONAL = const ParameterKind._("OPTIONAL");
-
- /**
- * A required parameter.
- */
- static const ParameterKind REQUIRED = const ParameterKind._("REQUIRED");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<ParameterKind> VALUES = const <ParameterKind>[
- NAMED,
- OPTIONAL,
- REQUIRED
- ];
-
- @override
- final String name;
-
- const ParameterKind._(this.name);
-
- factory ParameterKind(String name) {
- switch (name) {
- case "NAMED":
- return NAMED;
- case "OPTIONAL":
- return OPTIONAL;
- case "REQUIRED":
- return REQUIRED;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory ParameterKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new ParameterKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "ParameterKind", json);
- }
-
- @override
- String toString() => "ParameterKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * Position
- *
- * {
- * "file": FilePath
- * "offset": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class Position implements HasToJson {
- String _file;
-
- int _offset;
-
- /**
- * The file containing the position.
- */
- String get file => _file;
-
- /**
- * The file containing the position.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset of the position.
- */
- int get offset => _offset;
-
- /**
- * The offset of the position.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- Position(String file, int offset) {
- this.file = file;
- this.offset = offset;
- }
-
- factory Position.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- return new Position(file, offset);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "Position", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is Position) {
- return file == other.file && offset == other.offset;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RefactoringKind
- *
- * enum {
- * CONVERT_GETTER_TO_METHOD
- * CONVERT_METHOD_TO_GETTER
- * EXTRACT_LOCAL_VARIABLE
- * EXTRACT_METHOD
- * EXTRACT_WIDGET
- * INLINE_LOCAL_VARIABLE
- * INLINE_METHOD
- * MOVE_FILE
- * RENAME
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringKind implements Enum {
- static const RefactoringKind CONVERT_GETTER_TO_METHOD =
- const RefactoringKind._("CONVERT_GETTER_TO_METHOD");
-
- static const RefactoringKind CONVERT_METHOD_TO_GETTER =
- const RefactoringKind._("CONVERT_METHOD_TO_GETTER");
-
- static const RefactoringKind EXTRACT_LOCAL_VARIABLE =
- const RefactoringKind._("EXTRACT_LOCAL_VARIABLE");
-
- static const RefactoringKind EXTRACT_METHOD =
- const RefactoringKind._("EXTRACT_METHOD");
-
- static const RefactoringKind EXTRACT_WIDGET =
- const RefactoringKind._("EXTRACT_WIDGET");
-
- static const RefactoringKind INLINE_LOCAL_VARIABLE =
- const RefactoringKind._("INLINE_LOCAL_VARIABLE");
-
- static const RefactoringKind INLINE_METHOD =
- const RefactoringKind._("INLINE_METHOD");
-
- static const RefactoringKind MOVE_FILE = const RefactoringKind._("MOVE_FILE");
-
- static const RefactoringKind RENAME = const RefactoringKind._("RENAME");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<RefactoringKind> VALUES = const <RefactoringKind>[
- CONVERT_GETTER_TO_METHOD,
- CONVERT_METHOD_TO_GETTER,
- EXTRACT_LOCAL_VARIABLE,
- EXTRACT_METHOD,
- EXTRACT_WIDGET,
- INLINE_LOCAL_VARIABLE,
- INLINE_METHOD,
- MOVE_FILE,
- RENAME
- ];
-
- @override
- final String name;
-
- const RefactoringKind._(this.name);
-
- factory RefactoringKind(String name) {
- switch (name) {
- case "CONVERT_GETTER_TO_METHOD":
- return CONVERT_GETTER_TO_METHOD;
- case "CONVERT_METHOD_TO_GETTER":
- return CONVERT_METHOD_TO_GETTER;
- case "EXTRACT_LOCAL_VARIABLE":
- return EXTRACT_LOCAL_VARIABLE;
- case "EXTRACT_METHOD":
- return EXTRACT_METHOD;
- case "EXTRACT_WIDGET":
- return EXTRACT_WIDGET;
- case "INLINE_LOCAL_VARIABLE":
- return INLINE_LOCAL_VARIABLE;
- case "INLINE_METHOD":
- return INLINE_METHOD;
- case "MOVE_FILE":
- return MOVE_FILE;
- case "RENAME":
- return RENAME;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory RefactoringKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new RefactoringKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "RefactoringKind", json);
- }
-
- @override
- String toString() => "RefactoringKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * RefactoringMethodParameter
- *
- * {
- * "id": optional String
- * "kind": RefactoringMethodParameterKind
- * "type": String
- * "name": String
- * "parameters": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringMethodParameter implements HasToJson {
- String _id;
-
- RefactoringMethodParameterKind _kind;
-
- String _type;
-
- String _name;
-
- String _parameters;
-
- /**
- * The unique identifier of the parameter. Clients may omit this field for
- * the parameters they want to add.
- */
- String get id => _id;
-
- /**
- * The unique identifier of the parameter. Clients may omit this field for
- * the parameters they want to add.
- */
- set id(String value) {
- this._id = value;
- }
-
- /**
- * The kind of the parameter.
- */
- RefactoringMethodParameterKind get kind => _kind;
-
- /**
- * The kind of the parameter.
- */
- set kind(RefactoringMethodParameterKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The type that should be given to the parameter, or the return type of the
- * parameter's function type.
- */
- String get type => _type;
-
- /**
- * The type that should be given to the parameter, or the return type of the
- * parameter's function type.
- */
- set type(String value) {
- assert(value != null);
- this._type = value;
- }
-
- /**
- * The name that should be given to the parameter.
- */
- String get name => _name;
-
- /**
- * The name that should be given to the parameter.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * The parameter list of the parameter's function type. If the parameter is
- * not of a function type, this field will not be defined. If the function
- * type has zero parameters, this field will have a value of '()'.
- */
- String get parameters => _parameters;
-
- /**
- * The parameter list of the parameter's function type. If the parameter is
- * not of a function type, this field will not be defined. If the function
- * type has zero parameters, this field will have a value of '()'.
- */
- set parameters(String value) {
- this._parameters = value;
- }
-
- RefactoringMethodParameter(
- RefactoringMethodParameterKind kind, String type, String name,
- {String id, String parameters}) {
- this.id = id;
- this.kind = kind;
- this.type = type;
- this.name = name;
- this.parameters = parameters;
- }
-
- factory RefactoringMethodParameter.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String id;
- if (json.containsKey("id")) {
- id = jsonDecoder.decodeString(jsonPath + ".id", json["id"]);
- }
- RefactoringMethodParameterKind kind;
- if (json.containsKey("kind")) {
- kind = new RefactoringMethodParameterKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- String type;
- if (json.containsKey("type")) {
- type = jsonDecoder.decodeString(jsonPath + ".type", json["type"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "type");
- }
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- String parameters;
- if (json.containsKey("parameters")) {
- parameters = jsonDecoder.decodeString(
- jsonPath + ".parameters", json["parameters"]);
- }
- return new RefactoringMethodParameter(kind, type, name,
- id: id, parameters: parameters);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "RefactoringMethodParameter", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- if (id != null) {
- result["id"] = id;
- }
- result["kind"] = kind.toJson();
- result["type"] = type;
- result["name"] = name;
- if (parameters != null) {
- result["parameters"] = parameters;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RefactoringMethodParameter) {
- return id == other.id &&
- kind == other.kind &&
- type == other.type &&
- name == other.name &&
- parameters == other.parameters;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, id.hashCode);
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, type.hashCode);
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameters.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RefactoringMethodParameterKind
- *
- * enum {
- * REQUIRED
- * POSITIONAL
- * NAMED
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringMethodParameterKind implements Enum {
- static const RefactoringMethodParameterKind REQUIRED =
- const RefactoringMethodParameterKind._("REQUIRED");
-
- static const RefactoringMethodParameterKind POSITIONAL =
- const RefactoringMethodParameterKind._("POSITIONAL");
-
- static const RefactoringMethodParameterKind NAMED =
- const RefactoringMethodParameterKind._("NAMED");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<RefactoringMethodParameterKind> VALUES =
- const <RefactoringMethodParameterKind>[REQUIRED, POSITIONAL, NAMED];
-
- @override
- final String name;
-
- const RefactoringMethodParameterKind._(this.name);
-
- factory RefactoringMethodParameterKind(String name) {
- switch (name) {
- case "REQUIRED":
- return REQUIRED;
- case "POSITIONAL":
- return POSITIONAL;
- case "NAMED":
- return NAMED;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory RefactoringMethodParameterKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new RefactoringMethodParameterKind(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(
- jsonPath, "RefactoringMethodParameterKind", json);
- }
-
- @override
- String toString() => "RefactoringMethodParameterKind.$name";
-
- String toJson() => name;
-}
-
-/**
- * RefactoringProblem
- *
- * {
- * "severity": RefactoringProblemSeverity
- * "message": String
- * "location": optional Location
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringProblem implements HasToJson {
- RefactoringProblemSeverity _severity;
-
- String _message;
-
- Location _location;
-
- /**
- * The severity of the problem being represented.
- */
- RefactoringProblemSeverity get severity => _severity;
-
- /**
- * The severity of the problem being represented.
- */
- set severity(RefactoringProblemSeverity value) {
- assert(value != null);
- this._severity = value;
- }
-
- /**
- * A human-readable description of the problem being represented.
- */
- String get message => _message;
-
- /**
- * A human-readable description of the problem being represented.
- */
- set message(String value) {
- assert(value != null);
- this._message = value;
- }
-
- /**
- * The location of the problem being represented. This field is omitted
- * unless there is a specific location associated with the problem (such as a
- * location where an element being renamed will be shadowed).
- */
- Location get location => _location;
-
- /**
- * The location of the problem being represented. This field is omitted
- * unless there is a specific location associated with the problem (such as a
- * location where an element being renamed will be shadowed).
- */
- set location(Location value) {
- this._location = value;
- }
-
- RefactoringProblem(RefactoringProblemSeverity severity, String message,
- {Location location}) {
- this.severity = severity;
- this.message = message;
- this.location = location;
- }
-
- factory RefactoringProblem.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- RefactoringProblemSeverity severity;
- if (json.containsKey("severity")) {
- severity = new RefactoringProblemSeverity.fromJson(
- jsonDecoder, jsonPath + ".severity", json["severity"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "severity");
- }
- String message;
- if (json.containsKey("message")) {
- message =
- jsonDecoder.decodeString(jsonPath + ".message", json["message"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "message");
- }
- Location location;
- if (json.containsKey("location")) {
- location = new Location.fromJson(
- jsonDecoder, jsonPath + ".location", json["location"]);
- }
- return new RefactoringProblem(severity, message, location: location);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "RefactoringProblem", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["severity"] = severity.toJson();
- result["message"] = message;
- if (location != null) {
- result["location"] = location.toJson();
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RefactoringProblem) {
- return severity == other.severity &&
- message == other.message &&
- location == other.location;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, severity.hashCode);
- hash = JenkinsSmiHash.combine(hash, message.hashCode);
- hash = JenkinsSmiHash.combine(hash, location.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RefactoringProblemSeverity
- *
- * enum {
- * INFO
- * WARNING
- * ERROR
- * FATAL
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringProblemSeverity implements Enum {
- /**
- * A minor code problem. No example, because it is not used yet.
- */
- static const RefactoringProblemSeverity INFO =
- const RefactoringProblemSeverity._("INFO");
-
- /**
- * A minor code problem. For example names of local variables should be camel
- * case and start with a lower case letter. Staring the name of a variable
- * with an upper case is OK from the language point of view, but it is nice
- * to warn the user.
- */
- static const RefactoringProblemSeverity WARNING =
- const RefactoringProblemSeverity._("WARNING");
-
- /**
- * The refactoring technically can be performed, but there is a logical
- * problem. For example the name of a local variable being extracted
- * conflicts with another name in the scope, or duplicate parameter names in
- * the method being extracted, or a conflict between a parameter name and a
- * local variable, etc. In some cases the location of the problem is also
- * provided, so the IDE can show user the location and the problem, and let
- * the user decide whether they want to perform the refactoring. For example
- * the name conflict might be expected, and the user wants to fix it
- * afterwards.
- */
- static const RefactoringProblemSeverity ERROR =
- const RefactoringProblemSeverity._("ERROR");
-
- /**
- * A fatal error, which prevents performing the refactoring. For example the
- * name of a local variable being extracted is not a valid identifier, or
- * selection is not a valid expression.
- */
- static const RefactoringProblemSeverity FATAL =
- const RefactoringProblemSeverity._("FATAL");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<RefactoringProblemSeverity> VALUES =
- const <RefactoringProblemSeverity>[INFO, WARNING, ERROR, FATAL];
-
- @override
- final String name;
-
- const RefactoringProblemSeverity._(this.name);
-
- factory RefactoringProblemSeverity(String name) {
- switch (name) {
- case "INFO":
- return INFO;
- case "WARNING":
- return WARNING;
- case "ERROR":
- return ERROR;
- case "FATAL":
- return FATAL;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory RefactoringProblemSeverity.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new RefactoringProblemSeverity(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "RefactoringProblemSeverity", json);
- }
-
- /**
- * Returns the [RefactoringProblemSeverity] with the maximal severity.
- */
- static RefactoringProblemSeverity max(
- RefactoringProblemSeverity a, RefactoringProblemSeverity b) =>
- maxRefactoringProblemSeverity(a, b);
-
- @override
- String toString() => "RefactoringProblemSeverity.$name";
-
- String toJson() => name;
-}
-
-/**
- * RemoveContentOverlay
- *
- * {
- * "type": "remove"
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RemoveContentOverlay implements HasToJson {
- RemoveContentOverlay();
-
- factory RemoveContentOverlay.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- if (json["type"] != "remove") {
- throw jsonDecoder.mismatch(jsonPath, "equal " + "remove", json);
- }
- return new RemoveContentOverlay();
- } else {
- throw jsonDecoder.mismatch(jsonPath, "RemoveContentOverlay", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["type"] = "remove";
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RemoveContentOverlay) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, 114870849);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * SourceChange
- *
- * {
- * "message": String
- * "edits": List<SourceFileEdit>
- * "linkedEditGroups": List<LinkedEditGroup>
- * "selection": optional Position
- * "id": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class SourceChange implements HasToJson {
- String _message;
-
- List<SourceFileEdit> _edits;
-
- List<LinkedEditGroup> _linkedEditGroups;
-
- Position _selection;
-
- String _id;
-
- /**
- * A human-readable description of the change to be applied.
- */
- String get message => _message;
-
- /**
- * A human-readable description of the change to be applied.
- */
- set message(String value) {
- assert(value != null);
- this._message = value;
- }
-
- /**
- * A list of the edits used to effect the change, grouped by file.
- */
- List<SourceFileEdit> get edits => _edits;
-
- /**
- * A list of the edits used to effect the change, grouped by file.
- */
- set edits(List<SourceFileEdit> value) {
- assert(value != null);
- this._edits = value;
- }
-
- /**
- * A list of the linked editing groups used to customize the changes that
- * were made.
- */
- List<LinkedEditGroup> get linkedEditGroups => _linkedEditGroups;
-
- /**
- * A list of the linked editing groups used to customize the changes that
- * were made.
- */
- set linkedEditGroups(List<LinkedEditGroup> value) {
- assert(value != null);
- this._linkedEditGroups = value;
- }
-
- /**
- * The position that should be selected after the edits have been applied.
- */
- Position get selection => _selection;
-
- /**
- * The position that should be selected after the edits have been applied.
- */
- set selection(Position value) {
- this._selection = value;
- }
-
- /**
- * The optional identifier of the change kind. The identifier remains stable
- * even if the message changes, or is parameterized.
- */
- String get id => _id;
-
- /**
- * The optional identifier of the change kind. The identifier remains stable
- * even if the message changes, or is parameterized.
- */
- set id(String value) {
- this._id = value;
- }
-
- SourceChange(String message,
- {List<SourceFileEdit> edits,
- List<LinkedEditGroup> linkedEditGroups,
- Position selection,
- String id}) {
- this.message = message;
- if (edits == null) {
- this.edits = <SourceFileEdit>[];
- } else {
- this.edits = edits;
- }
- if (linkedEditGroups == null) {
- this.linkedEditGroups = <LinkedEditGroup>[];
- } else {
- this.linkedEditGroups = linkedEditGroups;
- }
- this.selection = selection;
- this.id = id;
- }
-
- factory SourceChange.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String message;
- if (json.containsKey("message")) {
- message =
- jsonDecoder.decodeString(jsonPath + ".message", json["message"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "message");
- }
- List<SourceFileEdit> edits;
- if (json.containsKey("edits")) {
- edits = jsonDecoder.decodeList(
- jsonPath + ".edits",
- json["edits"],
- (String jsonPath, Object json) =>
- new SourceFileEdit.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edits");
- }
- List<LinkedEditGroup> linkedEditGroups;
- if (json.containsKey("linkedEditGroups")) {
- linkedEditGroups = jsonDecoder.decodeList(
- jsonPath + ".linkedEditGroups",
- json["linkedEditGroups"],
- (String jsonPath, Object json) =>
- new LinkedEditGroup.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "linkedEditGroups");
- }
- Position selection;
- if (json.containsKey("selection")) {
- selection = new Position.fromJson(
- jsonDecoder, jsonPath + ".selection", json["selection"]);
- }
- String id;
- if (json.containsKey("id")) {
- id = jsonDecoder.decodeString(jsonPath + ".id", json["id"]);
- }
- return new SourceChange(message,
- edits: edits,
- linkedEditGroups: linkedEditGroups,
- selection: selection,
- id: id);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "SourceChange", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["message"] = message;
- result["edits"] =
- edits.map((SourceFileEdit value) => value.toJson()).toList();
- result["linkedEditGroups"] = linkedEditGroups
- .map((LinkedEditGroup value) => value.toJson())
- .toList();
- if (selection != null) {
- result["selection"] = selection.toJson();
- }
- if (id != null) {
- result["id"] = id;
- }
- return result;
- }
-
- /**
- * Adds [edit] to the [FileEdit] for the given [file].
- */
- void addEdit(String file, int fileStamp, SourceEdit edit) =>
- addEditToSourceChange(this, file, fileStamp, edit);
-
- /**
- * Adds the given [FileEdit].
- */
- void addFileEdit(SourceFileEdit edit) {
- edits.add(edit);
- }
-
- /**
- * Adds the given [LinkedEditGroup].
- */
- void addLinkedEditGroup(LinkedEditGroup linkedEditGroup) {
- linkedEditGroups.add(linkedEditGroup);
- }
-
- /**
- * Returns the [FileEdit] for the given [file], maybe `null`.
- */
- SourceFileEdit getFileEdit(String file) => getChangeFileEdit(this, file);
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is SourceChange) {
- return message == other.message &&
- listEqual(edits, other.edits,
- (SourceFileEdit a, SourceFileEdit b) => a == b) &&
- listEqual(linkedEditGroups, other.linkedEditGroups,
- (LinkedEditGroup a, LinkedEditGroup b) => a == b) &&
- selection == other.selection &&
- id == other.id;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, message.hashCode);
- hash = JenkinsSmiHash.combine(hash, edits.hashCode);
- hash = JenkinsSmiHash.combine(hash, linkedEditGroups.hashCode);
- hash = JenkinsSmiHash.combine(hash, selection.hashCode);
- hash = JenkinsSmiHash.combine(hash, id.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * SourceEdit
- *
- * {
- * "offset": int
- * "length": int
- * "replacement": String
- * "id": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class SourceEdit implements HasToJson {
- /**
- * Get the result of applying a set of [edits] to the given [code]. Edits are
- * applied in the order they appear in [edits].
- */
- static String applySequence(String code, Iterable<SourceEdit> edits) =>
- applySequenceOfEdits(code, edits);
-
- int _offset;
-
- int _length;
-
- String _replacement;
-
- String _id;
-
- /**
- * The offset of the region to be modified.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region to be modified.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region to be modified.
- */
- int get length => _length;
-
- /**
- * The length of the region to be modified.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The code that is to replace the specified region in the original code.
- */
- String get replacement => _replacement;
-
- /**
- * The code that is to replace the specified region in the original code.
- */
- set replacement(String value) {
- assert(value != null);
- this._replacement = value;
- }
-
- /**
- * An identifier that uniquely identifies this source edit from other edits
- * in the same response. This field is omitted unless a containing structure
- * needs to be able to identify the edit for some reason.
- *
- * For example, some refactoring operations can produce edits that might not
- * be appropriate (referred to as potential edits). Such edits will have an
- * id so that they can be referenced. Edits in the same response that do not
- * need to be referenced will not have an id.
- */
- String get id => _id;
-
- /**
- * An identifier that uniquely identifies this source edit from other edits
- * in the same response. This field is omitted unless a containing structure
- * needs to be able to identify the edit for some reason.
- *
- * For example, some refactoring operations can produce edits that might not
- * be appropriate (referred to as potential edits). Such edits will have an
- * id so that they can be referenced. Edits in the same response that do not
- * need to be referenced will not have an id.
- */
- set id(String value) {
- this._id = value;
- }
-
- SourceEdit(int offset, int length, String replacement, {String id}) {
- this.offset = offset;
- this.length = length;
- this.replacement = replacement;
- this.id = id;
- }
-
- factory SourceEdit.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- String replacement;
- if (json.containsKey("replacement")) {
- replacement = jsonDecoder.decodeString(
- jsonPath + ".replacement", json["replacement"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "replacement");
- }
- String id;
- if (json.containsKey("id")) {
- id = jsonDecoder.decodeString(jsonPath + ".id", json["id"]);
- }
- return new SourceEdit(offset, length, replacement, id: id);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "SourceEdit", json);
- }
- }
-
- /**
- * The end of the region to be modified.
- */
- int get end => offset + length;
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["offset"] = offset;
- result["length"] = length;
- result["replacement"] = replacement;
- if (id != null) {
- result["id"] = id;
- }
- return result;
- }
-
- /**
- * Get the result of applying the edit to the given [code].
- */
- String apply(String code) => applyEdit(code, this);
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is SourceEdit) {
- return offset == other.offset &&
- length == other.length &&
- replacement == other.replacement &&
- id == other.id;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, replacement.hashCode);
- hash = JenkinsSmiHash.combine(hash, id.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * SourceFileEdit
- *
- * {
- * "file": FilePath
- * "fileStamp": long
- * "edits": List<SourceEdit>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class SourceFileEdit implements HasToJson {
- String _file;
-
- int _fileStamp;
-
- List<SourceEdit> _edits;
-
- /**
- * The file containing the code to be modified.
- */
- String get file => _file;
-
- /**
- * The file containing the code to be modified.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The modification stamp of the file at the moment when the change was
- * created, in milliseconds since the "Unix epoch". Will be -1 if the file
- * did not exist and should be created. The client may use this field to make
- * sure that the file was not changed since then, so it is safe to apply the
- * change.
- */
- int get fileStamp => _fileStamp;
-
- /**
- * The modification stamp of the file at the moment when the change was
- * created, in milliseconds since the "Unix epoch". Will be -1 if the file
- * did not exist and should be created. The client may use this field to make
- * sure that the file was not changed since then, so it is safe to apply the
- * change.
- */
- set fileStamp(int value) {
- assert(value != null);
- this._fileStamp = value;
- }
-
- /**
- * A list of the edits used to effect the change.
- */
- List<SourceEdit> get edits => _edits;
-
- /**
- * A list of the edits used to effect the change.
- */
- set edits(List<SourceEdit> value) {
- assert(value != null);
- this._edits = value;
- }
-
- SourceFileEdit(String file, int fileStamp, {List<SourceEdit> edits}) {
- this.file = file;
- this.fileStamp = fileStamp;
- if (edits == null) {
- this.edits = <SourceEdit>[];
- } else {
- this.edits = edits;
- }
- }
-
- factory SourceFileEdit.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int fileStamp;
- if (json.containsKey("fileStamp")) {
- fileStamp =
- jsonDecoder.decodeInt(jsonPath + ".fileStamp", json["fileStamp"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "fileStamp");
- }
- List<SourceEdit> edits;
- if (json.containsKey("edits")) {
- edits = jsonDecoder.decodeList(
- jsonPath + ".edits",
- json["edits"],
- (String jsonPath, Object json) =>
- new SourceEdit.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edits");
- }
- return new SourceFileEdit(file, fileStamp, edits: edits);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "SourceFileEdit", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["fileStamp"] = fileStamp;
- result["edits"] = edits.map((SourceEdit value) => value.toJson()).toList();
- return result;
- }
-
- /**
- * Adds the given [Edit] to the list.
- */
- void add(SourceEdit edit) => addEditForSource(this, edit);
-
- /**
- * Adds the given [Edit]s.
- */
- void addAll(Iterable<SourceEdit> edits) => addAllEditsForSource(this, edits);
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is SourceFileEdit) {
- return file == other.file &&
- fileStamp == other.fileStamp &&
- listEqual(edits, other.edits, (SourceEdit a, SourceEdit b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, fileStamp.hashCode);
- hash = JenkinsSmiHash.combine(hash, edits.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
diff --git a/analyzer_plugin/lib/protocol/protocol_constants.dart b/analyzer_plugin/lib/protocol/protocol_constants.dart
deleted file mode 100644
index fe304d5..0000000
--- a/analyzer_plugin/lib/protocol/protocol_constants.dart
+++ /dev/null
@@ -1,101 +0,0 @@
-// 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.
-//
-// This file has been automatically generated. Please do not edit it manually.
-// To regenerate the file, use the script
-// "pkg/analysis_server/tool/spec/generate_files".
-
-const String ANALYSIS_NOTIFICATION_ERRORS = 'analysis.errors';
-const String ANALYSIS_NOTIFICATION_ERRORS_ERRORS = 'errors';
-const String ANALYSIS_NOTIFICATION_ERRORS_FILE = 'file';
-const String ANALYSIS_NOTIFICATION_FOLDING = 'analysis.folding';
-const String ANALYSIS_NOTIFICATION_FOLDING_FILE = 'file';
-const String ANALYSIS_NOTIFICATION_FOLDING_REGIONS = 'regions';
-const String ANALYSIS_NOTIFICATION_HIGHLIGHTS = 'analysis.highlights';
-const String ANALYSIS_NOTIFICATION_HIGHLIGHTS_FILE = 'file';
-const String ANALYSIS_NOTIFICATION_HIGHLIGHTS_REGIONS = 'regions';
-const String ANALYSIS_NOTIFICATION_NAVIGATION = 'analysis.navigation';
-const String ANALYSIS_NOTIFICATION_NAVIGATION_FILE = 'file';
-const String ANALYSIS_NOTIFICATION_NAVIGATION_FILES = 'files';
-const String ANALYSIS_NOTIFICATION_NAVIGATION_REGIONS = 'regions';
-const String ANALYSIS_NOTIFICATION_NAVIGATION_TARGETS = 'targets';
-const String ANALYSIS_NOTIFICATION_OCCURRENCES = 'analysis.occurrences';
-const String ANALYSIS_NOTIFICATION_OCCURRENCES_FILE = 'file';
-const String ANALYSIS_NOTIFICATION_OCCURRENCES_OCCURRENCES = 'occurrences';
-const String ANALYSIS_NOTIFICATION_OUTLINE = 'analysis.outline';
-const String ANALYSIS_NOTIFICATION_OUTLINE_FILE = 'file';
-const String ANALYSIS_NOTIFICATION_OUTLINE_OUTLINE = 'outline';
-const String ANALYSIS_REQUEST_GET_NAVIGATION = 'analysis.getNavigation';
-const String ANALYSIS_REQUEST_GET_NAVIGATION_FILE = 'file';
-const String ANALYSIS_REQUEST_GET_NAVIGATION_LENGTH = 'length';
-const String ANALYSIS_REQUEST_GET_NAVIGATION_OFFSET = 'offset';
-const String ANALYSIS_REQUEST_HANDLE_WATCH_EVENTS =
- 'analysis.handleWatchEvents';
-const String ANALYSIS_REQUEST_HANDLE_WATCH_EVENTS_EVENTS = 'events';
-const String ANALYSIS_REQUEST_SET_CONTEXT_ROOTS = 'analysis.setContextRoots';
-const String ANALYSIS_REQUEST_SET_CONTEXT_ROOTS_ROOTS = 'roots';
-const String ANALYSIS_REQUEST_SET_PRIORITY_FILES = 'analysis.setPriorityFiles';
-const String ANALYSIS_REQUEST_SET_PRIORITY_FILES_FILES = 'files';
-const String ANALYSIS_REQUEST_SET_SUBSCRIPTIONS = 'analysis.setSubscriptions';
-const String ANALYSIS_REQUEST_SET_SUBSCRIPTIONS_SUBSCRIPTIONS = 'subscriptions';
-const String ANALYSIS_REQUEST_UPDATE_CONTENT = 'analysis.updateContent';
-const String ANALYSIS_REQUEST_UPDATE_CONTENT_FILES = 'files';
-const String ANALYSIS_RESPONSE_GET_NAVIGATION_FILES = 'files';
-const String ANALYSIS_RESPONSE_GET_NAVIGATION_REGIONS = 'regions';
-const String ANALYSIS_RESPONSE_GET_NAVIGATION_TARGETS = 'targets';
-const String COMPLETION_REQUEST_GET_SUGGESTIONS = 'completion.getSuggestions';
-const String COMPLETION_REQUEST_GET_SUGGESTIONS_FILE = 'file';
-const String COMPLETION_REQUEST_GET_SUGGESTIONS_OFFSET = 'offset';
-const String COMPLETION_RESPONSE_GET_SUGGESTIONS_REPLACEMENT_LENGTH =
- 'replacementLength';
-const String COMPLETION_RESPONSE_GET_SUGGESTIONS_REPLACEMENT_OFFSET =
- 'replacementOffset';
-const String COMPLETION_RESPONSE_GET_SUGGESTIONS_RESULTS = 'results';
-const String EDIT_REQUEST_GET_ASSISTS = 'edit.getAssists';
-const String EDIT_REQUEST_GET_ASSISTS_FILE = 'file';
-const String EDIT_REQUEST_GET_ASSISTS_LENGTH = 'length';
-const String EDIT_REQUEST_GET_ASSISTS_OFFSET = 'offset';
-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS =
- 'edit.getAvailableRefactorings';
-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS_FILE = 'file';
-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS_LENGTH = 'length';
-const String EDIT_REQUEST_GET_AVAILABLE_REFACTORINGS_OFFSET = 'offset';
-const String EDIT_REQUEST_GET_FIXES = 'edit.getFixes';
-const String EDIT_REQUEST_GET_FIXES_FILE = 'file';
-const String EDIT_REQUEST_GET_FIXES_OFFSET = 'offset';
-const String EDIT_REQUEST_GET_REFACTORING = 'edit.getRefactoring';
-const String EDIT_REQUEST_GET_REFACTORING_FILE = 'file';
-const String EDIT_REQUEST_GET_REFACTORING_KIND = 'kind';
-const String EDIT_REQUEST_GET_REFACTORING_LENGTH = 'length';
-const String EDIT_REQUEST_GET_REFACTORING_OFFSET = 'offset';
-const String EDIT_REQUEST_GET_REFACTORING_OPTIONS = 'options';
-const String EDIT_REQUEST_GET_REFACTORING_VALIDATE_ONLY = 'validateOnly';
-const String EDIT_RESPONSE_GET_ASSISTS_ASSISTS = 'assists';
-const String EDIT_RESPONSE_GET_AVAILABLE_REFACTORINGS_KINDS = 'kinds';
-const String EDIT_RESPONSE_GET_FIXES_FIXES = 'fixes';
-const String EDIT_RESPONSE_GET_REFACTORING_CHANGE = 'change';
-const String EDIT_RESPONSE_GET_REFACTORING_FEEDBACK = 'feedback';
-const String EDIT_RESPONSE_GET_REFACTORING_FINAL_PROBLEMS = 'finalProblems';
-const String EDIT_RESPONSE_GET_REFACTORING_INITIAL_PROBLEMS = 'initialProblems';
-const String EDIT_RESPONSE_GET_REFACTORING_OPTIONS_PROBLEMS = 'optionsProblems';
-const String EDIT_RESPONSE_GET_REFACTORING_POTENTIAL_EDITS = 'potentialEdits';
-const String KYTHE_REQUEST_GET_KYTHE_ENTRIES = 'kythe.getKytheEntries';
-const String KYTHE_REQUEST_GET_KYTHE_ENTRIES_FILE = 'file';
-const String KYTHE_RESPONSE_GET_KYTHE_ENTRIES_ENTRIES = 'entries';
-const String KYTHE_RESPONSE_GET_KYTHE_ENTRIES_FILES = 'files';
-const String PLUGIN_NOTIFICATION_ERROR = 'plugin.error';
-const String PLUGIN_NOTIFICATION_ERROR_IS_FATAL = 'isFatal';
-const String PLUGIN_NOTIFICATION_ERROR_MESSAGE = 'message';
-const String PLUGIN_NOTIFICATION_ERROR_STACK_TRACE = 'stackTrace';
-const String PLUGIN_REQUEST_SHUTDOWN = 'plugin.shutdown';
-const String PLUGIN_REQUEST_VERSION_CHECK = 'plugin.versionCheck';
-const String PLUGIN_REQUEST_VERSION_CHECK_BYTE_STORE_PATH = 'byteStorePath';
-const String PLUGIN_REQUEST_VERSION_CHECK_SDK_PATH = 'sdkPath';
-const String PLUGIN_REQUEST_VERSION_CHECK_VERSION = 'version';
-const String PLUGIN_RESPONSE_VERSION_CHECK_CONTACT_INFO = 'contactInfo';
-const String PLUGIN_RESPONSE_VERSION_CHECK_INTERESTING_FILES =
- 'interestingFiles';
-const String PLUGIN_RESPONSE_VERSION_CHECK_IS_COMPATIBLE = 'isCompatible';
-const String PLUGIN_RESPONSE_VERSION_CHECK_NAME = 'name';
-const String PLUGIN_RESPONSE_VERSION_CHECK_VERSION = 'version';
diff --git a/analyzer_plugin/lib/protocol/protocol_generated.dart b/analyzer_plugin/lib/protocol/protocol_generated.dart
deleted file mode 100644
index 756f1eb..0000000
--- a/analyzer_plugin/lib/protocol/protocol_generated.dart
+++ /dev/null
@@ -1,6391 +0,0 @@
-// 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.
-//
-// This file has been automatically generated. Please do not edit it manually.
-// To regenerate the file, use the script
-// "pkg/analysis_server/tool/spec/generate_files".
-
-import 'dart:convert' hide JsonDecoder;
-
-import 'package:analyzer/src/generated/utilities_general.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-
-/**
- * AnalysisErrorFixes
- *
- * {
- * "error": AnalysisError
- * "fixes": List<PrioritizedSourceChange>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisErrorFixes implements HasToJson {
- AnalysisError _error;
-
- List<PrioritizedSourceChange> _fixes;
-
- /**
- * The error with which the fixes are associated.
- */
- AnalysisError get error => _error;
-
- /**
- * The error with which the fixes are associated.
- */
- set error(AnalysisError value) {
- assert(value != null);
- this._error = value;
- }
-
- /**
- * The fixes associated with the error.
- */
- List<PrioritizedSourceChange> get fixes => _fixes;
-
- /**
- * The fixes associated with the error.
- */
- set fixes(List<PrioritizedSourceChange> value) {
- assert(value != null);
- this._fixes = value;
- }
-
- AnalysisErrorFixes(AnalysisError error,
- {List<PrioritizedSourceChange> fixes}) {
- this.error = error;
- if (fixes == null) {
- this.fixes = <PrioritizedSourceChange>[];
- } else {
- this.fixes = fixes;
- }
- }
-
- factory AnalysisErrorFixes.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- AnalysisError error;
- if (json.containsKey("error")) {
- error = new AnalysisError.fromJson(
- jsonDecoder, jsonPath + ".error", json["error"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "error");
- }
- List<PrioritizedSourceChange> fixes;
- if (json.containsKey("fixes")) {
- fixes = jsonDecoder.decodeList(
- jsonPath + ".fixes",
- json["fixes"],
- (String jsonPath, Object json) =>
- new PrioritizedSourceChange.fromJson(
- jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "fixes");
- }
- return new AnalysisErrorFixes(error, fixes: fixes);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "AnalysisErrorFixes", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["error"] = error.toJson();
- result["fixes"] =
- fixes.map((PrioritizedSourceChange value) => value.toJson()).toList();
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisErrorFixes) {
- return error == other.error &&
- listEqual(fixes, other.fixes,
- (PrioritizedSourceChange a, PrioritizedSourceChange b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, error.hashCode);
- hash = JenkinsSmiHash.combine(hash, fixes.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.errors params
- *
- * {
- * "file": FilePath
- * "errors": List<AnalysisError>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisErrorsParams implements HasToJson {
- String _file;
-
- List<AnalysisError> _errors;
-
- /**
- * The file containing the errors.
- */
- String get file => _file;
-
- /**
- * The file containing the errors.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The errors contained in the file.
- */
- List<AnalysisError> get errors => _errors;
-
- /**
- * The errors contained in the file.
- */
- set errors(List<AnalysisError> value) {
- assert(value != null);
- this._errors = value;
- }
-
- AnalysisErrorsParams(String file, List<AnalysisError> errors) {
- this.file = file;
- this.errors = errors;
- }
-
- factory AnalysisErrorsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- List<AnalysisError> errors;
- if (json.containsKey("errors")) {
- errors = jsonDecoder.decodeList(
- jsonPath + ".errors",
- json["errors"],
- (String jsonPath, Object json) =>
- new AnalysisError.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "errors");
- }
- return new AnalysisErrorsParams(file, errors);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "analysis.errors params", json);
- }
- }
-
- factory AnalysisErrorsParams.fromNotification(Notification notification) {
- return new AnalysisErrorsParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["errors"] =
- errors.map((AnalysisError value) => value.toJson()).toList();
- return result;
- }
-
- Notification toNotification() {
- return new Notification("analysis.errors", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisErrorsParams) {
- return file == other.file &&
- listEqual(errors, other.errors,
- (AnalysisError a, AnalysisError b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, errors.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.folding params
- *
- * {
- * "file": FilePath
- * "regions": List<FoldingRegion>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisFoldingParams implements HasToJson {
- String _file;
-
- List<FoldingRegion> _regions;
-
- /**
- * The file containing the folding regions.
- */
- String get file => _file;
-
- /**
- * The file containing the folding regions.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The folding regions contained in the file.
- */
- List<FoldingRegion> get regions => _regions;
-
- /**
- * The folding regions contained in the file.
- */
- set regions(List<FoldingRegion> value) {
- assert(value != null);
- this._regions = value;
- }
-
- AnalysisFoldingParams(String file, List<FoldingRegion> regions) {
- this.file = file;
- this.regions = regions;
- }
-
- factory AnalysisFoldingParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- List<FoldingRegion> regions;
- if (json.containsKey("regions")) {
- regions = jsonDecoder.decodeList(
- jsonPath + ".regions",
- json["regions"],
- (String jsonPath, Object json) =>
- new FoldingRegion.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "regions");
- }
- return new AnalysisFoldingParams(file, regions);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "analysis.folding params", json);
- }
- }
-
- factory AnalysisFoldingParams.fromNotification(Notification notification) {
- return new AnalysisFoldingParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["regions"] =
- regions.map((FoldingRegion value) => value.toJson()).toList();
- return result;
- }
-
- Notification toNotification() {
- return new Notification("analysis.folding", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisFoldingParams) {
- return file == other.file &&
- listEqual(regions, other.regions,
- (FoldingRegion a, FoldingRegion b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, regions.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.getNavigation params
- *
- * {
- * "file": FilePath
- * "offset": int
- * "length": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisGetNavigationParams implements RequestParams {
- String _file;
-
- int _offset;
-
- int _length;
-
- /**
- * The file in which navigation information is being requested.
- */
- String get file => _file;
-
- /**
- * The file in which navigation information is being requested.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset of the region for which navigation information is being
- * requested.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region for which navigation information is being
- * requested.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region for which navigation information is being
- * requested.
- */
- int get length => _length;
-
- /**
- * The length of the region for which navigation information is being
- * requested.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- AnalysisGetNavigationParams(String file, int offset, int length) {
- this.file = file;
- this.offset = offset;
- this.length = length;
- }
-
- factory AnalysisGetNavigationParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- return new AnalysisGetNavigationParams(file, offset, length);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.getNavigation params", json);
- }
- }
-
- factory AnalysisGetNavigationParams.fromRequest(Request request) {
- return new AnalysisGetNavigationParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- result["length"] = length;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "analysis.getNavigation", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisGetNavigationParams) {
- return file == other.file &&
- offset == other.offset &&
- length == other.length;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.getNavigation result
- *
- * {
- * "files": List<FilePath>
- * "targets": List<NavigationTarget>
- * "regions": List<NavigationRegion>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisGetNavigationResult implements ResponseResult {
- List<String> _files;
-
- List<NavigationTarget> _targets;
-
- List<NavigationRegion> _regions;
-
- /**
- * A list of the paths of files that are referenced by the navigation
- * targets.
- */
- List<String> get files => _files;
-
- /**
- * A list of the paths of files that are referenced by the navigation
- * targets.
- */
- set files(List<String> value) {
- assert(value != null);
- this._files = value;
- }
-
- /**
- * A list of the navigation targets that are referenced by the navigation
- * regions.
- */
- List<NavigationTarget> get targets => _targets;
-
- /**
- * A list of the navigation targets that are referenced by the navigation
- * regions.
- */
- set targets(List<NavigationTarget> value) {
- assert(value != null);
- this._targets = value;
- }
-
- /**
- * A list of the navigation regions within the requested region of the file.
- */
- List<NavigationRegion> get regions => _regions;
-
- /**
- * A list of the navigation regions within the requested region of the file.
- */
- set regions(List<NavigationRegion> value) {
- assert(value != null);
- this._regions = value;
- }
-
- AnalysisGetNavigationResult(List<String> files,
- List<NavigationTarget> targets, List<NavigationRegion> regions) {
- this.files = files;
- this.targets = targets;
- this.regions = regions;
- }
-
- factory AnalysisGetNavigationResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<String> files;
- if (json.containsKey("files")) {
- files = jsonDecoder.decodeList(
- jsonPath + ".files", json["files"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "files");
- }
- List<NavigationTarget> targets;
- if (json.containsKey("targets")) {
- targets = jsonDecoder.decodeList(
- jsonPath + ".targets",
- json["targets"],
- (String jsonPath, Object json) =>
- new NavigationTarget.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "targets");
- }
- List<NavigationRegion> regions;
- if (json.containsKey("regions")) {
- regions = jsonDecoder.decodeList(
- jsonPath + ".regions",
- json["regions"],
- (String jsonPath, Object json) =>
- new NavigationRegion.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "regions");
- }
- return new AnalysisGetNavigationResult(files, targets, regions);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.getNavigation result", json);
- }
- }
-
- factory AnalysisGetNavigationResult.fromResponse(Response response) {
- return new AnalysisGetNavigationResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["files"] = files;
- result["targets"] =
- targets.map((NavigationTarget value) => value.toJson()).toList();
- result["regions"] =
- regions.map((NavigationRegion value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisGetNavigationResult) {
- return listEqual(files, other.files, (String a, String b) => a == b) &&
- listEqual(targets, other.targets,
- (NavigationTarget a, NavigationTarget b) => a == b) &&
- listEqual(regions, other.regions,
- (NavigationRegion a, NavigationRegion b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, files.hashCode);
- hash = JenkinsSmiHash.combine(hash, targets.hashCode);
- hash = JenkinsSmiHash.combine(hash, regions.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.handleWatchEvents params
- *
- * {
- * "events": List<WatchEvent>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisHandleWatchEventsParams implements RequestParams {
- List<WatchEvent> _events;
-
- /**
- * The watch events that the plugin should handle.
- */
- List<WatchEvent> get events => _events;
-
- /**
- * The watch events that the plugin should handle.
- */
- set events(List<WatchEvent> value) {
- assert(value != null);
- this._events = value;
- }
-
- AnalysisHandleWatchEventsParams(List<WatchEvent> events) {
- this.events = events;
- }
-
- factory AnalysisHandleWatchEventsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<WatchEvent> events;
- if (json.containsKey("events")) {
- events = jsonDecoder.decodeList(
- jsonPath + ".events",
- json["events"],
- (String jsonPath, Object json) =>
- new WatchEvent.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "events");
- }
- return new AnalysisHandleWatchEventsParams(events);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.handleWatchEvents params", json);
- }
- }
-
- factory AnalysisHandleWatchEventsParams.fromRequest(Request request) {
- return new AnalysisHandleWatchEventsParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["events"] =
- events.map((WatchEvent value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "analysis.handleWatchEvents", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisHandleWatchEventsParams) {
- return listEqual(
- events, other.events, (WatchEvent a, WatchEvent b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, events.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.handleWatchEvents result
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisHandleWatchEventsResult implements ResponseResult {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: null);
- }
-
- @override
- bool operator ==(other) {
- if (other is AnalysisHandleWatchEventsResult) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 779767607;
- }
-}
-
-/**
- * analysis.highlights params
- *
- * {
- * "file": FilePath
- * "regions": List<HighlightRegion>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisHighlightsParams implements HasToJson {
- String _file;
-
- List<HighlightRegion> _regions;
-
- /**
- * The file containing the highlight regions.
- */
- String get file => _file;
-
- /**
- * The file containing the highlight regions.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The highlight regions contained in the file.
- */
- List<HighlightRegion> get regions => _regions;
-
- /**
- * The highlight regions contained in the file.
- */
- set regions(List<HighlightRegion> value) {
- assert(value != null);
- this._regions = value;
- }
-
- AnalysisHighlightsParams(String file, List<HighlightRegion> regions) {
- this.file = file;
- this.regions = regions;
- }
-
- factory AnalysisHighlightsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- List<HighlightRegion> regions;
- if (json.containsKey("regions")) {
- regions = jsonDecoder.decodeList(
- jsonPath + ".regions",
- json["regions"],
- (String jsonPath, Object json) =>
- new HighlightRegion.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "regions");
- }
- return new AnalysisHighlightsParams(file, regions);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "analysis.highlights params", json);
- }
- }
-
- factory AnalysisHighlightsParams.fromNotification(Notification notification) {
- return new AnalysisHighlightsParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["regions"] =
- regions.map((HighlightRegion value) => value.toJson()).toList();
- return result;
- }
-
- Notification toNotification() {
- return new Notification("analysis.highlights", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisHighlightsParams) {
- return file == other.file &&
- listEqual(regions, other.regions,
- (HighlightRegion a, HighlightRegion b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, regions.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.navigation params
- *
- * {
- * "file": FilePath
- * "regions": List<NavigationRegion>
- * "targets": List<NavigationTarget>
- * "files": List<FilePath>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisNavigationParams implements HasToJson {
- String _file;
-
- List<NavigationRegion> _regions;
-
- List<NavigationTarget> _targets;
-
- List<String> _files;
-
- /**
- * The file containing the navigation regions.
- */
- String get file => _file;
-
- /**
- * The file containing the navigation regions.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The navigation regions contained in the file.
- */
- List<NavigationRegion> get regions => _regions;
-
- /**
- * The navigation regions contained in the file.
- */
- set regions(List<NavigationRegion> value) {
- assert(value != null);
- this._regions = value;
- }
-
- /**
- * The navigation targets referenced in the file. They are referenced by
- * NavigationRegions by their index in this array.
- */
- List<NavigationTarget> get targets => _targets;
-
- /**
- * The navigation targets referenced in the file. They are referenced by
- * NavigationRegions by their index in this array.
- */
- set targets(List<NavigationTarget> value) {
- assert(value != null);
- this._targets = value;
- }
-
- /**
- * The files containing navigation targets referenced in the file. They are
- * referenced by NavigationTargets by their index in this array.
- */
- List<String> get files => _files;
-
- /**
- * The files containing navigation targets referenced in the file. They are
- * referenced by NavigationTargets by their index in this array.
- */
- set files(List<String> value) {
- assert(value != null);
- this._files = value;
- }
-
- AnalysisNavigationParams(String file, List<NavigationRegion> regions,
- List<NavigationTarget> targets, List<String> files) {
- this.file = file;
- this.regions = regions;
- this.targets = targets;
- this.files = files;
- }
-
- factory AnalysisNavigationParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- List<NavigationRegion> regions;
- if (json.containsKey("regions")) {
- regions = jsonDecoder.decodeList(
- jsonPath + ".regions",
- json["regions"],
- (String jsonPath, Object json) =>
- new NavigationRegion.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "regions");
- }
- List<NavigationTarget> targets;
- if (json.containsKey("targets")) {
- targets = jsonDecoder.decodeList(
- jsonPath + ".targets",
- json["targets"],
- (String jsonPath, Object json) =>
- new NavigationTarget.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "targets");
- }
- List<String> files;
- if (json.containsKey("files")) {
- files = jsonDecoder.decodeList(
- jsonPath + ".files", json["files"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "files");
- }
- return new AnalysisNavigationParams(file, regions, targets, files);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "analysis.navigation params", json);
- }
- }
-
- factory AnalysisNavigationParams.fromNotification(Notification notification) {
- return new AnalysisNavigationParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["regions"] =
- regions.map((NavigationRegion value) => value.toJson()).toList();
- result["targets"] =
- targets.map((NavigationTarget value) => value.toJson()).toList();
- result["files"] = files;
- return result;
- }
-
- Notification toNotification() {
- return new Notification("analysis.navigation", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisNavigationParams) {
- return file == other.file &&
- listEqual(regions, other.regions,
- (NavigationRegion a, NavigationRegion b) => a == b) &&
- listEqual(targets, other.targets,
- (NavigationTarget a, NavigationTarget b) => a == b) &&
- listEqual(files, other.files, (String a, String b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, regions.hashCode);
- hash = JenkinsSmiHash.combine(hash, targets.hashCode);
- hash = JenkinsSmiHash.combine(hash, files.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.occurrences params
- *
- * {
- * "file": FilePath
- * "occurrences": List<Occurrences>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisOccurrencesParams implements HasToJson {
- String _file;
-
- List<Occurrences> _occurrences;
-
- /**
- * The file in which the references occur.
- */
- String get file => _file;
-
- /**
- * The file in which the references occur.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The occurrences of references to elements within the file.
- */
- List<Occurrences> get occurrences => _occurrences;
-
- /**
- * The occurrences of references to elements within the file.
- */
- set occurrences(List<Occurrences> value) {
- assert(value != null);
- this._occurrences = value;
- }
-
- AnalysisOccurrencesParams(String file, List<Occurrences> occurrences) {
- this.file = file;
- this.occurrences = occurrences;
- }
-
- factory AnalysisOccurrencesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- List<Occurrences> occurrences;
- if (json.containsKey("occurrences")) {
- occurrences = jsonDecoder.decodeList(
- jsonPath + ".occurrences",
- json["occurrences"],
- (String jsonPath, Object json) =>
- new Occurrences.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "occurrences");
- }
- return new AnalysisOccurrencesParams(file, occurrences);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "analysis.occurrences params", json);
- }
- }
-
- factory AnalysisOccurrencesParams.fromNotification(
- Notification notification) {
- return new AnalysisOccurrencesParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["occurrences"] =
- occurrences.map((Occurrences value) => value.toJson()).toList();
- return result;
- }
-
- Notification toNotification() {
- return new Notification("analysis.occurrences", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisOccurrencesParams) {
- return file == other.file &&
- listEqual(occurrences, other.occurrences,
- (Occurrences a, Occurrences b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, occurrences.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.outline params
- *
- * {
- * "file": FilePath
- * "outline": List<Outline>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisOutlineParams implements HasToJson {
- String _file;
-
- List<Outline> _outline;
-
- /**
- * The file with which the outline is associated.
- */
- String get file => _file;
-
- /**
- * The file with which the outline is associated.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The outline fragments associated with the file.
- */
- List<Outline> get outline => _outline;
-
- /**
- * The outline fragments associated with the file.
- */
- set outline(List<Outline> value) {
- assert(value != null);
- this._outline = value;
- }
-
- AnalysisOutlineParams(String file, List<Outline> outline) {
- this.file = file;
- this.outline = outline;
- }
-
- factory AnalysisOutlineParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- List<Outline> outline;
- if (json.containsKey("outline")) {
- outline = jsonDecoder.decodeList(
- jsonPath + ".outline",
- json["outline"],
- (String jsonPath, Object json) =>
- new Outline.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "outline");
- }
- return new AnalysisOutlineParams(file, outline);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "analysis.outline params", json);
- }
- }
-
- factory AnalysisOutlineParams.fromNotification(Notification notification) {
- return new AnalysisOutlineParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["outline"] = outline.map((Outline value) => value.toJson()).toList();
- return result;
- }
-
- Notification toNotification() {
- return new Notification("analysis.outline", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisOutlineParams) {
- return file == other.file &&
- listEqual(outline, other.outline, (Outline a, Outline b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, outline.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * AnalysisService
- *
- * enum {
- * FOLDING
- * HIGHLIGHTS
- * NAVIGATION
- * OCCURRENCES
- * OUTLINE
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisService implements Enum {
- static const AnalysisService FOLDING = const AnalysisService._("FOLDING");
-
- static const AnalysisService HIGHLIGHTS =
- const AnalysisService._("HIGHLIGHTS");
-
- static const AnalysisService NAVIGATION =
- const AnalysisService._("NAVIGATION");
-
- static const AnalysisService OCCURRENCES =
- const AnalysisService._("OCCURRENCES");
-
- static const AnalysisService OUTLINE = const AnalysisService._("OUTLINE");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<AnalysisService> VALUES = const <AnalysisService>[
- FOLDING,
- HIGHLIGHTS,
- NAVIGATION,
- OCCURRENCES,
- OUTLINE
- ];
-
- @override
- final String name;
-
- const AnalysisService._(this.name);
-
- factory AnalysisService(String name) {
- switch (name) {
- case "FOLDING":
- return FOLDING;
- case "HIGHLIGHTS":
- return HIGHLIGHTS;
- case "NAVIGATION":
- return NAVIGATION;
- case "OCCURRENCES":
- return OCCURRENCES;
- case "OUTLINE":
- return OUTLINE;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory AnalysisService.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new AnalysisService(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "AnalysisService", json);
- }
-
- @override
- String toString() => "AnalysisService.$name";
-
- String toJson() => name;
-}
-
-/**
- * analysis.setContextRoots params
- *
- * {
- * "roots": List<ContextRoot>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisSetContextRootsParams implements RequestParams {
- List<ContextRoot> _roots;
-
- /**
- * A list of the context roots that should be analyzed.
- */
- List<ContextRoot> get roots => _roots;
-
- /**
- * A list of the context roots that should be analyzed.
- */
- set roots(List<ContextRoot> value) {
- assert(value != null);
- this._roots = value;
- }
-
- AnalysisSetContextRootsParams(List<ContextRoot> roots) {
- this.roots = roots;
- }
-
- factory AnalysisSetContextRootsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<ContextRoot> roots;
- if (json.containsKey("roots")) {
- roots = jsonDecoder.decodeList(
- jsonPath + ".roots",
- json["roots"],
- (String jsonPath, Object json) =>
- new ContextRoot.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "roots");
- }
- return new AnalysisSetContextRootsParams(roots);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.setContextRoots params", json);
- }
- }
-
- factory AnalysisSetContextRootsParams.fromRequest(Request request) {
- return new AnalysisSetContextRootsParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["roots"] = roots.map((ContextRoot value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "analysis.setContextRoots", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisSetContextRootsParams) {
- return listEqual(
- roots, other.roots, (ContextRoot a, ContextRoot b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, roots.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.setContextRoots result
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisSetContextRootsResult implements ResponseResult {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: null);
- }
-
- @override
- bool operator ==(other) {
- if (other is AnalysisSetContextRootsResult) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 969645618;
- }
-}
-
-/**
- * analysis.setPriorityFiles params
- *
- * {
- * "files": List<FilePath>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisSetPriorityFilesParams implements RequestParams {
- List<String> _files;
-
- /**
- * The files that are to be a priority for analysis.
- */
- List<String> get files => _files;
-
- /**
- * The files that are to be a priority for analysis.
- */
- set files(List<String> value) {
- assert(value != null);
- this._files = value;
- }
-
- AnalysisSetPriorityFilesParams(List<String> files) {
- this.files = files;
- }
-
- factory AnalysisSetPriorityFilesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<String> files;
- if (json.containsKey("files")) {
- files = jsonDecoder.decodeList(
- jsonPath + ".files", json["files"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "files");
- }
- return new AnalysisSetPriorityFilesParams(files);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.setPriorityFiles params", json);
- }
- }
-
- factory AnalysisSetPriorityFilesParams.fromRequest(Request request) {
- return new AnalysisSetPriorityFilesParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["files"] = files;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "analysis.setPriorityFiles", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisSetPriorityFilesParams) {
- return listEqual(files, other.files, (String a, String b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, files.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.setPriorityFiles result
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisSetPriorityFilesResult implements ResponseResult {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: null);
- }
-
- @override
- bool operator ==(other) {
- if (other is AnalysisSetPriorityFilesResult) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 330050055;
- }
-}
-
-/**
- * analysis.setSubscriptions params
- *
- * {
- * "subscriptions": Map<AnalysisService, List<FilePath>>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisSetSubscriptionsParams implements RequestParams {
- Map<AnalysisService, List<String>> _subscriptions;
-
- /**
- * A table mapping services to a list of the files being subscribed to the
- * service.
- */
- Map<AnalysisService, List<String>> get subscriptions => _subscriptions;
-
- /**
- * A table mapping services to a list of the files being subscribed to the
- * service.
- */
- set subscriptions(Map<AnalysisService, List<String>> value) {
- assert(value != null);
- this._subscriptions = value;
- }
-
- AnalysisSetSubscriptionsParams(
- Map<AnalysisService, List<String>> subscriptions) {
- this.subscriptions = subscriptions;
- }
-
- factory AnalysisSetSubscriptionsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- Map<AnalysisService, List<String>> subscriptions;
- if (json.containsKey("subscriptions")) {
- subscriptions = jsonDecoder.decodeMap(
- jsonPath + ".subscriptions", json["subscriptions"],
- keyDecoder: (String jsonPath, Object json) =>
- new AnalysisService.fromJson(jsonDecoder, jsonPath, json),
- valueDecoder: (String jsonPath, Object json) => jsonDecoder
- .decodeList(jsonPath, json, jsonDecoder.decodeString));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "subscriptions");
- }
- return new AnalysisSetSubscriptionsParams(subscriptions);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.setSubscriptions params", json);
- }
- }
-
- factory AnalysisSetSubscriptionsParams.fromRequest(Request request) {
- return new AnalysisSetSubscriptionsParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["subscriptions"] = mapMap(subscriptions,
- keyCallback: (AnalysisService value) => value.toJson());
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "analysis.setSubscriptions", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisSetSubscriptionsParams) {
- return mapEqual(
- subscriptions,
- other.subscriptions,
- (List<String> a, List<String> b) =>
- listEqual(a, b, (String a, String b) => a == b));
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, subscriptions.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.setSubscriptions result
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisSetSubscriptionsResult implements ResponseResult {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: null);
- }
-
- @override
- bool operator ==(other) {
- if (other is AnalysisSetSubscriptionsResult) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 218088493;
- }
-}
-
-/**
- * analysis.updateContent params
- *
- * {
- * "files": Map<FilePath, AddContentOverlay | ChangeContentOverlay | RemoveContentOverlay>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisUpdateContentParams implements RequestParams {
- Map<String, dynamic> _files;
-
- /**
- * A table mapping the files whose content has changed to a description of
- * the content change.
- */
- Map<String, dynamic> get files => _files;
-
- /**
- * A table mapping the files whose content has changed to a description of
- * the content change.
- */
- set files(Map<String, dynamic> value) {
- assert(value != null);
- this._files = value;
- }
-
- AnalysisUpdateContentParams(Map<String, dynamic> files) {
- this.files = files;
- }
-
- factory AnalysisUpdateContentParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- Map<String, dynamic> files;
- if (json.containsKey("files")) {
- files = jsonDecoder.decodeMap(jsonPath + ".files", json["files"],
- valueDecoder: (String jsonPath, Object json) =>
- jsonDecoder.decodeUnion(jsonPath, json as Map, "type", {
- "add": (String jsonPath, Object json) =>
- new AddContentOverlay.fromJson(
- jsonDecoder, jsonPath, json),
- "change": (String jsonPath, Object json) =>
- new ChangeContentOverlay.fromJson(
- jsonDecoder, jsonPath, json),
- "remove": (String jsonPath, Object json) =>
- new RemoveContentOverlay.fromJson(
- jsonDecoder, jsonPath, json)
- }));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "files");
- }
- return new AnalysisUpdateContentParams(files);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "analysis.updateContent params", json);
- }
- }
-
- factory AnalysisUpdateContentParams.fromRequest(Request request) {
- return new AnalysisUpdateContentParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["files"] =
- mapMap(files, valueCallback: (dynamic value) => value.toJson());
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "analysis.updateContent", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is AnalysisUpdateContentParams) {
- return mapEqual(files, other.files, (dynamic a, dynamic b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, files.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * analysis.updateContent result
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalysisUpdateContentResult implements ResponseResult {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: null);
- }
-
- @override
- bool operator ==(other) {
- if (other is AnalysisUpdateContentResult) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 468798730;
- }
-}
-
-/**
- * completion.getSuggestions params
- *
- * {
- * "file": FilePath
- * "offset": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class CompletionGetSuggestionsParams implements RequestParams {
- String _file;
-
- int _offset;
-
- /**
- * The file containing the point at which suggestions are to be made.
- */
- String get file => _file;
-
- /**
- * The file containing the point at which suggestions are to be made.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset within the file at which suggestions are to be made.
- */
- int get offset => _offset;
-
- /**
- * The offset within the file at which suggestions are to be made.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- CompletionGetSuggestionsParams(String file, int offset) {
- this.file = file;
- this.offset = offset;
- }
-
- factory CompletionGetSuggestionsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- return new CompletionGetSuggestionsParams(file, offset);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "completion.getSuggestions params", json);
- }
- }
-
- factory CompletionGetSuggestionsParams.fromRequest(Request request) {
- return new CompletionGetSuggestionsParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "completion.getSuggestions", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is CompletionGetSuggestionsParams) {
- return file == other.file && offset == other.offset;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * completion.getSuggestions result
- *
- * {
- * "replacementOffset": int
- * "replacementLength": int
- * "results": List<CompletionSuggestion>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class CompletionGetSuggestionsResult implements ResponseResult {
- int _replacementOffset;
-
- int _replacementLength;
-
- List<CompletionSuggestion> _results;
-
- /**
- * The offset of the start of the text to be replaced. This will be different
- * than the offset used to request the completion suggestions if there was a
- * portion of an identifier before the original offset. In particular, the
- * replacementOffset will be the offset of the beginning of said identifier.
- */
- int get replacementOffset => _replacementOffset;
-
- /**
- * The offset of the start of the text to be replaced. This will be different
- * than the offset used to request the completion suggestions if there was a
- * portion of an identifier before the original offset. In particular, the
- * replacementOffset will be the offset of the beginning of said identifier.
- */
- set replacementOffset(int value) {
- assert(value != null);
- this._replacementOffset = value;
- }
-
- /**
- * The length of the text to be replaced if the remainder of the identifier
- * containing the cursor is to be replaced when the suggestion is applied
- * (that is, the number of characters in the existing identifier).
- */
- int get replacementLength => _replacementLength;
-
- /**
- * The length of the text to be replaced if the remainder of the identifier
- * containing the cursor is to be replaced when the suggestion is applied
- * (that is, the number of characters in the existing identifier).
- */
- set replacementLength(int value) {
- assert(value != null);
- this._replacementLength = value;
- }
-
- /**
- * The completion suggestions being reported. The notification contains all
- * possible completions at the requested cursor position, even those that do
- * not match the characters the user has already typed. This allows the
- * client to respond to further keystrokes from the user without having to
- * make additional requests.
- */
- List<CompletionSuggestion> get results => _results;
-
- /**
- * The completion suggestions being reported. The notification contains all
- * possible completions at the requested cursor position, even those that do
- * not match the characters the user has already typed. This allows the
- * client to respond to further keystrokes from the user without having to
- * make additional requests.
- */
- set results(List<CompletionSuggestion> value) {
- assert(value != null);
- this._results = value;
- }
-
- CompletionGetSuggestionsResult(int replacementOffset, int replacementLength,
- List<CompletionSuggestion> results) {
- this.replacementOffset = replacementOffset;
- this.replacementLength = replacementLength;
- this.results = results;
- }
-
- factory CompletionGetSuggestionsResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- int replacementOffset;
- if (json.containsKey("replacementOffset")) {
- replacementOffset = jsonDecoder.decodeInt(
- jsonPath + ".replacementOffset", json["replacementOffset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "replacementOffset");
- }
- int replacementLength;
- if (json.containsKey("replacementLength")) {
- replacementLength = jsonDecoder.decodeInt(
- jsonPath + ".replacementLength", json["replacementLength"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "replacementLength");
- }
- List<CompletionSuggestion> results;
- if (json.containsKey("results")) {
- results = jsonDecoder.decodeList(
- jsonPath + ".results",
- json["results"],
- (String jsonPath, Object json) =>
- new CompletionSuggestion.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "results");
- }
- return new CompletionGetSuggestionsResult(
- replacementOffset, replacementLength, results);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "completion.getSuggestions result", json);
- }
- }
-
- factory CompletionGetSuggestionsResult.fromResponse(Response response) {
- return new CompletionGetSuggestionsResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["replacementOffset"] = replacementOffset;
- result["replacementLength"] = replacementLength;
- result["results"] =
- results.map((CompletionSuggestion value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is CompletionGetSuggestionsResult) {
- return replacementOffset == other.replacementOffset &&
- replacementLength == other.replacementLength &&
- listEqual(results, other.results,
- (CompletionSuggestion a, CompletionSuggestion b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, replacementOffset.hashCode);
- hash = JenkinsSmiHash.combine(hash, replacementLength.hashCode);
- hash = JenkinsSmiHash.combine(hash, results.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * ContextRoot
- *
- * {
- * "root": FilePath
- * "exclude": List<FilePath>
- * "optionsFile": optional FilePath
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ContextRoot implements HasToJson {
- String _root;
-
- List<String> _exclude;
-
- String _optionsFile;
-
- /**
- * The absolute path of the root directory containing the files to be
- * analyzed.
- */
- String get root => _root;
-
- /**
- * The absolute path of the root directory containing the files to be
- * analyzed.
- */
- set root(String value) {
- assert(value != null);
- this._root = value;
- }
-
- /**
- * A list of the absolute paths of files and directories within the root
- * directory that should not be analyzed.
- */
- List<String> get exclude => _exclude;
-
- /**
- * A list of the absolute paths of files and directories within the root
- * directory that should not be analyzed.
- */
- set exclude(List<String> value) {
- assert(value != null);
- this._exclude = value;
- }
-
- /**
- * The absolute path of the analysis options file that should be used to
- * control the analysis of the files in the context.
- */
- String get optionsFile => _optionsFile;
-
- /**
- * The absolute path of the analysis options file that should be used to
- * control the analysis of the files in the context.
- */
- set optionsFile(String value) {
- this._optionsFile = value;
- }
-
- ContextRoot(String root, List<String> exclude, {String optionsFile}) {
- this.root = root;
- this.exclude = exclude;
- this.optionsFile = optionsFile;
- }
-
- factory ContextRoot.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String root;
- if (json.containsKey("root")) {
- root = jsonDecoder.decodeString(jsonPath + ".root", json["root"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "root");
- }
- List<String> exclude;
- if (json.containsKey("exclude")) {
- exclude = jsonDecoder.decodeList(
- jsonPath + ".exclude", json["exclude"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "exclude");
- }
- String optionsFile;
- if (json.containsKey("optionsFile")) {
- optionsFile = jsonDecoder.decodeString(
- jsonPath + ".optionsFile", json["optionsFile"]);
- }
- return new ContextRoot(root, exclude, optionsFile: optionsFile);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "ContextRoot", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["root"] = root;
- result["exclude"] = exclude;
- if (optionsFile != null) {
- result["optionsFile"] = optionsFile;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ContextRoot) {
- return root == other.root &&
- listEqual(exclude, other.exclude, (String a, String b) => a == b) &&
- optionsFile == other.optionsFile;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, root.hashCode);
- hash = JenkinsSmiHash.combine(hash, exclude.hashCode);
- hash = JenkinsSmiHash.combine(hash, optionsFile.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * convertGetterToMethod feedback
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ConvertGetterToMethodFeedback extends RefactoringFeedback
- implements HasToJson {
- @override
- bool operator ==(other) {
- if (other is ConvertGetterToMethodFeedback) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 616032599;
- }
-}
-
-/**
- * convertGetterToMethod options
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ConvertGetterToMethodOptions extends RefactoringOptions
- implements HasToJson {
- @override
- bool operator ==(other) {
- if (other is ConvertGetterToMethodOptions) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 488848400;
- }
-}
-
-/**
- * convertMethodToGetter feedback
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ConvertMethodToGetterFeedback extends RefactoringFeedback
- implements HasToJson {
- @override
- bool operator ==(other) {
- if (other is ConvertMethodToGetterFeedback) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 165291526;
- }
-}
-
-/**
- * convertMethodToGetter options
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ConvertMethodToGetterOptions extends RefactoringOptions
- implements HasToJson {
- @override
- bool operator ==(other) {
- if (other is ConvertMethodToGetterOptions) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 27952290;
- }
-}
-
-/**
- * edit.getAssists params
- *
- * {
- * "file": FilePath
- * "offset": int
- * "length": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetAssistsParams implements RequestParams {
- String _file;
-
- int _offset;
-
- int _length;
-
- /**
- * The file containing the code for which assists are being requested.
- */
- String get file => _file;
-
- /**
- * The file containing the code for which assists are being requested.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset of the code for which assists are being requested.
- */
- int get offset => _offset;
-
- /**
- * The offset of the code for which assists are being requested.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the code for which assists are being requested.
- */
- int get length => _length;
-
- /**
- * The length of the code for which assists are being requested.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- EditGetAssistsParams(String file, int offset, int length) {
- this.file = file;
- this.offset = offset;
- this.length = length;
- }
-
- factory EditGetAssistsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- return new EditGetAssistsParams(file, offset, length);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edit.getAssists params", json);
- }
- }
-
- factory EditGetAssistsParams.fromRequest(Request request) {
- return new EditGetAssistsParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- result["length"] = length;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "edit.getAssists", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetAssistsParams) {
- return file == other.file &&
- offset == other.offset &&
- length == other.length;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getAssists result
- *
- * {
- * "assists": List<PrioritizedSourceChange>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetAssistsResult implements ResponseResult {
- List<PrioritizedSourceChange> _assists;
-
- /**
- * The assists that are available at the given location.
- */
- List<PrioritizedSourceChange> get assists => _assists;
-
- /**
- * The assists that are available at the given location.
- */
- set assists(List<PrioritizedSourceChange> value) {
- assert(value != null);
- this._assists = value;
- }
-
- EditGetAssistsResult(List<PrioritizedSourceChange> assists) {
- this.assists = assists;
- }
-
- factory EditGetAssistsResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<PrioritizedSourceChange> assists;
- if (json.containsKey("assists")) {
- assists = jsonDecoder.decodeList(
- jsonPath + ".assists",
- json["assists"],
- (String jsonPath, Object json) =>
- new PrioritizedSourceChange.fromJson(
- jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "assists");
- }
- return new EditGetAssistsResult(assists);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edit.getAssists result", json);
- }
- }
-
- factory EditGetAssistsResult.fromResponse(Response response) {
- return new EditGetAssistsResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["assists"] =
- assists.map((PrioritizedSourceChange value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetAssistsResult) {
- return listEqual(assists, other.assists,
- (PrioritizedSourceChange a, PrioritizedSourceChange b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, assists.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getAvailableRefactorings params
- *
- * {
- * "file": FilePath
- * "offset": int
- * "length": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetAvailableRefactoringsParams implements RequestParams {
- String _file;
-
- int _offset;
-
- int _length;
-
- /**
- * The file containing the code on which the refactoring would be based.
- */
- String get file => _file;
-
- /**
- * The file containing the code on which the refactoring would be based.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset of the code on which the refactoring would be based.
- */
- int get offset => _offset;
-
- /**
- * The offset of the code on which the refactoring would be based.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the code on which the refactoring would be based.
- */
- int get length => _length;
-
- /**
- * The length of the code on which the refactoring would be based.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- EditGetAvailableRefactoringsParams(String file, int offset, int length) {
- this.file = file;
- this.offset = offset;
- this.length = length;
- }
-
- factory EditGetAvailableRefactoringsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- return new EditGetAvailableRefactoringsParams(file, offset, length);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "edit.getAvailableRefactorings params", json);
- }
- }
-
- factory EditGetAvailableRefactoringsParams.fromRequest(Request request) {
- return new EditGetAvailableRefactoringsParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- result["length"] = length;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "edit.getAvailableRefactorings", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetAvailableRefactoringsParams) {
- return file == other.file &&
- offset == other.offset &&
- length == other.length;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getAvailableRefactorings result
- *
- * {
- * "kinds": List<RefactoringKind>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetAvailableRefactoringsResult implements ResponseResult {
- List<RefactoringKind> _kinds;
-
- /**
- * The kinds of refactorings that are valid for the given selection.
- *
- * The list of refactoring kinds is currently limited to those defined by the
- * server API, preventing plugins from adding their own refactorings.
- * However, plugins can support pre-defined refactorings, such as a rename
- * refactoring, at locations not supported by server.
- */
- List<RefactoringKind> get kinds => _kinds;
-
- /**
- * The kinds of refactorings that are valid for the given selection.
- *
- * The list of refactoring kinds is currently limited to those defined by the
- * server API, preventing plugins from adding their own refactorings.
- * However, plugins can support pre-defined refactorings, such as a rename
- * refactoring, at locations not supported by server.
- */
- set kinds(List<RefactoringKind> value) {
- assert(value != null);
- this._kinds = value;
- }
-
- EditGetAvailableRefactoringsResult(List<RefactoringKind> kinds) {
- this.kinds = kinds;
- }
-
- factory EditGetAvailableRefactoringsResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<RefactoringKind> kinds;
- if (json.containsKey("kinds")) {
- kinds = jsonDecoder.decodeList(
- jsonPath + ".kinds",
- json["kinds"],
- (String jsonPath, Object json) =>
- new RefactoringKind.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kinds");
- }
- return new EditGetAvailableRefactoringsResult(kinds);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "edit.getAvailableRefactorings result", json);
- }
- }
-
- factory EditGetAvailableRefactoringsResult.fromResponse(Response response) {
- return new EditGetAvailableRefactoringsResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kinds"] =
- kinds.map((RefactoringKind value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetAvailableRefactoringsResult) {
- return listEqual(
- kinds, other.kinds, (RefactoringKind a, RefactoringKind b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kinds.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getFixes params
- *
- * {
- * "file": FilePath
- * "offset": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetFixesParams implements RequestParams {
- String _file;
-
- int _offset;
-
- /**
- * The file containing the errors for which fixes are being requested.
- */
- String get file => _file;
-
- /**
- * The file containing the errors for which fixes are being requested.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset used to select the errors for which fixes will be returned.
- */
- int get offset => _offset;
-
- /**
- * The offset used to select the errors for which fixes will be returned.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- EditGetFixesParams(String file, int offset) {
- this.file = file;
- this.offset = offset;
- }
-
- factory EditGetFixesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- return new EditGetFixesParams(file, offset);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edit.getFixes params", json);
- }
- }
-
- factory EditGetFixesParams.fromRequest(Request request) {
- return new EditGetFixesParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- result["offset"] = offset;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "edit.getFixes", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetFixesParams) {
- return file == other.file && offset == other.offset;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getFixes result
- *
- * {
- * "fixes": List<AnalysisErrorFixes>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetFixesResult implements ResponseResult {
- List<AnalysisErrorFixes> _fixes;
-
- /**
- * The fixes that are available for the errors at the given offset.
- */
- List<AnalysisErrorFixes> get fixes => _fixes;
-
- /**
- * The fixes that are available for the errors at the given offset.
- */
- set fixes(List<AnalysisErrorFixes> value) {
- assert(value != null);
- this._fixes = value;
- }
-
- EditGetFixesResult(List<AnalysisErrorFixes> fixes) {
- this.fixes = fixes;
- }
-
- factory EditGetFixesResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<AnalysisErrorFixes> fixes;
- if (json.containsKey("fixes")) {
- fixes = jsonDecoder.decodeList(
- jsonPath + ".fixes",
- json["fixes"],
- (String jsonPath, Object json) =>
- new AnalysisErrorFixes.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "fixes");
- }
- return new EditGetFixesResult(fixes);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edit.getFixes result", json);
- }
- }
-
- factory EditGetFixesResult.fromResponse(Response response) {
- return new EditGetFixesResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["fixes"] =
- fixes.map((AnalysisErrorFixes value) => value.toJson()).toList();
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetFixesResult) {
- return listEqual(fixes, other.fixes,
- (AnalysisErrorFixes a, AnalysisErrorFixes b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, fixes.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getRefactoring params
- *
- * {
- * "kind": RefactoringKind
- * "file": FilePath
- * "offset": int
- * "length": int
- * "validateOnly": bool
- * "options": optional RefactoringOptions
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetRefactoringParams implements RequestParams {
- RefactoringKind _kind;
-
- String _file;
-
- int _offset;
-
- int _length;
-
- bool _validateOnly;
-
- RefactoringOptions _options;
-
- /**
- * The kind of refactoring to be performed.
- */
- RefactoringKind get kind => _kind;
-
- /**
- * The kind of refactoring to be performed.
- */
- set kind(RefactoringKind value) {
- assert(value != null);
- this._kind = value;
- }
-
- /**
- * The file containing the code involved in the refactoring.
- */
- String get file => _file;
-
- /**
- * The file containing the code involved in the refactoring.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- /**
- * The offset of the region involved in the refactoring.
- */
- int get offset => _offset;
-
- /**
- * The offset of the region involved in the refactoring.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the region involved in the refactoring.
- */
- int get length => _length;
-
- /**
- * The length of the region involved in the refactoring.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * True if the client is only requesting that the values of the options be
- * validated and no change be generated.
- */
- bool get validateOnly => _validateOnly;
-
- /**
- * True if the client is only requesting that the values of the options be
- * validated and no change be generated.
- */
- set validateOnly(bool value) {
- assert(value != null);
- this._validateOnly = value;
- }
-
- /**
- * Data used to provide values provided by the user. The structure of the
- * data is dependent on the kind of refactoring being performed. The data
- * that is expected is documented in the section titled Refactorings, labeled
- * as "Options". This field can be omitted if the refactoring does not
- * require any options or if the values of those options are not known.
- */
- RefactoringOptions get options => _options;
-
- /**
- * Data used to provide values provided by the user. The structure of the
- * data is dependent on the kind of refactoring being performed. The data
- * that is expected is documented in the section titled Refactorings, labeled
- * as "Options". This field can be omitted if the refactoring does not
- * require any options or if the values of those options are not known.
- */
- set options(RefactoringOptions value) {
- this._options = value;
- }
-
- EditGetRefactoringParams(RefactoringKind kind, String file, int offset,
- int length, bool validateOnly,
- {RefactoringOptions options}) {
- this.kind = kind;
- this.file = file;
- this.offset = offset;
- this.length = length;
- this.validateOnly = validateOnly;
- this.options = options;
- }
-
- factory EditGetRefactoringParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- RefactoringKind kind;
- if (json.containsKey("kind")) {
- kind = new RefactoringKind.fromJson(
- jsonDecoder, jsonPath + ".kind", json["kind"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "kind");
- }
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- bool validateOnly;
- if (json.containsKey("validateOnly")) {
- validateOnly = jsonDecoder.decodeBool(
- jsonPath + ".validateOnly", json["validateOnly"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "validateOnly");
- }
- RefactoringOptions options;
- if (json.containsKey("options")) {
- options = new RefactoringOptions.fromJson(
- jsonDecoder, jsonPath + ".options", json["options"], kind);
- }
- return new EditGetRefactoringParams(
- kind, file, offset, length, validateOnly,
- options: options);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edit.getRefactoring params", json);
- }
- }
-
- factory EditGetRefactoringParams.fromRequest(Request request) {
- var params = new EditGetRefactoringParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- REQUEST_ID_REFACTORING_KINDS[request.id] = params.kind;
- return params;
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["kind"] = kind.toJson();
- result["file"] = file;
- result["offset"] = offset;
- result["length"] = length;
- result["validateOnly"] = validateOnly;
- if (options != null) {
- result["options"] = options.toJson();
- }
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "edit.getRefactoring", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetRefactoringParams) {
- return kind == other.kind &&
- file == other.file &&
- offset == other.offset &&
- length == other.length &&
- validateOnly == other.validateOnly &&
- options == other.options;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, kind.hashCode);
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, validateOnly.hashCode);
- hash = JenkinsSmiHash.combine(hash, options.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * edit.getRefactoring result
- *
- * {
- * "initialProblems": List<RefactoringProblem>
- * "optionsProblems": List<RefactoringProblem>
- * "finalProblems": List<RefactoringProblem>
- * "feedback": optional RefactoringFeedback
- * "change": optional SourceChange
- * "potentialEdits": optional List<String>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EditGetRefactoringResult implements ResponseResult {
- List<RefactoringProblem> _initialProblems;
-
- List<RefactoringProblem> _optionsProblems;
-
- List<RefactoringProblem> _finalProblems;
-
- RefactoringFeedback _feedback;
-
- SourceChange _change;
-
- List<String> _potentialEdits;
-
- /**
- * The initial status of the refactoring, that is, problems related to the
- * context in which the refactoring is requested. The list should be empty if
- * there are no known problems.
- */
- List<RefactoringProblem> get initialProblems => _initialProblems;
-
- /**
- * The initial status of the refactoring, that is, problems related to the
- * context in which the refactoring is requested. The list should be empty if
- * there are no known problems.
- */
- set initialProblems(List<RefactoringProblem> value) {
- assert(value != null);
- this._initialProblems = value;
- }
-
- /**
- * The options validation status, that is, problems in the given options,
- * such as light-weight validation of a new name, flags compatibility, etc.
- * The list should be empty if there are no known problems.
- */
- List<RefactoringProblem> get optionsProblems => _optionsProblems;
-
- /**
- * The options validation status, that is, problems in the given options,
- * such as light-weight validation of a new name, flags compatibility, etc.
- * The list should be empty if there are no known problems.
- */
- set optionsProblems(List<RefactoringProblem> value) {
- assert(value != null);
- this._optionsProblems = value;
- }
-
- /**
- * The final status of the refactoring, that is, problems identified in the
- * result of a full, potentially expensive validation and / or change
- * creation. The list should be empty if there are no known problems.
- */
- List<RefactoringProblem> get finalProblems => _finalProblems;
-
- /**
- * The final status of the refactoring, that is, problems identified in the
- * result of a full, potentially expensive validation and / or change
- * creation. The list should be empty if there are no known problems.
- */
- set finalProblems(List<RefactoringProblem> value) {
- assert(value != null);
- this._finalProblems = value;
- }
-
- /**
- * Data used to provide feedback to the user. The structure of the data is
- * dependent on the kind of refactoring being created. The data that is
- * returned is documented in the section titled Refactorings, labeled as
- * "Feedback".
- */
- RefactoringFeedback get feedback => _feedback;
-
- /**
- * Data used to provide feedback to the user. The structure of the data is
- * dependent on the kind of refactoring being created. The data that is
- * returned is documented in the section titled Refactorings, labeled as
- * "Feedback".
- */
- set feedback(RefactoringFeedback value) {
- this._feedback = value;
- }
-
- /**
- * The changes that are to be applied to affect the refactoring. This field
- * can be omitted if there are problems that prevent a set of changes from
- * being computed, such as having no options specified for a refactoring that
- * requires them, or if only validation was requested.
- */
- SourceChange get change => _change;
-
- /**
- * The changes that are to be applied to affect the refactoring. This field
- * can be omitted if there are problems that prevent a set of changes from
- * being computed, such as having no options specified for a refactoring that
- * requires them, or if only validation was requested.
- */
- set change(SourceChange value) {
- this._change = value;
- }
-
- /**
- * The ids of source edits that are not known to be valid. An edit is not
- * known to be valid if there was insufficient type information for the
- * plugin to be able to determine whether or not the code needs to be
- * modified, such as when a member is being renamed and there is a reference
- * to a member from an unknown type. This field can be omitted if the change
- * field is omitted or if there are no potential edits for the refactoring.
- */
- List<String> get potentialEdits => _potentialEdits;
-
- /**
- * The ids of source edits that are not known to be valid. An edit is not
- * known to be valid if there was insufficient type information for the
- * plugin to be able to determine whether or not the code needs to be
- * modified, such as when a member is being renamed and there is a reference
- * to a member from an unknown type. This field can be omitted if the change
- * field is omitted or if there are no potential edits for the refactoring.
- */
- set potentialEdits(List<String> value) {
- this._potentialEdits = value;
- }
-
- EditGetRefactoringResult(
- List<RefactoringProblem> initialProblems,
- List<RefactoringProblem> optionsProblems,
- List<RefactoringProblem> finalProblems,
- {RefactoringFeedback feedback,
- SourceChange change,
- List<String> potentialEdits}) {
- this.initialProblems = initialProblems;
- this.optionsProblems = optionsProblems;
- this.finalProblems = finalProblems;
- this.feedback = feedback;
- this.change = change;
- this.potentialEdits = potentialEdits;
- }
-
- factory EditGetRefactoringResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<RefactoringProblem> initialProblems;
- if (json.containsKey("initialProblems")) {
- initialProblems = jsonDecoder.decodeList(
- jsonPath + ".initialProblems",
- json["initialProblems"],
- (String jsonPath, Object json) =>
- new RefactoringProblem.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "initialProblems");
- }
- List<RefactoringProblem> optionsProblems;
- if (json.containsKey("optionsProblems")) {
- optionsProblems = jsonDecoder.decodeList(
- jsonPath + ".optionsProblems",
- json["optionsProblems"],
- (String jsonPath, Object json) =>
- new RefactoringProblem.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "optionsProblems");
- }
- List<RefactoringProblem> finalProblems;
- if (json.containsKey("finalProblems")) {
- finalProblems = jsonDecoder.decodeList(
- jsonPath + ".finalProblems",
- json["finalProblems"],
- (String jsonPath, Object json) =>
- new RefactoringProblem.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "finalProblems");
- }
- RefactoringFeedback feedback;
- if (json.containsKey("feedback")) {
- feedback = new RefactoringFeedback.fromJson(
- jsonDecoder, jsonPath + ".feedback", json["feedback"], json);
- }
- SourceChange change;
- if (json.containsKey("change")) {
- change = new SourceChange.fromJson(
- jsonDecoder, jsonPath + ".change", json["change"]);
- }
- List<String> potentialEdits;
- if (json.containsKey("potentialEdits")) {
- potentialEdits = jsonDecoder.decodeList(jsonPath + ".potentialEdits",
- json["potentialEdits"], jsonDecoder.decodeString);
- }
- return new EditGetRefactoringResult(
- initialProblems, optionsProblems, finalProblems,
- feedback: feedback, change: change, potentialEdits: potentialEdits);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "edit.getRefactoring result", json);
- }
- }
-
- factory EditGetRefactoringResult.fromResponse(Response response) {
- return new EditGetRefactoringResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["initialProblems"] = initialProblems
- .map((RefactoringProblem value) => value.toJson())
- .toList();
- result["optionsProblems"] = optionsProblems
- .map((RefactoringProblem value) => value.toJson())
- .toList();
- result["finalProblems"] = finalProblems
- .map((RefactoringProblem value) => value.toJson())
- .toList();
- if (feedback != null) {
- result["feedback"] = feedback.toJson();
- }
- if (change != null) {
- result["change"] = change.toJson();
- }
- if (potentialEdits != null) {
- result["potentialEdits"] = potentialEdits;
- }
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is EditGetRefactoringResult) {
- return listEqual(initialProblems, other.initialProblems,
- (RefactoringProblem a, RefactoringProblem b) => a == b) &&
- listEqual(optionsProblems, other.optionsProblems,
- (RefactoringProblem a, RefactoringProblem b) => a == b) &&
- listEqual(finalProblems, other.finalProblems,
- (RefactoringProblem a, RefactoringProblem b) => a == b) &&
- feedback == other.feedback &&
- change == other.change &&
- listEqual(potentialEdits, other.potentialEdits,
- (String a, String b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, initialProblems.hashCode);
- hash = JenkinsSmiHash.combine(hash, optionsProblems.hashCode);
- hash = JenkinsSmiHash.combine(hash, finalProblems.hashCode);
- hash = JenkinsSmiHash.combine(hash, feedback.hashCode);
- hash = JenkinsSmiHash.combine(hash, change.hashCode);
- hash = JenkinsSmiHash.combine(hash, potentialEdits.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * extractLocalVariable feedback
- *
- * {
- * "coveringExpressionOffsets": optional List<int>
- * "coveringExpressionLengths": optional List<int>
- * "names": List<String>
- * "offsets": List<int>
- * "lengths": List<int>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ExtractLocalVariableFeedback extends RefactoringFeedback {
- List<int> _coveringExpressionOffsets;
-
- List<int> _coveringExpressionLengths;
-
- List<String> _names;
-
- List<int> _offsets;
-
- List<int> _lengths;
-
- /**
- * The offsets of the expressions that cover the specified selection, from
- * the down most to the up most.
- */
- List<int> get coveringExpressionOffsets => _coveringExpressionOffsets;
-
- /**
- * The offsets of the expressions that cover the specified selection, from
- * the down most to the up most.
- */
- set coveringExpressionOffsets(List<int> value) {
- this._coveringExpressionOffsets = value;
- }
-
- /**
- * The lengths of the expressions that cover the specified selection, from
- * the down most to the up most.
- */
- List<int> get coveringExpressionLengths => _coveringExpressionLengths;
-
- /**
- * The lengths of the expressions that cover the specified selection, from
- * the down most to the up most.
- */
- set coveringExpressionLengths(List<int> value) {
- this._coveringExpressionLengths = value;
- }
-
- /**
- * The proposed names for the local variable.
- */
- List<String> get names => _names;
-
- /**
- * The proposed names for the local variable.
- */
- set names(List<String> value) {
- assert(value != null);
- this._names = value;
- }
-
- /**
- * The offsets of the expressions that would be replaced by a reference to
- * the variable.
- */
- List<int> get offsets => _offsets;
-
- /**
- * The offsets of the expressions that would be replaced by a reference to
- * the variable.
- */
- set offsets(List<int> value) {
- assert(value != null);
- this._offsets = value;
- }
-
- /**
- * The lengths of the expressions that would be replaced by a reference to
- * the variable. The lengths correspond to the offsets. In other words, for a
- * given expression, if the offset of that expression is offsets[i], then the
- * length of that expression is lengths[i].
- */
- List<int> get lengths => _lengths;
-
- /**
- * The lengths of the expressions that would be replaced by a reference to
- * the variable. The lengths correspond to the offsets. In other words, for a
- * given expression, if the offset of that expression is offsets[i], then the
- * length of that expression is lengths[i].
- */
- set lengths(List<int> value) {
- assert(value != null);
- this._lengths = value;
- }
-
- ExtractLocalVariableFeedback(
- List<String> names, List<int> offsets, List<int> lengths,
- {List<int> coveringExpressionOffsets,
- List<int> coveringExpressionLengths}) {
- this.coveringExpressionOffsets = coveringExpressionOffsets;
- this.coveringExpressionLengths = coveringExpressionLengths;
- this.names = names;
- this.offsets = offsets;
- this.lengths = lengths;
- }
-
- factory ExtractLocalVariableFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<int> coveringExpressionOffsets;
- if (json.containsKey("coveringExpressionOffsets")) {
- coveringExpressionOffsets = jsonDecoder.decodeList(
- jsonPath + ".coveringExpressionOffsets",
- json["coveringExpressionOffsets"],
- jsonDecoder.decodeInt);
- }
- List<int> coveringExpressionLengths;
- if (json.containsKey("coveringExpressionLengths")) {
- coveringExpressionLengths = jsonDecoder.decodeList(
- jsonPath + ".coveringExpressionLengths",
- json["coveringExpressionLengths"],
- jsonDecoder.decodeInt);
- }
- List<String> names;
- if (json.containsKey("names")) {
- names = jsonDecoder.decodeList(
- jsonPath + ".names", json["names"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "names");
- }
- List<int> offsets;
- if (json.containsKey("offsets")) {
- offsets = jsonDecoder.decodeList(
- jsonPath + ".offsets", json["offsets"], jsonDecoder.decodeInt);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offsets");
- }
- List<int> lengths;
- if (json.containsKey("lengths")) {
- lengths = jsonDecoder.decodeList(
- jsonPath + ".lengths", json["lengths"], jsonDecoder.decodeInt);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "lengths");
- }
- return new ExtractLocalVariableFeedback(names, offsets, lengths,
- coveringExpressionOffsets: coveringExpressionOffsets,
- coveringExpressionLengths: coveringExpressionLengths);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "extractLocalVariable feedback", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- if (coveringExpressionOffsets != null) {
- result["coveringExpressionOffsets"] = coveringExpressionOffsets;
- }
- if (coveringExpressionLengths != null) {
- result["coveringExpressionLengths"] = coveringExpressionLengths;
- }
- result["names"] = names;
- result["offsets"] = offsets;
- result["lengths"] = lengths;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ExtractLocalVariableFeedback) {
- return listEqual(coveringExpressionOffsets,
- other.coveringExpressionOffsets, (int a, int b) => a == b) &&
- listEqual(coveringExpressionLengths, other.coveringExpressionLengths,
- (int a, int b) => a == b) &&
- listEqual(names, other.names, (String a, String b) => a == b) &&
- listEqual(offsets, other.offsets, (int a, int b) => a == b) &&
- listEqual(lengths, other.lengths, (int a, int b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, coveringExpressionOffsets.hashCode);
- hash = JenkinsSmiHash.combine(hash, coveringExpressionLengths.hashCode);
- hash = JenkinsSmiHash.combine(hash, names.hashCode);
- hash = JenkinsSmiHash.combine(hash, offsets.hashCode);
- hash = JenkinsSmiHash.combine(hash, lengths.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * extractLocalVariable options
- *
- * {
- * "name": String
- * "extractAll": bool
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ExtractLocalVariableOptions extends RefactoringOptions {
- String _name;
-
- bool _extractAll;
-
- /**
- * The name that the local variable should be given.
- */
- String get name => _name;
-
- /**
- * The name that the local variable should be given.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * True if all occurrences of the expression within the scope in which the
- * variable will be defined should be replaced by a reference to the local
- * variable. The expression used to initiate the refactoring will always be
- * replaced.
- */
- bool get extractAll => _extractAll;
-
- /**
- * True if all occurrences of the expression within the scope in which the
- * variable will be defined should be replaced by a reference to the local
- * variable. The expression used to initiate the refactoring will always be
- * replaced.
- */
- set extractAll(bool value) {
- assert(value != null);
- this._extractAll = value;
- }
-
- ExtractLocalVariableOptions(String name, bool extractAll) {
- this.name = name;
- this.extractAll = extractAll;
- }
-
- factory ExtractLocalVariableOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- bool extractAll;
- if (json.containsKey("extractAll")) {
- extractAll = jsonDecoder.decodeBool(
- jsonPath + ".extractAll", json["extractAll"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "extractAll");
- }
- return new ExtractLocalVariableOptions(name, extractAll);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "extractLocalVariable options", json);
- }
- }
-
- factory ExtractLocalVariableOptions.fromRefactoringParams(
- EditGetRefactoringParams refactoringParams, Request request) {
- return new ExtractLocalVariableOptions.fromJson(
- new RequestDecoder(request), "options", refactoringParams.options);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["name"] = name;
- result["extractAll"] = extractAll;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ExtractLocalVariableOptions) {
- return name == other.name && extractAll == other.extractAll;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, extractAll.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * extractMethod feedback
- *
- * {
- * "offset": int
- * "length": int
- * "returnType": String
- * "names": List<String>
- * "canCreateGetter": bool
- * "parameters": List<RefactoringMethodParameter>
- * "offsets": List<int>
- * "lengths": List<int>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ExtractMethodFeedback extends RefactoringFeedback {
- int _offset;
-
- int _length;
-
- String _returnType;
-
- List<String> _names;
-
- bool _canCreateGetter;
-
- List<RefactoringMethodParameter> _parameters;
-
- List<int> _offsets;
-
- List<int> _lengths;
-
- /**
- * The offset to the beginning of the expression or statements that will be
- * extracted.
- */
- int get offset => _offset;
-
- /**
- * The offset to the beginning of the expression or statements that will be
- * extracted.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the expression or statements that will be extracted.
- */
- int get length => _length;
-
- /**
- * The length of the expression or statements that will be extracted.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The proposed return type for the method. If the returned element does not
- * have a declared return type, this field will contain an empty string.
- */
- String get returnType => _returnType;
-
- /**
- * The proposed return type for the method. If the returned element does not
- * have a declared return type, this field will contain an empty string.
- */
- set returnType(String value) {
- assert(value != null);
- this._returnType = value;
- }
-
- /**
- * The proposed names for the method.
- */
- List<String> get names => _names;
-
- /**
- * The proposed names for the method.
- */
- set names(List<String> value) {
- assert(value != null);
- this._names = value;
- }
-
- /**
- * True if a getter could be created rather than a method.
- */
- bool get canCreateGetter => _canCreateGetter;
-
- /**
- * True if a getter could be created rather than a method.
- */
- set canCreateGetter(bool value) {
- assert(value != null);
- this._canCreateGetter = value;
- }
-
- /**
- * The proposed parameters for the method.
- */
- List<RefactoringMethodParameter> get parameters => _parameters;
-
- /**
- * The proposed parameters for the method.
- */
- set parameters(List<RefactoringMethodParameter> value) {
- assert(value != null);
- this._parameters = value;
- }
-
- /**
- * The offsets of the expressions or statements that would be replaced by an
- * invocation of the method.
- */
- List<int> get offsets => _offsets;
-
- /**
- * The offsets of the expressions or statements that would be replaced by an
- * invocation of the method.
- */
- set offsets(List<int> value) {
- assert(value != null);
- this._offsets = value;
- }
-
- /**
- * The lengths of the expressions or statements that would be replaced by an
- * invocation of the method. The lengths correspond to the offsets. In other
- * words, for a given expression (or block of statements), if the offset of
- * that expression is offsets[i], then the length of that expression is
- * lengths[i].
- */
- List<int> get lengths => _lengths;
-
- /**
- * The lengths of the expressions or statements that would be replaced by an
- * invocation of the method. The lengths correspond to the offsets. In other
- * words, for a given expression (or block of statements), if the offset of
- * that expression is offsets[i], then the length of that expression is
- * lengths[i].
- */
- set lengths(List<int> value) {
- assert(value != null);
- this._lengths = value;
- }
-
- ExtractMethodFeedback(
- int offset,
- int length,
- String returnType,
- List<String> names,
- bool canCreateGetter,
- List<RefactoringMethodParameter> parameters,
- List<int> offsets,
- List<int> lengths) {
- this.offset = offset;
- this.length = length;
- this.returnType = returnType;
- this.names = names;
- this.canCreateGetter = canCreateGetter;
- this.parameters = parameters;
- this.offsets = offsets;
- this.lengths = lengths;
- }
-
- factory ExtractMethodFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- String returnType;
- if (json.containsKey("returnType")) {
- returnType = jsonDecoder.decodeString(
- jsonPath + ".returnType", json["returnType"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "returnType");
- }
- List<String> names;
- if (json.containsKey("names")) {
- names = jsonDecoder.decodeList(
- jsonPath + ".names", json["names"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "names");
- }
- bool canCreateGetter;
- if (json.containsKey("canCreateGetter")) {
- canCreateGetter = jsonDecoder.decodeBool(
- jsonPath + ".canCreateGetter", json["canCreateGetter"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "canCreateGetter");
- }
- List<RefactoringMethodParameter> parameters;
- if (json.containsKey("parameters")) {
- parameters = jsonDecoder.decodeList(
- jsonPath + ".parameters",
- json["parameters"],
- (String jsonPath, Object json) =>
- new RefactoringMethodParameter.fromJson(
- jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "parameters");
- }
- List<int> offsets;
- if (json.containsKey("offsets")) {
- offsets = jsonDecoder.decodeList(
- jsonPath + ".offsets", json["offsets"], jsonDecoder.decodeInt);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offsets");
- }
- List<int> lengths;
- if (json.containsKey("lengths")) {
- lengths = jsonDecoder.decodeList(
- jsonPath + ".lengths", json["lengths"], jsonDecoder.decodeInt);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "lengths");
- }
- return new ExtractMethodFeedback(offset, length, returnType, names,
- canCreateGetter, parameters, offsets, lengths);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "extractMethod feedback", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["offset"] = offset;
- result["length"] = length;
- result["returnType"] = returnType;
- result["names"] = names;
- result["canCreateGetter"] = canCreateGetter;
- result["parameters"] = parameters
- .map((RefactoringMethodParameter value) => value.toJson())
- .toList();
- result["offsets"] = offsets;
- result["lengths"] = lengths;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ExtractMethodFeedback) {
- return offset == other.offset &&
- length == other.length &&
- returnType == other.returnType &&
- listEqual(names, other.names, (String a, String b) => a == b) &&
- canCreateGetter == other.canCreateGetter &&
- listEqual(
- parameters,
- other.parameters,
- (RefactoringMethodParameter a, RefactoringMethodParameter b) =>
- a == b) &&
- listEqual(offsets, other.offsets, (int a, int b) => a == b) &&
- listEqual(lengths, other.lengths, (int a, int b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, returnType.hashCode);
- hash = JenkinsSmiHash.combine(hash, names.hashCode);
- hash = JenkinsSmiHash.combine(hash, canCreateGetter.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameters.hashCode);
- hash = JenkinsSmiHash.combine(hash, offsets.hashCode);
- hash = JenkinsSmiHash.combine(hash, lengths.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * extractMethod options
- *
- * {
- * "returnType": String
- * "createGetter": bool
- * "name": String
- * "parameters": List<RefactoringMethodParameter>
- * "extractAll": bool
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class ExtractMethodOptions extends RefactoringOptions {
- String _returnType;
-
- bool _createGetter;
-
- String _name;
-
- List<RefactoringMethodParameter> _parameters;
-
- bool _extractAll;
-
- /**
- * The return type that should be defined for the method.
- */
- String get returnType => _returnType;
-
- /**
- * The return type that should be defined for the method.
- */
- set returnType(String value) {
- assert(value != null);
- this._returnType = value;
- }
-
- /**
- * True if a getter should be created rather than a method. It is an error if
- * this field is true and the list of parameters is non-empty.
- */
- bool get createGetter => _createGetter;
-
- /**
- * True if a getter should be created rather than a method. It is an error if
- * this field is true and the list of parameters is non-empty.
- */
- set createGetter(bool value) {
- assert(value != null);
- this._createGetter = value;
- }
-
- /**
- * The name that the method should be given.
- */
- String get name => _name;
-
- /**
- * The name that the method should be given.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * The parameters that should be defined for the method.
- *
- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL
- * parameter. It is an error if a REQUIRED or POSITIONAL parameter follows a
- * NAMED parameter.
- *
- * - To change the order and/or update proposed parameters, add parameters
- * with the same identifiers as proposed.
- * - To add new parameters, omit their identifier.
- * - To remove some parameters, omit them in this list.
- */
- List<RefactoringMethodParameter> get parameters => _parameters;
-
- /**
- * The parameters that should be defined for the method.
- *
- * It is an error if a REQUIRED or NAMED parameter follows a POSITIONAL
- * parameter. It is an error if a REQUIRED or POSITIONAL parameter follows a
- * NAMED parameter.
- *
- * - To change the order and/or update proposed parameters, add parameters
- * with the same identifiers as proposed.
- * - To add new parameters, omit their identifier.
- * - To remove some parameters, omit them in this list.
- */
- set parameters(List<RefactoringMethodParameter> value) {
- assert(value != null);
- this._parameters = value;
- }
-
- /**
- * True if all occurrences of the expression or statements should be replaced
- * by an invocation of the method. The expression or statements used to
- * initiate the refactoring will always be replaced.
- */
- bool get extractAll => _extractAll;
-
- /**
- * True if all occurrences of the expression or statements should be replaced
- * by an invocation of the method. The expression or statements used to
- * initiate the refactoring will always be replaced.
- */
- set extractAll(bool value) {
- assert(value != null);
- this._extractAll = value;
- }
-
- ExtractMethodOptions(String returnType, bool createGetter, String name,
- List<RefactoringMethodParameter> parameters, bool extractAll) {
- this.returnType = returnType;
- this.createGetter = createGetter;
- this.name = name;
- this.parameters = parameters;
- this.extractAll = extractAll;
- }
-
- factory ExtractMethodOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String returnType;
- if (json.containsKey("returnType")) {
- returnType = jsonDecoder.decodeString(
- jsonPath + ".returnType", json["returnType"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "returnType");
- }
- bool createGetter;
- if (json.containsKey("createGetter")) {
- createGetter = jsonDecoder.decodeBool(
- jsonPath + ".createGetter", json["createGetter"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "createGetter");
- }
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- List<RefactoringMethodParameter> parameters;
- if (json.containsKey("parameters")) {
- parameters = jsonDecoder.decodeList(
- jsonPath + ".parameters",
- json["parameters"],
- (String jsonPath, Object json) =>
- new RefactoringMethodParameter.fromJson(
- jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "parameters");
- }
- bool extractAll;
- if (json.containsKey("extractAll")) {
- extractAll = jsonDecoder.decodeBool(
- jsonPath + ".extractAll", json["extractAll"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "extractAll");
- }
- return new ExtractMethodOptions(
- returnType, createGetter, name, parameters, extractAll);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "extractMethod options", json);
- }
- }
-
- factory ExtractMethodOptions.fromRefactoringParams(
- EditGetRefactoringParams refactoringParams, Request request) {
- return new ExtractMethodOptions.fromJson(
- new RequestDecoder(request), "options", refactoringParams.options);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["returnType"] = returnType;
- result["createGetter"] = createGetter;
- result["name"] = name;
- result["parameters"] = parameters
- .map((RefactoringMethodParameter value) => value.toJson())
- .toList();
- result["extractAll"] = extractAll;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is ExtractMethodOptions) {
- return returnType == other.returnType &&
- createGetter == other.createGetter &&
- name == other.name &&
- listEqual(
- parameters,
- other.parameters,
- (RefactoringMethodParameter a, RefactoringMethodParameter b) =>
- a == b) &&
- extractAll == other.extractAll;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, returnType.hashCode);
- hash = JenkinsSmiHash.combine(hash, createGetter.hashCode);
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, parameters.hashCode);
- hash = JenkinsSmiHash.combine(hash, extractAll.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * inlineLocalVariable feedback
- *
- * {
- * "name": String
- * "occurrences": int
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class InlineLocalVariableFeedback extends RefactoringFeedback {
- String _name;
-
- int _occurrences;
-
- /**
- * The name of the variable being inlined.
- */
- String get name => _name;
-
- /**
- * The name of the variable being inlined.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * The number of times the variable occurs.
- */
- int get occurrences => _occurrences;
-
- /**
- * The number of times the variable occurs.
- */
- set occurrences(int value) {
- assert(value != null);
- this._occurrences = value;
- }
-
- InlineLocalVariableFeedback(String name, int occurrences) {
- this.name = name;
- this.occurrences = occurrences;
- }
-
- factory InlineLocalVariableFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- int occurrences;
- if (json.containsKey("occurrences")) {
- occurrences = jsonDecoder.decodeInt(
- jsonPath + ".occurrences", json["occurrences"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "occurrences");
- }
- return new InlineLocalVariableFeedback(name, occurrences);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "inlineLocalVariable feedback", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["name"] = name;
- result["occurrences"] = occurrences;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is InlineLocalVariableFeedback) {
- return name == other.name && occurrences == other.occurrences;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, occurrences.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * inlineLocalVariable options
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class InlineLocalVariableOptions extends RefactoringOptions
- implements HasToJson {
- @override
- bool operator ==(other) {
- if (other is InlineLocalVariableOptions) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 540364977;
- }
-}
-
-/**
- * inlineMethod feedback
- *
- * {
- * "className": optional String
- * "methodName": String
- * "isDeclaration": bool
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class InlineMethodFeedback extends RefactoringFeedback {
- String _className;
-
- String _methodName;
-
- bool _isDeclaration;
-
- /**
- * The name of the class enclosing the method being inlined. If not a class
- * member is being inlined, this field will be absent.
- */
- String get className => _className;
-
- /**
- * The name of the class enclosing the method being inlined. If not a class
- * member is being inlined, this field will be absent.
- */
- set className(String value) {
- this._className = value;
- }
-
- /**
- * The name of the method (or function) being inlined.
- */
- String get methodName => _methodName;
-
- /**
- * The name of the method (or function) being inlined.
- */
- set methodName(String value) {
- assert(value != null);
- this._methodName = value;
- }
-
- /**
- * True if the declaration of the method is selected and all references
- * should be inlined.
- */
- bool get isDeclaration => _isDeclaration;
-
- /**
- * True if the declaration of the method is selected and all references
- * should be inlined.
- */
- set isDeclaration(bool value) {
- assert(value != null);
- this._isDeclaration = value;
- }
-
- InlineMethodFeedback(String methodName, bool isDeclaration,
- {String className}) {
- this.className = className;
- this.methodName = methodName;
- this.isDeclaration = isDeclaration;
- }
-
- factory InlineMethodFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String className;
- if (json.containsKey("className")) {
- className = jsonDecoder.decodeString(
- jsonPath + ".className", json["className"]);
- }
- String methodName;
- if (json.containsKey("methodName")) {
- methodName = jsonDecoder.decodeString(
- jsonPath + ".methodName", json["methodName"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "methodName");
- }
- bool isDeclaration;
- if (json.containsKey("isDeclaration")) {
- isDeclaration = jsonDecoder.decodeBool(
- jsonPath + ".isDeclaration", json["isDeclaration"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "isDeclaration");
- }
- return new InlineMethodFeedback(methodName, isDeclaration,
- className: className);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "inlineMethod feedback", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- if (className != null) {
- result["className"] = className;
- }
- result["methodName"] = methodName;
- result["isDeclaration"] = isDeclaration;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is InlineMethodFeedback) {
- return className == other.className &&
- methodName == other.methodName &&
- isDeclaration == other.isDeclaration;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, className.hashCode);
- hash = JenkinsSmiHash.combine(hash, methodName.hashCode);
- hash = JenkinsSmiHash.combine(hash, isDeclaration.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * inlineMethod options
- *
- * {
- * "deleteSource": bool
- * "inlineAll": bool
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class InlineMethodOptions extends RefactoringOptions {
- bool _deleteSource;
-
- bool _inlineAll;
-
- /**
- * True if the method being inlined should be removed. It is an error if this
- * field is true and inlineAll is false.
- */
- bool get deleteSource => _deleteSource;
-
- /**
- * True if the method being inlined should be removed. It is an error if this
- * field is true and inlineAll is false.
- */
- set deleteSource(bool value) {
- assert(value != null);
- this._deleteSource = value;
- }
-
- /**
- * True if all invocations of the method should be inlined, or false if only
- * the invocation site used to create this refactoring should be inlined.
- */
- bool get inlineAll => _inlineAll;
-
- /**
- * True if all invocations of the method should be inlined, or false if only
- * the invocation site used to create this refactoring should be inlined.
- */
- set inlineAll(bool value) {
- assert(value != null);
- this._inlineAll = value;
- }
-
- InlineMethodOptions(bool deleteSource, bool inlineAll) {
- this.deleteSource = deleteSource;
- this.inlineAll = inlineAll;
- }
-
- factory InlineMethodOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- bool deleteSource;
- if (json.containsKey("deleteSource")) {
- deleteSource = jsonDecoder.decodeBool(
- jsonPath + ".deleteSource", json["deleteSource"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "deleteSource");
- }
- bool inlineAll;
- if (json.containsKey("inlineAll")) {
- inlineAll =
- jsonDecoder.decodeBool(jsonPath + ".inlineAll", json["inlineAll"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "inlineAll");
- }
- return new InlineMethodOptions(deleteSource, inlineAll);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "inlineMethod options", json);
- }
- }
-
- factory InlineMethodOptions.fromRefactoringParams(
- EditGetRefactoringParams refactoringParams, Request request) {
- return new InlineMethodOptions.fromJson(
- new RequestDecoder(request), "options", refactoringParams.options);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["deleteSource"] = deleteSource;
- result["inlineAll"] = inlineAll;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is InlineMethodOptions) {
- return deleteSource == other.deleteSource && inlineAll == other.inlineAll;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, deleteSource.hashCode);
- hash = JenkinsSmiHash.combine(hash, inlineAll.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * kythe.getKytheEntries params
- *
- * {
- * "file": FilePath
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class KytheGetKytheEntriesParams implements RequestParams {
- String _file;
-
- /**
- * The file containing the code for which the Kythe Entry objects are being
- * requested.
- */
- String get file => _file;
-
- /**
- * The file containing the code for which the Kythe Entry objects are being
- * requested.
- */
- set file(String value) {
- assert(value != null);
- this._file = value;
- }
-
- KytheGetKytheEntriesParams(String file) {
- this.file = file;
- }
-
- factory KytheGetKytheEntriesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String file;
- if (json.containsKey("file")) {
- file = jsonDecoder.decodeString(jsonPath + ".file", json["file"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "file");
- }
- return new KytheGetKytheEntriesParams(file);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "kythe.getKytheEntries params", json);
- }
- }
-
- factory KytheGetKytheEntriesParams.fromRequest(Request request) {
- return new KytheGetKytheEntriesParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["file"] = file;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "kythe.getKytheEntries", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is KytheGetKytheEntriesParams) {
- return file == other.file;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, file.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * kythe.getKytheEntries result
- *
- * {
- * "entries": List<KytheEntry>
- * "files": List<FilePath>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class KytheGetKytheEntriesResult implements ResponseResult {
- List<KytheEntry> _entries;
-
- List<String> _files;
-
- /**
- * The list of KytheEntry objects for the queried file.
- */
- List<KytheEntry> get entries => _entries;
-
- /**
- * The list of KytheEntry objects for the queried file.
- */
- set entries(List<KytheEntry> value) {
- assert(value != null);
- this._entries = value;
- }
-
- /**
- * The set of files paths that were required, but not in the file system, to
- * give a complete and accurate Kythe graph for the file. This could be due
- * to a referenced file that does not exist or generated files not being
- * generated or passed before the call to "getKytheEntries".
- */
- List<String> get files => _files;
-
- /**
- * The set of files paths that were required, but not in the file system, to
- * give a complete and accurate Kythe graph for the file. This could be due
- * to a referenced file that does not exist or generated files not being
- * generated or passed before the call to "getKytheEntries".
- */
- set files(List<String> value) {
- assert(value != null);
- this._files = value;
- }
-
- KytheGetKytheEntriesResult(List<KytheEntry> entries, List<String> files) {
- this.entries = entries;
- this.files = files;
- }
-
- factory KytheGetKytheEntriesResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- List<KytheEntry> entries;
- if (json.containsKey("entries")) {
- entries = jsonDecoder.decodeList(
- jsonPath + ".entries",
- json["entries"],
- (String jsonPath, Object json) =>
- new KytheEntry.fromJson(jsonDecoder, jsonPath, json));
- } else {
- throw jsonDecoder.mismatch(jsonPath, "entries");
- }
- List<String> files;
- if (json.containsKey("files")) {
- files = jsonDecoder.decodeList(
- jsonPath + ".files", json["files"], jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "files");
- }
- return new KytheGetKytheEntriesResult(entries, files);
- } else {
- throw jsonDecoder.mismatch(
- jsonPath, "kythe.getKytheEntries result", json);
- }
- }
-
- factory KytheGetKytheEntriesResult.fromResponse(Response response) {
- return new KytheGetKytheEntriesResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["entries"] =
- entries.map((KytheEntry value) => value.toJson()).toList();
- result["files"] = files;
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is KytheGetKytheEntriesResult) {
- return listEqual(
- entries, other.entries, (KytheEntry a, KytheEntry b) => a == b) &&
- listEqual(files, other.files, (String a, String b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, entries.hashCode);
- hash = JenkinsSmiHash.combine(hash, files.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * moveFile feedback
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class MoveFileFeedback extends RefactoringFeedback implements HasToJson {
- @override
- bool operator ==(other) {
- if (other is MoveFileFeedback) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 438975893;
- }
-}
-
-/**
- * moveFile options
- *
- * {
- * "newFile": FilePath
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class MoveFileOptions extends RefactoringOptions {
- String _newFile;
-
- /**
- * The new file path to which the given file is being moved.
- */
- String get newFile => _newFile;
-
- /**
- * The new file path to which the given file is being moved.
- */
- set newFile(String value) {
- assert(value != null);
- this._newFile = value;
- }
-
- MoveFileOptions(String newFile) {
- this.newFile = newFile;
- }
-
- factory MoveFileOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String newFile;
- if (json.containsKey("newFile")) {
- newFile =
- jsonDecoder.decodeString(jsonPath + ".newFile", json["newFile"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "newFile");
- }
- return new MoveFileOptions(newFile);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "moveFile options", json);
- }
- }
-
- factory MoveFileOptions.fromRefactoringParams(
- EditGetRefactoringParams refactoringParams, Request request) {
- return new MoveFileOptions.fromJson(
- new RequestDecoder(request), "options", refactoringParams.options);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["newFile"] = newFile;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is MoveFileOptions) {
- return newFile == other.newFile;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, newFile.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * plugin.error params
- *
- * {
- * "isFatal": bool
- * "message": String
- * "stackTrace": String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class PluginErrorParams implements HasToJson {
- bool _isFatal;
-
- String _message;
-
- String _stackTrace;
-
- /**
- * A flag indicating whether the error is a fatal error, meaning that the
- * plugin will shutdown automatically after sending this notification. If
- * true, the server will not expect any other responses or notifications from
- * the plugin.
- */
- bool get isFatal => _isFatal;
-
- /**
- * A flag indicating whether the error is a fatal error, meaning that the
- * plugin will shutdown automatically after sending this notification. If
- * true, the server will not expect any other responses or notifications from
- * the plugin.
- */
- set isFatal(bool value) {
- assert(value != null);
- this._isFatal = value;
- }
-
- /**
- * The error message indicating what kind of error was encountered.
- */
- String get message => _message;
-
- /**
- * The error message indicating what kind of error was encountered.
- */
- set message(String value) {
- assert(value != null);
- this._message = value;
- }
-
- /**
- * The stack trace associated with the generation of the error, used for
- * debugging the plugin.
- */
- String get stackTrace => _stackTrace;
-
- /**
- * The stack trace associated with the generation of the error, used for
- * debugging the plugin.
- */
- set stackTrace(String value) {
- assert(value != null);
- this._stackTrace = value;
- }
-
- PluginErrorParams(bool isFatal, String message, String stackTrace) {
- this.isFatal = isFatal;
- this.message = message;
- this.stackTrace = stackTrace;
- }
-
- factory PluginErrorParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- bool isFatal;
- if (json.containsKey("isFatal")) {
- isFatal =
- jsonDecoder.decodeBool(jsonPath + ".isFatal", json["isFatal"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "isFatal");
- }
- String message;
- if (json.containsKey("message")) {
- message =
- jsonDecoder.decodeString(jsonPath + ".message", json["message"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "message");
- }
- String stackTrace;
- if (json.containsKey("stackTrace")) {
- stackTrace = jsonDecoder.decodeString(
- jsonPath + ".stackTrace", json["stackTrace"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "stackTrace");
- }
- return new PluginErrorParams(isFatal, message, stackTrace);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "plugin.error params", json);
- }
- }
-
- factory PluginErrorParams.fromNotification(Notification notification) {
- return new PluginErrorParams.fromJson(
- new ResponseDecoder(null), "params", notification.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["isFatal"] = isFatal;
- result["message"] = message;
- result["stackTrace"] = stackTrace;
- return result;
- }
-
- Notification toNotification() {
- return new Notification("plugin.error", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is PluginErrorParams) {
- return isFatal == other.isFatal &&
- message == other.message &&
- stackTrace == other.stackTrace;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, isFatal.hashCode);
- hash = JenkinsSmiHash.combine(hash, message.hashCode);
- hash = JenkinsSmiHash.combine(hash, stackTrace.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * plugin.shutdown params
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class PluginShutdownParams implements RequestParams {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Request toRequest(String id) {
- return new Request(id, "plugin.shutdown", null);
- }
-
- @override
- bool operator ==(other) {
- if (other is PluginShutdownParams) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 478064585;
- }
-}
-
-/**
- * plugin.shutdown result
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class PluginShutdownResult implements ResponseResult {
- @override
- Map<String, dynamic> toJson() => <String, dynamic>{};
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: null);
- }
-
- @override
- bool operator ==(other) {
- if (other is PluginShutdownResult) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- return 9389109;
- }
-}
-
-/**
- * plugin.versionCheck params
- *
- * {
- * "byteStorePath": FilePath
- * "sdkPath": FilePath
- * "version": String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class PluginVersionCheckParams implements RequestParams {
- String _byteStorePath;
-
- String _sdkPath;
-
- String _version;
-
- /**
- * The path to the directory containing the on-disk byte store that is to be
- * used by any analysis drivers that are created.
- */
- String get byteStorePath => _byteStorePath;
-
- /**
- * The path to the directory containing the on-disk byte store that is to be
- * used by any analysis drivers that are created.
- */
- set byteStorePath(String value) {
- assert(value != null);
- this._byteStorePath = value;
- }
-
- /**
- * The path to the directory containing the SDK that is to be used by any
- * analysis drivers that are created.
- */
- String get sdkPath => _sdkPath;
-
- /**
- * The path to the directory containing the SDK that is to be used by any
- * analysis drivers that are created.
- */
- set sdkPath(String value) {
- assert(value != null);
- this._sdkPath = value;
- }
-
- /**
- * The version number of the plugin spec supported by the analysis server
- * that is executing the plugin.
- */
- String get version => _version;
-
- /**
- * The version number of the plugin spec supported by the analysis server
- * that is executing the plugin.
- */
- set version(String value) {
- assert(value != null);
- this._version = value;
- }
-
- PluginVersionCheckParams(
- String byteStorePath, String sdkPath, String version) {
- this.byteStorePath = byteStorePath;
- this.sdkPath = sdkPath;
- this.version = version;
- }
-
- factory PluginVersionCheckParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String byteStorePath;
- if (json.containsKey("byteStorePath")) {
- byteStorePath = jsonDecoder.decodeString(
- jsonPath + ".byteStorePath", json["byteStorePath"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "byteStorePath");
- }
- String sdkPath;
- if (json.containsKey("sdkPath")) {
- sdkPath =
- jsonDecoder.decodeString(jsonPath + ".sdkPath", json["sdkPath"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "sdkPath");
- }
- String version;
- if (json.containsKey("version")) {
- version =
- jsonDecoder.decodeString(jsonPath + ".version", json["version"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "version");
- }
- return new PluginVersionCheckParams(byteStorePath, sdkPath, version);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "plugin.versionCheck params", json);
- }
- }
-
- factory PluginVersionCheckParams.fromRequest(Request request) {
- return new PluginVersionCheckParams.fromJson(
- new RequestDecoder(request), "params", request.params);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["byteStorePath"] = byteStorePath;
- result["sdkPath"] = sdkPath;
- result["version"] = version;
- return result;
- }
-
- @override
- Request toRequest(String id) {
- return new Request(id, "plugin.versionCheck", toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is PluginVersionCheckParams) {
- return byteStorePath == other.byteStorePath &&
- sdkPath == other.sdkPath &&
- version == other.version;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, byteStorePath.hashCode);
- hash = JenkinsSmiHash.combine(hash, sdkPath.hashCode);
- hash = JenkinsSmiHash.combine(hash, version.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * plugin.versionCheck result
- *
- * {
- * "isCompatible": bool
- * "name": String
- * "version": String
- * "contactInfo": optional String
- * "interestingFiles": List<String>
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class PluginVersionCheckResult implements ResponseResult {
- bool _isCompatible;
-
- String _name;
-
- String _version;
-
- String _contactInfo;
-
- List<String> _interestingFiles;
-
- /**
- * A flag indicating whether the plugin supports the same version of the
- * plugin spec as the analysis server. If the value is false, then the plugin
- * is expected to shutdown after returning the response.
- */
- bool get isCompatible => _isCompatible;
-
- /**
- * A flag indicating whether the plugin supports the same version of the
- * plugin spec as the analysis server. If the value is false, then the plugin
- * is expected to shutdown after returning the response.
- */
- set isCompatible(bool value) {
- assert(value != null);
- this._isCompatible = value;
- }
-
- /**
- * The name of the plugin. This value is only used when the server needs to
- * identify the plugin, either to the user or for debugging purposes.
- */
- String get name => _name;
-
- /**
- * The name of the plugin. This value is only used when the server needs to
- * identify the plugin, either to the user or for debugging purposes.
- */
- set name(String value) {
- assert(value != null);
- this._name = value;
- }
-
- /**
- * The version of the plugin. This value is only used when the server needs
- * to identify the plugin, either to the user or for debugging purposes.
- */
- String get version => _version;
-
- /**
- * The version of the plugin. This value is only used when the server needs
- * to identify the plugin, either to the user or for debugging purposes.
- */
- set version(String value) {
- assert(value != null);
- this._version = value;
- }
-
- /**
- * Information that the user can use to use to contact the maintainers of the
- * plugin when there is a problem.
- */
- String get contactInfo => _contactInfo;
-
- /**
- * Information that the user can use to use to contact the maintainers of the
- * plugin when there is a problem.
- */
- set contactInfo(String value) {
- this._contactInfo = value;
- }
-
- /**
- * The glob patterns of the files for which the plugin will provide
- * information. This value is ignored if the isCompatible field is false.
- * Otherwise, it will be used to identify the files for which the plugin
- * should be notified of changes.
- */
- List<String> get interestingFiles => _interestingFiles;
-
- /**
- * The glob patterns of the files for which the plugin will provide
- * information. This value is ignored if the isCompatible field is false.
- * Otherwise, it will be used to identify the files for which the plugin
- * should be notified of changes.
- */
- set interestingFiles(List<String> value) {
- assert(value != null);
- this._interestingFiles = value;
- }
-
- PluginVersionCheckResult(bool isCompatible, String name, String version,
- List<String> interestingFiles,
- {String contactInfo}) {
- this.isCompatible = isCompatible;
- this.name = name;
- this.version = version;
- this.contactInfo = contactInfo;
- this.interestingFiles = interestingFiles;
- }
-
- factory PluginVersionCheckResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- bool isCompatible;
- if (json.containsKey("isCompatible")) {
- isCompatible = jsonDecoder.decodeBool(
- jsonPath + ".isCompatible", json["isCompatible"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "isCompatible");
- }
- String name;
- if (json.containsKey("name")) {
- name = jsonDecoder.decodeString(jsonPath + ".name", json["name"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "name");
- }
- String version;
- if (json.containsKey("version")) {
- version =
- jsonDecoder.decodeString(jsonPath + ".version", json["version"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "version");
- }
- String contactInfo;
- if (json.containsKey("contactInfo")) {
- contactInfo = jsonDecoder.decodeString(
- jsonPath + ".contactInfo", json["contactInfo"]);
- }
- List<String> interestingFiles;
- if (json.containsKey("interestingFiles")) {
- interestingFiles = jsonDecoder.decodeList(
- jsonPath + ".interestingFiles",
- json["interestingFiles"],
- jsonDecoder.decodeString);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "interestingFiles");
- }
- return new PluginVersionCheckResult(
- isCompatible, name, version, interestingFiles,
- contactInfo: contactInfo);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "plugin.versionCheck result", json);
- }
- }
-
- factory PluginVersionCheckResult.fromResponse(Response response) {
- return new PluginVersionCheckResult.fromJson(
- new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id)),
- "result",
- response.result);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["isCompatible"] = isCompatible;
- result["name"] = name;
- result["version"] = version;
- if (contactInfo != null) {
- result["contactInfo"] = contactInfo;
- }
- result["interestingFiles"] = interestingFiles;
- return result;
- }
-
- @override
- Response toResponse(String id, int requestTime) {
- return new Response(id, requestTime, result: toJson());
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is PluginVersionCheckResult) {
- return isCompatible == other.isCompatible &&
- name == other.name &&
- version == other.version &&
- contactInfo == other.contactInfo &&
- listEqual(interestingFiles, other.interestingFiles,
- (String a, String b) => a == b);
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, isCompatible.hashCode);
- hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, version.hashCode);
- hash = JenkinsSmiHash.combine(hash, contactInfo.hashCode);
- hash = JenkinsSmiHash.combine(hash, interestingFiles.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * PrioritizedSourceChange
- *
- * {
- * "priority": int
- * "change": SourceChange
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class PrioritizedSourceChange implements HasToJson {
- int _priority;
-
- SourceChange _change;
-
- /**
- * The priority of the change. The value is expected to be non-negative, and
- * zero (0) is the lowest priority.
- */
- int get priority => _priority;
-
- /**
- * The priority of the change. The value is expected to be non-negative, and
- * zero (0) is the lowest priority.
- */
- set priority(int value) {
- assert(value != null);
- this._priority = value;
- }
-
- /**
- * The change with which the relevance is associated.
- */
- SourceChange get change => _change;
-
- /**
- * The change with which the relevance is associated.
- */
- set change(SourceChange value) {
- assert(value != null);
- this._change = value;
- }
-
- PrioritizedSourceChange(int priority, SourceChange change) {
- this.priority = priority;
- this.change = change;
- }
-
- factory PrioritizedSourceChange.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- int priority;
- if (json.containsKey("priority")) {
- priority =
- jsonDecoder.decodeInt(jsonPath + ".priority", json["priority"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "priority");
- }
- SourceChange change;
- if (json.containsKey("change")) {
- change = new SourceChange.fromJson(
- jsonDecoder, jsonPath + ".change", json["change"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "change");
- }
- return new PrioritizedSourceChange(priority, change);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "PrioritizedSourceChange", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["priority"] = priority;
- result["change"] = change.toJson();
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is PrioritizedSourceChange) {
- return priority == other.priority && change == other.change;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, priority.hashCode);
- hash = JenkinsSmiHash.combine(hash, change.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RefactoringFeedback
- *
- * {
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringFeedback implements HasToJson {
- RefactoringFeedback();
-
- factory RefactoringFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json, Map responseJson) {
- return refactoringFeedbackFromJson(
- jsonDecoder, jsonPath, json, responseJson);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RefactoringFeedback) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RefactoringOptions
- *
- * {
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RefactoringOptions implements HasToJson {
- RefactoringOptions();
-
- factory RefactoringOptions.fromJson(JsonDecoder jsonDecoder, String jsonPath,
- Object json, RefactoringKind kind) {
- return refactoringOptionsFromJson(jsonDecoder, jsonPath, json, kind);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RefactoringOptions) {
- return true;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * rename feedback
- *
- * {
- * "offset": int
- * "length": int
- * "elementKindName": String
- * "oldName": String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RenameFeedback extends RefactoringFeedback {
- int _offset;
-
- int _length;
-
- String _elementKindName;
-
- String _oldName;
-
- /**
- * The offset to the beginning of the name selected to be renamed.
- */
- int get offset => _offset;
-
- /**
- * The offset to the beginning of the name selected to be renamed.
- */
- set offset(int value) {
- assert(value != null);
- this._offset = value;
- }
-
- /**
- * The length of the name selected to be renamed.
- */
- int get length => _length;
-
- /**
- * The length of the name selected to be renamed.
- */
- set length(int value) {
- assert(value != null);
- this._length = value;
- }
-
- /**
- * The human-readable description of the kind of element being renamed (such
- * as “class” or “function type alias”).
- */
- String get elementKindName => _elementKindName;
-
- /**
- * The human-readable description of the kind of element being renamed (such
- * as “class” or “function type alias”).
- */
- set elementKindName(String value) {
- assert(value != null);
- this._elementKindName = value;
- }
-
- /**
- * The old name of the element before the refactoring.
- */
- String get oldName => _oldName;
-
- /**
- * The old name of the element before the refactoring.
- */
- set oldName(String value) {
- assert(value != null);
- this._oldName = value;
- }
-
- RenameFeedback(
- int offset, int length, String elementKindName, String oldName) {
- this.offset = offset;
- this.length = length;
- this.elementKindName = elementKindName;
- this.oldName = oldName;
- }
-
- factory RenameFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- int offset;
- if (json.containsKey("offset")) {
- offset = jsonDecoder.decodeInt(jsonPath + ".offset", json["offset"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "offset");
- }
- int length;
- if (json.containsKey("length")) {
- length = jsonDecoder.decodeInt(jsonPath + ".length", json["length"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "length");
- }
- String elementKindName;
- if (json.containsKey("elementKindName")) {
- elementKindName = jsonDecoder.decodeString(
- jsonPath + ".elementKindName", json["elementKindName"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "elementKindName");
- }
- String oldName;
- if (json.containsKey("oldName")) {
- oldName =
- jsonDecoder.decodeString(jsonPath + ".oldName", json["oldName"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "oldName");
- }
- return new RenameFeedback(offset, length, elementKindName, oldName);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "rename feedback", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["offset"] = offset;
- result["length"] = length;
- result["elementKindName"] = elementKindName;
- result["oldName"] = oldName;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RenameFeedback) {
- return offset == other.offset &&
- length == other.length &&
- elementKindName == other.elementKindName &&
- oldName == other.oldName;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, offset.hashCode);
- hash = JenkinsSmiHash.combine(hash, length.hashCode);
- hash = JenkinsSmiHash.combine(hash, elementKindName.hashCode);
- hash = JenkinsSmiHash.combine(hash, oldName.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * rename options
- *
- * {
- * "newName": String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RenameOptions extends RefactoringOptions {
- String _newName;
-
- /**
- * The name that the element should have after the refactoring.
- */
- String get newName => _newName;
-
- /**
- * The name that the element should have after the refactoring.
- */
- set newName(String value) {
- assert(value != null);
- this._newName = value;
- }
-
- RenameOptions(String newName) {
- this.newName = newName;
- }
-
- factory RenameOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- String newName;
- if (json.containsKey("newName")) {
- newName =
- jsonDecoder.decodeString(jsonPath + ".newName", json["newName"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "newName");
- }
- return new RenameOptions(newName);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "rename options", json);
- }
- }
-
- factory RenameOptions.fromRefactoringParams(
- EditGetRefactoringParams refactoringParams, Request request) {
- return new RenameOptions.fromJson(
- new RequestDecoder(request), "options", refactoringParams.options);
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["newName"] = newName;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RenameOptions) {
- return newName == other.newName;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, newName.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RequestError
- *
- * {
- * "code": RequestErrorCode
- * "message": String
- * "stackTrace": optional String
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RequestError implements HasToJson {
- RequestErrorCode _code;
-
- String _message;
-
- String _stackTrace;
-
- /**
- * A code that uniquely identifies the error that occurred.
- */
- RequestErrorCode get code => _code;
-
- /**
- * A code that uniquely identifies the error that occurred.
- */
- set code(RequestErrorCode value) {
- assert(value != null);
- this._code = value;
- }
-
- /**
- * A short description of the error.
- */
- String get message => _message;
-
- /**
- * A short description of the error.
- */
- set message(String value) {
- assert(value != null);
- this._message = value;
- }
-
- /**
- * The stack trace associated with processing the request, used for debugging
- * the plugin.
- */
- String get stackTrace => _stackTrace;
-
- /**
- * The stack trace associated with processing the request, used for debugging
- * the plugin.
- */
- set stackTrace(String value) {
- this._stackTrace = value;
- }
-
- RequestError(RequestErrorCode code, String message, {String stackTrace}) {
- this.code = code;
- this.message = message;
- this.stackTrace = stackTrace;
- }
-
- factory RequestError.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- RequestErrorCode code;
- if (json.containsKey("code")) {
- code = new RequestErrorCode.fromJson(
- jsonDecoder, jsonPath + ".code", json["code"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "code");
- }
- String message;
- if (json.containsKey("message")) {
- message =
- jsonDecoder.decodeString(jsonPath + ".message", json["message"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "message");
- }
- String stackTrace;
- if (json.containsKey("stackTrace")) {
- stackTrace = jsonDecoder.decodeString(
- jsonPath + ".stackTrace", json["stackTrace"]);
- }
- return new RequestError(code, message, stackTrace: stackTrace);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "RequestError", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["code"] = code.toJson();
- result["message"] = message;
- if (stackTrace != null) {
- result["stackTrace"] = stackTrace;
- }
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is RequestError) {
- return code == other.code &&
- message == other.message &&
- stackTrace == other.stackTrace;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, code.hashCode);
- hash = JenkinsSmiHash.combine(hash, message.hashCode);
- hash = JenkinsSmiHash.combine(hash, stackTrace.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * RequestErrorCode
- *
- * enum {
- * INVALID_OVERLAY_CHANGE
- * INVALID_PARAMETER
- * PLUGIN_ERROR
- * UNKNOWN_REQUEST
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class RequestErrorCode implements Enum {
- /**
- * An "analysis.updateContent" request contained a ChangeContentOverlay
- * object that can't be applied. This can happen for two reasons:
- *
- * - there was no preceding AddContentOverlay and hence no content to which
- * the edits could be applied, or
- * - one or more of the specified edits have an offset or length that is out
- * of range.
- */
- static const RequestErrorCode INVALID_OVERLAY_CHANGE =
- const RequestErrorCode._("INVALID_OVERLAY_CHANGE");
-
- /**
- * One of the method parameters was invalid.
- */
- static const RequestErrorCode INVALID_PARAMETER =
- const RequestErrorCode._("INVALID_PARAMETER");
-
- /**
- * An internal error occurred in the plugin while attempting to respond to a
- * request. Also see the plugin.error notification for errors that occur
- * outside of handling a request.
- */
- static const RequestErrorCode PLUGIN_ERROR =
- const RequestErrorCode._("PLUGIN_ERROR");
-
- /**
- * A request was received that the plugin does not recognize, or cannot
- * handle in its current configuration.
- */
- static const RequestErrorCode UNKNOWN_REQUEST =
- const RequestErrorCode._("UNKNOWN_REQUEST");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<RequestErrorCode> VALUES = const <RequestErrorCode>[
- INVALID_OVERLAY_CHANGE,
- INVALID_PARAMETER,
- PLUGIN_ERROR,
- UNKNOWN_REQUEST
- ];
-
- @override
- final String name;
-
- const RequestErrorCode._(this.name);
-
- factory RequestErrorCode(String name) {
- switch (name) {
- case "INVALID_OVERLAY_CHANGE":
- return INVALID_OVERLAY_CHANGE;
- case "INVALID_PARAMETER":
- return INVALID_PARAMETER;
- case "PLUGIN_ERROR":
- return PLUGIN_ERROR;
- case "UNKNOWN_REQUEST":
- return UNKNOWN_REQUEST;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory RequestErrorCode.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new RequestErrorCode(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "RequestErrorCode", json);
- }
-
- @override
- String toString() => "RequestErrorCode.$name";
-
- String toJson() => name;
-}
-
-/**
- * WatchEvent
- *
- * {
- * "type": WatchEventType
- * "path": FilePath
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class WatchEvent implements HasToJson {
- WatchEventType _type;
-
- String _path;
-
- /**
- * The type of change represented by this event.
- */
- WatchEventType get type => _type;
-
- /**
- * The type of change represented by this event.
- */
- set type(WatchEventType value) {
- assert(value != null);
- this._type = value;
- }
-
- /**
- * The absolute path of the file or directory that changed.
- */
- String get path => _path;
-
- /**
- * The absolute path of the file or directory that changed.
- */
- set path(String value) {
- assert(value != null);
- this._path = value;
- }
-
- WatchEvent(WatchEventType type, String path) {
- this.type = type;
- this.path = path;
- }
-
- factory WatchEvent.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json == null) {
- json = {};
- }
- if (json is Map) {
- WatchEventType type;
- if (json.containsKey("type")) {
- type = new WatchEventType.fromJson(
- jsonDecoder, jsonPath + ".type", json["type"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "type");
- }
- String path;
- if (json.containsKey("path")) {
- path = jsonDecoder.decodeString(jsonPath + ".path", json["path"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "path");
- }
- return new WatchEvent(type, path);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "WatchEvent", json);
- }
- }
-
- @override
- Map<String, dynamic> toJson() {
- Map<String, dynamic> result = {};
- result["type"] = type.toJson();
- result["path"] = path;
- return result;
- }
-
- @override
- String toString() => json.encode(toJson());
-
- @override
- bool operator ==(other) {
- if (other is WatchEvent) {
- return type == other.type && path == other.path;
- }
- return false;
- }
-
- @override
- int get hashCode {
- int hash = 0;
- hash = JenkinsSmiHash.combine(hash, type.hashCode);
- hash = JenkinsSmiHash.combine(hash, path.hashCode);
- return JenkinsSmiHash.finish(hash);
- }
-}
-
-/**
- * WatchEventType
- *
- * enum {
- * ADD
- * MODIFY
- * REMOVE
- * }
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class WatchEventType implements Enum {
- /**
- * An indication that the file or directory was added.
- */
- static const WatchEventType ADD = const WatchEventType._("ADD");
-
- /**
- * An indication that the file was modified.
- */
- static const WatchEventType MODIFY = const WatchEventType._("MODIFY");
-
- /**
- * An indication that the file or directory was removed.
- */
- static const WatchEventType REMOVE = const WatchEventType._("REMOVE");
-
- /**
- * A list containing all of the enum values that are defined.
- */
- static const List<WatchEventType> VALUES = const <WatchEventType>[
- ADD,
- MODIFY,
- REMOVE
- ];
-
- @override
- final String name;
-
- const WatchEventType._(this.name);
-
- factory WatchEventType(String name) {
- switch (name) {
- case "ADD":
- return ADD;
- case "MODIFY":
- return MODIFY;
- case "REMOVE":
- return REMOVE;
- }
- throw new Exception('Illegal enum value: $name');
- }
-
- factory WatchEventType.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
- if (json is String) {
- try {
- return new WatchEventType(json);
- } catch (_) {
- // Fall through
- }
- }
- throw jsonDecoder.mismatch(jsonPath, "WatchEventType", json);
- }
-
- @override
- String toString() => "WatchEventType.$name";
-
- String toJson() => name;
-}
diff --git a/analyzer_plugin/lib/src/channel/isolate_channel.dart b/analyzer_plugin/lib/src/channel/isolate_channel.dart
deleted file mode 100644
index aa65532..0000000
--- a/analyzer_plugin/lib/src/channel/isolate_channel.dart
+++ /dev/null
@@ -1,301 +0,0 @@
-// 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:async';
-import 'dart:convert';
-import 'dart:isolate';
-
-import 'package:analyzer/instrumentation/instrumentation.dart';
-import 'package:analyzer_plugin/channel/channel.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-
-/**
- * The type of the function used to run a built-in plugin in an isolate.
- */
-typedef void EntryPoint(SendPort sendPort);
-
-/**
- * A communication channel appropriate for built-in plugins.
- */
-class BuiltInServerIsolateChannel extends ServerIsolateChannel {
- /**
- * The entry point
- */
- final EntryPoint entryPoint;
-
- @override
- final String pluginId;
-
- /**
- * Initialize a newly created channel to communicate with an isolate running
- * the given [entryPoint].
- */
- BuiltInServerIsolateChannel(this.entryPoint, this.pluginId,
- InstrumentationService instrumentationService)
- : super._(instrumentationService);
-
- @override
- Future<Isolate> _spawnIsolate() {
- return Isolate.spawn(
- (message) => entryPoint(message as SendPort), _receivePort.sendPort,
- onError: _errorPort?.sendPort, onExit: _exitPort?.sendPort);
- }
-}
-
-/**
- * A communication channel appropriate for discovered plugins.
- */
-class DiscoveredServerIsolateChannel extends ServerIsolateChannel {
- /**
- * The URI for the Dart file that will be run in the isolate that this channel
- * communicates with.
- */
- final Uri pluginUri;
-
- /**
- * The URI for the '.packages' file that will control how 'package:' URIs are
- * resolved.
- */
- final Uri packagesUri;
-
- /**
- * Initialize a newly created channel to communicate with an isolate running
- * the code at the given [uri].
- */
- DiscoveredServerIsolateChannel(this.pluginUri, this.packagesUri,
- InstrumentationService instrumentationService)
- : super._(instrumentationService);
-
- @override
- String get pluginId => pluginUri.toString();
-
- @override
- Future<Isolate> _spawnIsolate() {
- return Isolate.spawnUri(pluginUri, <String>[], _receivePort.sendPort,
- onError: _errorPort?.sendPort,
- onExit: _exitPort?.sendPort,
- packageConfig: packagesUri);
- }
-}
-
-/**
- * The object that allows a [ServerPlugin] to receive [Request]s and to return
- * both [Response]s and [Notification]s. It communicates with the analysis
- * server by passing data to the server's main isolate.
- */
-class PluginIsolateChannel implements PluginCommunicationChannel {
- /**
- * The port used to send notifications and responses to the server.
- */
- SendPort _sendPort;
-
- /**
- * The port used to receive requests from the server.
- */
- ReceivePort _receivePort;
-
- /**
- * The subscription that needs to be cancelled when the channel is closed.
- */
- StreamSubscription _subscription;
-
- /**
- * Initialize a newly created channel to communicate with the server.
- */
- PluginIsolateChannel(this._sendPort) {
- _receivePort = new ReceivePort();
- _sendPort.send(_receivePort.sendPort);
- }
-
- @override
- void close() {
- if (_subscription != null) {
- _subscription.cancel();
- _subscription = null;
- }
- }
-
- @override
- void listen(void onRequest(Request request),
- {Function onError, void onDone()}) {
- void onData(data) {
- Map<String, Object> requestMap = data as Map<String, Object>;
- Request request = new Request.fromJson(requestMap);
- if (request != null) {
- onRequest(request);
- }
- }
-
- if (_subscription != null) {
- throw new StateError('Only one listener is allowed per channel');
- }
- _subscription = _receivePort.listen(onData,
- onError: onError, onDone: onDone, cancelOnError: false);
- }
-
- @override
- void sendNotification(Notification notification) {
- Map<String, Object> json = notification.toJson();
- _sendPort.send(json);
- }
-
- @override
- void sendResponse(Response response) {
- Map<String, Object> json = response.toJson();
- _sendPort.send(json);
- }
-}
-
-/**
- * A communication channel that allows an analysis server to send [Request]s
- * to, and to receive both [Response]s and [Notification]s from, a plugin.
- */
-abstract class ServerIsolateChannel implements ServerCommunicationChannel {
- /**
- * The instrumentation service that is being used by the analysis server.
- */
- final InstrumentationService instrumentationService;
-
- /**
- * The isolate in which the plugin is running, or `null` if the plugin has
- * not yet been started by invoking [listen].
- */
- Isolate _isolate;
-
- /**
- * The port used to send requests to the plugin, or `null` if the plugin has
- * not yet been started by invoking [listen].
- */
- SendPort _sendPort;
-
- /**
- * The port used to receive responses and notifications from the plugin.
- */
- ReceivePort _receivePort;
-
- /**
- * The port used to receive unhandled exceptions thrown in the plugin.
- */
- ReceivePort _errorPort;
-
- /**
- * The port used to receive notification when the plugin isolate has exited.
- */
- ReceivePort _exitPort;
-
- /**
- * Return a communication channel appropriate for communicating with a
- * built-in plugin.
- */
- factory ServerIsolateChannel.builtIn(EntryPoint entryPoint, String pluginId,
- InstrumentationService instrumentationService) =
- BuiltInServerIsolateChannel;
-
- /**
- * Return a communication channel appropriate for communicating with a
- * discovered plugin.
- */
- factory ServerIsolateChannel.discovered(Uri pluginUri, Uri packagesUri,
- InstrumentationService instrumentationService) =
- DiscoveredServerIsolateChannel;
-
- /**
- * Initialize a newly created channel.
- */
- ServerIsolateChannel._(this.instrumentationService);
-
- /**
- * Return the id of the plugin running in the isolate, used to identify the
- * plugin to the instrumentation service.
- */
- String get pluginId;
-
- @override
- void close() {
- _receivePort?.close();
- _errorPort?.close();
- _exitPort?.close();
- _isolate = null;
- }
-
- @override
- void kill() {
- _isolate?.kill(priority: Isolate.immediate);
- }
-
- @override
- Future<void> listen(void onResponse(Response response),
- void onNotification(Notification notification),
- {void onError(dynamic error), void onDone()}) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- if (_isolate != null) {
- throw new StateError('Cannot listen to the same channel more than once.');
- }
- _receivePort = new ReceivePort();
- if (onError != null) {
- _errorPort = new ReceivePort();
- _errorPort.listen((error) {
- onError(error);
- });
- }
- if (onDone != null) {
- _exitPort = new ReceivePort();
- _exitPort.listen((_) {
- onDone();
- });
- }
- try {
- _isolate = await _spawnIsolate();
- } catch (exception, stackTrace) {
- instrumentationService.logPluginError(
- new PluginData(pluginId, null, null),
- RequestErrorCode.PLUGIN_ERROR.toString(),
- exception.toString(),
- stackTrace.toString());
- if (onError != null) {
- onError([exception.toString(), stackTrace.toString()]);
- }
- if (onDone != null) {
- onDone();
- }
- close();
- return null;
- }
- Completer<void> channelReady = new Completer<void>();
- _receivePort.listen((dynamic input) {
- if (input is SendPort) {
- _sendPort = input;
- channelReady.complete(null);
- } else if (input is Map) {
- if (input.containsKey('id')) {
- String encodedInput = json.encode(input);
- instrumentationService.logPluginResponse(pluginId, encodedInput);
- onResponse(new Response.fromJson(input));
- } else if (input.containsKey('event')) {
- String encodedInput = json.encode(input);
- instrumentationService.logPluginNotification(pluginId, encodedInput);
- onNotification(new Notification.fromJson(input));
- }
- }
- });
- return channelReady.future;
- }
-
- @override
- void sendRequest(Request request) {
- if (_sendPort != null) {
- Map<String, Object> jsonData = request.toJson();
- String encodedRequest = json.encode(jsonData);
- instrumentationService.logPluginRequest(pluginId, encodedRequest);
- _sendPort.send(jsonData);
- }
- }
-
- /**
- * Spawn the isolate in which the plugin is running.
- */
- Future<Isolate> _spawnIsolate();
-}
diff --git a/analyzer_plugin/lib/src/driver.dart b/analyzer_plugin/lib/src/driver.dart
deleted file mode 100644
index a4415d8..0000000
--- a/analyzer_plugin/lib/src/driver.dart
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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:isolate';
-
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/src/channel/isolate_channel.dart';
-import 'package:analyzer_plugin/starter.dart';
-
-/**
- * The [Driver] class represents a single running instance of an analysis
- * server plugin. It is responsible for handling the communications with the
- * server and forwarding requests on to the plugin.
- */
-class Driver implements ServerPluginStarter {
- /**
- * The plugin that will be started.
- */
- final ServerPlugin plugin;
-
- /**
- * Initialize a newly created driver that can be used to start the given
- * plugin.
- */
- Driver(this.plugin);
-
- @override
- void start(SendPort sendPort) {
- PluginIsolateChannel channel = new PluginIsolateChannel(sendPort);
- plugin.start(channel);
- }
-}
diff --git a/analyzer_plugin/lib/src/protocol/protocol_internal.dart b/analyzer_plugin/lib/src/protocol/protocol_internal.dart
deleted file mode 100644
index 1e78106..0000000
--- a/analyzer_plugin/lib/src/protocol/protocol_internal.dart
+++ /dev/null
@@ -1,493 +0,0 @@
-// 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:convert' hide JsonDecoder;
-
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-
-final Map<String, RefactoringKind> REQUEST_ID_REFACTORING_KINDS =
- new HashMap<String, RefactoringKind>();
-
-/**
- * Adds the given [sourceEdits] to the list in [sourceFileEdit].
- */
-void addAllEditsForSource(
- SourceFileEdit sourceFileEdit, Iterable<SourceEdit> edits) {
- edits.forEach(sourceFileEdit.add);
-}
-
-/**
- * Adds the given [sourceEdit] to the list in [sourceFileEdit].
- */
-void addEditForSource(SourceFileEdit sourceFileEdit, SourceEdit sourceEdit) {
- List<SourceEdit> edits = sourceFileEdit.edits;
- int index = 0;
- while (index < edits.length && edits[index].offset > sourceEdit.offset) {
- index++;
- }
- edits.insert(index, sourceEdit);
-}
-
-/**
- * Adds [edit] to the [FileEdit] for the given [file].
- */
-void addEditToSourceChange(
- SourceChange change, String file, int fileStamp, SourceEdit edit) {
- SourceFileEdit fileEdit = change.getFileEdit(file);
- if (fileEdit == null) {
- fileEdit = new SourceFileEdit(file, fileStamp);
- change.addFileEdit(fileEdit);
- }
- fileEdit.add(edit);
-}
-
-/**
- * Get the result of applying the edit to the given [code]. Access via
- * SourceEdit.apply().
- */
-String applyEdit(String code, SourceEdit edit) {
- if (edit.length < 0) {
- throw new RangeError('length is negative');
- }
- return code.replaceRange(edit.offset, edit.end, edit.replacement);
-}
-
-/**
- * Get the result of applying a set of [edits] to the given [code]. Edits
- * are applied in the order they appear in [edits]. Access via
- * SourceEdit.applySequence().
- */
-String applySequenceOfEdits(String code, Iterable<SourceEdit> edits) {
- edits.forEach((SourceEdit edit) {
- code = edit.apply(code);
- });
- return code;
-}
-
-/**
- * Returns the [FileEdit] for the given [file], maybe `null`.
- */
-SourceFileEdit getChangeFileEdit(SourceChange change, String file) {
- for (SourceFileEdit fileEdit in change.edits) {
- if (fileEdit.file == file) {
- return fileEdit;
- }
- }
- return null;
-}
-
-/**
- * Compare the lists [listA] and [listB], using [itemEqual] to compare
- * list elements.
- */
-bool listEqual<T>(List<T> listA, List<T> listB, bool itemEqual(T a, T b)) {
- if (listA == null) {
- return listB == null;
- }
- if (listB == null) {
- return false;
- }
- if (listA.length != listB.length) {
- return false;
- }
- for (int i = 0; i < listA.length; i++) {
- if (!itemEqual(listA[i], listB[i])) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * Compare the maps [mapA] and [mapB], using [valueEqual] to compare map
- * values.
- */
-bool mapEqual<K, V>(Map<K, V> mapA, Map<K, V> mapB, bool valueEqual(V a, V b)) {
- if (mapA == null) {
- return mapB == null;
- }
- if (mapB == null) {
- return false;
- }
- if (mapA.length != mapB.length) {
- return false;
- }
- for (var key in mapA.keys) {
- if (!mapB.containsKey(key)) {
- return false;
- }
- if (!valueEqual(mapA[key], mapB[key])) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * Translate the input [map], applying [keyCallback] to all its keys, and
- * [valueCallback] to all its values.
- */
-Map<KR, VR> mapMap<KP, VP, KR, VR>(Map<KP, VP> map,
- {KR keyCallback(KP key), VR valueCallback(VP value)}) {
- Map<KR, VR> result = new HashMap<KR, VR>();
- map.forEach((key, value) {
- KR resultKey;
- VR resultValue;
- if (keyCallback != null) {
- resultKey = keyCallback(key);
- } else {
- resultKey = key as KR;
- }
- if (valueCallback != null) {
- resultValue = valueCallback(value);
- } else {
- resultValue = value as VR;
- }
- result[resultKey] = resultValue;
- });
- return result;
-}
-
-RefactoringProblemSeverity maxRefactoringProblemSeverity(
- RefactoringProblemSeverity a, RefactoringProblemSeverity b) {
- if (b == null) {
- return a;
- }
- if (a == null) {
- return b;
- } else if (a == RefactoringProblemSeverity.INFO) {
- return b;
- } else if (a == RefactoringProblemSeverity.WARNING) {
- if (b == RefactoringProblemSeverity.ERROR ||
- b == RefactoringProblemSeverity.FATAL) {
- return b;
- }
- } else if (a == RefactoringProblemSeverity.ERROR) {
- if (b == RefactoringProblemSeverity.FATAL) {
- return b;
- }
- }
- return a;
-}
-
-/**
- * Create a [RefactoringFeedback] corresponding the given [kind].
- */
-RefactoringFeedback refactoringFeedbackFromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json, Map feedbackJson) {
- RefactoringKind kind = jsonDecoder.refactoringKind;
- if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
- return new ExtractLocalVariableFeedback.fromJson(
- jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.EXTRACT_METHOD) {
- return new ExtractMethodFeedback.fromJson(jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.INLINE_LOCAL_VARIABLE) {
- return new InlineLocalVariableFeedback.fromJson(
- jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.INLINE_METHOD) {
- return new InlineMethodFeedback.fromJson(jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.RENAME) {
- return new RenameFeedback.fromJson(jsonDecoder, jsonPath, json);
- }
- return null;
-}
-
-/**
- * Create a [RefactoringOptions] corresponding the given [kind].
- */
-RefactoringOptions refactoringOptionsFromJson(JsonDecoder jsonDecoder,
- String jsonPath, Object json, RefactoringKind kind) {
- if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
- return new ExtractLocalVariableOptions.fromJson(
- jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.EXTRACT_METHOD) {
- return new ExtractMethodOptions.fromJson(jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.INLINE_METHOD) {
- return new InlineMethodOptions.fromJson(jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.MOVE_FILE) {
- return new MoveFileOptions.fromJson(jsonDecoder, jsonPath, json);
- }
- if (kind == RefactoringKind.RENAME) {
- return new RenameOptions.fromJson(jsonDecoder, jsonPath, json);
- }
- return null;
-}
-
-/**
- * Type of callbacks used to decode parts of JSON objects. [jsonPath] is a
- * string describing the part of the JSON object being decoded, and [value] is
- * the part to decode.
- */
-typedef E JsonDecoderCallback<E>(String jsonPath, dynamic value);
-
-/**
- * Instances of the class [HasToJson] implement [toJson] method that returns
- * a JSON presentation.
- */
-abstract class HasToJson {
- /**
- * Returns a JSON presentation of the object.
- */
- Map<String, Object> toJson();
-}
-
-/**
- * Base class for decoding JSON objects. The derived class must implement
- * error reporting logic.
- */
-abstract class JsonDecoder {
- /**
- * Retrieve the RefactoringKind that should be assumed when decoding
- * refactoring feedback objects, or null if no refactoring feedback object is
- * expected to be encountered.
- */
- RefactoringKind get refactoringKind;
-
- /**
- * Decode a JSON object that is expected to be a boolean. The strings "true"
- * and "false" are also accepted.
- */
- bool decodeBool(String jsonPath, Object json) {
- if (json is bool) {
- return json;
- } else if (json == 'true') {
- return true;
- } else if (json == 'false') {
- return false;
- }
- throw mismatch(jsonPath, 'bool', json);
- }
-
- /**
- * Decode a JSON object that is expected to be a double. A string
- * representation of a double is also accepted.
- */
- double decodeDouble(String jsonPath, Object json) {
- if (json is double) {
- return json;
- } else if (json is int) {
- return json.toDouble();
- } else if (json is String) {
- double value = double.tryParse(json);
- if (value == null) {
- throw mismatch(jsonPath, 'double', json);
- }
- return value;
- }
- throw mismatch(jsonPath, 'double', json);
- }
-
- /**
- * Decode a JSON object that is expected to be an integer. A string
- * representation of an integer is also accepted.
- */
- int decodeInt(String jsonPath, Object json) {
- if (json is int) {
- return json;
- } else if (json is String) {
- int value = int.tryParse(json);
- if (value == null) {
- throw mismatch(jsonPath, 'int', json);
- }
- return value;
- }
- throw mismatch(jsonPath, 'int', json);
- }
-
- /**
- * Decode a JSON object that is expected to be a List. The [decoder] is used
- * to decode the items in the list.
- *
- * The type parameter [E] is the expected type of the elements in the list.
- */
- List<E> decodeList<E>(String jsonPath, Object json,
- [JsonDecoderCallback<E> decoder]) {
- if (json == null) {
- return <E>[];
- } else if (json is List) {
- List<E> result = <E>[];
- for (int i = 0; i < json.length; i++) {
- result.add(decoder('$jsonPath[$i]', json[i]));
- }
- return result;
- } else {
- throw mismatch(jsonPath, 'List', json);
- }
- }
-
- /**
- * Decode a JSON object that is expected to be a Map. [keyDecoder] is used
- * to decode the keys, and [valueDecoder] is used to decode the values.
- */
- Map<K, V> decodeMap<K, V>(String jsonPath, Object jsonData,
- {JsonDecoderCallback<K> keyDecoder,
- JsonDecoderCallback<V> valueDecoder}) {
- if (jsonData == null) {
- return {};
- } else if (jsonData is Map) {
- Map<K, V> result = <K, V>{};
- jsonData.forEach((key, value) {
- K decodedKey;
- if (keyDecoder != null) {
- decodedKey = keyDecoder('$jsonPath.key', key);
- } else {
- decodedKey = key as K;
- }
- if (valueDecoder != null) {
- value = valueDecoder('$jsonPath[${json.encode(key)}]', value);
- }
- result[decodedKey] = value as V;
- });
- return result;
- } else {
- throw mismatch(jsonPath, 'Map', jsonData);
- }
- }
-
- /**
- * Decode a JSON object that is expected to be a string.
- */
- String decodeString(String jsonPath, Object json) {
- if (json is String) {
- return json;
- } else {
- throw mismatch(jsonPath, 'String', json);
- }
- }
-
- /**
- * Decode a JSON object that is expected to be one of several choices,
- * where the choices are disambiguated by the contents of the field [field].
- * [decoders] is a map from each possible string in the field to the decoder
- * that should be used to decode the JSON object.
- */
- Object decodeUnion(String jsonPath, Map jsonData, String field,
- Map<String, JsonDecoderCallback> decoders) {
- if (jsonData is Map) {
- if (!jsonData.containsKey(field)) {
- throw missingKey(jsonPath, field);
- }
- var disambiguatorPath = '$jsonPath[${json.encode(field)}]';
- String disambiguator = decodeString(disambiguatorPath, jsonData[field]);
- if (!decoders.containsKey(disambiguator)) {
- throw mismatch(
- disambiguatorPath, 'One of: ${decoders.keys.toList()}', jsonData);
- }
- return decoders[disambiguator](jsonPath, jsonData);
- } else {
- throw mismatch(jsonPath, 'Map', jsonData);
- }
- }
-
- /**
- * Create an exception to throw if the JSON object at [jsonPath] fails to
- * match the API definition of [expected].
- */
- dynamic mismatch(String jsonPath, String expected, [Object actual]);
-
- /**
- * Create an exception to throw if the JSON object at [jsonPath] is missing
- * the key [key].
- */
- dynamic missingKey(String jsonPath, String key);
-}
-
-/**
- * JsonDecoder for decoding requests. Errors are reporting by throwing a
- * [RequestFailure].
- */
-class RequestDecoder extends JsonDecoder {
- /**
- * The request being deserialized.
- */
- final Request request;
-
- RequestDecoder(this.request);
-
- @override
- RefactoringKind get refactoringKind {
- // Refactoring feedback objects should never appear in requests.
- return null;
- }
-
- @override
- dynamic mismatch(String jsonPath, String expected, [Object actual]) {
- StringBuffer buffer = new StringBuffer();
- buffer.write('Expected to be ');
- buffer.write(expected);
- if (actual != null) {
- buffer.write('; found "');
- buffer.write(json.encode(actual));
- buffer.write('"');
- }
- return new RequestFailure(
- RequestErrorFactory.invalidParameter(jsonPath, buffer.toString()));
- }
-
- @override
- dynamic missingKey(String jsonPath, String key) {
- return new RequestFailure(RequestErrorFactory.invalidParameter(
- jsonPath, 'Expected to contain key ${json.encode(key)}'));
- }
-}
-
-abstract class RequestParams implements HasToJson {
- /**
- * Return a request whose parameters are taken from this object and that has
- * the given [id].
- */
- Request toRequest(String id);
-}
-
-/**
- * JsonDecoder for decoding responses from the server. This is intended to be
- * used only for testing. Errors are reported using bare [Exception] objects.
- */
-class ResponseDecoder extends JsonDecoder {
- @override
- final RefactoringKind refactoringKind;
-
- ResponseDecoder(this.refactoringKind);
-
- @override
- dynamic mismatch(String jsonPath, String expected, [Object actual]) {
- StringBuffer buffer = new StringBuffer();
- buffer.write('Expected ');
- buffer.write(expected);
- if (actual != null) {
- buffer.write(' found "');
- buffer.write(json.encode(actual));
- buffer.write('"');
- }
- buffer.write(' at ');
- buffer.write(jsonPath);
- return new Exception(buffer.toString());
- }
-
- @override
- dynamic missingKey(String jsonPath, String key) {
- return new Exception('Missing key $key at $jsonPath');
- }
-}
-
-/**
- * The result data associated with a response.
- */
-abstract class ResponseResult implements HasToJson {
- /**
- * Return a response whose result data is this object for the request with the
- * given [id], where the request was received at the given [requestTime].
- */
- Response toResponse(String id, int requestTime);
-}
diff --git a/analyzer_plugin/lib/src/utilities/assist/assist.dart b/analyzer_plugin/lib/src/utilities/assist/assist.dart
deleted file mode 100644
index 95b0893..0000000
--- a/analyzer_plugin/lib/src/utilities/assist/assist.dart
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/utilities/assist/assist.dart';
-
-/**
- * A concrete implementation of [AssistCollector].
- */
-class AssistCollectorImpl implements AssistCollector {
- /**
- * The list of assists that have been collected.
- */
- final List<PrioritizedSourceChange> assists = <PrioritizedSourceChange>[];
-
- @override
- void addAssist(PrioritizedSourceChange assist) {
- assists.add(assist);
- }
-}
-
-/**
- * A concrete implementation of [DartAssistRequest].
- */
-class DartAssistRequestImpl implements DartAssistRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final int offset;
-
- @override
- final int length;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartAssistRequestImpl(
- this.resourceProvider, this.offset, this.length, this.result);
-}
diff --git a/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart b/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
deleted file mode 100644
index 404dacb..0000000
--- a/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
+++ /dev/null
@@ -1,490 +0,0 @@
-// 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:async';
-import 'dart:collection';
-import 'dart:math' as math;
-
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
-
-/**
- * A builder used to build a [SourceChange].
- */
-class ChangeBuilderImpl implements ChangeBuilder {
- /**
- * The end-of-line marker used in the file being edited, or `null` if the
- * default marker should be used.
- */
- String eol = null;
-
- /**
- * A table mapping group ids to the associated linked edit groups.
- */
- final Map<String, LinkedEditGroup> _linkedEditGroups =
- <String, LinkedEditGroup>{};
-
- /**
- * The source change selection or `null` if none.
- */
- Position _selection;
-
- /**
- * The range of the selection for the change being built, or `null` if there
- * is no selection.
- */
- SourceRange _selectionRange;
-
- /**
- * The set of [Position]s that belong to the current [EditBuilderImpl] and
- * should not be updated in result of inserting this builder.
- */
- final Set<Position> _lockedPositions = new HashSet<Position>.identity();
-
- /**
- * A map of absolute normalized path to file edit builder.
- */
- final _fileEditBuilders = <String, FileEditBuilderImpl>{};
-
- /**
- * Initialize a newly created change builder.
- */
- ChangeBuilderImpl();
-
- @override
- SourceRange get selectionRange => _selectionRange;
-
- @override
- SourceChange get sourceChange {
- final SourceChange change = new SourceChange('');
- for (var builder in _fileEditBuilders.values) {
- if (builder.hasEdits) {
- change.addFileEdit(builder.fileEdit);
- builder.finalize();
- }
- }
- _linkedEditGroups.forEach((String name, LinkedEditGroup group) {
- change.addLinkedEditGroup(group);
- });
- if (_selection != null) {
- change.selection = _selection;
- }
- return change;
- }
-
- @override
- Future<void> addFileEdit(
- String path, void buildFileEdit(FileEditBuilder builder)) async {
- FileEditBuilderImpl builder = _fileEditBuilders[path];
- if (builder == null) {
- builder = await createFileEditBuilder(path);
- if (builder != null) {
- _fileEditBuilders[path] = builder;
- }
- }
- if (builder != null) {
- buildFileEdit(builder);
- }
- }
-
- /**
- * Create and return a [FileEditBuilder] that can be used to build edits to
- * the file with the given [path] and [timeStamp].
- */
- Future<FileEditBuilderImpl> createFileEditBuilder(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- return new FileEditBuilderImpl(this, path, 0);
- }
-
- /**
- * Return the linked edit group with the given [groupName], creating it if it
- * did not already exist.
- */
- LinkedEditGroup getLinkedEditGroup(String groupName) {
- LinkedEditGroup group = _linkedEditGroups[groupName];
- if (group == null) {
- group = new LinkedEditGroup.empty();
- _linkedEditGroups[groupName] = group;
- }
- return group;
- }
-
- @override
- void setSelection(Position position) {
- _selection = position;
- }
-
- void _setSelectionRange(SourceRange range) {
- _selectionRange = range;
- }
-
- /**
- * Update the offsets of any positions that occur at or after the given
- * [offset] such that the positions are offset by the given [delta]. Positions
- * occur in linked edit groups and as the post-change selection.
- */
- void _updatePositions(int offset, int delta) {
- void _updatePosition(Position position) {
- if (position.offset >= offset && !_lockedPositions.contains(position)) {
- position.offset = position.offset + delta;
- }
- }
-
- for (LinkedEditGroup group in _linkedEditGroups.values) {
- for (Position position in group.positions) {
- _updatePosition(position);
- }
- }
- if (_selection != null) {
- _updatePosition(_selection);
- }
- }
-}
-
-/**
- * A builder used to build a [SourceEdit] as part of a [SourceFileEdit].
- */
-class EditBuilderImpl implements EditBuilder {
- /**
- * The builder being used to create the source file edit of which the source
- * edit will be a part.
- */
- final FileEditBuilderImpl fileEditBuilder;
-
- /**
- * The offset of the region being replaced.
- */
- final int offset;
-
- /**
- * The length of the region being replaced.
- */
- final int length;
-
- /**
- * The range of the selection for the change being built, or `null` if the
- * selection is not inside the change being built.
- */
- SourceRange _selectionRange;
-
- /**
- * The end-of-line marker used in the file being edited, or `null` if the
- * default marker should be used.
- */
- String _eol = null;
-
- /**
- * The buffer in which the content of the edit is being composed.
- */
- final StringBuffer _buffer = new StringBuffer();
-
- /**
- * Initialize a newly created builder to build a source edit.
- */
- EditBuilderImpl(this.fileEditBuilder, this.offset, this.length) {
- _eol = fileEditBuilder.changeBuilder.eol;
- }
-
- /**
- * Create and return an edit representing the replacement of a region of the
- * file with the accumulated text.
- */
- SourceEdit get sourceEdit =>
- new SourceEdit(offset, length, _buffer.toString());
-
- @override
- void addLinkedEdit(
- String groupName, void buildLinkedEdit(LinkedEditBuilder builder)) {
- LinkedEditBuilderImpl builder = createLinkedEditBuilder();
- int start = offset + _buffer.length;
- try {
- buildLinkedEdit(builder);
- } finally {
- int end = offset + _buffer.length;
- int length = end - start;
- if (length != 0) {
- Position position = new Position(fileEditBuilder.fileEdit.file, start);
- fileEditBuilder.changeBuilder._lockedPositions.add(position);
- LinkedEditGroup group =
- fileEditBuilder.changeBuilder.getLinkedEditGroup(groupName);
- group.addPosition(position, length);
- for (LinkedEditSuggestion suggestion in builder.suggestions) {
- group.addSuggestion(suggestion);
- }
- }
- }
- }
-
- @override
- void addSimpleLinkedEdit(String groupName, String text,
- {LinkedEditSuggestionKind kind, List<String> suggestions}) {
- addLinkedEdit(groupName, (LinkedEditBuilder builder) {
- builder.write(text);
- if (kind != null && suggestions != null) {
- for (String suggestion in suggestions) {
- builder.addSuggestion(kind, suggestion);
- }
- } else if (kind != null || suggestions != null) {
- throw new ArgumentError(
- 'Either both kind and suggestions must be provided or neither.');
- }
- });
- }
-
- LinkedEditBuilderImpl createLinkedEditBuilder() {
- return new LinkedEditBuilderImpl(this);
- }
-
- @override
- void selectAll(void writer()) {
- int rangeOffset = _buffer.length;
- writer();
- int rangeLength = _buffer.length - rangeOffset;
- _selectionRange = new SourceRange(offset + rangeOffset, rangeLength);
- }
-
- @override
- void selectHere() {
- _selectionRange = new SourceRange(offset + _buffer.length, 0);
- }
-
- @override
- void write(String string) {
- _buffer.write(string);
- }
-
- @override
- void writeln([String string]) {
- if (string != null) {
- _buffer.write(string);
- }
- if (_eol == null) {
- _buffer.writeln();
- } else {
- _buffer.write(_eol);
- }
- }
-}
-
-/**
- * A builder used to build a [SourceFileEdit] within a [SourceChange].
- */
-class FileEditBuilderImpl implements FileEditBuilder {
- /**
- * The builder being used to create the source change of which the source file
- * edit will be a part.
- */
- final ChangeBuilderImpl changeBuilder;
-
- /**
- * The source file edit that is being built.
- */
- final SourceFileEdit fileEdit;
-
- /**
- * Initialize a newly created builder to build a source file edit within the
- * change being built by the given [changeBuilder]. The file being edited has
- * the given absolute [path] and [timeStamp].
- */
- FileEditBuilderImpl(this.changeBuilder, String path, int timeStamp)
- : fileEdit = new SourceFileEdit(path, timeStamp);
-
- /**
- * Return `true` if this builder has edits to be applied.
- */
- bool get hasEdits => fileEdit.edits.isNotEmpty;
-
- @override
- void addDeletion(SourceRange range) {
- if (range.length > 0) {
- EditBuilderImpl builder = createEditBuilder(range.offset, range.length);
- _addEditBuilder(builder);
- }
- }
-
- @override
- void addInsertion(int offset, void buildEdit(EditBuilder builder)) {
- EditBuilderImpl builder = createEditBuilder(offset, 0);
- try {
- buildEdit(builder);
- } finally {
- _addEditBuilder(builder);
- }
- }
-
- @override
- void addLinkedPosition(SourceRange range, String groupName) {
- LinkedEditGroup group = changeBuilder.getLinkedEditGroup(groupName);
- Position position = new Position(
- fileEdit.file, range.offset + _deltaToOffset(range.offset));
- group.addPosition(position, range.length);
- }
-
- @override
- void addReplacement(SourceRange range, void buildEdit(EditBuilder builder)) {
- EditBuilderImpl builder = createEditBuilder(range.offset, range.length);
- try {
- buildEdit(builder);
- } finally {
- _addEditBuilder(builder);
- }
- }
-
- @override
- void addSimpleInsertion(int offset, String text) {
- EditBuilderImpl builder = createEditBuilder(offset, 0);
- try {
- builder.write(text);
- } finally {
- _addEditBuilder(builder);
- }
- }
-
- @override
- void addSimpleReplacement(SourceRange range, String text) {
- EditBuilderImpl builder = createEditBuilder(range.offset, range.length);
- try {
- builder.write(text);
- } finally {
- _addEditBuilder(builder);
- }
- }
-
- EditBuilderImpl createEditBuilder(int offset, int length) {
- return new EditBuilderImpl(this, offset, length);
- }
-
- /**
- * Finalize the source file edit that is being built.
- */
- void finalize() {
- // Nothing to do.
- }
-
- /**
- * Replace edits in the [range] with the given [edit].
- * The [range] is relative to the original code.
- */
- void replaceEdits(SourceRange range, SourceEdit edit) {
- fileEdit.edits.removeWhere((edit) {
- if (range.contains(edit.offset)) {
- if (!range.contains(edit.end)) {
- throw StateError('$edit is not completely in $range');
- }
- return true;
- } else if (range.contains(edit.end)) {
- throw StateError('$edit is not completely in $range');
- }
- return false;
- });
-
- _addEdit(edit);
- }
-
- /**
- * Add the edit from the given [edit] to the edits associates with the
- * current file.
- */
- void _addEdit(SourceEdit edit) {
- fileEdit.add(edit);
- int delta = _editDelta(edit);
- changeBuilder._updatePositions(
- edit.offset + math.max<int>(0, delta), delta);
- changeBuilder._lockedPositions.clear();
- }
-
- /**
- * Add the edit from the given [builder] to the edits associates with the
- * current file.
- */
- void _addEditBuilder(EditBuilderImpl builder) {
- SourceEdit edit = builder.sourceEdit;
- _addEdit(edit);
- _captureSelection(builder, edit);
- }
-
- /**
- * Capture the selection offset if one was set.
- */
- void _captureSelection(EditBuilderImpl builder, SourceEdit edit) {
- SourceRange range = builder._selectionRange;
- if (range != null) {
- Position position =
- new Position(fileEdit.file, range.offset + _deltaToEdit(edit));
- changeBuilder.setSelection(position);
- changeBuilder._setSelectionRange(range);
- }
- }
-
- /**
- * Return the current delta caused by edits that will be applied before the
- * [targetEdit]. In other words, if all of the edits that occur before the
- * target edit were to be applied, then the text at the offset of the target
- * edit before the applied edits will be at `offset + _deltaToOffset(offset)`
- * after the edits.
- */
- int _deltaToEdit(SourceEdit targetEdit) {
- int delta = 0;
- for (SourceEdit edit in fileEdit.edits) {
- if (edit.offset < targetEdit.offset) {
- delta += _editDelta(edit);
- }
- }
- return delta;
- }
-
- /**
- * Return the current delta caused by edits that will be applied before the
- * given [offset]. In other words, if all of the edits that have so far been
- * added were to be applied, then the text at the given `offset` before the
- * applied edits will be at `offset + _deltaToOffset(offset)` after the edits.
- */
- int _deltaToOffset(int offset) {
- int delta = 0;
- for (SourceEdit edit in fileEdit.edits) {
- if (edit.offset <= offset) {
- delta += _editDelta(edit);
- }
- }
- return delta;
- }
-
- /**
- * Return the delta introduced by the given `edit`.
- */
- int _editDelta(SourceEdit edit) => edit.replacement.length - edit.length;
-}
-
-/**
- * A builder used to build a [LinkedEdit] region within an edit.
- */
-class LinkedEditBuilderImpl implements LinkedEditBuilder {
- final EditBuilderImpl editBuilder;
-
- final List<LinkedEditSuggestion> suggestions = <LinkedEditSuggestion>[];
-
- LinkedEditBuilderImpl(this.editBuilder);
-
- @override
- void addSuggestion(LinkedEditSuggestionKind kind, String value) {
- suggestions.add(new LinkedEditSuggestion(value, kind));
- }
-
- @override
- void addSuggestions(LinkedEditSuggestionKind kind, Iterable<String> values) {
- values.forEach((value) => addSuggestion(kind, value));
- }
-
- @override
- void write(String string) {
- editBuilder.write(string);
- }
-
- @override
- void writeln([String string]) {
- editBuilder.writeln(string);
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart b/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart
deleted file mode 100644
index d4a9061..0000000
--- a/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart
+++ /dev/null
@@ -1,1713 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/analysis/session.dart';
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/token.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/exception/exception.dart';
-import 'package:analyzer/src/dart/ast/utilities.dart';
-import 'package:analyzer/src/dart/element/type.dart';
-import 'package:analyzer/src/generated/resolver.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide Element, ElementKind;
-import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
-import 'package:analyzer_plugin/src/utilities/string_utilities.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_workspace.dart';
-import 'package:analyzer_plugin/utilities/range_factory.dart';
-import 'package:charcode/ascii.dart';
-import 'package:dart_style/dart_style.dart';
-
-/**
- * A [ChangeBuilder] used to build changes in Dart files.
- */
-class DartChangeBuilderImpl extends ChangeBuilderImpl
- implements DartChangeBuilder {
- /**
- * The analysis session in which the files are analyzed and edited.
- */
- final ChangeWorkspace workspace;
-
- /**
- * Initialize a newly created change builder.
- */
- DartChangeBuilderImpl(AnalysisSession session)
- : this.forWorkspace(_SingleSessionWorkspace(session));
-
- DartChangeBuilderImpl.forWorkspace(this.workspace);
-
- @override
- Future<void> addFileEdit(
- String path, void buildFileEdit(DartFileEditBuilder builder),
- {ImportPrefixGenerator importPrefixGenerator}) {
- return super.addFileEdit(path, (builder) {
- DartFileEditBuilderImpl dartBuilder = builder as DartFileEditBuilderImpl;
- dartBuilder.importPrefixGenerator = importPrefixGenerator;
- buildFileEdit(dartBuilder);
- });
- }
-
- @override
- Future<DartFileEditBuilderImpl> createFileEditBuilder(String path) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
-
- if (!workspace.containsFile(path)) {
- return null;
- }
-
- var session = workspace.getSession(path);
- ResolvedUnitResult result = await session.getResolvedUnit(path);
- ResultState state = result?.state ?? ResultState.INVALID_FILE_TYPE;
- if (state == ResultState.INVALID_FILE_TYPE) {
- throw new AnalysisException('Cannot analyze "$path"');
- }
- int timeStamp = state == ResultState.VALID ? 0 : -1;
-
- CompilationUnitElement declaredUnit = result.unit.declaredElement;
- CompilationUnitElement libraryUnit =
- declaredUnit.library.definingCompilationUnit;
-
- DartFileEditBuilderImpl libraryEditBuilder;
- if (libraryUnit != declaredUnit) {
- // If the receiver is a part file builder, then proactively cache the
- // library file builder so that imports can be finalized synchronously.
- await addFileEdit(libraryUnit.source.fullName,
- (DartFileEditBuilder builder) {
- libraryEditBuilder = builder as DartFileEditBuilderImpl;
- });
- }
-
- return DartFileEditBuilderImpl(this, result, timeStamp, libraryEditBuilder);
- }
-}
-
-/**
- * An [EditBuilder] used to build edits in Dart files.
- */
-class DartEditBuilderImpl extends EditBuilderImpl implements DartEditBuilder {
- List<String> _KNOWN_METHOD_NAME_PREFIXES = ['get', 'is', 'to'];
-
- /**
- * Whether [_enclosingClass] and [_enclosingExecutable] have been initialized.
- */
- bool _hasEnclosingElementsInitialized = false;
-
- /**
- * The enclosing class element, possibly `null`.
- * This field is lazily initialized in [_initializeEnclosingElements].
- */
- ClassElement _enclosingClass;
-
- /**
- * The enclosing executable element, possibly `null`.
- * This field is lazily initialized in [_initializeEnclosingElements].
- */
- ExecutableElement _enclosingExecutable;
-
- /**
- * If not `null`, [write] will copy everything into this buffer.
- */
- StringBuffer _carbonCopyBuffer;
-
- /**
- * Initialize a newly created builder to build a source edit.
- */
- DartEditBuilderImpl(
- DartFileEditBuilderImpl sourceFileEditBuilder, int offset, int length)
- : super(sourceFileEditBuilder, offset, length);
-
- DartFileEditBuilderImpl get dartFileEditBuilder =>
- fileEditBuilder as DartFileEditBuilderImpl;
-
- @override
- void addLinkedEdit(String groupName,
- void buildLinkedEdit(DartLinkedEditBuilder builder)) =>
- super.addLinkedEdit(groupName,
- (builder) => buildLinkedEdit(builder as DartLinkedEditBuilder));
-
- @override
- LinkedEditBuilderImpl createLinkedEditBuilder() {
- return new DartLinkedEditBuilderImpl(this);
- }
-
- /**
- * Returns the indentation with the given [level].
- */
- String getIndent(int level) => ' ' * level;
-
- @override
- void write(String string) {
- super.write(string);
- _carbonCopyBuffer?.write(string);
- }
-
- @override
- void writeClassDeclaration(String name,
- {Iterable<DartType> interfaces,
- bool isAbstract: false,
- void membersWriter(),
- Iterable<DartType> mixins,
- String nameGroupName,
- DartType superclass,
- String superclassGroupName}) {
- // TODO(brianwilkerson) Add support for type parameters, probably as a
- // parameterWriter parameter.
- if (isAbstract) {
- write(Keyword.ABSTRACT.lexeme);
- write(' ');
- }
- write('class ');
- if (nameGroupName == null) {
- write(name);
- } else {
- addSimpleLinkedEdit(nameGroupName, name);
- }
- if (superclass != null) {
- write(' extends ');
- writeType(superclass, groupName: superclassGroupName);
- } else if (mixins != null && mixins.isNotEmpty) {
- // TODO(brianwilkerson) Remove this branch when 2.1 semantics are
- // supported everywhere.
- write(' extends Object ');
- }
- writeTypes(mixins, prefix: ' with ');
- writeTypes(interfaces, prefix: ' implements ');
- writeln(' {');
- if (membersWriter != null) {
- membersWriter();
- }
- write('}');
- }
-
- @override
- void writeConstructorDeclaration(String className,
- {ArgumentList argumentList,
- void bodyWriter(),
- SimpleIdentifier constructorName,
- String constructorNameGroupName,
- List<String> fieldNames,
- void initializerWriter(),
- bool isConst: false,
- void parameterWriter()}) {
- if (isConst) {
- write(Keyword.CONST.lexeme);
- write(' ');
- }
- write(className);
- if (constructorName != null) {
- write('.');
- if (constructorNameGroupName == null) {
- write(constructorName.name);
- } else {
- addSimpleLinkedEdit(constructorNameGroupName, constructorName.name);
- }
- }
- write('(');
- if (parameterWriter != null) {
- parameterWriter();
- } else if (argumentList != null) {
- writeParametersMatchingArguments(argumentList);
- } else if (fieldNames != null) {
- for (int i = 0; i < fieldNames.length; i++) {
- if (i > 0) {
- write(', ');
- }
- write('this.');
- write(fieldNames[i]);
- }
- }
- write(')');
-
- if (initializerWriter != null) {
- write(' : ');
- initializerWriter();
- }
-
- if (bodyWriter != null) {
- bodyWriter();
- } else {
- write(';');
- }
- }
-
- @override
- void writeFieldDeclaration(String name,
- {void initializerWriter(),
- bool isConst: false,
- bool isFinal: false,
- bool isStatic: false,
- String nameGroupName,
- DartType type,
- String typeGroupName}) {
- if (isStatic) {
- write(Keyword.STATIC.lexeme);
- write(' ');
- }
- bool typeRequired = true;
- if (isConst) {
- write(Keyword.CONST.lexeme);
- write(' ');
- typeRequired = false;
- } else if (isFinal) {
- write(Keyword.FINAL.lexeme);
- write(' ');
- typeRequired = false;
- }
- if (type != null) {
- writeType(type, groupName: typeGroupName, required: true);
- write(' ');
- } else if (typeRequired) {
- write(Keyword.VAR.lexeme);
- write(' ');
- }
- if (nameGroupName != null) {
- addSimpleLinkedEdit(nameGroupName, name);
- } else {
- write(name);
- }
- if (initializerWriter != null) {
- write(' = ');
- initializerWriter();
- }
- write(';');
- }
-
- @override
- void writeFunctionDeclaration(String name,
- {void bodyWriter(),
- bool isStatic: false,
- String nameGroupName,
- void parameterWriter(),
- DartType returnType,
- String returnTypeGroupName}) {
- if (isStatic) {
- write(Keyword.STATIC.lexeme);
- write(' ');
- }
- if (returnType != null) {
- if (writeType(returnType, groupName: returnTypeGroupName)) {
- write(' ');
- }
- }
- if (nameGroupName != null) {
- addSimpleLinkedEdit(nameGroupName, name);
- } else {
- write(name);
- }
- write('(');
- if (parameterWriter != null) {
- parameterWriter();
- }
- write(')');
- if (bodyWriter == null) {
- if (returnType != null) {
- write(' => null;');
- } else {
- write(' {}');
- }
- } else {
- write(' ');
- bodyWriter();
- }
- }
-
- @override
- void writeGetterDeclaration(String name,
- {void bodyWriter(),
- bool isStatic: false,
- String nameGroupName,
- DartType returnType,
- String returnTypeGroupName}) {
- if (isStatic) {
- write(Keyword.STATIC.lexeme);
- write(' ');
- }
- if (returnType != null && !returnType.isDynamic) {
- if (writeType(returnType, groupName: returnTypeGroupName)) {
- write(' ');
- }
- }
- write(Keyword.GET.lexeme);
- write(' ');
- if (nameGroupName != null) {
- addSimpleLinkedEdit(nameGroupName, name);
- } else {
- write(name);
- }
- if (bodyWriter == null) {
- write(' => null;');
- } else {
- write(' ');
- bodyWriter();
- }
- }
-
- @override
- void writeLocalVariableDeclaration(String name,
- {void initializerWriter(),
- bool isConst: false,
- bool isFinal: false,
- String nameGroupName,
- DartType type,
- String typeGroupName}) {
- bool typeRequired = true;
- if (isConst) {
- write(Keyword.CONST.lexeme);
- typeRequired = false;
- } else if (isFinal) {
- write(Keyword.FINAL.lexeme);
- typeRequired = false;
- }
- if (type != null) {
- if (!typeRequired) {
- // The type is required unless we've written a keyword.
- write(' ');
- }
- writeType(type, groupName: typeGroupName);
- } else if (typeRequired) {
- write(Keyword.VAR.lexeme);
- }
- write(' ');
- if (nameGroupName != null) {
- addSimpleLinkedEdit(nameGroupName, name);
- } else {
- write(name);
- }
- if (initializerWriter != null) {
- write(' = ');
- initializerWriter();
- }
- write(';');
- }
-
- @override
- void writeMixinDeclaration(String name,
- {Iterable<DartType> interfaces,
- void membersWriter(),
- String nameGroupName,
- Iterable<DartType> superclassConstraints}) {
- // TODO(brianwilkerson) Add support for type parameters, probably as a
- // parameterWriter parameter.
- write('mixin ');
- if (nameGroupName == null) {
- write(name);
- } else {
- addSimpleLinkedEdit(nameGroupName, name);
- }
- writeTypes(superclassConstraints, prefix: ' on ');
- writeTypes(interfaces, prefix: ' implements ');
- writeln(' {');
- if (membersWriter != null) {
- membersWriter();
- }
- write('}');
- }
-
- @override
- void writeOverride(
- ExecutableElement element, {
- StringBuffer displayTextBuffer,
- String returnTypeGroupName,
- bool invokeSuper: false,
- }) {
- void withCarbonCopyBuffer(f()) {
- this._carbonCopyBuffer = displayTextBuffer;
- try {
- f();
- } finally {
- this._carbonCopyBuffer = null;
- }
- }
-
- String prefix = getIndent(1);
- String prefix2 = getIndent(2);
- ElementKind elementKind = element.kind;
-
- bool isGetter = elementKind == ElementKind.GETTER;
- bool isSetter = elementKind == ElementKind.SETTER;
- bool isMethod = elementKind == ElementKind.METHOD;
- bool isOperator = isMethod && (element as MethodElement).isOperator;
- String memberName = element.displayName;
-
- // @override
- writeln('@override');
- write(prefix);
-
- if (isGetter) {
- writeln('// TODO: implement ${element.displayName}');
- write(prefix);
- }
-
- // return type
- DartType returnType = element.returnType;
- bool typeWritten = writeType(returnType,
- groupName: returnTypeGroupName, methodBeingCopied: element);
- if (typeWritten) {
- write(' ');
- }
- if (isGetter) {
- write(Keyword.GET.lexeme);
- write(' ');
- } else if (isSetter) {
- write(Keyword.SET.lexeme);
- write(' ');
- } else if (isOperator) {
- write(Keyword.OPERATOR.lexeme);
- write(' ');
- }
-
- // name
- withCarbonCopyBuffer(() {
- write(memberName);
- });
-
- // parameters + body
- if (isGetter) {
- if (invokeSuper) {
- write(' => ');
- selectAll(() {
- write('super.');
- write(memberName);
- });
- writeln(';');
- } else {
- write(' => ');
- selectAll(() {
- write('null');
- });
- write(';');
- }
- displayTextBuffer?.write(' => …');
- } else {
- List<ParameterElement> parameters = element.parameters;
- withCarbonCopyBuffer(() {
- writeTypeParameters(element.type.typeFormals,
- methodBeingCopied: element);
- writeParameters(parameters, methodBeingCopied: element);
- });
- writeln(' {');
-
- // TO-DO
- write(prefix2);
- write('// TODO: implement $memberName');
-
- if (isSetter) {
- if (invokeSuper) {
- writeln();
- write(prefix2);
- selectAll(() {
- write('super.');
- write(memberName);
- write(' = ');
- write(parameters[0].name);
- write(';');
- });
- writeln();
- } else {
- selectHere();
- writeln();
- }
- } else if (returnType.isVoid) {
- if (invokeSuper) {
- writeln();
- write(prefix2);
- selectAll(() {
- write('super.');
- write(memberName);
- write('(');
- for (int i = 0; i < parameters.length; i++) {
- if (i > 0) {
- write(', ');
- }
- write(parameters[i].name);
- }
- write(');');
- });
- writeln();
- } else {
- selectHere();
- writeln();
- }
- } else {
- writeln();
- write(prefix2);
- if (invokeSuper) {
- selectAll(() {
- write('return super.');
- write(memberName);
- write('(');
- for (int i = 0; i < parameters.length; i++) {
- if (i > 0) {
- write(', ');
- }
- write(parameters[i].name);
- }
- write(');');
- });
- } else {
- selectAll(() {
- write('return null;');
- });
- }
- writeln();
- }
- // close method
- write(prefix);
- write('}');
- displayTextBuffer?.write(' { … }');
- }
- }
-
- @override
- void writeParameter(String name,
- {ExecutableElement methodBeingCopied, DartType type}) {
- if (type != null) {
- bool hasType = _writeType(type, methodBeingCopied: methodBeingCopied);
- if (name.isNotEmpty) {
- if (hasType) {
- write(' ');
- }
- write(name);
- }
- } else {
- write(name);
- }
- }
-
- @override
- void writeParameterMatchingArgument(
- Expression argument, int index, Set<String> usedNames) {
- // append type name
- DartType type = argument.staticType;
- if (type == null || type.isBottom || type.isDartCoreNull) {
- type = DynamicTypeImpl.instance;
- }
- if (writeType(type, addSupertypeProposals: true, groupName: 'TYPE$index')) {
- write(' ');
- }
- // append parameter name
- if (argument is NamedExpression) {
- write(argument.name.label.name);
- } else {
- List<String> suggestions =
- _getParameterNameSuggestions(usedNames, type, argument, index);
- String favorite = suggestions[0];
- usedNames.add(favorite);
- addSimpleLinkedEdit('PARAM$index', favorite,
- kind: LinkedEditSuggestionKind.PARAMETER, suggestions: suggestions);
- }
- }
-
- @override
- void writeParameters(Iterable<ParameterElement> parameters,
- {ExecutableElement methodBeingCopied}) {
- write('(');
- bool sawNamed = false;
- bool sawPositional = false;
- for (int i = 0; i < parameters.length; i++) {
- ParameterElement parameter = parameters.elementAt(i);
- if (i > 0) {
- write(', ');
- }
- // Might be optional
- if (parameter.isNamed) {
- if (!sawNamed) {
- write('{');
- sawNamed = true;
- }
- } else if (parameter.isOptionalPositional) {
- if (!sawPositional) {
- write('[');
- sawPositional = true;
- }
- }
- // parameter
- writeParameter(parameter.name,
- methodBeingCopied: methodBeingCopied, type: parameter.type);
- // default value
- String defaultCode = parameter.defaultValueCode;
- if (defaultCode != null) {
- write(' = ');
- write(defaultCode);
- }
- }
- // close parameters
- if (sawNamed) {
- write('}');
- }
- if (sawPositional) {
- write(']');
- }
- write(')');
- }
-
- @override
- void writeParametersMatchingArguments(ArgumentList argumentList) {
- // TODO(brianwilkerson) Handle the case when there are required parameters
- // after named parameters.
- Set<String> usedNames = new Set<String>();
- List<Expression> arguments = argumentList.arguments;
- bool hasNamedParameters = false;
- for (int i = 0; i < arguments.length; i++) {
- Expression argument = arguments[i];
- if (i > 0) {
- write(', ');
- }
- if (argument is NamedExpression && !hasNamedParameters) {
- hasNamedParameters = true;
- write('{');
- }
- writeParameterMatchingArgument(argument, i, usedNames);
- }
- if (hasNamedParameters) {
- write('}');
- }
- }
-
- @override
- void writeReference(Element element) {
- if (element.enclosingElement is CompilationUnitElement) {
- _writeLibraryReference(element);
- }
- write(element.displayName);
- }
-
- @override
- void writeSetterDeclaration(String name,
- {void bodyWriter(),
- bool isStatic: false,
- String nameGroupName,
- DartType parameterType,
- String parameterTypeGroupName}) {
- if (isStatic) {
- write(Keyword.STATIC.lexeme);
- write(' ');
- }
- write(Keyword.SET.lexeme);
- write(' ');
- if (nameGroupName != null) {
- addSimpleLinkedEdit(nameGroupName, name);
- } else {
- write(name);
- }
- write('(');
- if (parameterType != null && !parameterType.isDynamic) {
- if (writeType(parameterType, groupName: parameterTypeGroupName)) {
- write(' ');
- }
- }
- // TODO(brianwilkerson) The name of the setter is unlikely to be a good name
- // for the parameter. We need to find a better name to produce here.
- write(name);
- write(') ');
- if (bodyWriter == null) {
- write('{}');
- } else {
- bodyWriter();
- }
- }
-
- @override
- bool writeType(DartType type,
- {bool addSupertypeProposals: false,
- String groupName,
- ExecutableElement methodBeingCopied,
- bool required: false}) {
- bool wroteType = false;
- if (type != null && !type.isDynamic) {
- if (groupName != null) {
- addLinkedEdit(groupName, (LinkedEditBuilder builder) {
- wroteType = _writeType(type, methodBeingCopied: methodBeingCopied);
- if (wroteType && addSupertypeProposals) {
- _addSuperTypeProposals(builder, type, new Set<DartType>());
- }
- });
- } else {
- wroteType = _writeType(type, methodBeingCopied: methodBeingCopied);
- }
- }
- if (!wroteType && required) {
- write(Keyword.VAR.lexeme);
- return true;
- }
- return wroteType;
- }
-
- @override
- void writeTypeParameter(TypeParameterElement typeParameter,
- {ExecutableElement methodBeingCopied}) {
- write(typeParameter.name);
- if (typeParameter.bound != null) {
- write(' extends ');
- _writeType(typeParameter.bound, methodBeingCopied: methodBeingCopied);
- }
- }
-
- @override
- void writeTypeParameters(List<TypeParameterElement> typeParameters,
- {ExecutableElement methodBeingCopied}) {
- if (typeParameters.isNotEmpty) {
- write('<');
- bool isFirst = true;
- for (TypeParameterElement typeParameter in typeParameters) {
- if (!isFirst) {
- write(', ');
- }
- isFirst = false;
- writeTypeParameter(typeParameter, methodBeingCopied: methodBeingCopied);
- }
- write('>');
- }
- }
-
- @override
- void writeTypes(Iterable<DartType> types, {String prefix}) {
- if (types == null || types.isEmpty) {
- return;
- }
- bool first = true;
- for (DartType type in types) {
- if (first) {
- if (prefix != null) {
- write(prefix);
- }
- first = false;
- } else {
- write(', ');
- }
- writeType(type);
- }
- }
-
- /**
- * Adds [toAdd] items which are not excluded.
- */
- void _addAll(
- Set<String> excluded, Set<String> result, Iterable<String> toAdd) {
- for (String item in toAdd) {
- // add name based on "item", but not "excluded"
- for (int suffix = 1;; suffix++) {
- // prepare name, just "item" or "item2", "item3", etc
- String name = item;
- if (suffix > 1) {
- name += suffix.toString();
- }
- // add once found not excluded
- if (!excluded.contains(name)) {
- result.add(name);
- break;
- }
- }
- }
- }
-
- /**
- * Adds to [result] either [c] or the first ASCII character after it.
- */
- void _addSingleCharacterName(
- Set<String> excluded, Set<String> result, int c) {
- while (c < $z) {
- String name = new String.fromCharCode(c);
- // may be done
- if (!excluded.contains(name)) {
- result.add(name);
- break;
- }
- // next character
- c = c + 1;
- }
- }
-
- void _addSuperTypeProposals(
- LinkedEditBuilder builder, DartType type, Set<DartType> alreadyAdded) {
- if (type is InterfaceType && alreadyAdded.add(type)) {
- builder.addSuggestion(LinkedEditSuggestionKind.TYPE, type.displayName);
- _addSuperTypeProposals(builder, type.superclass, alreadyAdded);
- for (InterfaceType interfaceType in type.interfaces) {
- _addSuperTypeProposals(builder, interfaceType, alreadyAdded);
- }
- }
- }
-
- String _getBaseNameFromExpression(Expression expression) {
- if (expression is AsExpression) {
- return _getBaseNameFromExpression(expression.expression);
- } else if (expression is ParenthesizedExpression) {
- return _getBaseNameFromExpression(expression.expression);
- }
- return _getBaseNameFromUnwrappedExpression(expression);
- }
-
- String _getBaseNameFromLocationInParent(Expression expression) {
- // value in named expression
- if (expression.parent is NamedExpression) {
- NamedExpression namedExpression = expression.parent as NamedExpression;
- if (namedExpression.expression == expression) {
- return namedExpression.name.label.name;
- }
- }
- // positional argument
- ParameterElement parameter = expression.staticParameterElement;
- if (parameter != null) {
- return parameter.displayName;
- }
-
- // unknown
- return null;
- }
-
- String _getBaseNameFromUnwrappedExpression(Expression expression) {
- String name = null;
- // analyze expressions
- if (expression is SimpleIdentifier) {
- return expression.name;
- } else if (expression is PrefixedIdentifier) {
- return expression.identifier.name;
- } else if (expression is PropertyAccess) {
- return expression.propertyName.name;
- } else if (expression is MethodInvocation) {
- name = expression.methodName.name;
- } else if (expression is InstanceCreationExpression) {
- ConstructorName constructorName = expression.constructorName;
- TypeName typeName = constructorName.type;
- if (typeName != null) {
- Identifier typeNameIdentifier = typeName.name;
- // new ClassName()
- if (typeNameIdentifier is SimpleIdentifier) {
- return typeNameIdentifier.name;
- }
- // new prefix.name();
- if (typeNameIdentifier is PrefixedIdentifier) {
- PrefixedIdentifier prefixed = typeNameIdentifier;
- // new prefix.ClassName()
- if (prefixed.prefix.staticElement is PrefixElement) {
- return prefixed.identifier.name;
- }
- // new ClassName.constructorName()
- return prefixed.prefix.name;
- }
- }
- } else if (expression is IndexExpression) {
- name = _getBaseNameFromExpression(expression.realTarget);
- if (name.endsWith('es')) {
- name = name.substring(0, name.length - 2);
- } else if (name.endsWith('s')) {
- name = name.substring(0, name.length - 1);
- }
- }
- // strip known prefixes
- if (name != null) {
- for (int i = 0; i < _KNOWN_METHOD_NAME_PREFIXES.length; i++) {
- String prefix = _KNOWN_METHOD_NAME_PREFIXES[i];
- if (name.startsWith(prefix)) {
- if (name == prefix) {
- return null;
- } else if (isUpperCase(name.codeUnitAt(prefix.length))) {
- return name.substring(prefix.length);
- }
- }
- }
- }
- // done
- return name;
- }
-
- /**
- * Returns all variants of names by removing leading words one by one.
- */
- List<String> _getCamelWordCombinations(String name) {
- List<String> result = [];
- List<String> parts = getCamelWords(name);
- for (int i = 0; i < parts.length; i++) {
- String s1 = parts[i].toLowerCase();
- String s2 = parts.skip(i + 1).join();
- String suggestion = '$s1$s2';
- result.add(suggestion);
- }
- return result;
- }
-
- /**
- * Return a list containing the suggested names for a parameter with the given
- * [type] whose value in one location is computed by the given [expression].
- * The list will not contain any names in the set of [excluded] names. The
- * [index] is the index of the argument, used to create a name if no better
- * name could be created. The first name in the list will be the best name.
- */
- List<String> _getParameterNameSuggestions(
- Set<String> usedNames, DartType type, Expression expression, int index) {
- List<String> suggestions =
- _getVariableNameSuggestionsForExpression(type, expression, usedNames);
- if (suggestions.length != 0) {
- return suggestions;
- }
- // TODO(brianwilkerson) Verify that the name below is not in the set of used names.
- return <String>['param$index'];
- }
-
- /**
- * Returns possible names for a variable with the given expected type and
- * expression assigned.
- */
- List<String> _getVariableNameSuggestionsForExpression(DartType expectedType,
- Expression assignedExpression, Set<String> excluded) {
- Set<String> res = new Set();
- // use expression
- if (assignedExpression != null) {
- String nameFromExpression =
- _getBaseNameFromExpression(assignedExpression);
- if (nameFromExpression != null) {
- nameFromExpression = removeStart(nameFromExpression, '_');
- _addAll(excluded, res, _getCamelWordCombinations(nameFromExpression));
- }
- String nameFromParent =
- _getBaseNameFromLocationInParent(assignedExpression);
- if (nameFromParent != null) {
- _addAll(excluded, res, _getCamelWordCombinations(nameFromParent));
- }
- }
- // use type
- if (expectedType != null && !expectedType.isDynamic) {
- String typeName = expectedType.name;
- if ('int' == typeName) {
- _addSingleCharacterName(excluded, res, $i);
- } else if ('double' == typeName) {
- _addSingleCharacterName(excluded, res, $d);
- } else if ('String' == typeName) {
- _addSingleCharacterName(excluded, res, $s);
- } else {
- _addAll(excluded, res, _getCamelWordCombinations(typeName));
- }
- res.remove(typeName);
- }
- // done
- return new List.from(res);
- }
-
- /**
- * If the given [type] is visible in either the [_enclosingExecutable] or
- * [_enclosingClass], or if there is a local equivalent to the type (such as
- * in the case of a type parameter from a superclass), then return the type
- * that is locally visible. Otherwise, return `null`.
- */
- DartType _getVisibleType(DartType type,
- {ExecutableElement methodBeingCopied}) {
- Element element = type.element;
- if (type is TypeParameterType) {
- _initializeEnclosingElements();
- Element enclosing = element.enclosingElement;
- while (enclosing is GenericFunctionTypeElement ||
- enclosing is ParameterElement) {
- enclosing = enclosing.enclosingElement;
- }
- if (enclosing == _enclosingExecutable ||
- enclosing == _enclosingClass ||
- enclosing == methodBeingCopied) {
- return type;
- }
- return null;
- }
- if (element == null) {
- return type;
- }
- if (element.isPrivate && !dartFileEditBuilder._isDefinedLocally(element)) {
- return null;
- }
- return type;
- }
-
- /**
- * Initialize the [_enclosingClass] and [_enclosingExecutable].
- */
- void _initializeEnclosingElements() {
- if (!_hasEnclosingElementsInitialized) {
- _EnclosingElementFinder finder = new _EnclosingElementFinder();
- finder.find(dartFileEditBuilder.resolvedUnit.unit, offset);
- _enclosingClass = finder.enclosingClass;
- _enclosingExecutable = finder.enclosingExecutable;
- _hasEnclosingElementsInitialized = true;
- }
- }
-
- /**
- * Write the import prefix to reference the [element], if needed.
- *
- * The prefix is not needed if the [element] is defined in the target library,
- * or there is already an import without prefix that exports the [element].
- * If there there are no existing import that exports the [element], a library
- * that exports the [element] is scheduled for import, possibly with a prefix.
- */
- void _writeLibraryReference(Element element) {
- // If the element is defined in the library, then no prefix needed.
- if (dartFileEditBuilder._isDefinedLocally(element)) {
- return;
- }
-
- // TODO(scheglov) We should use "methodBeingCopied" to verify that
- // we really are just copying this type parameter.
- if (element is TypeParameterElement) {
- return;
- }
-
- ImportElement import = dartFileEditBuilder._getImportElement(element);
- if (import != null) {
- if (import.prefix != null) {
- write(import.prefix.displayName);
- write('.');
- }
- } else {
- Uri library = element.library.source.uri;
- _LibraryToImport import = dartFileEditBuilder._importLibrary(library);
- if (import.prefix != null) {
- write(import.prefix);
- write('.');
- }
- }
- }
-
- /**
- * Write the code to reference [type] in this compilation unit.
- *
- * If a [methodBeingCopied] is provided, then the type parameters of that
- * method will be duplicated in the copy and will therefore be visible.
- *
- * Causes any libraries whose elements are used by the generated code, to be
- * imported.
- */
- bool _writeType(DartType type, {ExecutableElement methodBeingCopied}) {
- type = _getVisibleType(type, methodBeingCopied: methodBeingCopied);
-
- // If not a useful type, don't write it.
- if (type == null || type.isDynamic || type.isBottom) {
- return false;
- }
-
- Element element = type.element;
-
- // The type `void` does not have an element.
- if (type is VoidType) {
- write(type.displayName);
- return true;
- }
-
- // Typedef(s) are represented as GenericFunctionTypeElement(s).
- if (element is GenericFunctionTypeElement &&
- element.typeParameters.isEmpty &&
- element.enclosingElement is GenericTypeAliasElement) {
- element = element.enclosingElement;
- }
-
- // Just a Function, not FunctionTypeAliasElement.
- if (type is FunctionType && element is! FunctionTypeAliasElement) {
- if (_writeType(type.returnType, methodBeingCopied: methodBeingCopied)) {
- write(' ');
- }
- write('Function');
- writeTypeParameters(type.typeFormals,
- methodBeingCopied: methodBeingCopied);
- writeParameters(type.parameters, methodBeingCopied: methodBeingCopied);
- return true;
- }
-
- // Ensure that the element is imported.
- _writeLibraryReference(element);
-
- // Write the simple name.
- String name = element.displayName;
- write(name);
-
- // Write type arguments.
- if (type is ParameterizedType) {
- List<DartType> arguments = type.typeArguments;
- // Check if has arguments.
- bool hasArguments = false;
- bool allArgumentsVisible = true;
- for (DartType argument in arguments) {
- hasArguments = hasArguments || !argument.isDynamic;
- allArgumentsVisible = allArgumentsVisible &&
- _getVisibleType(argument, methodBeingCopied: methodBeingCopied) !=
- null;
- }
- // Write type arguments only if they are useful.
- if (hasArguments && allArgumentsVisible) {
- write('<');
- for (int i = 0; i < arguments.length; i++) {
- DartType argument = arguments[i];
- if (i != 0) {
- write(', ');
- }
- _writeType(argument, methodBeingCopied: methodBeingCopied);
- }
- write('>');
- }
- }
-
- return true;
- }
-}
-
-/**
- * A [FileEditBuilder] used to build edits for Dart files.
- */
-class DartFileEditBuilderImpl extends FileEditBuilderImpl
- implements DartFileEditBuilder {
- /**
- * The resolved unit for the file.
- */
- final ResolvedUnitResult resolvedUnit;
-
- /**
- * The change builder for the library
- * or `null` if the receiver is the builder for the library.
- */
- final DartFileEditBuilderImpl libraryChangeBuilder;
-
- /**
- * The optional generator of prefixes for new imports.
- */
- ImportPrefixGenerator importPrefixGenerator;
-
- /**
- * A mapping from libraries that need to be imported in order to make visible
- * the names used in generated code, to information about these imports.
- */
- Map<Uri, _LibraryToImport> librariesToImport = {};
-
- /**
- * A mapping from libraries that need to be imported relatively in order to
- * make visible the names used in generated code, to information about these
- * imports.
- */
- Map<String, _LibraryToImport> librariesToRelativelyImport = {};
-
- /**
- * Initialize a newly created builder to build a source file edit within the
- * change being built by the given [changeBuilder]. The file being edited has
- * the given [resolvedUnit] and [timeStamp].
- */
- DartFileEditBuilderImpl(DartChangeBuilderImpl changeBuilder,
- this.resolvedUnit, int timeStamp, this.libraryChangeBuilder)
- : super(changeBuilder, resolvedUnit.path, timeStamp);
-
- @override
- bool get hasEdits =>
- super.hasEdits ||
- librariesToImport.isNotEmpty ||
- librariesToRelativelyImport.isNotEmpty;
-
- @override
- void addInsertion(int offset, void buildEdit(DartEditBuilder builder)) =>
- super.addInsertion(
- offset, (builder) => buildEdit(builder as DartEditBuilder));
-
- @override
- void addReplacement(
- SourceRange range, void buildEdit(DartEditBuilder builder)) =>
- super.addReplacement(
- range, (builder) => buildEdit(builder as DartEditBuilder));
-
- @override
- void convertFunctionFromSyncToAsync(
- FunctionBody body, TypeProvider typeProvider) {
- if (body == null && body.keyword != null) {
- throw new ArgumentError(
- 'The function must have a synchronous, non-generator body.');
- }
- if (body is! EmptyFunctionBody) {
- addInsertion(body.offset, (EditBuilder builder) {
- if (_isFusedWithPreviousToken(body.beginToken)) {
- builder.write(' ');
- }
- builder.write('async ');
- });
- }
- _replaceReturnTypeWithFuture(body, typeProvider);
- }
-
- @override
- DartEditBuilderImpl createEditBuilder(int offset, int length) {
- return new DartEditBuilderImpl(this, offset, length);
- }
-
- @override
- void finalize() {
- if (librariesToImport.isNotEmpty) {
- _addLibraryImports(librariesToImport.values);
- }
- if (librariesToRelativelyImport.isNotEmpty) {
- _addLibraryImports(librariesToRelativelyImport.values);
- }
- }
-
- @override
- void format(SourceRange range) {
- var newContent = resolvedUnit.content;
- var newRangeOffset = range.offset;
- var newRangeLength = range.length;
- for (var edit in fileEdit.edits) {
- newContent = edit.apply(newContent);
-
- var lengthDelta = edit.replacement.length - edit.length;
- if (edit.offset < newRangeOffset) {
- newRangeOffset += lengthDelta;
- } else if (edit.offset < newRangeOffset + newRangeLength) {
- newRangeLength += lengthDelta;
- }
- }
-
- var formattedResult = DartFormatter().formatSource(
- SourceCode(
- newContent,
- isCompilationUnit: true,
- selectionStart: newRangeOffset,
- selectionLength: newRangeLength,
- ),
- );
-
- replaceEdits(
- range,
- SourceEdit(
- range.offset,
- range.length,
- formattedResult.selectedText,
- ),
- );
- }
-
- @override
- String importLibrary(Uri uri) {
- return _importLibrary(uri).uriText;
- }
-
- @override
- ImportLibraryElementResult importLibraryElement(Uri uri) {
- if (resolvedUnit.libraryElement.source.uri == uri) {
- return ImportLibraryElementResultImpl(null);
- }
-
- for (var import in resolvedUnit.libraryElement.imports) {
- if (import.importedLibrary.source.uri == uri) {
- return ImportLibraryElementResultImpl(import.prefix?.name);
- }
- }
-
- importLibrary(uri);
- return ImportLibraryElementResultImpl(null);
- }
-
- String importLibraryWithRelativeUri(String uriText, [String prefix = null]) {
- return _importLibraryWithRelativeUri(uriText, prefix).uriText;
- }
-
- @override
- void replaceTypeWithFuture(
- TypeAnnotation typeAnnotation, TypeProvider typeProvider) {
- //
- // Check whether the type needs to be replaced.
- //
- DartType type = typeAnnotation?.type;
- if (type == null || type.isDynamic || type.isDartAsyncFuture) {
- return;
- }
-
- addReplacement(range.node(typeAnnotation), (EditBuilder builder) {
- var futureType = typeProvider.futureType2(type);
- if (!(builder as DartEditBuilder).writeType(futureType)) {
- builder.write('void');
- }
- });
- }
-
- /**
- * Adds edits ensure that all the [imports] are imported into the library.
- */
- void _addLibraryImports(Iterable<_LibraryToImport> imports) {
- // Prepare information about existing imports.
- LibraryDirective libraryDirective;
- List<ImportDirective> importDirectives = <ImportDirective>[];
- PartDirective partDirective;
- for (Directive directive in resolvedUnit.unit.directives) {
- if (directive is LibraryDirective) {
- libraryDirective = directive;
- } else if (directive is ImportDirective) {
- importDirectives.add(directive);
- } else if (directive is PartDirective) {
- partDirective = directive;
- }
- }
-
- // Sort imports by URIs.
- List<_LibraryToImport> importList = imports.toList();
- importList.sort((a, b) => a.uriText.compareTo(b.uriText));
-
- void writeImport(EditBuilder builder, _LibraryToImport import) {
- builder.write("import '");
- builder.write(import.uriText);
- builder.write("'");
- if (import.prefix != null) {
- builder.write(' as ');
- builder.write(import.prefix);
- }
- builder.write(';');
- }
-
- // Insert imports: between existing imports.
- if (importDirectives.isNotEmpty) {
- for (var import in importList) {
- bool isDart = import.uriText.startsWith('dart:');
- bool isPackage = import.uriText.startsWith('package:');
- bool inserted = false;
-
- void insert(
- {ImportDirective prev,
- ImportDirective next,
- bool trailingNewLine: false}) {
- LineInfo lineInfo = resolvedUnit.lineInfo;
- if (prev != null) {
- int offset = prev.end;
- int line = lineInfo.getLocation(offset).lineNumber;
- Token comment = prev.endToken.next.precedingComments;
- while (comment != null) {
- if (lineInfo.getLocation(comment.offset).lineNumber == line) {
- offset = comment.end;
- }
- comment = comment.next;
- }
- addInsertion(offset, (EditBuilder builder) {
- builder.writeln();
- writeImport(builder, import);
- });
- } else {
- int offset = next.offset;
- addInsertion(offset, (EditBuilder builder) {
- writeImport(builder, import);
- builder.writeln();
- if (trailingNewLine) {
- builder.writeln();
- }
- });
- }
- inserted = true;
- }
-
- ImportDirective lastExisting;
- ImportDirective lastExistingDart;
- ImportDirective lastExistingPackage;
- bool isLastExistingDart = false;
- bool isLastExistingPackage = false;
- for (ImportDirective existingImport in importDirectives) {
- String existingUri = existingImport.uriContent;
-
- bool isExistingDart = existingUri.startsWith('dart:');
- bool isExistingPackage = existingUri.startsWith('package:');
- bool isExistingRelative = !existingUri.contains(':');
-
- bool isNewBeforeExisting = import.uriText.compareTo(existingUri) < 0;
-
- if (isDart) {
- if (!isExistingDart || isNewBeforeExisting) {
- insert(
- prev: lastExistingDart,
- next: existingImport,
- trailingNewLine: !isExistingDart);
- break;
- }
- } else if (isPackage) {
- if (isExistingRelative || isNewBeforeExisting) {
- insert(
- prev: lastExistingPackage,
- next: existingImport,
- trailingNewLine: isExistingRelative);
- break;
- }
- } else {
- if (!isExistingDart && !isExistingPackage && isNewBeforeExisting) {
- insert(next: existingImport);
- break;
- }
- }
-
- lastExisting = existingImport;
- if (isExistingDart) {
- lastExistingDart = existingImport;
- } else if (isExistingPackage) {
- lastExistingPackage = existingImport;
- }
- isLastExistingDart = isExistingDart;
- isLastExistingPackage = isExistingPackage;
- }
- if (!inserted) {
- addInsertion(lastExisting.end, (EditBuilder builder) {
- if (isPackage) {
- if (isLastExistingDart) {
- builder.writeln();
- }
- } else {
- if (isLastExistingDart || isLastExistingPackage) {
- builder.writeln();
- }
- }
- builder.writeln();
- writeImport(builder, import);
- });
- }
- }
- return;
- }
-
- // Insert imports: after the library directive.
- if (libraryDirective != null) {
- addInsertion(libraryDirective.end, (EditBuilder builder) {
- builder.writeln();
- builder.writeln();
- for (int i = 0; i < importList.length; i++) {
- var import = importList[i];
- writeImport(builder, import);
- if (i != importList.length - 1) {
- builder.writeln();
- }
- }
- });
- return;
- }
-
- // Insert imports: before a part directive.
- if (partDirective != null) {
- addInsertion(partDirective.offset, (EditBuilder builder) {
- for (int i = 0; i < importList.length; i++) {
- var import = importList[i];
- writeImport(builder, import);
- builder.writeln();
- }
- builder.writeln();
- });
- return;
- }
-
- // If still at the beginning of the file, add before the first declaration.
- int offset;
- bool insertEmptyLineAfter = false;
- if (resolvedUnit.unit.declarations.isNotEmpty) {
- offset = resolvedUnit.unit.declarations.first.offset;
- insertEmptyLineAfter = true;
- } else {
- offset = resolvedUnit.unit.end;
- }
- addInsertion(offset, (EditBuilder builder) {
- for (int i = 0; i < importList.length; i++) {
- var import = importList[i];
- writeImport(builder, import);
- builder.writeln();
- if (i == importList.length - 1 && insertEmptyLineAfter) {
- builder.writeln();
- }
- }
- });
- }
-
- /**
- * Return the import element used to import the given [element] into the
- * target library, or `null` if the element was not imported, such as when
- * the element is declared in the same library.
- */
- ImportElement _getImportElement(Element element) {
- for (ImportElement import in resolvedUnit.libraryElement.imports) {
- Map<String, Element> definedNames = import.namespace.definedNames;
- if (definedNames.containsValue(element)) {
- return import;
- }
- }
- return null;
- }
-
- /**
- * Computes the best URI to import [uri] into the target library.
- */
- String _getLibraryUriText(Uri uri) {
- if (uri.scheme == 'file') {
- var pathContext = resolvedUnit.session.resourceProvider.pathContext;
- String whatPath = pathContext.fromUri(uri);
- String libraryPath = resolvedUnit.libraryElement.source.fullName;
- String libraryFolder = pathContext.dirname(libraryPath);
- String relativeFile = pathContext.relative(whatPath, from: libraryFolder);
- return pathContext.split(relativeFile).join('/');
- }
- return uri.toString();
- }
-
- /**
- * Arrange to have an import added for the library with the given [uri].
- */
- _LibraryToImport _importLibrary(Uri uri) {
- var import = (libraryChangeBuilder ?? this).librariesToImport[uri];
- if (import == null) {
- String uriText = _getLibraryUriText(uri);
- String prefix =
- importPrefixGenerator != null ? importPrefixGenerator(uri) : null;
- import = new _LibraryToImport(uriText, prefix);
- (libraryChangeBuilder ?? this).librariesToImport[uri] = import;
- }
- return import;
- }
-
- /**
- * Arrange to have an import added for the library with the given relative
- * [uriText].
- */
- _LibraryToImport _importLibraryWithRelativeUri(String uriText,
- [String prefix = null]) {
- var import = librariesToRelativelyImport[uriText];
- if (import == null) {
- import = new _LibraryToImport(uriText, prefix);
- librariesToRelativelyImport[uriText] = import;
- }
- return import;
- }
-
- /**
- * Return `true` if the [element] is defined in the target library.
- */
- bool _isDefinedLocally(Element element) {
- return element.library == resolvedUnit.libraryElement;
- }
-
- /**
- * Create an edit to replace the return type of the innermost function
- * containing the given [node] with the type `Future`. The [typeProvider] is
- * used to check the current return type, because if it is already `Future` no
- * edit will be added.
- */
- void _replaceReturnTypeWithFuture(AstNode node, TypeProvider typeProvider) {
- while (node != null) {
- node = node.parent;
- if (node is FunctionDeclaration) {
- replaceTypeWithFuture(node.returnType, typeProvider);
- return;
- } else if (node is FunctionExpression &&
- node.parent is! FunctionDeclaration) {
- // Closures don't have a return type.
- return;
- } else if (node is MethodDeclaration) {
- replaceTypeWithFuture(node.returnType, typeProvider);
- return;
- }
- }
- }
-
- static bool _isFusedWithPreviousToken(Token token) {
- return token.previous.end == token.offset;
- }
-}
-
-/**
- * A [LinkedEditBuilder] used to build linked edits for Dart files.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class DartLinkedEditBuilderImpl extends LinkedEditBuilderImpl
- implements DartLinkedEditBuilder {
- /**
- * Initialize a newly created linked edit builder.
- */
- DartLinkedEditBuilderImpl(EditBuilderImpl editBuilder) : super(editBuilder);
-
- @override
- void addSuperTypesAsSuggestions(DartType type) {
- _addSuperTypesAsSuggestions(type, new Set<DartType>());
- }
-
- /**
- * Safely implement [addSuperTypesAsSuggestions] by using the set of
- * [alreadyAdded] types to prevent infinite loops.
- */
- void _addSuperTypesAsSuggestions(DartType type, Set<DartType> alreadyAdded) {
- if (type is InterfaceType && alreadyAdded.add(type)) {
- addSuggestion(LinkedEditSuggestionKind.TYPE, type.displayName);
- _addSuperTypesAsSuggestions(type.superclass, alreadyAdded);
- for (InterfaceType interfaceType in type.interfaces) {
- _addSuperTypesAsSuggestions(interfaceType, alreadyAdded);
- }
- }
- }
-}
-
-/// Information about a library to import.
-class ImportLibraryElementResultImpl implements ImportLibraryElementResult {
- @override
- final String prefix;
-
- ImportLibraryElementResultImpl(this.prefix);
-}
-
-class _EnclosingElementFinder {
- ClassElement enclosingClass;
- ExecutableElement enclosingExecutable;
-
- _EnclosingElementFinder();
-
- void find(AstNode target, int offset) {
- AstNode node = new NodeLocator2(offset).searchWithin(target);
- while (node != null) {
- if (node is ClassDeclaration) {
- enclosingClass = node.declaredElement;
- } else if (node is ConstructorDeclaration) {
- enclosingExecutable = node.declaredElement;
- } else if (node is MethodDeclaration) {
- enclosingExecutable = node.declaredElement;
- } else if (node is FunctionDeclaration) {
- enclosingExecutable = node.declaredElement;
- }
- node = node.parent;
- }
- }
-}
-
-/**
- * Information about a new library to import.
- */
-class _LibraryToImport {
- final String uriText;
- final String prefix;
-
- _LibraryToImport(this.uriText, this.prefix);
-
- @override
- int get hashCode => uriText.hashCode;
-
- @override
- bool operator ==(other) {
- return other is _LibraryToImport &&
- other.uriText == uriText &&
- other.prefix == prefix;
- }
-}
-
-/// Workspace that wraps a single [AnalysisSession].
-class _SingleSessionWorkspace extends ChangeWorkspace {
- final AnalysisSession session;
-
- _SingleSessionWorkspace(this.session);
-
- @override
- bool containsFile(String path) {
- var analysisContext = session.analysisContext;
- return analysisContext.contextRoot.isAnalyzed(path);
- }
-
- @override
- AnalysisSession getSession(String path) {
- if (containsFile(path)) {
- return session;
- }
- throw StateError('Not in a context root: $path');
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/completion/completion_core.dart b/analyzer_plugin/lib/src/utilities/completion/completion_core.dart
deleted file mode 100644
index 4b7909e..0000000
--- a/analyzer_plugin/lib/src/utilities/completion/completion_core.dart
+++ /dev/null
@@ -1,112 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
-
-/**
- * An object that can collect completion suggestions.
- */
-class CompletionCollectorImpl implements CompletionCollector {
- /**
- * The length of the region of text that should be replaced by the selected
- * completion suggestion.
- */
- int _length;
-
- /**
- * The offset of the region of text that should be replaced by the selected
- * completion suggestion.
- */
- int _offset;
-
- /**
- * A list of the completion suggestions that have been collected.
- */
- List<CompletionSuggestion> suggestions = <CompletionSuggestion>[];
-
- /**
- * Initialize a newly created completion collector.
- */
- CompletionCollectorImpl();
-
- /**
- * Return the length of the region of text that should be replaced by the
- * selected completion suggestion, or `null` if the length has not been set.
- */
- int get length => _length;
-
- @override
- set length(int length) {
- if (_length != null) {
- throw new StateError('The length can only be set once');
- }
- _length = length;
- }
-
- /**
- * Return the offset of the region of text that should be replaced by the
- * selected completion suggestion, or `null` if the offset has not been set.
- */
- int get offset => _offset;
-
- @override
- set offset(int length) {
- if (_offset != null) {
- throw new StateError('The offset can only be set once');
- }
- _offset = length;
- }
-
- @override
- bool get offsetIsSet => offset != null;
-
- @override
- int get suggestionsLength => suggestions.length;
-
- @override
- void addSuggestion(CompletionSuggestion suggestion) {
- suggestions.add(suggestion);
- }
-}
-
-/**
-* A concrete implementation of [DartCompletionRequest].
-*/
-class DartCompletionRequestImpl implements DartCompletionRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final int offset;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * A flag indicating whether completion has been aborted.
- */
- bool _aborted = false;
-
- /**
- * Initialize a newly created request.
- */
- DartCompletionRequestImpl(this.resourceProvider, this.offset, this.result);
-
- /**
- * Abort the current completion request.
- */
- void abort() {
- _aborted = true;
- }
-
- @override
- void checkAborted() {
- if (_aborted) {
- throw new AbortCompletion();
- }
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/completion/completion_target.dart b/analyzer_plugin/lib/src/utilities/completion/completion_target.dart
deleted file mode 100644
index 4050a75..0000000
--- a/analyzer_plugin/lib/src/utilities/completion/completion_target.dart
+++ /dev/null
@@ -1,617 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/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/token.dart';
-import 'package:analyzer/src/generated/source.dart';
-
-/**
- * A CompletionTarget represents an edge in the parse tree which connects an
- * AST node (the [containingNode] of the completion) to one of its children
- * (the [entity], which represents the place in the parse tree where the newly
- * completed text will be inserted).
- *
- * To illustrate, consider the following snippet of code, and its associated
- * parse tree. (T's represent tokens, N's represent AST nodes. Some trivial
- * AST nodes are not shown).
- *
- * ___N (function declaration)
- * / \
- * / __N_______ (function body)
- * / / |a \
- * / / N______ \ (statement)
- * / / / \ \
- * / / N____ \ \ (assignment expression)
- * | / /| \ \ \
- * . | / | _N___ \ | ("as" expression)
- * . | | | / | \c | |
- * . | N | N |b N | | (simple identifiers)
- * | | | | | | | |
- * T T T T T T T T
- * m() { foo = bar as Baz; }
- *
- * The Completion target is usually placed as high in the tree as possible so
- * that we can produce the most meaningful completions with minimal effort.
- * For instance, if the cursor is inside the identifier "foo", the completion
- * target will be the edge marked "a", so that we will produce all completions
- * that could possibly start a statement, even those which would conflict with
- * the current parse (such as the keyword "for", which begins a "for"
- * statement). As a consequence of this, the [entity] will usually not be the
- * first child of the [containingNode] node.
- *
- * Note that the [containingNode] is always an AST node, but the [entity] may
- * not be. For instance, if the cursor is inside the keyword "as", the
- * completion target will be the edge marked "b", so the [entity] is the token
- * "as".
- *
- * If the cursor is between tokens, the completion target is usually associated
- * with the token that follows the cursor (since that's the token that will be
- * displaced when the new text is inserted). For example, if the cursor is
- * after the "{" character, then the completion target will be the edge marked
- * "a", just as it is if the cursor is inside the identifier "foo". However
- * there is one exception: if the cursor is at the rightmost edge of a keyword
- * or identifier, then the completion target is associated with that token,
- * since any further letters typed will change the meaning of the identifier or
- * keyword, rather than creating a new token. So for instance, if the cursor
- * is just after the "s" of "as", the completion target will be the edge marked
- * "b", but if the cursor target is after the first space following "as", then
- * the completion target will be the edge marked "c".
- *
- * If the file is empty, or the cursor is after all the text in the file, then
- * there may be no edge in the parse tree which is appropriate to act as the
- * completion target; in this case, [entity] is set to null and
- * [containingNode] is set to the CompilationUnit.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class CompletionTarget {
- /**
- * The compilation unit in which the completion is occurring.
- */
- final CompilationUnit unit;
-
- /**
- * The offset within the source at which the completion is being requested.
- */
- final int offset;
-
- /**
- * The context in which the completion is occurring. This is the AST node
- * which is a direct parent of [entity].
- */
- final AstNode containingNode;
-
- /**
- * The "dropped" identifier or keyword which the completed text will replace,
- * or `null` if none.
- *
- * For the purposes of code completion, a "dropped" token is an identifier
- * or keyword that is part of the token stream, but that the parser has
- * skipped and not reported in to the parser listeners, meaning that it is
- * not part of the AST.
- */
- Token droppedToken;
-
- /**
- * The entity which the completed text will replace (or which will be
- * displaced once the completed text is inserted). This may be an AstNode or
- * a Token, or it may be null if the cursor is after all tokens in the file.
- *
- * Usually, the entity won't be the first child of the [containingNode] (this
- * is a consequence of placing the completion target as high in the tree as
- * possible). However, there is one exception: when the cursor is inside of
- * a multi-character token which is not a keyword or identifier (e.g. a
- * comment, or a token like "+=", the entity will be always be the token.
- */
- final Object entity;
-
- /**
- * The [entity] is a comment token, which is either not a documentation
- * comment or the position is not in a [CommentReference].
- */
- final bool isCommentText;
-
- /**
- * If the target is an argument in an [ArgumentList], then this is the index
- * of the argument in the list, otherwise this is `null`.
- */
- final int argIndex;
-
- /**
- * If the target is an argument in an [ArgumentList], then this is the
- * invoked [ExecutableElement], otherwise this is `null`.
- */
- ExecutableElement _executableElement;
-
- /**
- * If the target is an argument in an [ArgumentList], then this is the
- * corresponding [ParameterElement] in the invoked [ExecutableElement],
- * otherwise this is `null`.
- */
- ParameterElement _parameterElement;
-
- /**
- * Compute the appropriate [CompletionTarget] for the given [offset] within
- * the [compilationUnit].
- *
- * Optionally, start the search from within [entryPoint] instead of using
- * the [compilationUnit], which is useful for analyzing ASTs that have no
- * [compilationUnit] such as dart expressions within angular templates.
- */
- factory CompletionTarget.forOffset(
- CompilationUnit compilationUnit, int offset,
- {AstNode entryPoint}) {
- // The precise algorithm is as follows. We perform a depth-first search of
- // all edges in the parse tree (both those that point to AST nodes and
- // those that point to tokens), visiting parents before children. The
- // first edge which points to an entity satisfying either _isCandidateToken
- // or _isCandidateNode is the completion target. If no edge is found that
- // satisfies these two predicates, then we set the completion target entity
- // to null and the containingNode to the entryPoint.
- //
- // Note that if a token is not a candidate target, then none of the tokens
- // that precede it are candidate targets either. Therefore any entity
- // whose last token is not a candidate target can be skipped. This lets us
- // prune the search to the point where no recursion is necessary; at each
- // step in the process we know exactly which child node we need to proceed
- // to.
- entryPoint ??= compilationUnit;
- AstNode containingNode = entryPoint;
- outerLoop:
- while (true) {
- if (containingNode is Comment) {
- // Comments are handled specially: we descend into any CommentReference
- // child node that contains the cursor offset.
- Comment comment = containingNode as Comment;
- for (CommentReference commentReference in comment.references) {
- if (commentReference.offset <= offset &&
- offset <= commentReference.end) {
- containingNode = commentReference;
- continue outerLoop;
- }
- }
- }
- for (var entity in containingNode.childEntities) {
- if (entity is Token) {
- if (_isCandidateToken(containingNode, entity, offset)) {
- // Try to replace with a comment token.
- Token commentToken = _getContainingCommentToken(entity, offset);
- if (commentToken != null) {
- return new CompletionTarget._(
- compilationUnit, offset, containingNode, commentToken, true);
- }
- // Target found.
- return new CompletionTarget._(
- compilationUnit, offset, containingNode, entity, false);
- } else {
- // Since entity is a token, we don't need to look inside it; just
- // proceed to the next entity.
- continue;
- }
- } else if (entity is AstNode) {
- // If the last token in the node isn't a candidate target, then
- // neither the node nor any of its descendants can possibly be the
- // completion target, so we can skip the node entirely.
- if (!_isCandidateToken(containingNode, entity.endToken, offset)) {
- continue;
- }
-
- // If the node is a candidate target, then we are done.
- if (_isCandidateNode(entity, offset)) {
- // Check to see if the offset is in a preceding comment
- Token commentToken =
- _getContainingCommentToken(entity.beginToken, offset);
- if (commentToken != null) {
- // If the preceding comment is dartdoc token, then update
- // the containing node to be the dartdoc comment.
- // Otherwise completion is not required.
- Comment docComment =
- _getContainingDocComment(containingNode, commentToken);
- if (docComment != null) {
- return new CompletionTarget._(
- compilationUnit, offset, docComment, commentToken, false);
- } else {
- return new CompletionTarget._(compilationUnit, offset,
- compilationUnit, commentToken, true);
- }
- }
- return new CompletionTarget._(
- compilationUnit, offset, containingNode, entity, false);
- }
-
- // Otherwise, the completion target is somewhere inside the entity,
- // so we need to jump to the start of the outer loop to examine its
- // contents.
- containingNode = entity;
- continue outerLoop;
- } else {
- // Unexpected entity found (all entities in a parse tree should be
- // AST nodes or tokens).
- assert(false);
- }
- }
-
- // No completion target found. It should only be possible to reach here
- // the first time through the outer loop (since we only jump to the start
- // of the outer loop after determining that the completion target is
- // inside an entity). We can check that assumption by verifying that
- // containingNode is still the entryPoint.
- assert(identical(containingNode, entryPoint));
-
- // Since no completion target was found, we set the completion target
- // entity to null and use the entryPoint as the parent.
- return new CompletionTarget._(
- compilationUnit, offset, entryPoint, null, false);
- }
- }
-
- /**
- * Create a [CompletionTarget] holding the given [containingNode] and
- * [entity].
- */
- CompletionTarget._(this.unit, this.offset, AstNode containingNode,
- Object entity, this.isCommentText)
- : this.containingNode = containingNode,
- this.entity = entity,
- this.argIndex = _computeArgIndex(containingNode, entity),
- this.droppedToken =
- _computeDroppedToken(containingNode, entity, offset);
-
- /**
- * If the target is an argument in an argument list, and the invocation is
- * resolved, return the invoked [ExecutableElement].
- */
- ExecutableElement get executableElement {
- if (_executableElement == null) {
- var argumentList = containingNode;
- if (argumentList is NamedExpression) {
- argumentList = argumentList.parent;
- }
- if (argumentList is! ArgumentList) {
- return null;
- }
-
- var invocation = argumentList.parent;
-
- Element executable;
- if (invocation is Annotation) {
- executable = invocation.element;
- } else if (invocation is InstanceCreationExpression) {
- executable = invocation.constructorName.staticElement;
- } else if (invocation is MethodInvocation) {
- executable = invocation.methodName.staticElement;
- }
-
- if (executable is ExecutableElement) {
- _executableElement = executable;
- }
- }
- return _executableElement;
- }
-
- /**
- * Return `true` if the [containingNode] is a cascade
- * and the completion insertion is not between the two dots.
- * For example, `..d^` and `..^d` are considered a cascade
- * from a completion standpoint, but `.^.d` is not.
- */
- bool get isCascade {
- AstNode node = containingNode;
- if (node is PropertyAccess) {
- return node.isCascaded && offset > node.operator.offset + 1;
- }
- if (node is MethodInvocation) {
- return node.isCascaded && offset > node.operator.offset + 1;
- }
- return false;
- }
-
- /**
- * If the target is an argument in an argument list, and the invocation is
- * resolved, return the corresponding [ParameterElement].
- */
- ParameterElement get parameterElement {
- if (_parameterElement == null) {
- var executable = executableElement;
- if (executable != null) {
- _parameterElement = _getParameterElement(
- executable.parameters, containingNode, argIndex);
- }
- }
- return _parameterElement;
- }
-
- /**
- * Return a source range that represents the region of text that should be
- * replaced when a suggestion based on this target is selected, given that the
- * completion was requested at the given [requestOffset].
- */
- SourceRange computeReplacementRange(int requestOffset) {
- bool isKeywordOrIdentifier(Token token) =>
- token.type.isKeyword || token.type == TokenType.IDENTIFIER;
-
- Token token = droppedToken ??
- (entity is AstNode ? (entity as AstNode).beginToken : entity as Token);
- if (token != null && requestOffset < token.offset) {
- token = containingNode.findPrevious(token);
- }
- if (token != null) {
- if (requestOffset == token.offset && !isKeywordOrIdentifier(token)) {
- // If the insertion point is at the beginning of the current token
- // and the current token is not an identifier
- // then check the previous token to see if it should be replaced
- token = containingNode.findPrevious(token);
- }
- if (token != null && isKeywordOrIdentifier(token)) {
- if (token.offset <= requestOffset && requestOffset <= token.end) {
- // Replacement range for typical identifier completion
- return new SourceRange(token.offset, token.length);
- }
- }
- if (token is StringToken) {
- SimpleStringLiteral uri =
- astFactory.simpleStringLiteral(token, token.lexeme);
- Keyword keyword = containingNode.findPrevious(token)?.keyword;
- if (keyword == Keyword.IMPORT ||
- keyword == Keyword.EXPORT ||
- keyword == Keyword.PART) {
- int start = uri.contentsOffset;
- int end = uri.contentsEnd;
- if (start <= requestOffset && requestOffset <= end) {
- // Replacement range for import URI
- return new SourceRange(start, end - start);
- }
- }
- }
- }
- return new SourceRange(requestOffset, 0);
- }
-
- /**
- * Return `true` if the target is a double or int literal.
- */
- bool isDoubleOrIntLiteral() {
- var entity = this.entity;
- if (entity is Token) {
- TokenType previousTokenType = containingNode.findPrevious(entity)?.type;
- return previousTokenType == TokenType.DOUBLE ||
- previousTokenType == TokenType.INT;
- }
- return false;
- }
-
- /**
- * Return `true` if the target is a functional argument in an argument list.
- * The target [AstNode] hierarchy *must* be resolved for this to work.
- */
- bool isFunctionalArgument() {
- return parameterElement?.type is FunctionType;
- }
-
- /**
- * Given that the [node] contains the [offset], return the [FormalParameter]
- * that encloses the [offset], or `null`.
- */
- static FormalParameter findFormalParameter(
- FormalParameterList node,
- int offset,
- ) {
- assert(node.offset < offset && offset < node.end);
- var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
- if (i == 0 && offset < parameter.offset) {
- return parameter;
- }
- if (parameter.offset <= offset) {
- if (i < parameters.length - 1) {
- if (offset < parameters[i + 1].offset) {
- return parameter;
- }
- } else if (offset <= node.rightParenthesis.offset) {
- return parameter;
- }
- }
- }
- return null;
- }
-
- static int _computeArgIndex(AstNode containingNode, Object entity) {
- var argList = containingNode;
- if (argList is NamedExpression) {
- entity = argList;
- argList = argList.parent;
- }
- if (argList is ArgumentList) {
- NodeList<Expression> args = argList.arguments;
- for (int index = 0; index < args.length; ++index) {
- if (entity == args[index]) {
- return index;
- }
- }
- if (args.isEmpty) {
- return 0;
- }
- if (entity == argList.rightParenthesis) {
- // Parser ignores trailing commas
- Token previous = containingNode.findPrevious(argList.rightParenthesis);
- if (previous?.lexeme == ',') {
- return args.length;
- }
- return args.length - 1;
- }
- }
- return null;
- }
-
- static Token _computeDroppedToken(
- AstNode containingNode, Object entity, int offset) {
- // Find the last token of the member before the entity.
- var previousMember;
- for (var member in containingNode.childEntities) {
- if (entity == member) {
- break;
- }
- if (member is! Comment && member is! CommentToken) {
- previousMember = member;
- }
- }
- Token token;
- if (previousMember is AstNode) {
- token = previousMember.endToken;
- } else if (previousMember is Token) {
- token = previousMember;
- }
- if (token == null) {
- return null;
- }
-
- // Find the first token of the entity (which may be the entity itself).
- Token endSearch;
- if (entity is AstNode) {
- endSearch = entity.beginToken;
- } else if (entity is Token) {
- endSearch = entity;
- }
- if (endSearch == null) {
- return null;
- }
-
- // Find a dropped token that overlaps the offset.
- token = token.next;
- while (token != endSearch && !token.isEof) {
- if (token.isKeywordOrIdentifier &&
- token.offset <= offset &&
- offset <= token.end) {
- return token;
- }
- token = token.next;
- }
- return null;
- }
-
- /**
- * Determine if the offset is contained in a preceding comment token
- * and return that token, otherwise return `null`.
- */
- static Token _getContainingCommentToken(Token token, int offset) {
- if (token == null) {
- return null;
- }
- if (offset >= token.offset) {
- return null;
- }
- token = token.precedingComments;
- while (token != null) {
- if (offset <= token.offset) {
- return null;
- }
- if (offset <= token.end) {
- if (token.type == TokenType.SINGLE_LINE_COMMENT || offset < token.end) {
- return token;
- }
- }
- token = token.next;
- }
- return null;
- }
-
- /**
- * Determine if the given token is part of the given node's dart doc.
- */
- static Comment _getContainingDocComment(AstNode node, Token token) {
- if (node is AnnotatedNode) {
- Comment docComment = node.documentationComment;
- if (docComment != null && docComment.tokens.contains(token)) {
- return docComment;
- }
- }
- return null;
- }
-
- /**
- * Return the [ParameterElement] that corresponds to the given [argumentNode]
- * at the given [argumentIndex].
- */
- static ParameterElement _getParameterElement(
- List<ParameterElement> parameters,
- AstNode argumentNode,
- int argumentIndex,
- ) {
- if (argumentNode is NamedExpression) {
- var name = argumentNode.name?.label?.name;
- for (var parameter in parameters) {
- if (parameter.name == name) {
- return parameter;
- }
- }
- return null;
- }
-
- if (argumentIndex < parameters.length) {
- return parameters[argumentIndex];
- }
-
- return null;
- }
-
- /**
- * Determine whether [node] could possibly be the [entity] for a
- * [CompletionTarget] associated with the given [offset].
- */
- static bool _isCandidateNode(AstNode node, int offset) {
- // If the node's first token is a keyword or identifier, then the node is a
- // candidate entity if its first token is.
- Token beginToken = node.beginToken;
- if (beginToken.type.isKeyword || beginToken.type == TokenType.IDENTIFIER) {
- return _isCandidateToken(node, beginToken, offset);
- }
-
- // Otherwise, the node is a candidate entity only if the offset is before
- // the beginning of the node. This ensures that completions within a token
- // (e.g. inside a literal string or inside a comment) are evaluated within
- // the context of the token itself.
- return offset <= node.offset;
- }
-
- /**
- * Determine whether [token] could possibly be the [entity] for a
- * [CompletionTarget] associated with the given [offset].
- */
- static bool _isCandidateToken(AstNode node, Token token, int offset) {
- if (token == null) {
- return false;
- }
- // A token is considered a candidate entity if the cursor offset is (a)
- // before the start of the token, (b) within the token, (c) at the end of
- // the token and the token is a keyword or identifier, or (d) at the
- // location of the token and the token is zero length.
- if (offset < token.end) {
- return true;
- } else if (offset == token.end) {
- return token.type.isKeyword ||
- token.type == TokenType.IDENTIFIER ||
- token.length == 0;
- } else if (!token.isSynthetic) {
- return false;
- }
- // If the current token is synthetic, then check the previous token
- // because it may have been dropped from the parse tree
- Token previous = node.findPrevious(token);
- if (previous == null) {
- // support dangling expression completion, where previous may be null.
- return false;
- } else if (offset < previous.end) {
- return true;
- } else if (offset == previous.end) {
- return token.type.isKeyword || previous.type == TokenType.IDENTIFIER;
- } else {
- return false;
- }
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart b/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart
deleted file mode 100644
index 8b93677..0000000
--- a/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide Element, ElementKind;
-import 'package:analyzer_plugin/protocol/protocol_common.dart' as protocol;
-import 'package:analyzer_plugin/src/utilities/completion/suggestion_builder.dart';
-import 'package:analyzer_plugin/utilities/completion/relevance.dart';
-
-/**
- * Common mixin for sharing behavior.
- */
-mixin ElementSuggestionBuilder {
- // Copied from analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
- /**
- * A collection of completion suggestions.
- */
- final List<CompletionSuggestion> suggestions = <CompletionSuggestion>[];
-
- /**
- * A set of existing completions used to prevent duplicate suggestions.
- */
- final Set<String> _completions = new Set<String>();
-
- /**
- * A map of element names to suggestions for synthetic getters and setters.
- */
- final Map<String, CompletionSuggestion> _syntheticMap =
- <String, CompletionSuggestion>{};
-
- /**
- * Return the library in which the completion is requested.
- */
- LibraryElement get containingLibrary;
-
- /**
- * Return the kind of suggestions that should be built.
- */
- CompletionSuggestionKind get kind;
-
- /**
- * Return the resource provider used to access the file system.
- */
- ResourceProvider get resourceProvider;
-
- /**
- * Add a suggestion based upon the given element.
- */
- void addSuggestion(Element element,
- {String prefix, int relevance: DART_RELEVANCE_DEFAULT}) {
- if (element.isPrivate) {
- if (element.library != containingLibrary) {
- return;
- }
- }
- String completion = element.displayName;
- if (prefix != null && prefix.length > 0) {
- if (completion == null || completion.length <= 0) {
- completion = prefix;
- } else {
- completion = '$prefix.$completion';
- }
- }
- if (completion == null || completion.length <= 0) {
- return;
- }
- SuggestionBuilderImpl builder = new SuggestionBuilderImpl(resourceProvider);
- CompletionSuggestion suggestion = builder.forElement(element,
- completion: completion, kind: kind, relevance: relevance);
- if (suggestion != null) {
- if (element.isSynthetic && element is PropertyAccessorElement) {
- String cacheKey;
- if (element.isGetter) {
- cacheKey = element.name;
- }
- if (element.isSetter) {
- cacheKey = element.name;
- cacheKey = cacheKey.substring(0, cacheKey.length - 1);
- }
- if (cacheKey != null) {
- CompletionSuggestion existingSuggestion = _syntheticMap[cacheKey];
-
- // Pair getter/setter by updating the existing suggestion
- if (existingSuggestion != null) {
- CompletionSuggestion getter =
- element.isGetter ? suggestion : existingSuggestion;
- protocol.ElementKind elemKind =
- element.enclosingElement is ClassElement
- ? protocol.ElementKind.FIELD
- : protocol.ElementKind.TOP_LEVEL_VARIABLE;
- existingSuggestion.element = new protocol.Element(
- elemKind,
- existingSuggestion.element.name,
- existingSuggestion.element.flags,
- location: getter.element.location,
- typeParameters: getter.element.typeParameters,
- parameters: null,
- returnType: getter.returnType);
- return;
- }
-
- // Cache lone getter/setter so that it can be paired
- _syntheticMap[cacheKey] = suggestion;
- }
- }
- if (_completions.add(suggestion.completion)) {
- suggestions.add(suggestion);
- }
- }
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/completion/optype.dart b/analyzer_plugin/lib/src/utilities/completion/optype.dart
deleted file mode 100644
index 2b22b73..0000000
--- a/analyzer_plugin/lib/src/utilities/completion/optype.dart
+++ /dev/null
@@ -1,1229 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/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/dart/element/type_system.dart';
-import 'package:analyzer/src/dart/ast/token.dart';
-import 'package:analyzer/src/dart/element/element.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Element;
-import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart';
-import 'package:analyzer_plugin/utilities/completion/relevance.dart';
-
-typedef int SuggestionsFilter(DartType dartType, int relevance);
-
-/**
- * An [AstVisitor] for determining whether top level suggestions or invocation
- * suggestions should be made based upon the type of node in which the
- * suggestions were requested.
- */
-class OpType {
- /**
- * The [TypeSystem] used during resolution of the current unit.
- */
- TypeSystem _typeSystem;
-
- /**
- * Indicates whether constructor suggestions should be included.
- */
- bool includeConstructorSuggestions = false;
-
- /**
- * Indicates whether type names should be suggested.
- */
- bool includeTypeNameSuggestions = false;
-
- /**
- * If [includeTypeNameSuggestions] is set to true, then this function may
- * be set to a non-default function to filter out potential suggestions (null)
- * based on their static [DartType], or change the relative relevance by
- * returning a higher or lower relevance.
- */
- SuggestionsFilter typeNameSuggestionsFilter =
- (DartType _, int relevance) => relevance;
-
- /**
- * Indicates whether setters along with methods and functions that
- * have a [void] return type should be suggested.
- */
- bool includeVoidReturnSuggestions = false;
-
- /**
- * Indicates whether fields and getters along with methods and functions that
- * have a non-[void] return type should be suggested.
- */
- bool includeReturnValueSuggestions = false;
-
- /**
- * If [includeReturnValueSuggestions] is set to true, then this function may
- * be set to a non-default function to filter out potential suggestions (null)
- * based on their static [DartType], or change the relative relevance by
- * returning a higher or lower relevance.
- */
- SuggestionsFilter returnValueSuggestionsFilter =
- (DartType _, int relevance) => relevance;
-
- /**
- * Indicates whether named arguments should be suggested.
- */
- bool includeNamedArgumentSuggestions = false;
-
- /**
- * Indicates whether statement labels should be suggested.
- */
- bool includeStatementLabelSuggestions = false;
-
- /**
- * Indicates whether case labels should be suggested.
- */
- bool includeCaseLabelSuggestions = false;
-
- /**
- * Indicates whether variable names should be suggested.
- */
- bool includeVarNameSuggestions = false;
-
- /**
- * Indicates whether the completion location is in a field declaration.
- */
- bool inFieldDeclaration = false;
-
- /**
- * Indicates whether the completion location is in a top-level variable
- * declaration.
- */
- bool inTopLevelVariableDeclaration = false;
-
- /**
- * Indicates whether the completion location is in the body of a static method.
- */
- bool inStaticMethodBody = false;
-
- /**
- * Indicates whether the completion location is in the body of a method.
- */
- bool inMethodBody = false;
-
- /**
- * Indicates whether the completion location is in the body of a function.
- */
- bool inFunctionBody = false;
-
- /**
- * Indicates whether the completion location is in the body of a constructor.
- */
- bool inConstructorBody = false;
-
- /**
- * Indicates whether the completion target is prefixed.
- */
- bool isPrefixed = false;
-
- /**
- * The suggested completion kind.
- */
- CompletionSuggestionKind suggestKind = CompletionSuggestionKind.INVOCATION;
-
- /**
- * The type that is required by the context in which the completion was
- * activated, or `null` if there is no such type, or it cannot be determined.
- */
- DartType _requiredType = null;
-
- /**
- * Determine the suggestions that should be made based upon the given
- * [CompletionTarget] and [offset].
- */
- factory OpType.forCompletion(CompletionTarget target, int offset) {
- OpType optype = new OpType._();
-
- // Don't suggest anything right after double or integer literals.
- if (target.isDoubleOrIntLiteral()) {
- return optype;
- }
-
- optype._typeSystem = target.unit?.declaredElement?.context?.typeSystem;
-
- var targetNode = target.containingNode;
- targetNode.accept(new _OpTypeAstVisitor(optype, target.entity, offset));
-
- var functionBody = targetNode.thisOrAncestorOfType<FunctionBody>();
- if (functionBody != null) {
- var parent = functionBody.parent;
-
- if (parent is ConstructorDeclaration) {
- optype.inConstructorBody = true;
- }
-
- if (parent is FunctionExpression) {
- optype.inFunctionBody = true;
- }
-
- if (parent is MethodDeclaration) {
- optype.inMethodBody = true;
- optype.inStaticMethodBody = parent.isStatic;
- }
- }
-
- optype.inFieldDeclaration =
- targetNode.thisOrAncestorOfType<FieldDeclaration>() != null;
- optype.inTopLevelVariableDeclaration =
- targetNode.thisOrAncestorOfType<TopLevelVariableDeclaration>() != null;
-
- // If a value should be suggested, suggest also constructors.
- if (optype.includeReturnValueSuggestions) {
- // Careful: in angular plugin, `target.unit` may be null!
- CompilationUnitElement unitElement = target.unit?.declaredElement;
- if (unitElement != null) {
- optype.includeConstructorSuggestions = true;
- }
- }
-
- // Compute the type required by the context and set filters.
- optype._computeRequiredTypeAndFilters(target);
-
- return optype;
- }
-
- OpType._();
-
- /**
- * Return `true` if free standing identifiers should be suggested
- */
- bool get includeIdentifiers {
- return !isPrefixed &&
- (includeReturnValueSuggestions ||
- includeTypeNameSuggestions ||
- includeVoidReturnSuggestions ||
- includeConstructorSuggestions);
- }
-
- /**
- * Indicate whether only type names should be suggested
- */
- bool get includeOnlyNamedArgumentSuggestions =>
- includeNamedArgumentSuggestions &&
- !includeTypeNameSuggestions &&
- !includeReturnValueSuggestions &&
- !includeVoidReturnSuggestions;
-
- /**
- * Indicate whether only type names should be suggested
- */
- bool get includeOnlyTypeNameSuggestions =>
- includeTypeNameSuggestions &&
- !includeNamedArgumentSuggestions &&
- !includeReturnValueSuggestions &&
- !includeVoidReturnSuggestions;
-
- /**
- * Try to determine the required context type, and configure filters.
- */
- void _computeRequiredTypeAndFilters(CompletionTarget target) {
- Object entity = target.entity;
- AstNode node = target.containingNode;
-
- if (node is InstanceCreationExpression &&
- node.keyword != null &&
- node.constructorName == entity) {
- entity = node;
- node = node.parent;
- }
-
- if (node is AssignmentExpression &&
- node.operator.type == TokenType.EQ &&
- node.rightHandSide == entity) {
- _requiredType = node.leftHandSide?.staticType;
- } else if (node is BinaryExpression &&
- node.operator.type == TokenType.EQ_EQ &&
- node.rightOperand == entity) {
- _requiredType = node.leftOperand?.staticType;
- } else if (node is NamedExpression && node.expression == entity) {
- _requiredType = node.staticParameterElement?.type;
- } else if (node is SwitchCase && node.expression == entity) {
- AstNode parent = node.parent;
- if (parent is SwitchStatement) {
- _requiredType = parent.expression?.staticType;
- }
- } else if (node is VariableDeclaration && node.initializer == entity) {
- _requiredType = node.declaredElement?.type;
- } else if (entity is Expression && entity.staticParameterElement != null) {
- _requiredType = entity.staticParameterElement.type;
- }
-
- if (_requiredType == null) {
- return;
- }
- if (_requiredType.isDynamic || _requiredType.isObject) {
- _requiredType = null;
- return;
- }
-
- returnValueSuggestionsFilter = (DartType dartType, int relevance) {
- if (dartType != null) {
- if (dartType == _requiredType) {
- return relevance + DART_RELEVANCE_BOOST_TYPE;
- } else if (_isSubtypeOf(dartType, _requiredType)) {
- return relevance + DART_RELEVANCE_BOOST_SUBTYPE;
- }
- }
- return relevance;
- };
- }
-
- /// Return `true` if the [leftType] is a subtype of the [rightType].
- bool _isSubtypeOf(DartType leftType, DartType rightType) {
- if (_typeSystem == null) {
- return false;
- }
-
- return _typeSystem.isSubtypeOf(leftType, rightType);
- }
-
- /// Return the statement before [entity]
- /// where [entity] can be a statement or the `}` closing the given block.
- static Statement getPreviousStatement(Block node, Object entity) {
- if (entity == node.rightBracket) {
- return node.statements.isNotEmpty ? node.statements.last : null;
- }
- if (entity is Statement) {
- int index = node.statements.indexOf(entity);
- if (index > 0) {
- return node.statements[index - 1];
- }
- return null;
- }
- return null;
- }
-}
-
-class _OpTypeAstVisitor extends GeneralizingAstVisitor {
- /**
- * The entity (AstNode or Token) which will be replaced or displaced by the
- * added text.
- */
- final Object entity;
-
- /**
- * The offset within the source at which the completion is requested.
- */
- final int offset;
-
- /**
- * The [OpType] being initialized
- */
- final OpType optype;
-
- _OpTypeAstVisitor(this.optype, this.entity, this.offset);
-
- @override
- void visitAnnotation(Annotation node) {
- if (identical(entity, node.name)) {
- optype.includeTypeNameSuggestions = true;
- optype.includeReturnValueSuggestions = true;
- } else if (identical(entity, node.constructorName)) {
- optype.includeTypeNameSuggestions = true;
- optype.includeReturnValueSuggestions = true;
- optype.isPrefixed = true;
- }
- }
-
- @override
- void visitArgumentList(ArgumentList node) {
- AstNode parent = node.parent;
- List<ParameterElement> parameters;
- if (parent is InstanceCreationExpression) {
- Element constructor;
- SimpleIdentifier name = parent.constructorName?.name;
- if (name != null) {
- constructor = name.staticElement;
- } else {
- var classElem = parent.constructorName?.type?.name?.staticElement;
- if (classElem is ClassElement) {
- constructor = classElem.unnamedConstructor;
- }
- }
- if (constructor is ConstructorElement) {
- parameters = constructor.parameters;
- } else if (constructor == null) {
- // If unresolved, then include named arguments
- optype.includeNamedArgumentSuggestions = true;
- }
- } else if (parent is InvocationExpression) {
- Expression function = parent.function;
- if (function is SimpleIdentifier) {
- var elem = function.staticElement;
- if (elem is FunctionTypedElement) {
- parameters = elem.parameters;
- } else if (elem == null) {
- // If unresolved, then include named arguments
- optype.includeNamedArgumentSuggestions = true;
- }
- }
- }
- // Based upon the insertion location and declared parameters
- // determine whether only named arguments should be suggested
- if (parameters != null) {
- int index;
- if (node.arguments.isEmpty) {
- index = 0;
- } else if (entity == node.rightParenthesis) {
- // Parser ignores trailing commas
- Token previous = node.findPrevious(node.rightParenthesis);
- if (previous?.lexeme == ',') {
- index = node.arguments.length;
- } else {
- index = node.arguments.length - 1;
- }
- } else {
- index = node.arguments.indexOf(entity as Expression);
- }
- if (0 <= index && index < parameters.length) {
- ParameterElement param = parameters[index];
- if (param?.isNamed == true) {
- optype.includeNamedArgumentSuggestions = true;
- return;
- }
- }
- }
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitAsExpression(AsExpression node) {
- if (identical(entity, node.type)) {
- optype.includeTypeNameSuggestions = true;
- optype.typeNameSuggestionsFilter = (DartType dartType, int relevance) {
- DartType staticType = node.expression.staticType;
- if (staticType != null &&
- (staticType.isDynamic ||
- (optype._isSubtypeOf(dartType, staticType) &&
- dartType != staticType))) {
- return relevance;
- } else {
- return null;
- }
- };
- }
- }
-
- @override
- void visitAssertInitializer(AssertInitializer node) {
- if (identical(entity, node.condition)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitAssertStatement(AssertStatement node) {
- if (identical(entity, node.condition)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitAssignmentExpression(AssignmentExpression node) {
- if (identical(entity, node.rightHandSide)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitAwaitExpression(AwaitExpression node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitBinaryExpression(BinaryExpression node) {
- if (identical(entity, node.rightOperand)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitBlock(Block node) {
- Statement prevStmt = OpType.getPreviousStatement(node, entity);
- if (prevStmt is TryStatement) {
- if (prevStmt.catchClauses.isEmpty && prevStmt.finallyBlock == null) {
- return;
- }
- }
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
-
- @override
- void visitBreakStatement(BreakStatement node) {
- if (node.label == null || identical(entity, node.label)) {
- optype.includeStatementLabelSuggestions = true;
- }
- }
-
- @override
- void visitCascadeExpression(CascadeExpression node) {
- if (node.cascadeSections.contains(entity)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- optype.isPrefixed = true;
- }
- }
-
- @override
- void visitCatchClause(CatchClause node) {
- if (identical(entity, node.exceptionType)) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitClassDeclaration(ClassDeclaration node) {
- // Make suggestions in the body of the class declaration
- if (node.members.contains(entity) || identical(entity, node.rightBracket)) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitClassMember(ClassMember node) {}
-
- @override
- void visitCommentReference(CommentReference node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- optype.suggestKind = CompletionSuggestionKind.IDENTIFIER;
- }
-
- @override
- void visitCompilationUnit(CompilationUnit node) {
- if (entity is! CommentToken) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitConditionalExpression(ConditionalExpression node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- visitConstructorName(ConstructorName node) {
- // some PrefixedIdentifier nodes are transformed into
- // ConstructorName nodes during the resolution process.
- if (identical(entity, node.name)) {
- TypeName type = node.type;
- if (type != null) {
- Identifier prefix = type.name;
- if (prefix != null) {
- optype.includeConstructorSuggestions = true;
- optype.isPrefixed = true;
- }
- }
- }
- }
-
- @override
- void visitContinueStatement(ContinueStatement node) {
- if (node.label == null || identical(entity, node.label)) {
- optype.includeStatementLabelSuggestions = true;
- optype.includeCaseLabelSuggestions = true;
- }
- }
-
- @override
- void visitDefaultFormalParameter(DefaultFormalParameter node) {
- if (identical(entity, node.defaultValue)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitDoStatement(DoStatement node) {
- if (identical(entity, node.condition)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitEmptyStatement(EmptyStatement node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
-
- @override
- void visitExpression(Expression node) {
- // This should never be called; we should always dispatch to the visitor
- // for a particular kind of expression.
- assert(false);
- }
-
- @override
- void visitExpressionFunctionBody(ExpressionFunctionBody node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitExpressionStatement(ExpressionStatement node) {
- // Given f[], the parser drops the [] from the expression statement
- // but the [] token is the CompletionTarget entity
- if (entity is Token) {
- Token token = entity as Token;
- if (token.lexeme == '[]' && offset == token.offset + 1) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- if ((token.isSynthetic || token.lexeme == ';') &&
- node.expression is Identifier) {
- optype.includeVarNameSuggestions = true;
- }
- }
- }
-
- @override
- void visitExtendsClause(ExtendsClause node) {
- if (identical(entity, node.superclass)) {
- optype.includeTypeNameSuggestions = true;
- optype.typeNameSuggestionsFilter = _nonMixinClasses;
- }
- }
-
- @override
- void visitExtensionDeclaration(ExtensionDeclaration node) {
- // Make suggestions in the body of the extension declaration
- if (node.members.contains(entity) || identical(entity, node.rightBracket)) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- visitFieldDeclaration(FieldDeclaration node) {
- if (offset <= node.semicolon.offset) {
- optype.includeVarNameSuggestions = true;
- }
- }
-
- @override
- void visitFieldFormalParameter(FieldFormalParameter node) {
- if (entity == node.identifier) {
- optype.isPrefixed = true;
- } else {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- visitForEachParts(ForEachParts node) {
- if (node is ForEachPartsWithIdentifier &&
- identical(entity, node.identifier)) {
- optype.includeTypeNameSuggestions = true;
- }
- if (node is ForEachPartsWithDeclaration &&
- identical(entity, node.loopVariable)) {
- optype.includeTypeNameSuggestions = true;
- }
- if (identical(entity, node.inKeyword) && offset <= node.inKeyword.offset) {
- if (!(node is ForEachPartsWithIdentifier && node.identifier != null ||
- node is ForEachPartsWithDeclaration && node.loopVariable != null)) {
- optype.includeTypeNameSuggestions = true;
- }
- }
- if (identical(entity, node.iterable)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- visitForElement(ForElement node) {
- // for (^) {}
- // for (Str^ str = null;) {}
- // In theory it is possible to specify any expression in initializer,
- // but for any practical use we need only types.
- if (entity == node.forLoopParts) {
- optype.includeTypeNameSuggestions = true;
- }
-
- if (entity == node.body) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitFormalParameterList(FormalParameterList node) {
- dynamic entity = this.entity;
- if (entity is Token) {
- Token previous = node.findPrevious(entity);
- if (previous != null) {
- TokenType type = previous.type;
- if (type == TokenType.OPEN_PAREN || type == TokenType.COMMA) {
- optype.includeTypeNameSuggestions = true;
- }
- }
- }
-
- // Find the containing parameter.
- var parameter = CompletionTarget.findFormalParameter(node, offset);
- if (parameter == null) return;
-
- // Handle default normal parameter just as a normal parameter.
- if (parameter is DefaultFormalParameter) {
- parameter = (parameter as DefaultFormalParameter).parameter;
- }
-
- // "(^ this.field)"
- if (parameter is FieldFormalParameter) {
- if (offset < parameter.thisKeyword.offset) {
- optype.includeTypeNameSuggestions = true;
- }
- return;
- }
-
- // "(Type name)"
- if (parameter is SimpleFormalParameter) {
- visitSimpleFormalParameter(parameter);
- }
- }
-
- @override
- visitForParts(ForParts node) {
- var entity = this.entity;
- if (_isEntityPrevTokenSynthetic()) {
- // Actual: for (var v i^)
- // Parsed: for (var i; i^;)
- } else if (entity is Token &&
- entity.isSynthetic &&
- node.leftSeparator == entity) {
- // Actual: for (String ^)
- // Parsed: for (String; ;)
- // ^
- optype.includeVarNameSuggestions = true;
- } else {
- // for (; ^) {}
- if (entity == node.condition) {
- optype.includeTypeNameSuggestions = true;
- optype.includeReturnValueSuggestions = true;
- }
- // for (; ; ^) {}
- if (node.updaters.contains(entity)) {
- optype.includeTypeNameSuggestions = true;
- optype.includeReturnValueSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
- }
- }
-
- @override
- void visitForStatement(ForStatement node) {
- // for (^) {}
- // for (Str^ str = null;) {}
- // In theory it is possible to specify any expression in initializer,
- // but for any practical use we need only types.
- if (entity == node.forLoopParts) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitFunctionDeclaration(FunctionDeclaration node) {
- if (identical(entity, node.returnType) ||
- identical(entity, node.name) && node.returnType == null) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitFunctionExpression(FunctionExpression node) {}
-
- @override
- void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {}
-
- @override
- void visitFunctionTypeAlias(FunctionTypeAlias node) {
- if (identical(entity, node.returnType) ||
- identical(entity, node.name) && node.returnType == null) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- visitIfElement(IfElement node) {
- if (identical(entity, node.condition)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- } else if (identical(entity, node.thenElement) ||
- identical(entity, node.elseElement)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
- }
-
- @override
- void visitIfStatement(IfStatement node) {
- if (_isEntityPrevTokenSynthetic()) {
- // Actual: if (var v i^)
- // Parsed: if (v) i^;
- } else if (identical(entity, node.condition)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- } else if (identical(entity, node.thenStatement) ||
- identical(entity, node.elseStatement)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
- }
-
- @override
- void visitImplementsClause(ImplementsClause node) {
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitIndexExpression(IndexExpression node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitInstanceCreationExpression(InstanceCreationExpression node) {
- if (identical(entity, node.constructorName)) {
- optype.includeConstructorSuggestions = true;
- }
- }
-
- @override
- void visitInterpolationExpression(InterpolationExpression node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- // Only include type names in a ${ } expression
- optype.includeTypeNameSuggestions =
- node.leftBracket != null && node.leftBracket.length > 1;
- }
- }
-
- @override
- void visitIsExpression(IsExpression node) {
- if (identical(entity, node.type)) {
- optype.includeTypeNameSuggestions = true;
- optype.typeNameSuggestionsFilter = (DartType dartType, int relevance) {
- DartType staticType = node.expression.staticType;
- if (staticType != null &&
- (staticType.isDynamic ||
- (optype._isSubtypeOf(dartType, staticType) &&
- dartType != staticType))) {
- return relevance;
- } else {
- return null;
- }
- };
- }
- }
-
- @override
- void visitLibraryIdentifier(LibraryIdentifier node) {
- // No suggestions.
- }
-
- @override
- void visitMapLiteralEntry(MapLiteralEntry node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitMethodDeclaration(MethodDeclaration node) {
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitMethodInvocation(MethodInvocation node) {
- bool isThis = node.target is ThisExpression;
- if (identical(entity, node.operator) && offset > node.operator.offset) {
- // The cursor is between the two dots of a ".." token, so we need to
- // generate the completions we would generate after a "." token.
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = !isThis;
- optype.includeVoidReturnSuggestions = true;
- optype.isPrefixed = true;
- } else if (identical(entity, node.methodName)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = !isThis;
- optype.includeVoidReturnSuggestions = true;
- optype.isPrefixed = true;
- }
- }
-
- @override
- visitMixinDeclaration(MixinDeclaration node) {
- // Make suggestions in the body of the mixin declaration
- if (node.members.contains(entity) || identical(entity, node.rightBracket)) {
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitNamedExpression(NamedExpression node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
-
- // Check for named parameters in constructor calls.
- AstNode grandparent = node.parent.parent;
- if (grandparent is ConstructorReferenceNode) {
- ConstructorElement element =
- // TODO(paulberry): remove the unnecessary cast when we are ready to
- // depend on a version of the analyzer that includes
- // https://dart-review.googlesource.com/c/sdk/+/89923
- (grandparent // ignore: unnecessary_cast
- as ConstructorReferenceNode)
- .staticElement;
- if (element != null) {
- List<ParameterElement> parameters = element.parameters;
- ParameterElement parameterElement = parameters.firstWhere((e) {
- if (e is DefaultFieldFormalParameterElementImpl) {
- return e.field?.name == node.name.label?.name;
- }
- return e.isNamed && e.name == node.name.label?.name;
- }, orElse: () => null);
- // Suggest tear-offs.
- if (parameterElement?.type is FunctionType) {
- optype.includeVoidReturnSuggestions = true;
- }
- }
- }
- }
- }
-
- @override
- void visitNode(AstNode node) {
- // no suggestion by default
- }
-
- @override
- void visitNormalFormalParameter(NormalFormalParameter node) {
- if (node.identifier != entity) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitOnClause(OnClause node) {
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitParenthesizedExpression(ParenthesizedExpression node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitPostfixExpression(PostfixExpression node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitPrefixedIdentifier(PrefixedIdentifier node) {
- if (identical(entity, node.identifier) ||
- // In addition to the standard case,
- // handle the exceptional case where the parser considers the would-be
- // identifier to be a keyword and inserts a synthetic identifier
- (node.identifier != null &&
- node.identifier.isSynthetic &&
- identical(entity, node.findPrevious(node.identifier.beginToken)))) {
- if (node.prefix.isSynthetic) {
- // If the access has no target (empty string)
- // then don't suggest anything
- return;
- }
- optype.isPrefixed = true;
- if (node.parent is TypeName && node.parent.parent is ConstructorName) {
- optype.includeConstructorSuggestions = true;
- } else {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions =
- node.parent is ExpressionStatement;
- }
- }
- }
-
- @override
- void visitPrefixExpression(PrefixExpression node) {
- if (identical(entity, node.operand)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitPropertyAccess(PropertyAccess node) {
- if (node.realTarget is SimpleIdentifier && node.realTarget.isSynthetic) {
- // If the access has no target (empty string)
- // then don't suggest anything
- return;
- }
- bool isThis = node.target is ThisExpression;
- if (identical(entity, node.operator) && offset > node.operator.offset) {
- // The cursor is between the two dots of a ".." token, so we need to
- // generate the completions we would generate after a "." token.
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = !isThis;
- optype.includeVoidReturnSuggestions = true;
- optype.isPrefixed = true;
- } else if (identical(entity, node.propertyName)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions =
- !isThis && (node.parent is! CascadeExpression);
- optype.includeVoidReturnSuggestions = true;
- optype.isPrefixed = true;
- }
- }
-
- @override
- void visitReturnStatement(ReturnStatement node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitSimpleFormalParameter(SimpleFormalParameter node) {
- var type = node.type;
- var name = node.identifier;
-
- // "(Type^)" is parsed as a parameter with the _name_ "Type".
- if (type == null &&
- name != null &&
- name.offset <= offset &&
- offset <= name.end) {
- optype.includeTypeNameSuggestions = true;
- return;
- }
-
- // If "(^ Type)", then include types.
- if (type == null && offset < name.offset) {
- optype.includeTypeNameSuggestions = true;
- return;
- }
-
- // If "(Type ^)", then include parameter names.
- if (type == null && name.end < offset && offset <= name.token.next.offset) {
- optype.includeVarNameSuggestions = true;
- return;
- }
-
- // If inside of "Type" in "(Type^ name)", then include types.
- if (type != null && type.offset <= offset && offset <= type.end) {
- optype.includeTypeNameSuggestions = true;
- return;
- }
-
- // If "(Type name^)", then include parameter names.
- if (type != null && name.offset <= offset && offset <= name.end) {
- optype.includeVarNameSuggestions = true;
- return;
- }
- }
-
- @override
- void visitSimpleIdentifier(SimpleIdentifier node) {
- // This should never happen; the containingNode will always be some node
- // higher up in the parse tree, and the SimpleIdentifier will be the
- // entity.
- assert(false);
- }
-
- @override
- visitSpreadElement(SpreadElement node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitStringLiteral(StringLiteral node) {
- // no suggestions
- }
-
- @override
- void visitSwitchCase(SwitchCase node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- } else if (node.statements.contains(entity)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
- }
-
- @override
- void visitSwitchStatement(SwitchStatement node) {
- if (identical(entity, node.expression)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- if (identical(entity, node.rightBracket)) {
- if (node.members.isNotEmpty) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
- }
- if (entity is SwitchMember && entity != node.members.first) {
- SwitchMember member = entity as SwitchMember;
- if (offset <= member.offset) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- optype.includeVoidReturnSuggestions = true;
- }
- }
- }
-
- @override
- void visitThrowExpression(ThrowExpression node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
- if (entity is Token) {
- Token token = entity as Token;
- if (token.isSynthetic || token.lexeme == ';') {
- optype.includeVarNameSuggestions = true;
- }
- }
- }
-
- @override
- void visitTypeArgumentList(TypeArgumentList node) {
- NodeList<TypeAnnotation> arguments = node.arguments;
- for (TypeAnnotation type in arguments) {
- if (identical(entity, type)) {
- optype.includeTypeNameSuggestions = true;
- break;
- }
- }
- }
-
- @override
- void visitTypedLiteral(TypedLiteral node) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitTypeName(TypeName node) {
- // The entity won't be the first child entity (node.name), since
- // CompletionTarget would have chosen an edge higher in the parse tree. So
- // it must be node.typeArguments, meaning that the cursor is between the
- // type name and the "<" that starts the type arguments. In this case,
- // we have no completions to offer.
- assert(identical(entity, node.typeArguments));
- }
-
- @override
- void visitTypeParameter(TypeParameter node) {
- optype.includeTypeNameSuggestions = true;
- }
-
- @override
- void visitVariableDeclaration(VariableDeclaration node) {
- // Make suggestions for the RHS of a variable declaration
- if (identical(entity, node.initializer)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitVariableDeclarationList(VariableDeclarationList node) {
- if (node.keyword == null || node.keyword.lexeme != 'var') {
- if (node.type == null || identical(entity, node.type)) {
- optype.includeTypeNameSuggestions = true;
- } else if (node.type != null && entity is VariableDeclaration) {
- optype.includeVarNameSuggestions = true;
- }
- }
- }
-
- @override
- void visitVariableDeclarationStatement(VariableDeclarationStatement node) {}
-
- @override
- void visitWhileStatement(WhileStatement node) {
- if (identical(entity, node.condition)) {
- optype.includeReturnValueSuggestions = true;
- optype.includeTypeNameSuggestions = true;
- }
- }
-
- @override
- void visitWithClause(WithClause node) {
- optype.includeTypeNameSuggestions = true;
- }
-
- bool _isEntityPrevTokenSynthetic() {
- Object entity = this.entity;
- if (entity is AstNode) {
- Token previous = entity.findPrevious(entity.beginToken);
- if (previous?.isSynthetic ?? false) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * A filter used to disable everything except classes (such as functions and
- * mixins).
- */
- int _nonMixinClasses(DartType type, int relevance) {
- if (type is InterfaceType) {
- if (type.element.isMixin) {
- return null;
- }
- return relevance;
- }
- return null;
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart b/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart
deleted file mode 100644
index 228f53d..0000000
--- a/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart
+++ /dev/null
@@ -1,158 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide Element, ElementKind;
-import 'package:analyzer_plugin/src/utilities/documentation.dart';
-import 'package:analyzer_plugin/utilities/analyzer_converter.dart';
-import 'package:analyzer_plugin/utilities/completion/relevance.dart';
-import 'package:analyzer_plugin/utilities/completion/suggestion_builder.dart';
-
-/**
- * An object used to build code completion suggestions for Dart code.
- */
-class SuggestionBuilderImpl implements SuggestionBuilder {
- /**
- * The resource provider used to access the file system.
- */
- final ResourceProvider resourceProvider;
-
- /**
- * The converter used to convert analyzer objects to protocol objects.
- */
- final AnalyzerConverter converter = new AnalyzerConverter();
-
- /**
- * Initialize a newly created suggestion builder.
- */
- SuggestionBuilderImpl(this.resourceProvider);
-
- /**
- * Add default argument list text and ranges based on the given [requiredParams]
- * and [namedParams].
- */
- void addDefaultArgDetails(
- CompletionSuggestion suggestion,
- Element element,
- Iterable<ParameterElement> requiredParams,
- Iterable<ParameterElement> namedParams) {
- // Copied from analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
- StringBuffer buffer = new StringBuffer();
- List<int> ranges = <int>[];
-
- int offset;
-
- for (ParameterElement param in requiredParams) {
- if (buffer.isNotEmpty) {
- buffer.write(', ');
- }
- offset = buffer.length;
- String name = param.name;
- buffer.write(name);
- ranges.addAll([offset, name.length]);
- }
-
- for (ParameterElement param in namedParams) {
- if (param.hasRequired) {
- if (buffer.isNotEmpty) {
- buffer.write(', ');
- }
- String name = param.name;
- buffer.write('$name: ');
- offset = buffer.length;
- String defaultValue = 'null'; // originally _getDefaultValue(param)
- buffer.write(defaultValue);
- ranges.addAll([offset, defaultValue.length]);
- }
- }
-
- suggestion.defaultArgumentListString =
- buffer.isNotEmpty ? buffer.toString() : null;
- suggestion.defaultArgumentListTextRanges =
- ranges.isNotEmpty ? ranges : null;
- }
-
- @override
- CompletionSuggestion forElement(Element element,
- {String completion,
- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION,
- int relevance: DART_RELEVANCE_DEFAULT}) {
- // Copied from analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
- if (element == null) {
- return null;
- }
- if (element is ExecutableElement && element.isOperator) {
- // Do not include operators in suggestions
- return null;
- }
- if (completion == null) {
- completion = element.displayName;
- }
- bool isDeprecated = element.hasDeprecated;
- CompletionSuggestion suggestion = new CompletionSuggestion(
- kind,
- isDeprecated ? DART_RELEVANCE_LOW : relevance,
- completion,
- completion.length,
- 0,
- isDeprecated,
- false);
-
- // Attach docs.
- String doc = removeDartDocDelimiters(element.documentationComment);
- suggestion.docComplete = doc;
- suggestion.docSummary = getDartDocSummary(doc);
-
- suggestion.element = converter.convertElement(element);
- Element enclosingElement = element.enclosingElement;
- if (enclosingElement is ClassElement) {
- suggestion.declaringType = enclosingElement.displayName;
- }
- suggestion.returnType = getReturnTypeString(element);
- if (element is ExecutableElement && element is! PropertyAccessorElement) {
- suggestion.parameterNames = element.parameters
- .map((ParameterElement parameter) => parameter.name)
- .toList();
- suggestion.parameterTypes =
- element.parameters.map((ParameterElement parameter) {
- DartType paramType = parameter.type;
- // Gracefully degrade if type not resolved yet
- return paramType != null ? paramType.displayName : 'var';
- }).toList();
-
- Iterable<ParameterElement> requiredParameters = element.parameters
- .where((ParameterElement param) => param.isRequiredPositional);
- suggestion.requiredParameterCount = requiredParameters.length;
-
- Iterable<ParameterElement> namedParameters =
- element.parameters.where((ParameterElement param) => param.isNamed);
- suggestion.hasNamedParameters = namedParameters.isNotEmpty;
-
- addDefaultArgDetails(
- suggestion, element, requiredParameters, namedParameters);
- }
- return suggestion;
- }
-
- String getReturnTypeString(Element element) {
- // Copied from analysis_server/lib/src/protocol_server.dart
- if (element is ExecutableElement) {
- if (element.kind == ElementKind.SETTER) {
- return null;
- } else {
- return element.returnType?.toString();
- }
- } else if (element is VariableElement) {
- DartType type = element.type;
- return type != null ? type.displayName : 'dynamic';
- } else if (element is FunctionTypeAliasElement) {
- return element.returnType.toString();
- } else {
- return null;
- }
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/documentation.dart b/analyzer_plugin/lib/src/utilities/documentation.dart
deleted file mode 100644
index 3373832..0000000
--- a/analyzer_plugin/lib/src/utilities/documentation.dart
+++ /dev/null
@@ -1,71 +0,0 @@
-// 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.
-
-/**
- * Return the summary of the given DartDoc [string], which is the content of the
- * lines before the first blank line.
- */
-String getDartDocSummary(String string) {
- if (string == null) {
- return null;
- }
- List<String> lines = string.split('\n');
- StringBuffer buffer = new StringBuffer();
- bool firstLine = true;
- for (String line in lines) {
- if (buffer.length != 0 && line.isEmpty) {
- return buffer.toString();
- }
- if (!firstLine) {
- buffer.write('\n');
- }
- firstLine = false;
- buffer.write(line);
- }
- return buffer.toString();
-}
-
-/**
- * Converts [string] from a DartDoc comment with slashes and stars to a plain
- * text representation of the comment.
- */
-String removeDartDocDelimiters(String string) {
- if (string == null) {
- return null;
- }
- // remove /** */
- if (string.startsWith('/**')) {
- string = string.substring(3);
- }
- if (string.endsWith('*/')) {
- string = string.substring(0, string.length - 2);
- }
- string = string.trim();
- // remove leading '* ' and '/// '
- List<String> lines = string.split('\n');
- StringBuffer buffer = new StringBuffer();
- bool firstLine = true;
- for (String 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 (!firstLine) {
- buffer.write('\n');
- }
- firstLine = false;
- buffer.write(line);
- }
- string = buffer.toString();
- // done
- return string;
-}
diff --git a/analyzer_plugin/lib/src/utilities/fixes/fixes.dart b/analyzer_plugin/lib/src/utilities/fixes/fixes.dart
deleted file mode 100644
index 8973624..0000000
--- a/analyzer_plugin/lib/src/utilities/fixes/fixes.dart
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/error/error.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/utilities/analyzer_converter.dart';
-import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
-
-/**
- * A concrete implementation of [DartFixesRequest].
- */
-class DartFixesRequestImpl implements DartFixesRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final int offset;
-
- @override
- final List<AnalysisError> errorsToFix;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartFixesRequestImpl(
- this.resourceProvider, this.offset, this.errorsToFix, this.result);
-}
-
-/**
- * A concrete implementation of [FixCollector].
- */
-class FixCollectorImpl implements FixCollector {
- /**
- * The list of fixes that have been collected.
- */
- final Map<AnalysisError, List<PrioritizedSourceChange>> fixMap =
- <AnalysisError, List<PrioritizedSourceChange>>{};
-
- /**
- * Return the fixes that have been collected up to this point.
- */
- List<AnalysisErrorFixes> get fixes {
- List<AnalysisErrorFixes> fixes = <AnalysisErrorFixes>[];
- AnalyzerConverter converter = new AnalyzerConverter();
- for (AnalysisError error in fixMap.keys) {
- fixes.add(new AnalysisErrorFixes(converter.convertAnalysisError(error),
- fixes: fixMap[error]));
- }
- return fixes;
- }
-
- @override
- void addFix(AnalysisError error, PrioritizedSourceChange change) {
- fixMap.putIfAbsent(error, () => <PrioritizedSourceChange>[]).add(change);
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/folding/folding.dart b/analyzer_plugin/lib/src/utilities/folding/folding.dart
deleted file mode 100644
index 2d5578c..0000000
--- a/analyzer_plugin/lib/src/utilities/folding/folding.dart
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/utilities/folding/folding.dart';
-
-/**
- * A concrete implementation of [DartFoldingRequest].
- */
-class DartFoldingRequestImpl implements DartFoldingRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartFoldingRequestImpl(this.resourceProvider, this.result);
-
- @override
- String get path => result.path;
-}
-
-/**
- * A concrete implementation of [FoldingCollector].
- */
-class FoldingCollectorImpl implements FoldingCollector {
- /**
- * The list of folding regions that have been collected.
- */
- List<FoldingRegion> regions = <FoldingRegion>[];
-
- /**
- * Initialize a newly created collector.
- */
- FoldingCollectorImpl();
-
- @override
- void addRange(SourceRange range, FoldingKind kind) {
- addRegion(range.offset, range.length, kind);
- }
-
- @override
- void addRegion(int offset, int length, FoldingKind kind) {
- regions.add(new FoldingRegion(kind, offset, length));
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/highlights/highlights.dart b/analyzer_plugin/lib/src/utilities/highlights/highlights.dart
deleted file mode 100644
index 8412dac..0000000
--- a/analyzer_plugin/lib/src/utilities/highlights/highlights.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/utilities/highlights/highlights.dart';
-
-/**
- * A concrete implementation of [DartHighlightsRequest].
- */
-class DartHighlightsRequestImpl implements DartHighlightsRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartHighlightsRequestImpl(this.resourceProvider, this.result);
-
- @override
- String get path => result.path;
-}
-
-/**
- * A concrete implementation of [HighlightsCollector].
- */
-class HighlightsCollectorImpl implements HighlightsCollector {
- /**
- * The regions that have been collected.
- */
- List<HighlightRegion> regions = <HighlightRegion>[];
-
- @override
- void addRange(SourceRange range, HighlightRegionType type) {
- regions.add(new HighlightRegion(type, range.offset, range.length));
- }
-
- @override
- void addRegion(int offset, int length, HighlightRegionType type) {
- regions.add(new HighlightRegion(type, offset, length));
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/kythe/entries.dart b/analyzer_plugin/lib/src/utilities/kythe/entries.dart
deleted file mode 100644
index eb4163a..0000000
--- a/analyzer_plugin/lib/src/utilities/kythe/entries.dart
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/utilities/kythe/entries.dart';
-
-/**
- * A concrete implementation of [EntryRequest].
- */
-class DartEntryRequestImpl implements DartEntryRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartEntryRequestImpl(this.resourceProvider, this.result);
-
- @override
- String get path => result.path;
-}
-
-/**
- * A concrete implementation of [EntryCollector].
- */
-class EntryCollectorImpl implements EntryCollector {
- /**
- * A list of entries.
- */
- final List<KytheEntry> entries = <KytheEntry>[];
-
- /**
- * A list of paths to files.
- */
- final List<String> files = <String>[];
-
- @override
- void addEntry(KytheEntry entry) {
- entries.add(entry);
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/navigation/navigation.dart b/analyzer_plugin/lib/src/utilities/navigation/navigation.dart
deleted file mode 100644
index 31e004b..0000000
--- a/analyzer_plugin/lib/src/utilities/navigation/navigation.dart
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart' show SourceRange;
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/utilities/navigation/navigation.dart';
-import 'package:analyzer_plugin/utilities/pair.dart';
-
-/**
- * A concrete implementation of [DartNavigationRequest].
- */
-class DartNavigationRequestImpl implements DartNavigationRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final int length;
-
- @override
- final int offset;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartNavigationRequestImpl(
- this.resourceProvider, this.offset, this.length, this.result);
-
- @override
- String get path => result.path;
-}
-
-/**
- * A concrete implementation of [NavigationCollector].
- */
-class NavigationCollectorImpl implements NavigationCollector {
- /**
- * A list of navigation regions.
- */
- final List<NavigationRegion> regions = <NavigationRegion>[];
- final Map<SourceRange, List<int>> regionMap = <SourceRange, List<int>>{};
-
- /**
- * All the unique targets referenced by [regions].
- */
- final List<NavigationTarget> targets = <NavigationTarget>[];
- final Map<Pair<ElementKind, Location>, int> targetMap =
- <Pair<ElementKind, Location>, int>{};
-
- /**
- * All the unique files referenced by [targets].
- */
- final List<String> files = <String>[];
- final Map<String, int> fileMap = <String, int>{};
-
- @override
- void addRange(
- SourceRange range, ElementKind targetKind, Location targetLocation) {
- addRegion(range.offset, range.length, targetKind, targetLocation);
- }
-
- @override
- void addRegion(
- int offset, int length, ElementKind targetKind, Location targetLocation) {
- SourceRange range = new SourceRange(offset, length);
- // add new target
- List<int> targets = regionMap.putIfAbsent(range, () => <int>[]);
- int targetIndex = _addTarget(targetKind, targetLocation);
- targets.add(targetIndex);
- }
-
- void createRegions() {
- regionMap.forEach((range, targets) {
- NavigationRegion region =
- new NavigationRegion(range.offset, range.length, targets);
- regions.add(region);
- });
- regions.sort((NavigationRegion first, NavigationRegion second) {
- return first.offset - second.offset;
- });
- }
-
- int _addFile(String file) {
- int index = fileMap[file];
- if (index == null) {
- index = files.length;
- files.add(file);
- fileMap[file] = index;
- }
- return index;
- }
-
- int _addTarget(ElementKind kind, Location location) {
- var pair = new Pair<ElementKind, Location>(kind, location);
- int index = targetMap[pair];
- if (index == null) {
- String file = location.file;
- int fileIndex = _addFile(file);
- index = targets.length;
- NavigationTarget target = new NavigationTarget(
- kind,
- fileIndex,
- location.offset,
- location.length,
- location.startLine,
- location.startColumn);
- targets.add(target);
- targetMap[pair] = index;
- }
- return index;
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/null_string_sink.dart b/analyzer_plugin/lib/src/utilities/null_string_sink.dart
deleted file mode 100644
index 28d910a..0000000
--- a/analyzer_plugin/lib/src/utilities/null_string_sink.dart
+++ /dev/null
@@ -1,20 +0,0 @@
-// 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.
-
-/**
- * A string sink that ignores everything written to it.
- */
-class NullStringSink implements StringSink {
- @override
- void write(Object obj) {}
-
- @override
- void writeAll(Iterable objects, [String separator = ""]) {}
-
- @override
- void writeCharCode(int charCode) {}
-
- @override
- void writeln([Object obj = ""]) {}
-}
diff --git a/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart b/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart
deleted file mode 100644
index 2538191..0000000
--- a/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/utilities/occurrences/occurrences.dart';
-
-/**
- * A concrete implementation of [DartOccurrencesRequest].
- */
-class DartOccurrencesRequestImpl implements DartOccurrencesRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartOccurrencesRequestImpl(this.resourceProvider, this.result);
-
- @override
- String get path => result.path;
-}
-
-/**
- * A concrete implementation of [OccurrencesCollector].
- */
-class OccurrencesCollectorImpl implements OccurrencesCollector {
- /**
- * The locations of the occurrences that have been collected.
- */
- Map<Element, List<int>> occurrenceLocations = <Element, List<int>>{};
-
- /**
- * Initialize a newly created collector.
- */
- OccurrencesCollectorImpl();
-
- /**
- * Return the list of occurrences that have been collected.
- */
- List<Occurrences> get occurrences {
- List<Occurrences> occurrences = <Occurrences>[];
- occurrenceLocations.forEach((Element element, List<int> offsets) {
- offsets.sort();
- occurrences.add(new Occurrences(element, offsets, element.name.length));
- });
- return occurrences;
- }
-
- @override
- void addOccurrence(Element element, int offset) {
- occurrenceLocations.putIfAbsent(element, () => <int>[]).add(offset);
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/outline/outline.dart b/analyzer_plugin/lib/src/utilities/outline/outline.dart
deleted file mode 100644
index 47fba67..0000000
--- a/analyzer_plugin/lib/src/utilities/outline/outline.dart
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/utilities/outline/outline.dart';
-
-/**
- * A concrete implementation of [DartOutlineRequest].
- */
-class DartOutlineRequestImpl implements DartOutlineRequest {
- @override
- final ResourceProvider resourceProvider;
-
- @override
- final ResolvedUnitResult result;
-
- /**
- * Initialize a newly create request with the given data.
- */
- DartOutlineRequestImpl(this.resourceProvider, this.result);
-
- @override
- String get path => result.path;
-}
-
-/**
- * A concrete implementation of [OutlineCollector].
- */
-class OutlineCollectorImpl implements OutlineCollector {
- /**
- * A list containing the top-level outline nodes.
- */
- List<Outline> outlines = <Outline>[];
-
- /**
- * A stack keeping track of the outline nodes that have been started but not
- * yet ended.
- */
- List<Outline> outlineStack = <Outline>[];
-
- @override
- void endElement() {
- outlineStack.removeLast();
- }
-
- @override
- void startElement(Element element, int offset, int length) {
- Outline outline = new Outline(element, offset, length, offset, length);
- if (outlineStack.isEmpty) {
- outlines.add(outline);
- } else {
- List<Outline> children = outlineStack.last.children;
- if (children == null) {
- children = <Outline>[];
- outlineStack.last.children = children;
- }
- children.add(outline);
- }
- outlineStack.add(outline);
- }
-}
diff --git a/analyzer_plugin/lib/src/utilities/string_utilities.dart b/analyzer_plugin/lib/src/utilities/string_utilities.dart
deleted file mode 100644
index c74fd8a..0000000
--- a/analyzer_plugin/lib/src/utilities/string_utilities.dart
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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:charcode/ascii.dart';
-
-/**
- * Returns a list of the words from which the given camel case [string] is
- * composed.
- *
- * 'getCamelWords' => ['get', 'Camel', 'Words']
- * 'getHTMLText' => ['get', 'HTML', 'Text']
- */
-List<String> getCamelWords(String string) {
- if (string == null || string.isEmpty) {
- return const <String>[];
- }
- List<String> parts = <String>[];
- bool wasLowerCase = false;
- bool wasUpperCase = false;
- int wordStart = 0;
- for (int i = 0; i < string.length; i++) {
- int c = string.codeUnitAt(i);
- var newLowerCase = isLowerCase(c);
- var newUpperCase = isUpperCase(c);
- // myWord
- // | ^
- if (wasLowerCase && newUpperCase) {
- parts.add(string.substring(wordStart, i));
- wordStart = i;
- }
- // myHTMLText
- // | ^
- if (wasUpperCase &&
- newUpperCase &&
- i + 1 < string.length &&
- isLowerCase(string.codeUnitAt(i + 1))) {
- parts.add(string.substring(wordStart, i));
- wordStart = i;
- }
- wasLowerCase = newLowerCase;
- wasUpperCase = newUpperCase;
- }
- parts.add(string.substring(wordStart));
- return parts;
-}
-
-/**
- * Return `true` if the given [string] is either `null` or empty.
- */
-bool isEmpty(String string) => string == null || string.isEmpty;
-
-/**
- * Return `true` if the given [character] is a lowercase ASCII character.
- */
-bool isLowerCase(int character) => character >= $a && character <= $z;
-
-/**
- * Return `true` if the given [character] is an uppercase ASCII character.
- */
-bool isUpperCase(int character) => character >= $A && character <= $Z;
-
-/**
- * If the given [string] starts with the text to [remove], then return the
- * portion of the string after the text to remove. Otherwise, return the
- * original string unmodified.
- */
-String removeStart(String string, String remove) {
- if (isEmpty(string) || isEmpty(remove)) {
- return string;
- }
- if (string.startsWith(remove)) {
- return string.substring(remove.length);
- }
- return string;
-}
diff --git a/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart b/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart
deleted file mode 100644
index d0a3556..0000000
--- a/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart
+++ /dev/null
@@ -1,325 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/standard_ast_factory.dart';
-import 'package:analyzer/dart/ast/token.dart';
-import 'package:analyzer/dart/ast/visitor.dart';
-import 'package:analyzer/src/dart/ast/token.dart';
-
-/**
- * A visitor that visits an [AstNode] and its parent recursively along with any
- * declarations in those nodes. Consumers typically call [visit] which catches
- * the exception thrown by [finished].
- */
-abstract class LocalDeclarationVisitor extends GeneralizingAstVisitor {
- static final TypeName STACKTRACE_TYPE = astFactory.typeName(
- astFactory.simpleIdentifier(
- new StringToken(TokenType.IDENTIFIER, 'StackTrace', 0)),
- null);
-
- final int offset;
-
- LocalDeclarationVisitor(this.offset);
-
- void declaredClass(ClassDeclaration declaration);
-
- void declaredClassTypeAlias(ClassTypeAlias declaration);
-
- void declaredEnum(EnumDeclaration declaration) {}
-
- void declaredExtension(ExtensionDeclaration declaration);
-
- void declaredField(FieldDeclaration fieldDecl, VariableDeclaration varDecl);
-
- void declaredFunction(FunctionDeclaration declaration);
-
- void declaredFunctionTypeAlias(FunctionTypeAlias declaration);
-
- void declaredGenericTypeAlias(GenericTypeAlias declaration);
-
- void declaredLabel(Label label, bool isCaseLabel);
-
- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type);
-
- void declaredMethod(MethodDeclaration declaration);
-
- void declaredMixin(MixinDeclaration declaration) {}
-
- void declaredParam(SimpleIdentifier name, TypeAnnotation type);
-
- void declaredTopLevelVar(
- VariableDeclarationList varList, VariableDeclaration varDecl);
-
- void declaredTypeParameter(TypeParameter node) {}
-
- /**
- * Throw an exception indicating that [LocalDeclarationVisitor] should
- * stop visiting. This is caught in [visit] which then exits normally.
- */
- void finished() {
- throw new _LocalDeclarationVisitorFinished();
- }
-
- /**
- * Visit the given [AstNode] and its parent recursively along with any
- * declarations in those nodes. Return `true` if [finished] is called
- * while visiting, else `false`.
- */
- bool visit(AstNode node) {
- try {
- node.accept(this);
- return false;
- } on _LocalDeclarationVisitorFinished {
- return true;
- }
- }
-
- @override
- void visitBlock(Block node) {
- _visitStatements(node.statements);
- visitNode(node);
- }
-
- @override
- void visitCatchClause(CatchClause node) {
- SimpleIdentifier param = node.exceptionParameter;
- if (param != null) {
- declaredParam(param, node.exceptionType);
- }
- param = node.stackTraceParameter;
- if (param != null) {
- declaredParam(param, STACKTRACE_TYPE);
- }
- visitNode(node);
- }
-
- @override
- void visitClassDeclaration(ClassDeclaration node) {
- _visitClassDeclarationMembers(node);
- visitNode(node);
- }
-
- @override
- void visitCompilationUnit(CompilationUnit node) {
- node.declarations.forEach((Declaration declaration) {
- if (declaration is ClassDeclaration) {
- declaredClass(declaration);
- _visitTypeParameters(declaration, declaration.typeParameters);
- } else if (declaration is EnumDeclaration) {
- declaredEnum(declaration);
- } else if (declaration is ExtensionDeclaration) {
- declaredExtension(declaration);
- _visitTypeParameters(declaration, declaration.typeParameters);
- } else if (declaration is FunctionDeclaration) {
- declaredFunction(declaration);
- _visitTypeParameters(
- declaration,
- declaration.functionExpression.typeParameters,
- );
- } else if (declaration is TopLevelVariableDeclaration) {
- var varList = declaration.variables;
- if (varList != null) {
- varList.variables.forEach((VariableDeclaration varDecl) {
- declaredTopLevelVar(varList, varDecl);
- });
- }
- } else if (declaration is ClassTypeAlias) {
- declaredClassTypeAlias(declaration);
- _visitTypeParameters(declaration, declaration.typeParameters);
- } else if (declaration is FunctionTypeAlias) {
- declaredFunctionTypeAlias(declaration);
- _visitTypeParameters(declaration, declaration.typeParameters);
- } else if (declaration is GenericTypeAlias) {
- declaredGenericTypeAlias(declaration);
- _visitTypeParameters(declaration, declaration.typeParameters);
- _visitTypeParameters(
- declaration.functionType,
- declaration.functionType?.typeParameters,
- );
- } else if (declaration is MixinDeclaration) {
- declaredMixin(declaration);
- _visitTypeParameters(declaration, declaration.typeParameters);
- }
- });
- }
-
- @override
- visitConstructorDeclaration(ConstructorDeclaration node) {
- _visitParamList(node.parameters);
- visitNode(node);
- }
-
- @override
- visitForStatement(ForStatement node) {
- var forLoopParts = node.forLoopParts;
- if (forLoopParts is ForEachPartsWithDeclaration) {
- DeclaredIdentifier loopVar = forLoopParts.loopVariable;
- if (loopVar != null) {
- SimpleIdentifier id = loopVar.identifier;
- if (id != null) {
- // If there is no loop variable, don't declare it.
- declaredLocalVar(id, loopVar.type);
- }
- }
- } else if (forLoopParts is ForEachPartsWithIdentifier) {
- SimpleIdentifier id = forLoopParts.identifier;
- if (id != null) {
- // If there is no loop variable, don't declare it.
- declaredLocalVar(id, null);
- }
- } else if (forLoopParts is ForPartsWithDeclarations) {
- VariableDeclarationList varList = forLoopParts.variables;
- if (varList != null) {
- varList.variables.forEach((VariableDeclaration varDecl) {
- declaredLocalVar(varDecl.name, varList.type);
- });
- }
- }
- visitNode(node);
- }
-
- @override
- void visitFunctionDeclaration(FunctionDeclaration node) {
- // declaredFunction is called by the compilation unit containing it
- visitNode(node);
- }
-
- @override
- void visitFunctionExpression(FunctionExpression node) {
- _visitParamList(node.parameters);
- visitNode(node);
- }
-
- @override
- void visitInterpolationExpression(InterpolationExpression node) {
- visitNode(node);
- }
-
- @override
- void visitLabeledStatement(LabeledStatement node) {
- for (Label label in node.labels) {
- declaredLabel(label, false);
- }
- visitNode(node);
- }
-
- @override
- void visitMethodDeclaration(MethodDeclaration node) {
- _visitParamList(node.parameters);
- visitNode(node);
- }
-
- @override
- void visitNode(AstNode node) {
- // Support the case of searching partial ASTs by aborting on nodes with no
- // parents. This is useful for the angular plugin.
- node.parent?.accept(this);
- }
-
- @override
- void visitStringInterpolation(StringInterpolation node) {
- visitNode(node);
- }
-
- @override
- void visitSwitchMember(SwitchMember node) {
- _visitStatements(node.statements);
- visitNode(node);
- }
-
- @override
- void visitSwitchStatement(SwitchStatement node) {
- for (SwitchMember member in node.members) {
- for (Label label in member.labels) {
- declaredLabel(label, true);
- }
- }
- visitNode(node);
- }
-
- void _visitClassDeclarationMembers(ClassDeclaration node) {
- for (ClassMember member in node.members) {
- if (member is FieldDeclaration) {
- member.fields.variables.forEach((VariableDeclaration varDecl) {
- declaredField(member, varDecl);
- });
- } else if (member is MethodDeclaration) {
- declaredMethod(member);
- _visitTypeParameters(member, member.typeParameters);
- }
- }
- }
-
- void _visitParamList(FormalParameterList paramList) {
- if (paramList != null) {
- paramList.parameters.forEach((FormalParameter param) {
- NormalFormalParameter normalParam;
- if (param is DefaultFormalParameter) {
- normalParam = param.parameter;
- } else if (param is NormalFormalParameter) {
- normalParam = param;
- }
- TypeAnnotation type = null;
- if (normalParam is FieldFormalParameter) {
- type = normalParam.type;
- } else if (normalParam is FunctionTypedFormalParameter) {
- type = normalParam.returnType;
- } else if (normalParam is SimpleFormalParameter) {
- type = normalParam.type;
- }
- SimpleIdentifier name = param.identifier;
- declaredParam(name, type);
- });
- }
- }
-
- _visitStatements(NodeList<Statement> statements) {
- for (Statement stmt in statements) {
- if (stmt.offset < offset) {
- if (stmt is VariableDeclarationStatement) {
- VariableDeclarationList varList = stmt.variables;
- if (varList != null) {
- for (VariableDeclaration varDecl in varList.variables) {
- if (varDecl.end < offset) {
- declaredLocalVar(varDecl.name, varList.type);
- }
- }
- }
- } else if (stmt is FunctionDeclarationStatement) {
- FunctionDeclaration declaration = stmt.functionDeclaration;
- if (declaration != null && declaration.offset < offset) {
- SimpleIdentifier id = declaration.name;
- if (id != null) {
- String name = id.name;
- if (name != null && name.length > 0) {
- declaredFunction(declaration);
- _visitTypeParameters(
- declaration,
- declaration.functionExpression.typeParameters,
- );
- }
- }
- }
- }
- }
- }
- }
-
- void _visitTypeParameters(AstNode node, TypeParameterList typeParameters) {
- if (typeParameters == null) return;
-
- if (node.offset < offset && offset < node.end) {
- for (var typeParameter in typeParameters.typeParameters) {
- declaredTypeParameter(typeParameter);
- }
- }
- }
-}
-
-/**
- * Internal exception used to indicate that [LocalDeclarationVisitor]
- * should stop visiting.
- */
-class _LocalDeclarationVisitorFinished {}
diff --git a/analyzer_plugin/lib/starter.dart b/analyzer_plugin/lib/starter.dart
deleted file mode 100644
index a72926c..0000000
--- a/analyzer_plugin/lib/starter.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// 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:isolate';
-
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/src/driver.dart';
-
-/**
- * An object that can be used to start an analysis server plugin. This class
- * exists so that clients can configure a plugin before starting it.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class ServerPluginStarter {
- /**
- * Create a starter that can be used to start the given [plugin].
- */
- factory ServerPluginStarter(ServerPlugin plugin) => new Driver(plugin);
-
- /**
- * Establish the channel used to communicate with the server and start the
- * plugin.
- */
- void start(SendPort sendPort);
-}
diff --git a/analyzer_plugin/lib/utilities/analyzer_converter.dart b/analyzer_plugin/lib/utilities/analyzer_converter.dart
deleted file mode 100644
index 0763e54..0000000
--- a/analyzer_plugin/lib/utilities/analyzer_converter.dart
+++ /dev/null
@@ -1,409 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart' as analyzer;
-import 'package:analyzer/dart/element/type.dart' as analyzer;
-import 'package:analyzer/diagnostic/diagnostic.dart' as analyzer;
-import 'package:analyzer/error/error.dart' as analyzer;
-import 'package:analyzer/exception/exception.dart' as analyzer;
-import 'package:analyzer/source/error_processor.dart' as analyzer;
-import 'package:analyzer/source/line_info.dart' as analyzer;
-import 'package:analyzer/src/generated/engine.dart' as analyzer;
-import 'package:analyzer/src/generated/source.dart' as analyzer;
-import 'package:analyzer/src/generated/utilities_dart.dart' as analyzer;
-import 'package:analyzer_plugin/protocol/protocol_common.dart' as plugin;
-import 'package:analyzer_plugin/protocol/protocol_constants.dart' as plugin;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
-
-/**
- * An object used to convert between objects defined by the 'analyzer' package
- * and those defined by the plugin protocol.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AnalyzerConverter {
- /**
- * Convert the analysis [error] from the 'analyzer' package to an analysis
- * error defined by the plugin API. If a [lineInfo] is provided then the
- * error's location will have a start line and start column. If a [severity]
- * is provided, then it will override the severity defined by the error.
- */
- plugin.AnalysisError convertAnalysisError(analyzer.AnalysisError error,
- {analyzer.LineInfo lineInfo, analyzer.ErrorSeverity severity}) {
- analyzer.ErrorCode errorCode = error.errorCode;
- severity ??= errorCode.errorSeverity;
- int offset = error.offset;
- int startLine = -1;
- int startColumn = -1;
- if (lineInfo != null) {
- analyzer.CharacterLocation lineLocation =
- lineInfo.getLocation(offset) as analyzer.CharacterLocation;
- if (lineLocation != null) {
- startLine = lineLocation.lineNumber;
- startColumn = lineLocation.columnNumber;
- }
- }
- List<plugin.DiagnosticMessage> contextMessages;
- if (error.contextMessages.isNotEmpty) {
- contextMessages = error.contextMessages
- .map((message) =>
- convertDiagnosticMessage(message, lineInfo: lineInfo))
- .toList();
- }
- return new plugin.AnalysisError(
- convertErrorSeverity(severity),
- convertErrorType(errorCode.type),
- new plugin.Location(error.source.fullName, offset, error.length,
- startLine, startColumn),
- error.message,
- errorCode.name.toLowerCase(),
- contextMessages: contextMessages,
- correction: error.correction,
- hasFix: true);
- }
-
- /**
- * Convert the list of analysis [errors] from the 'analyzer' package to a list
- * of analysis errors defined by the plugin API. If a [lineInfo] is provided
- * then the resulting errors locations will have a start line and start column.
- * If an analysis [options] is provided then the severities of the errors will
- * be altered based on those options.
- */
- List<plugin.AnalysisError> convertAnalysisErrors(
- List<analyzer.AnalysisError> errors,
- {analyzer.LineInfo lineInfo,
- analyzer.AnalysisOptions options}) {
- List<plugin.AnalysisError> serverErrors = <plugin.AnalysisError>[];
- for (analyzer.AnalysisError error in errors) {
- analyzer.ErrorProcessor processor =
- analyzer.ErrorProcessor.getProcessor(options, error);
- if (processor != null) {
- analyzer.ErrorSeverity severity = processor.severity;
- // Errors with null severity are filtered out.
- if (severity != null) {
- // Specified severities override.
- serverErrors.add(convertAnalysisError(error,
- lineInfo: lineInfo, severity: severity));
- }
- } else {
- serverErrors.add(convertAnalysisError(error, lineInfo: lineInfo));
- }
- }
- return serverErrors;
- }
-
- /**
- * Convert the diagnostic [message] from the 'analyzer' package to an analysis
- * error defined by the plugin API. If a [lineInfo] is provided then the
- * error's location will have a start line and start column.
- */
- plugin.DiagnosticMessage convertDiagnosticMessage(
- analyzer.DiagnosticMessage message,
- {analyzer.LineInfo lineInfo}) {
- String file = message.filePath;
- int offset = message.offset;
- int length = message.length;
- int startLine = -1;
- int startColumn = -1;
- if (lineInfo != null) {
- analyzer.CharacterLocation lineLocation =
- lineInfo.getLocation(offset) as analyzer.CharacterLocation;
- if (lineLocation != null) {
- startLine = lineLocation.lineNumber;
- startColumn = lineLocation.columnNumber;
- }
- }
- return plugin.DiagnosticMessage(message.message,
- plugin.Location(file, offset, length, startLine, startColumn));
- }
-
- /**
- * Convert the given [element] from the 'analyzer' package to an element
- * defined by the plugin API.
- */
- plugin.Element convertElement(analyzer.Element element) {
- plugin.ElementKind kind = _convertElementToElementKind(element);
- return new plugin.Element(
- kind,
- element.displayName,
- plugin.Element.makeFlags(
- isPrivate: element.isPrivate,
- isDeprecated: element.hasDeprecated,
- isAbstract: _isAbstract(element),
- isConst: _isConst(element),
- isFinal: _isFinal(element),
- isStatic: _isStatic(element)),
- location: _locationFromElement(element),
- typeParameters: _getTypeParametersString(element),
- parameters: _getParametersString(element),
- returnType: _getReturnTypeString(element));
- }
-
- /**
- * Convert the element [kind] from the 'analyzer' package to an element kind
- * defined by the plugin API.
- *
- * This method does not take into account that an instance of [ClassElement]
- * can be an enum and an instance of [FieldElement] can be an enum constant.
- * Use [_convertElementToElementKind] where possible.
- */
- plugin.ElementKind convertElementKind(analyzer.ElementKind kind) {
- if (kind == analyzer.ElementKind.CLASS) {
- return plugin.ElementKind.CLASS;
- } else if (kind == analyzer.ElementKind.COMPILATION_UNIT) {
- return plugin.ElementKind.COMPILATION_UNIT;
- } else if (kind == analyzer.ElementKind.CONSTRUCTOR) {
- return plugin.ElementKind.CONSTRUCTOR;
- } else if (kind == analyzer.ElementKind.FIELD) {
- return plugin.ElementKind.FIELD;
- } else if (kind == analyzer.ElementKind.FUNCTION) {
- return plugin.ElementKind.FUNCTION;
- } else if (kind == analyzer.ElementKind.FUNCTION_TYPE_ALIAS) {
- return plugin.ElementKind.FUNCTION_TYPE_ALIAS;
- } else if (kind == analyzer.ElementKind.GENERIC_FUNCTION_TYPE) {
- return plugin.ElementKind.FUNCTION_TYPE_ALIAS;
- } else if (kind == analyzer.ElementKind.GETTER) {
- return plugin.ElementKind.GETTER;
- } else if (kind == analyzer.ElementKind.LABEL) {
- return plugin.ElementKind.LABEL;
- } else if (kind == analyzer.ElementKind.LIBRARY) {
- return plugin.ElementKind.LIBRARY;
- } else if (kind == analyzer.ElementKind.LOCAL_VARIABLE) {
- return plugin.ElementKind.LOCAL_VARIABLE;
- } else if (kind == analyzer.ElementKind.METHOD) {
- return plugin.ElementKind.METHOD;
- } else if (kind == analyzer.ElementKind.PARAMETER) {
- return plugin.ElementKind.PARAMETER;
- } else if (kind == analyzer.ElementKind.PREFIX) {
- return plugin.ElementKind.PREFIX;
- } else if (kind == analyzer.ElementKind.SETTER) {
- return plugin.ElementKind.SETTER;
- } else if (kind == analyzer.ElementKind.TOP_LEVEL_VARIABLE) {
- return plugin.ElementKind.TOP_LEVEL_VARIABLE;
- } else if (kind == analyzer.ElementKind.TYPE_PARAMETER) {
- return plugin.ElementKind.TYPE_PARAMETER;
- }
- return plugin.ElementKind.UNKNOWN;
- }
-
- /**
- * Convert the error [severity] from the 'analyzer' package to an analysis
- * error severity defined by the plugin API.
- */
- plugin.AnalysisErrorSeverity convertErrorSeverity(
- analyzer.ErrorSeverity severity) =>
- new plugin.AnalysisErrorSeverity(severity.name);
-
- /**
- *Convert the error [type] from the 'analyzer' package to an analysis error
- * type defined by the plugin API.
- */
- plugin.AnalysisErrorType convertErrorType(analyzer.ErrorType type) =>
- new plugin.AnalysisErrorType(type.name);
-
- /**
- * Convert the element kind of the [element] from the 'analyzer' package to an
- * element kind defined by the plugin API.
- */
- plugin.ElementKind _convertElementToElementKind(analyzer.Element element) {
- if (element is analyzer.ClassElement && element.isEnum) {
- return plugin.ElementKind.ENUM;
- } else if (element is analyzer.FieldElement &&
- element.isEnumConstant &&
- // MyEnum.values and MyEnum.one.index return isEnumConstant = true
- // so these additional checks are necessary.
- // TODO(danrubel) MyEnum.values is constant, but is a list
- // so should it return isEnumConstant = true?
- // MyEnum.one.index is final but *not* constant
- // so should it return isEnumConstant = true?
- // Or should we return ElementKind.ENUM_CONSTANT here
- // in either or both of these cases?
- element.type != null &&
- element.type.element == element.enclosingElement) {
- return plugin.ElementKind.ENUM_CONSTANT;
- }
- return convertElementKind(element.kind);
- }
-
- /**
- * Return a textual representation of the parameters of the given [element],
- * or `null` if the element does not have any parameters.
- */
- String _getParametersString(analyzer.Element element) {
- // TODO(scheglov) expose the corresponding feature from ExecutableElement
- List<analyzer.ParameterElement> parameters;
- if (element is analyzer.ExecutableElement) {
- // valid getters don't have parameters
- if (element.kind == analyzer.ElementKind.GETTER &&
- element.parameters.isEmpty) {
- return null;
- }
- parameters = element.parameters;
- } else if (element is analyzer.FunctionTypeAliasElement) {
- parameters = element.parameters;
- } else {
- return null;
- }
- StringBuffer buffer = new StringBuffer();
- String closeOptionalString = '';
- buffer.write('(');
- for (int i = 0; i < parameters.length; i++) {
- analyzer.ParameterElement parameter = parameters[i];
- if (i > 0) {
- buffer.write(', ');
- }
- if (closeOptionalString.isEmpty) {
- if (parameter.isNamed) {
- buffer.write('{');
- closeOptionalString = '}';
- } else if (parameter.isOptionalPositional) {
- buffer.write('[');
- closeOptionalString = ']';
- }
- }
- parameter.appendToWithoutDelimiters(buffer);
- }
- buffer.write(closeOptionalString);
- buffer.write(')');
- return buffer.toString();
- }
-
- /**
- * Return a textual representation of the return type of the given [element],
- * or `null` if the element does not have a return type.
- */
- String _getReturnTypeString(analyzer.Element element) {
- if (element is analyzer.ExecutableElement) {
- if (element.kind == analyzer.ElementKind.SETTER) {
- return null;
- }
- return element.returnType?.toString();
- } else if (element is analyzer.VariableElement) {
- analyzer.DartType type = element.type;
- return type != null ? type.displayName : 'dynamic';
- } else if (element is analyzer.FunctionTypeAliasElement) {
- return element.returnType.toString();
- }
- return null;
- }
-
- /**
- * Return a textual representation of the type parameters of the given
- * [element], or `null` if the element does not have type parameters.
- */
- String _getTypeParametersString(analyzer.Element element) {
- if (element is analyzer.TypeParameterizedElement) {
- List<analyzer.TypeParameterElement> typeParameters =
- element.typeParameters;
- if (typeParameters == null || typeParameters.isEmpty) {
- return null;
- }
- return '<${typeParameters.join(', ')}>';
- }
- return null;
- }
-
- /**
- * Return the compilation unit containing the given [element].
- */
- analyzer.CompilationUnitElement _getUnitElement(analyzer.Element element) {
- if (element is analyzer.CompilationUnitElement) {
- return element;
- }
- if (element?.enclosingElement is analyzer.LibraryElement) {
- element = element.enclosingElement;
- }
- if (element is analyzer.LibraryElement) {
- return element.definingCompilationUnit;
- }
- for (; element != null; element = element.enclosingElement) {
- if (element is analyzer.CompilationUnitElement) {
- return element;
- }
- }
- return null;
- }
-
- bool _isAbstract(analyzer.Element element) {
- // TODO(scheglov) add isAbstract to Element API
- if (element is analyzer.ClassElement) {
- return element.isAbstract;
- } else if (element is analyzer.MethodElement) {
- return element.isAbstract;
- } else if (element is analyzer.PropertyAccessorElement) {
- return element.isAbstract;
- }
- return false;
- }
-
- bool _isConst(analyzer.Element element) {
- // TODO(scheglov) add isConst to Element API
- if (element is analyzer.ConstructorElement) {
- return element.isConst;
- } else if (element is analyzer.VariableElement) {
- return element.isConst;
- }
- return false;
- }
-
- bool _isFinal(analyzer.Element element) {
- // TODO(scheglov) add isFinal to Element API
- if (element is analyzer.VariableElement) {
- return element.isFinal;
- }
- return false;
- }
-
- bool _isStatic(analyzer.Element element) {
- // TODO(scheglov) add isStatic to Element API
- if (element is analyzer.ExecutableElement) {
- return element.isStatic;
- } else if (element is analyzer.PropertyInducingElement) {
- return element.isStatic;
- }
- return false;
- }
-
- /**
- * Create and return a location within the given [unitElement] at the given
- * [range].
- */
- plugin.Location _locationForArgs(
- analyzer.CompilationUnitElement unitElement, analyzer.SourceRange range) {
- int startLine = 0;
- int startColumn = 0;
- try {
- analyzer.LineInfo lineInfo = unitElement.lineInfo;
- if (lineInfo != null) {
- analyzer.CharacterLocation offsetLocation =
- lineInfo.getLocation(range.offset) as analyzer.CharacterLocation;
- startLine = offsetLocation.lineNumber;
- startColumn = offsetLocation.columnNumber;
- }
- } on analyzer.AnalysisException {
- // Ignore exceptions
- }
- return new plugin.Location(unitElement.source.fullName, range.offset,
- range.length, startLine, startColumn);
- }
-
- /**
- * Create a location based on an the given [element].
- */
- plugin.Location _locationFromElement(analyzer.Element element) {
- if (element == null || element.source == null) {
- return null;
- }
- int offset = element.nameOffset;
- int length = element.nameLength;
- if (element is analyzer.CompilationUnitElement ||
- (element is analyzer.LibraryElement && offset < 0)) {
- offset = 0;
- length = 0;
- }
- analyzer.CompilationUnitElement unitElement = _getUnitElement(element);
- analyzer.SourceRange range = new analyzer.SourceRange(offset, length);
- return _locationForArgs(unitElement, range);
- }
-}
diff --git a/analyzer_plugin/lib/utilities/assist/assist.dart b/analyzer_plugin/lib/utilities/assist/assist.dart
deleted file mode 100644
index 4dca383..0000000
--- a/analyzer_plugin/lib/utilities/assist/assist.dart
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/assist/assist.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * An object that [AssistContributor]s use to record assists.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class AssistCollector {
- /**
- * Record a new [assist].
- */
- void addAssist(PrioritizedSourceChange assist);
-}
-
-/**
- * An object used to produce assists.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class AssistContributor {
- /**
- * Contribute assists for the location in the file specified by the given
- * [request] into the given [collector].
- */
- void computeAssists(
- covariant AssistRequest request, AssistCollector collector);
-}
-
-/**
- * A generator that will generate an 'edit.getAssists' response.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AssistGenerator {
- /**
- * The contributors to be used to generate the assists.
- */
- final List<AssistContributor> contributors;
-
- /**
- * Initialize a newly created assists generator to use the given
- * [contributors].
- */
- AssistGenerator(this.contributors);
-
- /**
- * Create an 'edit.getAssists' response for the location in the file specified
- * by the given [request]. If any of the contributors throws an exception,
- * also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult<EditGetAssistsResult> generateAssistsResponse(
- AssistRequest request) {
- List<Notification> notifications = <Notification>[];
- AssistCollectorImpl collector = new AssistCollectorImpl();
- for (AssistContributor contributor in contributors) {
- try {
- contributor.computeAssists(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- EditGetAssistsResult result = new EditGetAssistsResult(collector.assists);
- return new GeneratorResult(result, notifications);
- }
-}
-
-/**
- * A description of a class of assists. Instances are intended to hold the
- * information that is common across a number of assists and to be shared by
- * those assists.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class AssistKind {
- /**
- * The unique identifier of this kind of assist.
- */
- final String id;
-
- /**
- * The priority of this kind of assist for the kind of error being addressed.
- */
- final int priority;
-
- /**
- * A human-readable description of the changes that will be applied by this
- * kind of assist. The message can contain parameters, where each parameter is
- * represented by a zero-based index inside curly braces. For example, the
- * message `"Create a component named '{0}' in '{1}'"` contains two parameters.
- */
- final String message;
-
- /**
- * A list of any associated error codes. Assists with associated error codes
- * can be presented as "fixes" for the associated errors by clients.
- */
- final List<String> associatedErrorCodes;
-
- /**
- * Initialize a newly created kind of assist to have the given [id],
- * [priority], [message] and optionally any [associatedErrorCodes].
- */
- const AssistKind(this.id, this.priority, this.message,
- {this.associatedErrorCodes});
-
- @override
- String toString() => id;
-}
-
-/**
- * The information about a requested set of assists.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class AssistRequest {
- /**
- * Return the length of the selection within the source for which assists are
- * being requested.
- */
- int get length;
-
- /**
- * Return the offset of the selection within the source for which assists are
- * being requested.
- */
- int get offset;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
-
-/**
- * The information about a requested set of assists when computing assists in a
- * `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartAssistRequest implements AssistRequest {
- /**
- * The analysis result for the file in which the assists are being requested.
- */
- ResolvedUnitResult get result;
-}
diff --git a/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart b/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart
deleted file mode 100644
index e6c1b3f..0000000
--- a/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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/src/generated/java_core.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/utilities/assist/assist.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
-
-/**
- * A partial implementation of an [AssistContributor] that provides a utility
- * method to make it easier to add assists.
- *
- * Clients may not extend or implement this class, but are allowed to use it as
- * a mix-in when creating a subclass of [AssistContributor].
- */
-abstract class AssistContributorMixin implements AssistContributor {
- /**
- * The collector to which assists should be added.
- */
- AssistCollector get collector;
-
- /**
- * Add an assist. Use the [kind] of the assist to get the message and priority,
- * and use the change [builder] to get the edits that comprise the assist. If
- * the message has parameters, then use the list of [args] to populate the
- * message.
- */
- void addAssist(AssistKind kind, ChangeBuilder builder, {List<Object> args}) {
- SourceChange change = builder.sourceChange;
- if (change.edits.isEmpty) {
- return;
- }
- change.message = formatList(kind.message, args);
- collector.addAssist(
- new PrioritizedSourceChange(kind.priority, builder.sourceChange));
- }
-}
diff --git a/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart b/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
deleted file mode 100644
index df5b278..0000000
--- a/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
+++ /dev/null
@@ -1,183 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
-
-/**
- * A builder used to build a [SourceChange].
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class ChangeBuilder {
- /**
- * Initialize a newly created change builder.
- */
- factory ChangeBuilder() = ChangeBuilderImpl;
-
- /**
- * Return the range of the selection for the change being built, or `null` if
- * there is no selection.
- */
- SourceRange get selectionRange;
-
- /**
- * Return the source change that was built. The source change will not be
- * complete until all of the futures returned by [addFileEdit] have completed.
- */
- SourceChange get sourceChange;
-
- /**
- * Use the [buildFileEdit] function to create a collection of edits to the
- * file with the given [path]. The edits will be added to the source change
- * that is being built.
- */
- Future<void> addFileEdit(
- String path, void buildFileEdit(FileEditBuilder builder));
-
- /**
- * Set the selection for the change being built to the given [position].
- */
- void setSelection(Position position);
-}
-
-/**
- * A builder used to build a [SourceEdit] as part of a [SourceFileEdit].
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class EditBuilder {
- /**
- * Add a region of text that is part of the linked edit group with the given
- * [groupName]. The [buildLinkedEdit] function is used to write the content of
- * the region of text and to add suggestions for other possible values for
- * that region.
- */
- void addLinkedEdit(
- String groupName, void buildLinkedEdit(LinkedEditBuilder builder));
-
- /**
- * Add the given text as a linked edit group with the given [groupName]. If
- * both a [kind] and a list of [suggestions] are provided, they will be added
- * as suggestions to the group with the given kind.
- *
- * Throws an [ArgumentError] if either [kind] or [suggestions] are provided
- * without the other.
- */
- void addSimpleLinkedEdit(String groupName, String text,
- {LinkedEditSuggestionKind kind, List<String> suggestions});
-
- /**
- * Set the selection to cover all of the code written by the given [writer].
- */
- void selectAll(void writer());
-
- /**
- * Set the selection to the current location within the edit being built.
- */
- void selectHere();
-
- /**
- * Add the given [string] to the content of the current edit.
- */
- void write(String string);
-
- /**
- * Add the given [string] to the content of the current edit and then add an
- * end-of-line marker.
- */
- void writeln([String string]);
-}
-
-/**
- * A builder used to build a [SourceFileEdit] within a [SourceChange].
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class FileEditBuilder {
- /**
- * Add a deletion of text specified by the given [range]. The [range] is
- * relative to the original source. This is fully equivalent to
- *
- * addSimpleReplacement(range, '');
- */
- void addDeletion(SourceRange range);
-
- /**
- * Add an insertion of text at the given [offset]. The [offset] is relative to
- * the original source. The [buildEdit] function is used to write the text to
- * be inserted. This is fully equivalent to
- *
- * addReplacement(new SourceRange(offset, 0), buildEdit);
- */
- void addInsertion(int offset, void buildEdit(EditBuilder builder));
-
- /**
- * Add the region of text specified by the given [range] to the linked edit
- * group with the given [groupName]. The [range] is relative to the original
- * source. This is typically used to include pre-existing regions of text in a
- * group. If the region to be included is part of newly generated text, then
- * the method [EditBuilder.addLinkedEdit] should be used instead.
- */
- void addLinkedPosition(SourceRange range, String groupName);
-
- /**
- * Add a replacement of text specified by the given [range]. The [range] is
- * relative to the original source. The [buildEdit] function is used to write
- * the text that will replace the specified region.
- */
- void addReplacement(SourceRange range, void buildEdit(EditBuilder builder));
-
- /**
- * Add an insertion of the given [text] at the given [offset]. The [offset] is
- * relative to the original source. This is fully equivalent to
- *
- * addInsertion(offset, (EditBuilder builder) {
- * builder.write(text);
- * });
- */
- void addSimpleInsertion(int offset, String text);
-
- /**
- * Add a replacement of the text specified by the given [range]. The [range]
- * is relative to the original source. The original content will be replaced
- * by the given [text]. This is fully equivalent to
- *
- * addReplacement(offset, length, (EditBuilder builder) {
- * builder.write(text);
- * });
- */
- void addSimpleReplacement(SourceRange range, String text);
-}
-
-/**
- * A builder used to build a [LinkedEdit] region within an edit.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class LinkedEditBuilder {
- /**
- * Add the given [value] as a suggestion with the given [kind].
- */
- void addSuggestion(LinkedEditSuggestionKind kind, String value);
-
- /**
- * Add each of the given [values] as a suggestion with the given [kind].
- */
- void addSuggestions(LinkedEditSuggestionKind kind, Iterable<String> values);
-
- /**
- * Add the given [string] to the content of the current edit.
- */
- void write(String string);
-
- /**
- * Add the given [string] to the content of the current edit and then add an
- * end-of-line marker.
- */
- void writeln([String string]);
-}
diff --git a/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart b/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart
deleted file mode 100644
index 2df3107..0000000
--- a/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart
+++ /dev/null
@@ -1,421 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/session.dart';
-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/generated/resolver.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_dart.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
-
-/**
- * The optional generator for prefix that should be used for new imports.
- */
-typedef ImportPrefixGenerator = String Function(Uri);
-
-/**
- * A [ChangeBuilder] used to build changes in Dart files.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartChangeBuilder implements ChangeBuilder {
- /**
- * Initialize a newly created change builder.
- *
- * TODO(scheglov) Replace this constructor with using workspace.
- */
- factory DartChangeBuilder(AnalysisSession session) = DartChangeBuilderImpl;
-
- /**
- * Use the [buildFileEdit] function to create a collection of edits to the
- * file with the given [path]. The edits will be added to the source change
- * that is being built.
- *
- * If [importPrefixGenerator] is provided, it will be asked to generate an
- * import prefix for every newly imported library.
- */
- @override
- Future<void> addFileEdit(
- String path, void buildFileEdit(DartFileEditBuilder builder),
- {ImportPrefixGenerator importPrefixGenerator});
-}
-
-/**
- * An [EditBuilder] used to build edits in Dart files.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartEditBuilder implements EditBuilder {
- @override
- void addLinkedEdit(
- String groupName, void buildLinkedEdit(DartLinkedEditBuilder builder));
-
- /**
- * Write the code for a declaration of a class with the given [name]. If a
- * list of [interfaces] is provided, then the class will implement those
- * interfaces. If [isAbstract] is `true`, then the class will be abstract. If
- * a [membersWriter] is provided, then it will be invoked to allow members to
- * be generated. If a list of [mixins] is provided, then the class
- * will mix in those classes. If a [nameGroupName] is provided, then the name
- * of the class will be included in the linked edit group with that name. If a
- * [superclass] is given then it will be the superclass of the class. (If a
- * list of [mixins] is provided but no [superclass] is given then the class
- * will extend `Object`.)
- */
- void writeClassDeclaration(String name,
- {Iterable<DartType> interfaces,
- bool isAbstract: false,
- void membersWriter(),
- Iterable<DartType> mixins,
- String nameGroupName,
- DartType superclass,
- String superclassGroupName});
-
- /**
- * Write the code for a constructor declaration in the class with the given
- * [className]. If [isConst] is `true`, then the constructor will be marked
- * as being a `const` constructor. If a [constructorName] is provided, then
- * the constructor will have the given name. If both a constructor name and a
- * [constructorNameGroupName] is provided, then the name of the constructor
- * will be included in the linked edit group with that name. If a
- * [parameterWriter] is provided then it is used to write the constructor
- * parameters (enclosing parenthesis are written for you). Otherwise, if an
- * [argumentList] is provided then the constructor will have parameters that
- * match the given arguments. If no argument list is given, but a list of
- * [fieldNames] is provided, then field formal parameters will be created for
- * each of the field names. If an [initializerWriter] is provided then it is
- * used to write the constructor initializers (the ` : ` prefix is written
- * for you). If a [bodyWriter] is provided then it is used to write the
- * constructor body, otherwise an empty body is written.
- */
- void writeConstructorDeclaration(String className,
- {ArgumentList argumentList,
- void bodyWriter(),
- SimpleIdentifier constructorName,
- String constructorNameGroupName,
- List<String> fieldNames,
- void initializerWriter(),
- bool isConst: false,
- void parameterWriter()});
-
- /**
- * Write the code for a declaration of a field with the given [name]. If an
- * [initializerWriter] is provided, it will be invoked to write the content of
- * the initializer. (The equal sign separating the field name from the
- * initializer expression will automatically be written.) If [isConst] is
- * `true`, then the declaration will be preceded by the `const` keyword. If
- * [isFinal] is `true`, then the declaration will be preceded by the `final`
- * keyword. (If both [isConst] and [isFinal] are `true`, then only the `const`
- * keyword will be written.) If [isStatic] is `true`, then the declaration
- * will be preceded by the `static` keyword. If a [nameGroupName] is
- * provided, the name of the field will be included in the linked edit group
- * with that name. If a [type] is provided, then it will be used as the type
- * of the field. (The keyword `var` will be provided automatically when
- * required.) If a [typeGroupName] is provided, then if a type was written
- * it will be in the linked edit group with that name.
- */
- void writeFieldDeclaration(String name,
- {void initializerWriter(),
- bool isConst: false,
- bool isFinal: false,
- bool isStatic: false,
- String nameGroupName,
- DartType type,
- String typeGroupName});
-
- /**
- * Write the code for a declaration of a function with the given [name]. If a
- * [bodyWriter] is provided, it will be invoked to write the body of the
- * function. (The space between the name and the body will automatically be
- * written.) If [isStatic] is `true`, then the declaration will be preceded
- * by the `static` keyword. If a [nameGroupName] is provided, the name of the
- * function will be included in the linked edit group with that name. If a
- * [returnType] is provided, then it will be used as the return type of the
- * function. If a [returnTypeGroupName] is provided, then if a return type was
- * written it will be in the linked edit group with that name. If a
- * [parameterWriter] is provided, then it will be invoked to write the
- * declarations of the parameters to the function. (The parentheses around the
- * parameters will automatically be written.)
- */
- void writeFunctionDeclaration(String name,
- {void bodyWriter(),
- bool isStatic: false,
- String nameGroupName,
- void parameterWriter(),
- DartType returnType,
- String returnTypeGroupName});
-
- /**
- * Write the code for a declaration of a getter with the given [name]. If a
- * [bodyWriter] is provided, it will be invoked to write the body of the
- * getter. (The space between the name and the body will automatically be
- * written.) If [isStatic] is `true`, then the declaration will be preceded
- * by the `static` keyword. If a [nameGroupName] is provided, the name of the
- * getter will be included in the linked edit group with that name. If a
- * [returnType] is provided, then it will be used as the return type of the
- * getter. If a [returnTypeGroupName] is provided, then if a return type was
- * written it will be in the linked edit group with that name.
- */
- void writeGetterDeclaration(String name,
- {void bodyWriter(),
- bool isStatic: false,
- String nameGroupName,
- DartType returnType,
- String returnTypeGroupName});
-
- /**
- * Write the code for a declaration of a local variable with the given [name].
- * If an [initializerWriter] is provided, it will be invoked to write the
- * content of the initializer. (The equal sign separating the variable name
- * from the initializer expression will automatically be written.) If
- * [isConst] is `true`, then the declaration will be preceded by the `const`
- * keyword. If [isFinal] is `true`, then the declaration will be preceded by
- * the `final` keyword. (If both [isConst] and [isFinal] are `true`, then only
- * the `const` keyword will be written.) If a [nameGroupName] is provided, the
- * name of the variable will be included in the linked edit group with that
- * name. If a [type] is provided, then it will be used as the type of the
- * variable. (The keyword `var` will be provided automatically when required.)
- * If a [typeGroupName] is provided, then if a type was written it will be in
- * the linked edit group with that name.
- */
- void writeLocalVariableDeclaration(String name,
- {void initializerWriter(),
- bool isConst: false,
- bool isFinal: false,
- String nameGroupName,
- DartType type,
- String typeGroupName});
-
- /**
- * Write the code for a declaration of a mixin with the given [name]. If a
- * list of [interfaces] is provided, then the mixin will implement those
- * interfaces. If a [membersWriter] is provided, then it will be invoked to
- * allow members to be generated. If a [nameGroupName] is provided, then the
- * name of the class will be included in the linked edit group with that name.
- */
- void writeMixinDeclaration(String name,
- {Iterable<DartType> interfaces,
- void membersWriter(),
- String nameGroupName,
- Iterable<DartType> superclassConstraints});
-
- /**
- * Append a placeholder for an override of the specified inherited
- * [element]. If provided, write a string value suitable for display
- * (e.g., in a completion popup) in the given [displayTextBuffer].
- * If [invokeSuper] is `true`, then the corresponding `super.name()` will be
- * added in the body.
- */
- void writeOverride(
- ExecutableElement element, {
- StringBuffer displayTextBuffer,
- bool invokeSuper: false,
- });
-
- /**
- * Write the code for a single parameter with the given [name].
- *
- * If a [methodBeingCopied] is provided, then type parameters defined by that
- * method are assumed to be part of what is being written and hence valid
- * types.
- *
- * If a [type] is provided, then it will be used as the type of the parameter.
- */
- void writeParameter(String name,
- {ExecutableElement methodBeingCopied, DartType type});
-
- /**
- * Write the code for a parameter that would match the given [argument]. The
- * name of the parameter will be generated based on the type of the argument,
- * but if the argument type is not known the [index] will be used to compose
- * a name. In any case, the set of [usedNames] will be used to ensure that the
- * name is unique (and the chosen name will be added to the set).
- */
- void writeParameterMatchingArgument(
- Expression argument, int index, Set<String> usedNames);
-
- /**
- * Write the code for a list of [parameters], including the surrounding
- * parentheses.
- *
- * If a [methodBeingCopied] is provided, then type parameters defined by that
- * method are assumed to be part of what is being written and hence valid
- * types.
- */
- void writeParameters(Iterable<ParameterElement> parameters,
- {ExecutableElement methodBeingCopied});
-
- /**
- * Write the code for a list of parameters that would match the given list of
- * [arguments]. The surrounding parentheses are *not* written.
- */
- void writeParametersMatchingArguments(ArgumentList arguments);
-
- /**
- * Write the code that references the [element]. If the [element] is a
- * top-level element that has not been imported into the current library,
- * imports will be updated.
- */
- void writeReference(Element element);
-
- /**
- * Write the code for a declaration of a setter with the given [name]. If a
- * [bodyWriter] is provided, it will be invoked to write the body of the
- * setter. (The space between the name and the body will automatically be
- * written.) If [isStatic] is `true`, then the declaration will be preceded
- * by the `static` keyword. If a [nameGroupName] is provided, the name of the
- * getter will be included in the linked edit group with that name. If a
- * [parameterType] is provided, then it will be used as the type of the
- * parameter. If a [parameterTypeGroupName] is provided, then if a parameter
- * type was written it will be in the linked edit group with that name.
- */
- void writeSetterDeclaration(String name,
- {void bodyWriter(),
- bool isStatic: false,
- String nameGroupName,
- DartType parameterType,
- String parameterTypeGroupName});
-
- /**
- * Write the code for a type annotation for the given [type]. If the [type] is
- * either `null` or represents the type 'dynamic', then the behavior depends
- * on whether a type is [required]. If [required] is `true`, then 'var' will
- * be written; otherwise, nothing is written.
- *
- * If the [groupName] is not `null`, then the name of the type (including type
- * parameters) will be included as a region in the linked edit group with that
- * name. If the [groupName] is not `null` and [addSupertypeProposals] is
- * `true`, then all of the supertypes of the [type] will be added as
- * suggestions for alternatives to the type name.
- *
- * If a [methodBeingCopied] is provided, then type parameters defined by that
- * method are assumed to be part of what is being written and hence valid
- * types.
- *
- * Return `true` if some text was written.
- */
- bool writeType(DartType type,
- {bool addSupertypeProposals: false,
- String groupName,
- ExecutableElement methodBeingCopied,
- bool required: false});
-
- /**
- * Write the code to declare the given [typeParameter]. The enclosing angle
- * brackets are not automatically written.
- *
- * If a [methodBeingCopied] is provided, then type parameters defined by that
- * method are assumed to be part of what is being written and hence valid
- * types.
- */
- void writeTypeParameter(TypeParameterElement typeParameter,
- {ExecutableElement methodBeingCopied});
-
- /**
- * Write the code to declare the given list of [typeParameters]. The enclosing
- * angle brackets are automatically written.
- *
- * If a [methodBeingCopied] is provided, then type parameters defined by that
- * method are assumed to be part of what is being written and hence valid
- * types.
- */
- void writeTypeParameters(List<TypeParameterElement> typeParameters,
- {ExecutableElement methodBeingCopied});
-
- /**
- * Write the code for a comma-separated list of [types], optionally prefixed
- * by a [prefix]. If the list of [types] is `null` or does not contain any
- * types, then nothing will be written.
- */
- void writeTypes(Iterable<DartType> types, {String prefix});
-}
-
-/**
- * A [FileEditBuilder] used to build edits for Dart files.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartFileEditBuilder implements FileEditBuilder {
- @override
- void addInsertion(int offset, void buildEdit(DartEditBuilder builder));
-
- @override
- void addReplacement(
- SourceRange range, void buildEdit(DartEditBuilder builder));
-
- /**
- * Create one or more edits that will convert the given function [body] from
- * being synchronous to be asynchronous. This includes adding the `async`
- * modifier to the body as well as potentially replacing the return type of
- * the function to `Future`.
- *
- * There is currently a limitation in that the function body must not be a
- * generator.
- *
- * Throws an [ArgumentError] if the function body is not both synchronous and
- * a non-generator.
- */
- void convertFunctionFromSyncToAsync(
- FunctionBody body, TypeProvider typeProvider);
-
- /**
- * Format the code covered by the [range].
- *
- * If there are any edits that are in the [range], these edits are applied
- * first, and replaced with a single new edit that produces the resulting
- * formatted code. The [range] is relative to the original code.
- */
- void format(SourceRange range);
-
- /**
- * Arrange to have an import added for the library with the given [uri].
- *
- * Returns the text of the URI that will be used in the import directive.
- * It can be different than the given [Uri].
- */
- String importLibrary(Uri uri);
-
- /**
- * Ensure that the library with the given [uri] is imported.
- *
- * If there is already an import for the requested library, return the import
- * prefix of the existing import directive.
- *
- * If there is no existing import, a new import is added.
- */
- ImportLibraryElementResult importLibraryElement(Uri uri);
-
- /**
- * Optionally create an edit to replace the given [typeAnnotation] with the
- * type `Future` (with the given type annotation as the type argument). The
- * [typeProvider] is used to check the current type, because if it is already
- * `Future` no edit will be added.
- */
- void replaceTypeWithFuture(
- TypeAnnotation typeAnnotation, TypeProvider typeProvider);
-}
-
-/**
- * A [LinkedEditBuilder] used to build linked edits for Dart files.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartLinkedEditBuilder implements LinkedEditBuilder {
- /**
- * Add the given [type] and all of its supertypes (other than mixins) as
- * suggestions for the current linked edit group.
- */
- void addSuperTypesAsSuggestions(DartType type);
-}
-
-/// Information about a library to import.
-abstract class ImportLibraryElementResult {
- /// If the library is already imported with a prefix, or should be imported
- /// with a prefix, the prefix name (without `.`). Otherwise `null`.
- String get prefix;
-}
diff --git a/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart b/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart
deleted file mode 100644
index a0f4469..0000000
--- a/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/session.dart';
-
-/// Information about the workspace in which change builders operate.
-abstract class ChangeWorkspace {
- /// Return `true` if the file with the given [path] is in a context root.
- bool containsFile(String path);
-
- /// Return the session that should analyze the given [path], or throw
- /// [StateError] if the [path] does not belong to a context root.
- AnalysisSession getSession(String path);
-}
diff --git a/analyzer_plugin/lib/utilities/completion/completion_core.dart b/analyzer_plugin/lib/utilities/completion/completion_core.dart
deleted file mode 100644
index 970306d..0000000
--- a/analyzer_plugin/lib/utilities/completion/completion_core.dart
+++ /dev/null
@@ -1,164 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/completion/completion_core.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * An exception that is thrown when the current completion request should be
- * aborted because either the source changed since the request was made, or
- * a new completion request was received. See [CompletionRequest.checkAborted].
- */
-class AbortCompletion {}
-
-/**
- * An object that [CompletionContributor]s use to record completion suggestions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class CompletionCollector {
- /**
- * Set the length of the region of text that should be replaced by the
- * selected completion suggestion.
- *
- * The length can only be set once and applies to all of the suggestions.
- * Hence, this setter throws a [StateError] if the length has already been
- * set.
- */
- set length(int length);
-
- /**
- * Set the offset of the region of text that should be replaced by the
- * selected completion suggestion.
- *
- * The offset can only be set once and applies to all of the suggestions.
- * Hence, this setter throws a [StateError] if the offset has already been
- * set.
- */
- set offset(int offset);
-
- /**
- * Indicates if the collector's offset has been set (and ultimately the
- * length too).
- */
- bool get offsetIsSet;
-
- /**
- * Returns length of suggestions currently held.
- */
- int get suggestionsLength;
-
- /**
- * Record the given completion [suggestion].
- */
- void addSuggestion(CompletionSuggestion suggestion);
-}
-
-/**
- * An object used to produce completion suggestions.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class CompletionContributor {
- /**
- * Contribute completion suggestions for the completion location specified by
- * the given [request] into the given [collector].
- */
- Future<void> computeSuggestions(
- covariant CompletionRequest request, CompletionCollector collector);
-}
-
-/**
- * A generator that will generate a 'completion.getSuggestions' response.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class CompletionGenerator {
- /**
- * The contributors to be used to generate the completion suggestions.
- */
- final List<CompletionContributor> contributors;
-
- /**
- * Initialize a newly created completion generator.
- */
- CompletionGenerator(this.contributors);
-
- /**
- * Create a 'completion.getSuggestions' response for the file with the given
- * [path]. If any of the contributors throws an exception, also create a
- * non-fatal 'plugin.error' notification.
- */
- Future<GeneratorResult<CompletionGetSuggestionsResult>>
- generateCompletionResponse(CompletionRequest request) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- List<Notification> notifications = <Notification>[];
- CompletionCollectorImpl collector = new CompletionCollectorImpl();
- try {
- for (CompletionContributor contributor in contributors) {
- request.checkAborted();
- try {
- await contributor.computeSuggestions(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- } on AbortCompletion {
- return new GeneratorResult(null, notifications);
- }
- collector.offset ??= request.offset;
- collector.length ??= 0;
-
- CompletionGetSuggestionsResult result = new CompletionGetSuggestionsResult(
- collector.offset, collector.length, collector.suggestions);
- return new GeneratorResult(result, notifications);
- }
-}
-
-/**
- * The information about a requested list of completions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class CompletionRequest {
- /**
- * Return the offset within the source at which the completion is being
- * requested.
- */
- int get offset;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-
- /**
- * Throw an [AbortCompletion] if the completion request has been aborted.
- */
- void checkAborted();
-}
-
-/**
- * The information about a requested list of completions when completing in a
- * `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartCompletionRequest implements CompletionRequest {
- /**
- * The analysis result for the file in which the completion is being
- * requested.
- */
- ResolvedUnitResult get result;
-}
diff --git a/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart b/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart
deleted file mode 100644
index 9e16b8f..0000000
--- a/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart
+++ /dev/null
@@ -1,171 +0,0 @@
-// 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:async';
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Element;
-import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart';
-import 'package:analyzer_plugin/src/utilities/completion/element_suggestion_builder.dart';
-import 'package:analyzer_plugin/src/utilities/completion/optype.dart';
-import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
-
-/**
- * A contributor for calculating suggestions for inherited references.
- *
- * Plugin developers should extend this function and primarily
- * overload `computeSuggestions` (if needed).
- */
-class InheritedReferenceContributor
- with ElementSuggestionBuilder
- implements CompletionContributor {
- @override
- LibraryElement containingLibrary;
-
- @override
- CompletionSuggestionKind kind;
-
- @override
- ResourceProvider resourceProvider;
-
- /**
- * Plugin contributors should primarily overload this function.
- * Should more parameters be needed for autocompletion needs, the
- * overloaded function should define those parameters and
- * call on `computeSuggestionsForClass`.
- */
- @override
- Future<void> computeSuggestions(
- DartCompletionRequest request, CompletionCollector collector) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- CompletionTarget target =
- new CompletionTarget.forOffset(request.result.unit, request.offset);
- OpType optype = new OpType.forCompletion(target, request.offset);
- if (!optype.includeIdentifiers) {
- return;
- }
- ClassDeclaration classDecl = _enclosingClass(target);
- if (classDecl == null || classDecl.declaredElement == null) {
- return;
- }
- containingLibrary = request.result.libraryElement;
- _computeSuggestionsForClass2(
- collector, target, classDecl.declaredElement, optype);
- }
-
- /**
- * Clients should not overload this function.
- */
- Future<void> computeSuggestionsForClass(
- DartCompletionRequest request,
- CompletionCollector collector,
- ClassElement classElement, {
- AstNode entryPoint,
- bool skipChildClass,
- CompletionTarget target,
- OpType optype,
- }) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- target ??= new CompletionTarget.forOffset(
- request.result.unit, request.offset,
- entryPoint: entryPoint);
- optype ??= new OpType.forCompletion(target, request.offset);
- if (!optype.includeIdentifiers) {
- return;
- }
- if (classElement == null) {
- ClassDeclaration classDecl = _enclosingClass(target);
- if (classDecl == null || classDecl.declaredElement == null) {
- return;
- }
- classElement = classDecl.declaredElement;
- }
- containingLibrary = request.result.libraryElement;
- _computeSuggestionsForClass2(collector, target, classElement, optype,
- skipChildClass: skipChildClass);
- }
-
- _addSuggestionsForType(InterfaceType type, OpType optype,
- {bool isFunctionalArgument: false}) {
- if (!isFunctionalArgument) {
- for (PropertyAccessorElement elem in type.accessors) {
- if (elem.isGetter) {
- if (optype.includeReturnValueSuggestions) {
- addSuggestion(elem);
- }
- } else {
- if (optype.includeVoidReturnSuggestions) {
- addSuggestion(elem);
- }
- }
- }
- }
- for (MethodElement elem in type.methods) {
- if (elem.returnType == null) {
- addSuggestion(elem);
- } else if (!elem.returnType.isVoid) {
- if (optype.includeReturnValueSuggestions) {
- addSuggestion(elem);
- }
- } else {
- if (optype.includeVoidReturnSuggestions) {
- addSuggestion(elem);
- }
- }
- }
- }
-
- void _computeSuggestionsForClass2(CompletionCollector collector,
- CompletionTarget target, ClassElement classElement, OpType optype,
- {bool skipChildClass: true}) {
- bool isFunctionalArgument = target.isFunctionalArgument();
- kind = isFunctionalArgument
- ? CompletionSuggestionKind.IDENTIFIER
- : CompletionSuggestionKind.INVOCATION;
-
- if (!skipChildClass) {
- _addSuggestionsForType(classElement.thisType, optype,
- isFunctionalArgument: isFunctionalArgument);
- }
-
- for (InterfaceType type in classElement.allSupertypes) {
- _addSuggestionsForType(type, optype,
- isFunctionalArgument: isFunctionalArgument);
- }
- for (CompletionSuggestion suggestion in suggestions) {
- collector.addSuggestion(suggestion);
- }
- }
-
- /**
- * Return the class containing the target
- * or `null` if the target is in a static method or field
- * or not in a class.
- */
- ClassDeclaration _enclosingClass(CompletionTarget target) {
- AstNode node = target.containingNode;
- while (node != null) {
- if (node is ClassDeclaration) {
- return node;
- }
- if (node is MethodDeclaration) {
- if (node.isStatic) {
- return null;
- }
- }
- if (node is FieldDeclaration) {
- if (node.isStatic) {
- return null;
- }
- }
- node = node.parent;
- }
- return null;
- }
-}
diff --git a/analyzer_plugin/lib/utilities/completion/relevance.dart b/analyzer_plugin/lib/utilities/completion/relevance.dart
deleted file mode 100644
index eca6b97..0000000
--- a/analyzer_plugin/lib/utilities/completion/relevance.dart
+++ /dev/null
@@ -1,37 +0,0 @@
-// 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.
-
-//
-// Constant values used for relevance values when creating completion
-// suggestions in Dart code.
-//
-
-/// The relevance boost for available declarations with the matching tag.
-const int DART_RELEVANCE_BOOST_AVAILABLE_DECLARATION = 10;
-
-/// The relevance boost for available enum constants with the matching tag.
-///
-/// It is so large to move enum constants to the very top.
-const int DART_RELEVANCE_BOOST_AVAILABLE_ENUM = 1100;
-
-const int DART_RELEVANCE_BOOST_SUBTYPE = 100;
-const int DART_RELEVANCE_BOOST_TYPE = 200;
-const int DART_RELEVANCE_COMMON_USAGE = 1200;
-const int DART_RELEVANCE_DEFAULT = 1000;
-const int DART_RELEVANCE_HIGH = 2000;
-const int DART_RELEVANCE_INHERITED_ACCESSOR = 1057;
-const int DART_RELEVANCE_INHERITED_FIELD = 1058;
-const int DART_RELEVANCE_INHERITED_METHOD = 1057;
-const int DART_RELEVANCE_KEYWORD = 1055;
-const int DART_RELEVANCE_LOCAL_ACCESSOR = 1057;
-const int DART_RELEVANCE_LOCAL_FIELD = 1058;
-const int DART_RELEVANCE_LOCAL_FUNCTION = 1056;
-const int DART_RELEVANCE_LOCAL_METHOD = 1057;
-const int DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE = 1056;
-const int DART_RELEVANCE_LOCAL_VARIABLE = 1059;
-const int DART_RELEVANCE_LOW = 500;
-const int DART_RELEVANCE_NAMED_PARAMETER = 1060;
-const int DART_RELEVANCE_NAMED_PARAMETER_REQUIRED = 1065;
-const int DART_RELEVANCE_PARAMETER = 1059;
-const int DART_RELEVANCE_TYPE_PARAMETER = 1058;
diff --git a/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart b/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart
deleted file mode 100644
index 3ad0713..0000000
--- a/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Element;
-import 'package:analyzer_plugin/utilities/completion/relevance.dart';
-
-/**
- * An object used to build code completion suggestions for Dart code.
- */
-abstract class SuggestionBuilder {
- /**
- * Return a suggestion based on the given [element], or `null` if a suggestion
- * is not appropriate for the given element.
- */
- CompletionSuggestion forElement(Element element,
- {String completion,
- CompletionSuggestionKind kind: CompletionSuggestionKind.INVOCATION,
- int relevance: DART_RELEVANCE_DEFAULT});
-}
diff --git a/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart b/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart
deleted file mode 100644
index eb6ee1c..0000000
--- a/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart
+++ /dev/null
@@ -1,517 +0,0 @@
-// 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:async';
-import 'dart:collection';
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Element;
-import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart';
-import 'package:analyzer_plugin/src/utilities/completion/suggestion_builder.dart';
-import 'package:analyzer_plugin/src/utilities/visitors/local_declaration_visitor.dart';
-import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
-import 'package:analyzer_plugin/utilities/completion/relevance.dart';
-import 'package:analyzer_plugin/utilities/completion/suggestion_builder.dart';
-
-/**
- * A completion contributor that will generate suggestions for instance
- * invocations and accesses.
- */
-class TypeMemberContributor implements CompletionContributor {
- /**
- * Plugin contributors should primarily overload this function.
- * Should more parameters be needed for autocompletion needs, the
- * overloaded function should define those parameters and
- * call on `computeSuggestionsWithEntryPoint`.
- */
- @override
- Future<void> computeSuggestions(
- DartCompletionRequest request, CompletionCollector collector) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- LibraryElement containingLibrary = request.result.libraryElement;
- // Gracefully degrade if the library element is not resolved
- // e.g. detached part file or source change
- if (containingLibrary == null) {
- return;
- }
-
- // Recompute the target since resolution may have changed it
- Expression expression = _computeDotTarget(request, null);
- if (expression == null || expression.isSynthetic) {
- return;
- }
- _computeSuggestions(request, collector, containingLibrary, expression);
- }
-
- /**
- * Clients should not overload this function.
- */
- Future<void> computeSuggestionsWithEntryPoint(DartCompletionRequest request,
- CompletionCollector collector, AstNode entryPoint) async {
- // TODO(brianwilkerson) Determine whether this await is necessary.
- await null;
- LibraryElement containingLibrary = request.result.libraryElement;
- // Gracefully degrade if the library element is not resolved
- // e.g. detached part file or source change
- if (containingLibrary == null) {
- return;
- }
-
- // Recompute the target since resolution may have changed it
- Expression expression = _computeDotTarget(request, entryPoint);
- if (expression == null || expression.isSynthetic) {
- return;
- }
- _computeSuggestions(request, collector, containingLibrary, expression);
- }
-
- /**
- * Update the completion [target] and [dotTarget] based on the given [unit].
- */
- Expression _computeDotTarget(
- DartCompletionRequest request, AstNode entryPoint) {
- CompletionTarget target = new CompletionTarget.forOffset(
- request.result.unit, request.offset,
- entryPoint: entryPoint);
- AstNode node = target.containingNode;
- if (node is MethodInvocation) {
- if (identical(node.methodName, target.entity)) {
- return node.realTarget;
- } else if (node.isCascaded && node.operator.offset + 1 == target.offset) {
- return node.realTarget;
- }
- }
- if (node is PropertyAccess) {
- if (identical(node.propertyName, target.entity)) {
- return node.realTarget;
- } else if (node.isCascaded && node.operator.offset + 1 == target.offset) {
- return node.realTarget;
- }
- }
- if (node is PrefixedIdentifier) {
- if (identical(node.identifier, target.entity)) {
- return node.prefix;
- }
- }
- return null;
- }
-
- void _computeSuggestions(
- DartCompletionRequest request,
- CompletionCollector collector,
- LibraryElement containingLibrary,
- Expression expression) {
- if (expression is Identifier) {
- Element element = expression.staticElement;
- if (element is ClassElement) {
- // Suggestions provided by StaticMemberContributor
- return;
- }
- if (element is PrefixElement) {
- // Suggestions provided by LibraryMemberContributor
- return;
- }
- }
-
- // Determine the target expression's type
- DartType type = expression.staticType;
- if (type == null || type.isDynamic) {
- // If the expression does not provide a good type
- // then attempt to get a better type from the element
- if (expression is Identifier) {
- Element elem = expression.staticElement;
- if (elem is FunctionTypedElement) {
- type = elem.returnType;
- } else if (elem is ParameterElement) {
- type = elem.type;
- } else if (elem is LocalVariableElement) {
- type = elem.type;
- }
- if ((type == null || type.isDynamic) &&
- expression is SimpleIdentifier) {
- // If the element does not provide a good type
- // then attempt to get a better type from a local declaration
- _LocalBestTypeVisitor visitor =
- new _LocalBestTypeVisitor(expression.name, request.offset);
- if (visitor.visit(expression) && visitor.typeFound != null) {
- type = visitor.typeFound;
- }
- }
- }
- }
- String containingMethodName;
- if (expression is SuperExpression && type is InterfaceType) {
- // Suggest members from superclass if target is "super"
- type = (type as InterfaceType).superclass;
- // Determine the name of the containing method because
- // the most likely completion is a super expression with same name
- MethodDeclaration containingMethod =
- expression.thisOrAncestorOfType<MethodDeclaration>();
- if (containingMethod != null) {
- SimpleIdentifier id = containingMethod.name;
- if (id != null) {
- containingMethodName = id.name;
- }
- }
- }
- if (type == null || type.isDynamic) {
- // Suggest members from object if target is "dynamic"
- type = request.result.typeProvider.objectType;
- }
-
- // Build the suggestions
- if (type is InterfaceType) {
- _SuggestionBuilder builder = new _SuggestionBuilder(
- request.resourceProvider, collector, containingLibrary);
- builder.buildSuggestions(type, containingMethodName);
- }
- }
-}
-
-/**
- * An [AstVisitor] which looks for a declaration with the given name
- * and if found, tries to determine a type for that declaration.
- */
-class _LocalBestTypeVisitor extends LocalDeclarationVisitor {
- /**
- * The name for the declaration to be found.
- */
- final String targetName;
-
- /**
- * The best type for the found declaration,
- * or `null` if no declaration found or failed to determine a type.
- */
- DartType typeFound;
-
- /**
- * Construct a new instance to search for a declaration
- */
- _LocalBestTypeVisitor(this.targetName, int offset) : super(offset);
-
- @override
- void declaredClass(ClassDeclaration declaration) {
- if (declaration.name.name == targetName) {
- // no type
- finished();
- }
- }
-
- @override
- void declaredClassTypeAlias(ClassTypeAlias declaration) {
- if (declaration.name.name == targetName) {
- // no type
- finished();
- }
- }
-
- @override
- void declaredExtension(ExtensionDeclaration declaration) {}
-
- @override
- void declaredField(FieldDeclaration fieldDecl, VariableDeclaration varDecl) {
- if (varDecl.name.name == targetName) {
- // Type provided by the element in computeFull above
- finished();
- }
- }
-
- @override
- void declaredFunction(FunctionDeclaration declaration) {
- if (declaration.name.name == targetName) {
- TypeAnnotation typeName = declaration.returnType;
- if (typeName != null) {
- typeFound = typeName.type;
- }
- finished();
- }
- }
-
- @override
- void declaredFunctionTypeAlias(FunctionTypeAlias declaration) {
- if (declaration.name.name == targetName) {
- TypeAnnotation typeName = declaration.returnType;
- if (typeName != null) {
- typeFound = typeName.type;
- }
- finished();
- }
- }
-
- @override
- void declaredGenericTypeAlias(GenericTypeAlias declaration) {
- if (declaration.name.name == targetName) {
- TypeAnnotation typeName = declaration.functionType.returnType;
- if (typeName != null) {
- typeFound = typeName.type;
- }
- finished();
- }
- }
-
- @override
- void declaredLabel(Label label, bool isCaseLabel) {
- if (label.label.name == targetName) {
- // no type
- finished();
- }
- }
-
- @override
- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) {
- if (name.name == targetName) {
- typeFound = name.staticType;
- finished();
- }
- }
-
- @override
- void declaredMethod(MethodDeclaration declaration) {
- if (declaration.name.name == targetName) {
- TypeAnnotation typeName = declaration.returnType;
- if (typeName != null) {
- typeFound = typeName.type;
- }
- finished();
- }
- }
-
- @override
- void declaredParam(SimpleIdentifier name, TypeAnnotation type) {
- if (name.name == targetName) {
- // Type provided by the element in computeFull above
- finished();
- }
- }
-
- @override
- void declaredTopLevelVar(
- VariableDeclarationList varList, VariableDeclaration varDecl) {
- if (varDecl.name.name == targetName) {
- // Type provided by the element in computeFull above
- finished();
- }
- }
-}
-
-/**
- * This class provides suggestions based upon the visible instance members in
- * an interface type.
- */
-class _SuggestionBuilder {
- /**
- * Enumerated value indicating that we have not generated any completions for
- * a given identifier yet.
- */
- static const int _COMPLETION_TYPE_NONE = 0;
-
- /**
- * Enumerated value indicating that we have generated a completion for a
- * getter.
- */
- static const int _COMPLETION_TYPE_GETTER = 1;
-
- /**
- * Enumerated value indicating that we have generated a completion for a
- * setter.
- */
- static const int _COMPLETION_TYPE_SETTER = 2;
-
- /**
- * Enumerated value indicating that we have generated a completion for a
- * field, a method, or a getter/setter pair.
- */
- static const int _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET = 3;
-
- /**
- * The resource provider used to access the file system.
- */
- final ResourceProvider resourceProvider;
-
- /**
- * The collector being used to collect completion suggestions.
- */
- final CompletionCollector collector;
-
- /**
- * The library containing the unit in which the completion is requested.
- */
- final LibraryElement containingLibrary;
-
- /**
- * Map indicating, for each possible completion identifier, whether we have
- * already generated completions for a getter, setter, or both. The "both"
- * case also handles the case where have generated a completion for a method
- * or a field.
- *
- * Note: the enumerated values stored in this map are intended to be bitwise
- * compared.
- */
- Map<String, int> _completionTypesGenerated = new HashMap<String, int>();
-
- /**
- * Map from completion identifier to completion suggestion
- */
- Map<String, CompletionSuggestion> _suggestionMap =
- <String, CompletionSuggestion>{};
-
- /**
- * The builder used to build suggestions.
- */
- final SuggestionBuilder builder;
-
- _SuggestionBuilder(
- this.resourceProvider, this.collector, this.containingLibrary)
- : builder = new SuggestionBuilderImpl(resourceProvider);
-
- Iterable<CompletionSuggestion> get suggestions => _suggestionMap.values;
-
- /**
- * Create completion suggestions for 'dot' completions on the given [type].
- * If the 'dot' completion is a super expression, then [containingMethodName]
- * is the name of the method in which the completion is requested.
- */
- void buildSuggestions(InterfaceType type, String containingMethodName) {
- // Visit all of the types in the class hierarchy, collecting possible
- // completions. If multiple elements are found that complete to the same
- // identifier, addSuggestion will discard all but the first (with a few
- // exceptions to handle getter/setter pairs).
- List<InterfaceType> types = _getTypeOrdering(type);
- for (InterfaceType targetType in types) {
- for (MethodElement method in targetType.methods) {
- // Exclude static methods when completion on an instance
- if (!method.isStatic) {
- // Boost the relevance of a super expression
- // calling a method of the same name as the containing method
- _addSuggestion(method,
- relevance: method.name == containingMethodName
- ? DART_RELEVANCE_HIGH
- : null);
- }
- }
- for (PropertyAccessorElement propertyAccessor in targetType.accessors) {
- if (!propertyAccessor.isStatic) {
- if (propertyAccessor.isSynthetic) {
- // Avoid visiting a field twice
- if (propertyAccessor.isGetter) {
- _addSuggestion(propertyAccessor.variable);
- }
- } else {
- _addSuggestion(propertyAccessor);
- }
- }
- }
- }
- for (CompletionSuggestion suggestion in suggestions) {
- collector.addSuggestion(suggestion);
- }
- }
-
- /**
- * Add a suggestion based upon the given element, provided that it is not
- * shadowed by a previously added suggestion.
- */
- void _addSuggestion(Element element, {int relevance}) {
- if (element.isPrivate) {
- if (element.library != containingLibrary) {
- // Do not suggest private members for imported libraries
- return;
- }
- }
- String identifier = element.displayName;
-
- if (relevance == null) {
- // Decrease relevance of suggestions starting with $
- // https://github.com/dart-lang/sdk/issues/27303
- if (identifier != null && identifier.startsWith(r'$')) {
- relevance = DART_RELEVANCE_LOW;
- } else {
- relevance = DART_RELEVANCE_DEFAULT;
- }
- }
-
- int alreadyGenerated = _completionTypesGenerated.putIfAbsent(
- identifier, () => _COMPLETION_TYPE_NONE);
- if (element is MethodElement) {
- // Anything shadows a method.
- if (alreadyGenerated != _COMPLETION_TYPE_NONE) {
- return;
- }
- _completionTypesGenerated[identifier] =
- _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET;
- } else if (element is PropertyAccessorElement) {
- if (element.isGetter) {
- // Getters, fields, and methods shadow a getter.
- if ((alreadyGenerated & _COMPLETION_TYPE_GETTER) != 0) {
- return;
- }
- _completionTypesGenerated[identifier] |= _COMPLETION_TYPE_GETTER;
- } else {
- // Setters, fields, and methods shadow a setter.
- if ((alreadyGenerated & _COMPLETION_TYPE_SETTER) != 0) {
- return;
- }
- _completionTypesGenerated[identifier] |= _COMPLETION_TYPE_SETTER;
- }
- } else if (element is FieldElement) {
- // Fields and methods shadow a field. A getter/setter pair shadows a
- // field, but a getter or setter by itself doesn't.
- if (alreadyGenerated == _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET) {
- return;
- }
- _completionTypesGenerated[identifier] =
- _COMPLETION_TYPE_FIELD_OR_METHOD_OR_GETSET;
- } else {
- // Unexpected element type; skip it.
- assert(false);
- return;
- }
- CompletionSuggestion suggestion =
- builder.forElement(element, relevance: relevance);
- if (suggestion != null) {
- _suggestionMap[suggestion.completion] = suggestion;
- }
- }
-
- /**
- * Get a list of [InterfaceType]s that should be searched to find the
- * possible completions for an object having type [type].
- */
- List<InterfaceType> _getTypeOrdering(InterfaceType type) {
- // Candidate completions can come from [type] as well as any types above it
- // in the class hierarchy (including mixins, superclasses, and interfaces).
- // If a given completion identifier shows up in multiple types, we should
- // use the element that is nearest in the superclass chain, so we will
- // visit [type] first, then its mixins, then its superclass, then its
- // superclass's mixins, etc., and only afterwards visit interfaces.
- //
- // We short-circuit loops in the class hierarchy by keeping track of the
- // classes seen (not the interfaces) so that we won't be fooled by nonsense
- // like "class C<T> extends C<List<T>> {}"
- List<InterfaceType> result = <InterfaceType>[];
- Set<ClassElement> classesSeen = new HashSet<ClassElement>();
- List<InterfaceType> typesToVisit = <InterfaceType>[type];
- while (typesToVisit.isNotEmpty) {
- InterfaceType nextType = typesToVisit.removeLast();
- if (!classesSeen.add(nextType.element)) {
- // Class had already been seen, so ignore this type.
- continue;
- }
- result.add(nextType);
- // typesToVisit is a stack, so push on the interfaces first, then the
- // superclass, then the mixins. This will ensure that they are visited
- // in the reverse order.
- typesToVisit.addAll(nextType.interfaces);
- if (nextType.superclass != null) {
- typesToVisit.add(nextType.superclass);
- }
- typesToVisit.addAll(nextType.mixins);
- }
- return result;
- }
-}
diff --git a/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart b/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart
deleted file mode 100644
index add68df..0000000
--- a/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/error/error.dart';
-import 'package:analyzer/src/generated/java_core.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
-import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
-
-/**
- * A partial implementation of a [FixContributor] that iterates over the list of
- * errors and provides a utility method to make it easier to add fixes.
- *
- * Clients may not extend or implement this class, but are allowed to use it as
- * a mix-in when creating a subclass of [FixContributor].
- */
-abstract class FixContributorMixin implements FixContributor {
- /**
- * The request that specifies the fixes that are to be built.
- */
- DartFixesRequest request;
-
- /**
- * The collector to which fixes should be added.
- */
- FixCollector collector;
-
- /**
- * Add a fix for the given [error]. Use the [kind] of the fix to get the
- * message and priority, and use the change [builder] to get the edits that
- * comprise the fix. If the message has parameters, then use the list of
- * [args] to populate the message.
- */
- void addFix(AnalysisError error, FixKind kind, ChangeBuilder builder,
- {List<Object> args}) {
- SourceChange change = builder.sourceChange;
- if (change.edits.isEmpty) {
- return;
- }
- change.message = formatList(kind.message, args);
- collector.addFix(error,
- new PrioritizedSourceChange(kind.priority, builder.sourceChange));
- }
-
- @override
- void computeFixes(DartFixesRequest request, FixCollector collector) {
- this.request = request;
- this.collector = collector;
- try {
- for (AnalysisError error in request.errorsToFix) {
- computeFixesForError(error);
- }
- } finally {
- this.request = null;
- this.collector = null;
- }
- }
-
- /**
- * Compute the fixes that are appropriate for the given [error] and add them
- * to the fix [collector].
- */
- void computeFixesForError(AnalysisError error);
-}
diff --git a/analyzer_plugin/lib/utilities/fixes/fixes.dart b/analyzer_plugin/lib/utilities/fixes/fixes.dart
deleted file mode 100644
index 377fe37..0000000
--- a/analyzer_plugin/lib/utilities/fixes/fixes.dart
+++ /dev/null
@@ -1,170 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/error/error.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/fixes/fixes.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of fixes when computing fixes in a
- * `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartFixesRequest implements FixesRequest {
- /**
- * The analysis result for the file in which the fixes are being requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [FixContributor]s use to record fixes.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class FixCollector {
- /**
- * Record a new [change] (fix) associated with the given [error].
- */
- void addFix(AnalysisError error, PrioritizedSourceChange change);
-}
-
-/**
- * An object used to produce fixes.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class FixContributor {
- /**
- * Contribute fixes for the location in the file specified by the given
- * [request] into the given [collector].
- */
- void computeFixes(covariant FixesRequest request, FixCollector collector);
-}
-
-/**
- * The information about a requested set of fixes.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class FixesRequest {
- /**
- * The analysis error to be fixed, or `null` if the error has not been
- * determined.
- */
- List<AnalysisError> get errorsToFix;
-
- /**
- * Return the offset within the source for which fixes are being requested.
- */
- int get offset;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
-
-/**
- * A generator that will generate an 'edit.getFixes' response.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class FixGenerator {
- /**
- * The contributors to be used to generate the fixes.
- */
- final List<FixContributor> contributors;
-
- /**
- * Initialize a newly created fix generator to use the given [contributors].
- */
- FixGenerator(this.contributors);
-
- /**
- * Create an 'edit.getFixes' response for the location in the file specified
- * by the given [request]. If any of the contributors throws an exception,
- * also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult<EditGetFixesResult> generateFixesResponse(
- FixesRequest request) {
- List<Notification> notifications = <Notification>[];
- FixCollectorImpl collector = new FixCollectorImpl();
- for (FixContributor contributor in contributors) {
- try {
- contributor.computeFixes(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- EditGetFixesResult result = new EditGetFixesResult(collector.fixes);
- return new GeneratorResult(result, notifications);
- }
-}
-
-/**
- * A description of a class of fixes. Instances are intended to hold the
- * information that is common across a number of fixes and to be shared by those
- * fixes. For example, if an unnecessary cast is found then one of the suggested
- * fixes will be to remove the cast. If there are multiple unnecessary casts in
- * a single file, then there will be multiple fixes, one per occurrence, but
- * they will all share the same kind.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class FixKind {
- /**
- * The name of this kind of fix, used for debugging.
- */
- final String name;
-
- /**
- * The priority of this kind of fix for the kind of error being addressed
- * where a higher integer value indicates a higher priority and relevance.
- */
- final int priority;
-
- /**
- * A human-readable description of the changes that will be applied by this
- * kind of fix. The message can contain parameters, where each parameter is
- * represented by a zero-based index inside curly braces. For example, the
- * message `"Create a component named '{0}' in '{1}'"` contains two parameters.
- */
- final String message;
-
- /**
- * A human-readable description of the changes that will be applied by this
- * kind of 'applied together' fix.
- */
- final String appliedTogetherMessage;
-
- /**
- * Initialize a newly created kind of fix to have the given [name],
- * [priority], [message], and optionally [canBeAppliedTogether] and
- * [appliedTogetherMessage].
- */
- const FixKind(this.name, this.priority, this.message,
- {this.appliedTogetherMessage: null});
-
- @override
- int get hashCode => name.hashCode;
-
- @override
- bool operator ==(o) => o is FixKind && o.name == name;
-
- /**
- * The change can be made with other fixes of this [FixKind].
- */
- bool canBeAppliedTogether() => appliedTogetherMessage != null;
-
- @override
- String toString() => name;
-}
diff --git a/analyzer_plugin/lib/utilities/folding/folding.dart b/analyzer_plugin/lib/utilities/folding/folding.dart
deleted file mode 100644
index 6408d2f..0000000
--- a/analyzer_plugin/lib/utilities/folding/folding.dart
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/folding/folding.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of folding regions when computing
- * folding regions in a `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartFoldingRequest implements FoldingRequest {
- /**
- * The analysis result for the file for which the folding regions are being
- * requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [FoldingContributor]s use to record folding regions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class FoldingCollector {
- /**
- * Record a new folding region corresponding to the given [range] that has the
- * given [kind].
- */
- void addRange(SourceRange range, FoldingKind kind);
-
- /**
- * Record a new folding region with the given [offset] and [length] that has
- * the given [kind].
- */
- void addRegion(int offset, int length, FoldingKind kind);
-}
-
-/**
- * An object used to produce folding regions.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class FoldingContributor {
- /**
- * Contribute folding regions into the given [collector].
- */
- void computeFolding(FoldingRequest request, FoldingCollector collector);
-}
-
-/**
- * A generator that will generate an 'analysis.folding' notification.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class FoldingGenerator {
- /**
- * The contributors to be used to generate the folding regions.
- */
- final List<FoldingContributor> contributors;
-
- /**
- * Initialize a newly created folding generator to use the given
- * [contributors].
- */
- FoldingGenerator(this.contributors);
-
- /**
- * Create an 'analysis.folding' notification. If any of the contributors
- * throws an exception, also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult generateFoldingNotification(FoldingRequest request) {
- List<Notification> notifications = <Notification>[];
- FoldingCollectorImpl collector = new FoldingCollectorImpl();
- for (FoldingContributor contributor in contributors) {
- try {
- contributor.computeFolding(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- notifications.add(new AnalysisFoldingParams(request.path, collector.regions)
- .toNotification());
- return new GeneratorResult(null, notifications);
- }
-}
-
-/**
- * The information about a requested set of folding regions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class FoldingRequest {
- /**
- * Return the path of the file for which folding regions are being requested.
- */
- String get path;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
diff --git a/analyzer_plugin/lib/utilities/generator.dart b/analyzer_plugin/lib/utilities/generator.dart
deleted file mode 100644
index aa61835..0000000
--- a/analyzer_plugin/lib/utilities/generator.dart
+++ /dev/null
@@ -1,42 +0,0 @@
-// 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_plugin/channel/channel.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/src/protocol/protocol_internal.dart';
-
-/**
- * The result produced by a generator.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class GeneratorResult<T extends ResponseResult> {
- /**
- * The result to be sent to the server, or `null` if there is no response, as
- * when the generator is generating a notification.
- */
- final T result;
-
- /**
- * The notifications that should be sent to the server. The list will be empty
- * if there are no notifications.
- */
- final List<Notification> notifications;
-
- /**
- * Initialize a newly created generator result with the given [result] and
- * [notifications].
- */
- GeneratorResult(this.result, this.notifications);
-
- /**
- * Use the given communications [channel] to send the notifications to the
- * server.
- */
- void sendNotifications(PluginCommunicationChannel channel) {
- for (final notification in notifications) {
- channel.sendNotification(notification);
- }
- }
-}
diff --git a/analyzer_plugin/lib/utilities/highlights/highlights.dart b/analyzer_plugin/lib/utilities/highlights/highlights.dart
deleted file mode 100644
index f24b280..0000000
--- a/analyzer_plugin/lib/utilities/highlights/highlights.dart
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/highlights/highlights.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of highlight regions when computing
- * highlight regions in a `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartHighlightsRequest implements HighlightsRequest {
- /**
- * The analysis result for the file for which the highlight regions are being
- * requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [HighlightsContributor]s use to record highlight regions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class HighlightsCollector {
- /**
- * Add a highlight region corresponding to the given source [range] whose type
- * is the given [type].
- */
- void addRange(SourceRange range, HighlightRegionType type);
-
- /**
- * Add a highlight region starting at the given [offset] and having the given
- * [length] whose type is the given [type].
- */
- void addRegion(int offset, int length, HighlightRegionType type);
-}
-
-/**
- * An object used to produce highlight regions.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class HighlightsContributor {
- /**
- * Contribute highlight regions into the given [collector].
- */
- void computeHighlights(
- HighlightsRequest request, HighlightsCollector collector);
-}
-
-/**
- * A generator that will generate an 'analysis.highlights' notification.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class HighlightsGenerator {
- /**
- * The contributors to be used to generate the highlight regions.
- */
- final List<HighlightsContributor> contributors;
-
- /**
- * Initialize a newly created highlights generator to use the given
- * [contributors].
- */
- HighlightsGenerator(this.contributors);
-
- /**
- * Create an 'analysis.highlights' notification. If any of the contributors
- * throws an exception, also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult generateHighlightsNotification(HighlightsRequest request) {
- List<Notification> notifications = <Notification>[];
- HighlightsCollectorImpl collector = new HighlightsCollectorImpl();
- for (HighlightsContributor contributor in contributors) {
- try {
- contributor.computeHighlights(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- notifications.add(
- new AnalysisHighlightsParams(request.path, collector.regions)
- .toNotification());
- return new GeneratorResult(null, notifications);
- }
-}
-
-/**
- * The information about a requested set of highlight regions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class HighlightsRequest {
- /**
- * Return the path of the file for which highlight regions are being
- * requested.
- */
- String get path;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
diff --git a/analyzer_plugin/lib/utilities/kythe/entries.dart b/analyzer_plugin/lib/utilities/kythe/entries.dart
deleted file mode 100644
index 11b42d1..0000000
--- a/analyzer_plugin/lib/utilities/kythe/entries.dart
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart' show KytheEntry;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/kythe/entries.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of entries when computing entries in a
- * `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartEntryRequest implements EntryRequest {
- /**
- * The analysis result for the file in which the entries are being requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [EntryContributor]s use to record entries.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class EntryCollector {
- /**
- * Record a new [entry].
- */
- void addEntry(KytheEntry entry);
-}
-
-/**
- * An object used to produce entries.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class EntryContributor {
- /**
- * Contribute entries for the file specified by the given [request] into the
- * given [collector].
- */
- void computeEntries(EntryRequest request, EntryCollector collector);
-}
-
-/**
- * A generator that will generate a 'kythe.getEntries' response.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class EntryGenerator {
- /**
- * The contributors to be used to generate the entries.
- */
- final List<EntryContributor> contributors;
-
- /**
- * Initialize a newly created entry generator to use the given [contributors].
- */
- EntryGenerator(this.contributors);
-
- /**
- * Create a 'kythe.getEntries' response for the file specified by the given
- * [request]. If any of the contributors throws an exception, also create a
- * non-fatal 'plugin.error' notification.
- */
- GeneratorResult<KytheGetKytheEntriesResult> generateGetEntriesResponse(
- EntryRequest request) {
- List<Notification> notifications = <Notification>[];
- EntryCollectorImpl collector = new EntryCollectorImpl();
- for (EntryContributor contributor in contributors) {
- try {
- contributor.computeEntries(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- KytheGetKytheEntriesResult result =
- new KytheGetKytheEntriesResult(collector.entries, collector.files);
- return new GeneratorResult(result, notifications);
- }
-}
-
-/**
- * The information about a requested set of entries.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class EntryRequest {
- /**
- * Return the path of the file in which entries are being requested.
- */
- String get path;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
diff --git a/analyzer_plugin/lib/utilities/navigation/navigation.dart b/analyzer_plugin/lib/utilities/navigation/navigation.dart
deleted file mode 100644
index 3bc3471..0000000
--- a/analyzer_plugin/lib/utilities/navigation/navigation.dart
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- show ElementKind, Location;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/navigation/navigation.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of navigation information when
- * computing navigation information in a `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartNavigationRequest implements NavigationRequest {
- /**
- * The analysis result for the file in which the navigation regions are being
- * requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [NavigationContributor]s use to record navigation regions.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class NavigationCollector {
- /**
- * Record a new navigation region corresponding to the given [range] that
- * should navigate to the given [targetLocation].
- */
- void addRange(
- SourceRange range, ElementKind targetKind, Location targetLocation);
-
- /**
- * Record a new navigation region with the given [offset] and [length] that
- * should navigate to the given [targetLocation].
- */
- void addRegion(
- int offset, int length, ElementKind targetKind, Location targetLocation);
-}
-
-/**
- * An object used to produce navigation regions.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class NavigationContributor {
- /**
- * Contribute navigation regions for the portion of the file specified by the
- * given [request] into the given [collector].
- */
- void computeNavigation(
- NavigationRequest request, NavigationCollector collector);
-}
-
-/**
- * A generator that will generate an 'analysis.navigation' notification.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class NavigationGenerator {
- /**
- * The contributors to be used to generate the navigation data.
- */
- final List<NavigationContributor> contributors;
-
- /**
- * Initialize a newly created navigation generator to use the given
- * [contributors].
- */
- NavigationGenerator(this.contributors);
-
- /**
- * Create an 'analysis.navigation' notification for the portion of the file
- * specified by the given [request]. If any of the contributors throws an
- * exception, also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult generateNavigationNotification(NavigationRequest request) {
- List<Notification> notifications = <Notification>[];
- NavigationCollectorImpl collector = new NavigationCollectorImpl();
- for (NavigationContributor contributor in contributors) {
- try {
- contributor.computeNavigation(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- collector.createRegions();
- notifications.add(new AnalysisNavigationParams(
- request.path, collector.regions, collector.targets, collector.files)
- .toNotification());
- return new GeneratorResult(null, notifications);
- }
-
- /**
- * Create an 'analysis.getNavigation' response for the portion of the file
- * specified by the given [request]. If any of the contributors throws an
- * exception, also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult<AnalysisGetNavigationResult> generateNavigationResponse(
- NavigationRequest request) {
- List<Notification> notifications = <Notification>[];
- NavigationCollectorImpl collector = new NavigationCollectorImpl();
- for (NavigationContributor contributor in contributors) {
- try {
- contributor.computeNavigation(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- collector.createRegions();
- AnalysisGetNavigationResult result = new AnalysisGetNavigationResult(
- collector.files, collector.targets, collector.regions);
- return new GeneratorResult(result, notifications);
- }
-}
-
-/**
- * The information about a requested set of navigation information.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class NavigationRequest {
- /**
- * Return the length of the region within the source for which navigation
- * regions are being requested.
- */
- int get length;
-
- /**
- * Return the offset of the region within the source for which navigation
- * regions are being requested.
- */
- int get offset;
-
- /**
- * Return the path of the file in which navigation regions are being requested.
- */
- String get path;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
diff --git a/analyzer_plugin/lib/utilities/occurrences/occurrences.dart b/analyzer_plugin/lib/utilities/occurrences/occurrences.dart
deleted file mode 100644
index 1fe0c1b..0000000
--- a/analyzer_plugin/lib/utilities/occurrences/occurrences.dart
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/occurrences/occurrences.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of occurrences information when
- * computing occurrences information in a `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartOccurrencesRequest implements OccurrencesRequest {
- /**
- * The analysis result for the file for which the occurrences information is
- * being requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [OccurrencesContributor]s use to record occurrences.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class OccurrencesCollector {
- /**
- * Add an occurrence of the given [element] at the given [offset].
- */
- void addOccurrence(Element element, int offset);
-}
-
-/**
- * An object used to produce occurrences information.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class OccurrencesContributor {
- /**
- * Contribute occurrences information into the given [collector].
- */
- void computeOccurrences(
- OccurrencesRequest request, OccurrencesCollector collector);
-}
-
-/**
- * A generator that will generate an 'analysis.occurrences' notification.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class OccurrencesGenerator {
- /**
- * The contributors to be used to generate the occurrences information.
- */
- final List<OccurrencesContributor> contributors;
-
- /**
- * Initialize a newly created occurrences generator to use the given
- * [contributors].
- */
- OccurrencesGenerator(this.contributors);
-
- /**
- * Create an 'analysis.occurrences' notification. If any of the contributors
- * throws an exception, also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult generateOccurrencesNotification(OccurrencesRequest request) {
- List<Notification> notifications = <Notification>[];
- OccurrencesCollectorImpl collector = new OccurrencesCollectorImpl();
- for (OccurrencesContributor contributor in contributors) {
- try {
- contributor.computeOccurrences(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- notifications.add(
- new AnalysisOccurrencesParams(request.path, collector.occurrences)
- .toNotification());
- return new GeneratorResult(null, notifications);
- }
-}
-
-/**
- * The information about a requested set of occurrences information.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class OccurrencesRequest {
- /**
- * Return the path of the file for which occurrences information is being
- * requested.
- */
- String get path;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
diff --git a/analyzer_plugin/lib/utilities/outline/outline.dart b/analyzer_plugin/lib/utilities/outline/outline.dart
deleted file mode 100644
index 21983f6..0000000
--- a/analyzer_plugin/lib/utilities/outline/outline.dart
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer_plugin/protocol/protocol.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart'
- hide AnalysisError;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:analyzer_plugin/src/utilities/outline/outline.dart';
-import 'package:analyzer_plugin/utilities/generator.dart';
-
-/**
- * The information about a requested set of outline information when
- * computing outline information in a `.dart` file.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class DartOutlineRequest implements OutlineRequest {
- /**
- * The analysis result for the file for which the outline is being requested.
- */
- ResolvedUnitResult get result;
-}
-
-/**
- * An object that [OutlineContributor]s use to record outline information.
- *
- * Invocations of the [startElement] and [endElement] methods must be paired.
- * Any elements started (and ended) between a [startElement] and [endElement]
- * pair are assumed to be children of the outer pair's element and as such will
- * automatically be added as children of the outer pair's outline node.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class OutlineCollector {
- /**
- * Stop recording information about the current element.
- */
- void endElement();
-
- /**
- * Start recording information about the given [element].
- */
- void startElement(Element element, int offset, int length);
-}
-
-/**
- * An object used to produce nodes in an outline.
- *
- * Clients may implement this class when implementing plugins.
- */
-abstract class OutlineContributor {
- /**
- * Contribute outline nodes into the given [collector].
- */
- void computeOutline(OutlineRequest request, OutlineCollector collector);
-}
-
-/**
- * A generator that will generate an 'analysis.outline' notification.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class OutlineGenerator {
- /**
- * The contributors to be used to generate the outline nodes.
- */
- final List<OutlineContributor> contributors;
-
- /**
- * Initialize a newly created outline generator to use the given
- * [contributors].
- */
- OutlineGenerator(this.contributors);
-
- /**
- * Create an 'analysis.outline' notification. If any of the contributors
- * throws an exception, also create a non-fatal 'plugin.error' notification.
- */
- GeneratorResult generateOutlineNotification(OutlineRequest request) {
- List<Notification> notifications = <Notification>[];
- OutlineCollectorImpl collector = new OutlineCollectorImpl();
- for (OutlineContributor contributor in contributors) {
- try {
- contributor.computeOutline(request, collector);
- } catch (exception, stackTrace) {
- notifications.add(new PluginErrorParams(
- false, exception.toString(), stackTrace.toString())
- .toNotification());
- }
- }
- notifications.add(
- new AnalysisOutlineParams(request.path, collector.outlines)
- .toNotification());
- return new GeneratorResult(null, notifications);
- }
-}
-
-/**
- * The information about a requested set of outline information.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-abstract class OutlineRequest {
- /**
- * Return the path of the file for which an outline is being requested.
- */
- String get path;
-
- /**
- * Return the resource provider associated with this request.
- */
- ResourceProvider get resourceProvider;
-}
diff --git a/analyzer_plugin/lib/utilities/pair.dart b/analyzer_plugin/lib/utilities/pair.dart
deleted file mode 100644
index 6461906..0000000
--- a/analyzer_plugin/lib/utilities/pair.dart
+++ /dev/null
@@ -1,27 +0,0 @@
-// 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.
-
-/**
- * A pair of values.
- */
-class Pair<E, F> {
- final E first;
- final F last;
-
- Pair(this.first, this.last);
-
- @override
- int get hashCode => first.hashCode ^ last.hashCode;
-
- @override
- bool operator ==(other) {
- if (other is! Pair) {
- return false;
- }
- return other.first == first && other.last == last;
- }
-
- @override
- String toString() => '($first, $last)';
-}
diff --git a/analyzer_plugin/lib/utilities/range_factory.dart b/analyzer_plugin/lib/utilities/range_factory.dart
deleted file mode 100644
index 1f58ec2..0000000
--- a/analyzer_plugin/lib/utilities/range_factory.dart
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/syntactic_entity.dart';
-import 'package:analyzer/dart/ast/token.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/error/error.dart';
-import 'package:analyzer/src/generated/source.dart';
-
-/**
- * An instance of [RangeFactory] made available for convenience.
- */
-final RangeFactory range = new RangeFactory();
-
-/**
- * A factory used to create instances of [SourceRange] based on various
- * syntactic and semantic entities.
- */
-class RangeFactory {
- /**
- * Return a source range that covers the name of the given [element].
- */
- SourceRange elementName(Element element) {
- return new SourceRange(element.nameOffset, element.nameLength);
- }
-
- /**
- * Return a source range that starts at the end of [leftEntity] and ends at
- * the end of [rightEntity].
- */
- SourceRange endEnd(SyntacticEntity leftEntity, SyntacticEntity rightEntity) {
- int offset = leftEntity.end;
- int length = rightEntity.end - offset;
- return new SourceRange(offset, length);
- }
-
- /**
- * Return a source range that starts at the end of [entity] and has the given
- * [length].
- */
- SourceRange endLength(SyntacticEntity entity, int length) {
- return new SourceRange(entity.end, length);
- }
-
- /**
- * Return a source range that starts at the end of [leftEntity] and ends at
- * the start of [rightEntity].
- */
- SourceRange endStart(
- SyntacticEntity leftEntity, SyntacticEntity rightEntity) {
- int offset = leftEntity.end;
- int length = rightEntity.offset - offset;
- return new SourceRange(offset, length);
- }
-
- /**
- * Return a source range that covers the same range as the given [error].
- */
- SourceRange error(AnalysisError error) {
- return new SourceRange(error.offset, error.length);
- }
-
- /**
- * Return a source range that covers the same range as the given [node].
- */
- SourceRange node(AstNode node) {
- return new SourceRange(node.offset, node.length);
- }
-
- /**
- * Return a source range that covers the given [item] (including a leading or
- * trailing comma as appropriate) in the containing [list].
- */
- SourceRange nodeInList<T extends AstNode>(NodeList<T> list, T item) {
- if (list.length == 1) {
- return node(item);
- }
- final index = list.indexOf(item);
- // Remove trailing comma.
- if (index == 0) {
- return startStart(item, list[1]);
- } else {
- // Remove leading comma.
- return endEnd(list[index - 1], item);
- }
- }
-
- /**
- * Return a source range that covers all of the given [nodes] (that is, from
- * the start of the first node to the end of the last node.
- */
- SourceRange nodes(List<AstNode> nodes) {
- if (nodes.isEmpty) {
- return new SourceRange(0, 0);
- }
- return startEnd(nodes.first, nodes.last);
- }
-
- /**
- * Return a source range whose length is the same as the given [range], but
- * whose offset is the offset of the given [range] with [offset] added to it.
- */
- SourceRange offsetBy(SourceRange range, int offset) {
- return new SourceRange(range.offset + offset, range.length);
- }
-
- /**
- * Return a source range that starts at the start of [leftEntity] and ends at
- * the end of [rightEntity].
- */
- SourceRange startEnd(
- SyntacticEntity leftEntity, SyntacticEntity rightEntity) {
- int offset = leftEntity.offset;
- int length = rightEntity.end - offset;
- return new SourceRange(offset, length);
- }
-
- /**
- * Return a source range that starts at the start of [entity] and has a length of [length].
- */
- SourceRange startLength(SyntacticEntity entity, int length) {
- return new SourceRange(entity.offset, length);
- }
-
- /**
- * Return a source range that starts at the given [startOffset] and ends at
- * the given [endOffset].
- */
- SourceRange startOffsetEndOffset(int startOffset, int endOffset) {
- int length = endOffset - startOffset;
- return new SourceRange(startOffset, length);
- }
-
- /**
- * Return a source range that starts at the start of [leftEntity] and ends at
- * the start of [rightEntity].
- */
- SourceRange startStart(
- SyntacticEntity leftEntity, SyntacticEntity rightEntity) {
- int offset = leftEntity.offset;
- int length = rightEntity.offset - offset;
- return new SourceRange(offset, length);
- }
-
- /**
- * Return a source range that covers the same range as the given [token].
- */
- SourceRange token(Token token) {
- return new SourceRange(token.offset, token.length);
- }
-}
diff --git a/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart b/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart
deleted file mode 100644
index e8a5dde..0000000
--- a/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart
+++ /dev/null
@@ -1,90 +0,0 @@
-// 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_plugin/protocol/protocol_generated.dart';
-
-/**
- * An object that manages the subscriptions for analysis results.
- *
- * Clients may not extend, implement or mix-in this class.
- */
-class SubscriptionManager {
- /**
- * The current set of subscriptions.
- */
- Map<AnalysisService, List<String>> _subscriptions;
-
- /**
- * Initialize a newly created subscription manager to have no subscriptions.
- */
- SubscriptionManager();
-
- /**
- * Return `true` if the file with the given [filePath] has a subscription for
- * the given [service].
- */
- bool hasSubscriptionForFile(String filePath, AnalysisService service) {
- if (_subscriptions == null) {
- return false;
- }
- List<String> files = _subscriptions[service];
- return files != null && files.contains(filePath);
- }
-
- /**
- * Return a list of the services for which the file with the given [filePath]
- * has been subscribed.
- */
- List<AnalysisService> servicesForFile(String filePath) {
- List<AnalysisService> services = <AnalysisService>[];
- if (_subscriptions != null) {
- _subscriptions.forEach((AnalysisService service, List<String> files) {
- if (files.contains(filePath)) {
- services.add(service);
- }
- });
- }
- return services;
- }
-
- /**
- * Set the current set of subscriptions to those described by the given map of
- * [subscriptions]. Return a map representing the subset of the subscriptions
- * that are new. These are the subscriptions for which a notification should
- * be sent. The returned map is keyed by the path of each file for which
- * notifications should be send and has values representing the list of
- * services that were added for that file.
- */
- Map<String, List<AnalysisService>> setSubscriptions(
- Map<AnalysisService, List<String>> subscriptions) {
- Map<String, List<AnalysisService>> newSubscriptions =
- <String, List<AnalysisService>>{};
- if (_subscriptions == null) {
- // This is the first time subscriptions have been set, so all of the
- // subscriptions are new.
- subscriptions.forEach((AnalysisService service, List<String> paths) {
- for (String path in paths) {
- newSubscriptions
- .putIfAbsent(path, () => <AnalysisService>[])
- .add(service);
- }
- });
- } else {
- // The subscriptions have been changed, to we need to compute the
- // difference.
- subscriptions.forEach((AnalysisService service, List<String> paths) {
- List<String> oldPaths = _subscriptions[service];
- for (String path in paths) {
- if (!oldPaths.contains(path)) {
- newSubscriptions
- .putIfAbsent(path, () => <AnalysisService>[])
- .add(service);
- }
- }
- });
- }
- _subscriptions = subscriptions;
- return newSubscriptions;
- }
-}
diff --git a/analyzer_plugin/pubspec.yaml b/analyzer_plugin/pubspec.yaml
deleted file mode 100644
index 59ee846..0000000
--- a/analyzer_plugin/pubspec.yaml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: analyzer_plugin
-description: A framework and support code for building plugins for the analysis server.
-version: 0.2.1
-author: Dart Team <misc@dartlang.org>
-homepage: https://github.com/dart-lang/sdk/tree/master/pkg/analyzer_plugin
-
-environment:
- sdk: '>=2.0.0 <3.0.0'
-
-dependencies:
- analyzer: '>=0.35.3 <0.39.0'
- charcode: '^1.1.0'
- dart_style: '^1.2.0'
- html: '>=0.13.1 <0.15.0'
- meta: ^1.0.2
- path: '^1.4.1'
- pub_semver: '^1.3.2'
-
-dev_dependencies:
- analysis_tool:
- path: ../analysis_tool
- front_end:
- path: ../front_end
- test_reflective_loader: ^0.1.8
- test: ^1.0.0
diff --git a/analyzer_plugin/tool/spec/api.dart b/analyzer_plugin/tool/spec/api.dart
deleted file mode 100644
index 6e98267..0000000
--- a/analyzer_plugin/tool/spec/api.dart
+++ /dev/null
@@ -1,528 +0,0 @@
-// 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.
-
-/**
- * Data structures representing an API definition, and visitor base classes
- * for visiting those data structures.
- */
-import 'dart:collection';
-
-import 'package:html/dom.dart' as dom;
-
-/**
- * Toplevel container for the API.
- */
-class Api extends ApiNode {
- final String version;
- final List<Domain> domains;
- final Types types;
- final Refactorings refactorings;
-
- Api(this.version, this.domains, this.types, this.refactorings,
- dom.Element html,
- {bool experimental})
- : super(html, experimental, false);
-}
-
-/**
- * Base class for objects in the API model.
- */
-class ApiNode {
- /**
- * A flag to indicate if this API is experimental.
- */
- final bool experimental;
-
- /**
- * A flag to indicate if this API is deprecated.
- */
- final bool deprecated;
-
- /**
- * Html element representing this part of the API.
- */
- final dom.Element html;
-
- ApiNode(this.html, bool experimental, bool deprecated)
- : this.experimental = experimental ?? false,
- this.deprecated = deprecated ?? false;
-}
-
-/**
- * Base class for visiting the API definition.
- */
-abstract class ApiVisitor<T> {
- /**
- * Dispatch the given [type] to the visitor.
- */
- T visitTypeDecl(TypeDecl type) => type.accept(this) as T;
- T visitTypeEnum(TypeEnum typeEnum);
- T visitTypeList(TypeList typeList);
- T visitTypeMap(TypeMap typeMap);
- T visitTypeObject(TypeObject typeObject);
- T visitTypeReference(TypeReference typeReference);
-
- T visitTypeUnion(TypeUnion typeUnion);
-}
-
-/**
- * Definition of a single domain.
- */
-class Domain extends ApiNode {
- final String name;
- final List<Request> requests;
- final List<Notification> notifications;
-
- Domain(this.name, this.requests, this.notifications, dom.Element html,
- {bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-}
-
-/**
- * API visitor that visits the entire API hierarchically by default.
- */
-class HierarchicalApiVisitor extends ApiVisitor {
- /**
- * The API to visit.
- */
- final Api api;
-
- HierarchicalApiVisitor(this.api);
-
- /**
- * If [type] is a [TypeReference] that is defined in the API, follow the
- * chain until a non-[TypeReference] is found, if possible.
- *
- * If it is not possible (because the chain ends with a [TypeReference] that
- * is not defined in the API), then that final [TypeReference] is returned.
- */
- TypeDecl resolveTypeReferenceChain(TypeDecl type) {
- while (type is TypeReference && api.types.containsKey(type.typeName)) {
- type = api.types[(type as TypeReference).typeName].type;
- }
- return type;
- }
-
- void visitApi() {
- api.domains.forEach(visitDomain);
- visitTypes(api.types);
- visitRefactorings(api.refactorings);
- }
-
- void visitDomain(Domain domain) {
- domain.requests.forEach(visitRequest);
- domain.notifications.forEach(visitNotification);
- }
-
- void visitNotification(Notification notification) {
- if (notification.params != null) {
- visitTypeDecl(notification.params);
- }
- }
-
- void visitRefactoring(Refactoring refactoring) {
- if (refactoring.feedback != null) {
- visitTypeDecl(refactoring.feedback);
- }
- if (refactoring.options != null) {
- visitTypeDecl(refactoring.options);
- }
- }
-
- void visitRefactorings(Refactorings refactorings) {
- refactorings?.forEach(visitRefactoring);
- }
-
- void visitRequest(Request request) {
- if (request.params != null) {
- visitTypeDecl(request.params);
- }
- if (request.result != null) {
- visitTypeDecl(request.result);
- }
- }
-
- void visitTypeDefinition(TypeDefinition typeDefinition) {
- visitTypeDecl(typeDefinition.type);
- }
-
- @override
- void visitTypeEnum(TypeEnum typeEnum) {
- typeEnum.values.forEach(visitTypeEnumValue);
- }
-
- void visitTypeEnumValue(TypeEnumValue typeEnumValue) {}
-
- @override
- void visitTypeList(TypeList typeList) {
- visitTypeDecl(typeList.itemType);
- }
-
- @override
- void visitTypeMap(TypeMap typeMap) {
- visitTypeDecl(typeMap.keyType);
- visitTypeDecl(typeMap.valueType);
- }
-
- @override
- void visitTypeObject(TypeObject typeObject) {
- typeObject.fields.forEach(visitTypeObjectField);
- }
-
- void visitTypeObjectField(TypeObjectField typeObjectField) {
- visitTypeDecl(typeObjectField.type);
- }
-
- @override
- void visitTypeReference(TypeReference typeReference) {}
-
- void visitTypes(Types types) {
- types.forEach(visitTypeDefinition);
- }
-
- @override
- void visitTypeUnion(TypeUnion typeUnion) {
- typeUnion.choices.forEach(visitTypeDecl);
- }
-}
-
-/**
- * Description of a notification method.
- */
-class Notification extends ApiNode {
- /**
- * Name of the domain enclosing this request.
- */
- final String domainName;
-
- /**
- * Name of the notification, without the domain prefix.
- */
- final String event;
-
- /**
- * Type of the object associated with the "params" key in the notification
- * object, or null if the notification has no parameters.
- */
- final TypeObject params;
-
- Notification(this.domainName, this.event, this.params, dom.Element html,
- {bool experimental})
- : super(html, experimental, false);
-
- /**
- * Get the name of the notification, including the domain prefix.
- */
- String get longEvent => '$domainName.$event';
-
- /**
- * Get the full type of the notification object, including the common "id"
- * and "error" fields.
- */
- TypeDecl get notificationType {
- List<TypeObjectField> fields = [
- new TypeObjectField('event', new TypeReference('String', null), null,
- value: '$domainName.$event')
- ];
- if (params != null) {
- fields.add(new TypeObjectField('params', params, null));
- }
- return new TypeObject(fields, null);
- }
-}
-
-/**
- * Description of a single refactoring.
- */
-class Refactoring extends ApiNode {
- /**
- * Name of the refactoring. This should match one of the values allowed for
- * RefactoringKind.
- */
- final String kind;
-
- /**
- * Type of the refactoring feedback, or null if the refactoring has no
- * feedback.
- */
- final TypeObject feedback;
-
- /**
- * Type of the refactoring options, or null if the refactoring has no options.
- */
- final TypeObject options;
-
- Refactoring(this.kind, this.feedback, this.options, dom.Element html,
- {bool experimental})
- : super(html, experimental, false);
-}
-
-/**
- * A collection of refactoring definitions.
- */
-class Refactorings extends ApiNode with IterableMixin<Refactoring> {
- final List<Refactoring> refactorings;
-
- Refactorings(this.refactorings, dom.Element html, {bool experimental})
- : super(html, experimental, false);
-
- @override
- Iterator<Refactoring> get iterator => refactorings.iterator;
-}
-
-/**
- * Description of a request method.
- */
-class Request extends ApiNode {
- /**
- * Name of the domain enclosing this request.
- */
- final String domainName;
-
- /**
- * Name of the request, without the domain prefix.
- */
- final String method;
-
- /**
- * Type of the object associated with the "params" key in the request object,
- * or null if the request has no parameters.
- */
- final TypeObject params;
-
- /**
- * Type of the object associated with the "result" key in the response object,
- * or null if the response has no results.
- */
- final TypeObject result;
-
- Request(
- this.domainName, this.method, this.params, this.result, dom.Element html,
- {bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-
- /**
- * Get the name of the request, including the domain prefix.
- */
- String get longMethod => '$domainName.$method';
-
- /**
- * Get the full type of the request object, including the common "id" and
- * "method" fields.
- */
- TypeDecl get requestType {
- List<TypeObjectField> fields = [
- new TypeObjectField('id', new TypeReference('String', null), null),
- new TypeObjectField('method', new TypeReference('String', null), null,
- value: '$domainName.$method')
- ];
- if (params != null) {
- fields.add(new TypeObjectField('params', params, null));
- }
- return new TypeObject(fields, null);
- }
-
- /**
- * Get the full type of the response object, including the common "id" and
- * "error" fields.
- */
- TypeDecl get responseType {
- List<TypeObjectField> fields = [
- new TypeObjectField('id', new TypeReference('String', null), null),
- new TypeObjectField(
- 'error', new TypeReference('RequestError', null), null,
- optional: true)
- ];
- if (result != null) {
- fields.add(new TypeObjectField('result', result, null));
- }
- return new TypeObject(fields, null);
- }
-}
-
-/**
- * Base class for all possible types.
- */
-abstract class TypeDecl extends ApiNode {
- TypeDecl(dom.Element html, bool experimental, bool deprecated)
- : super(html, experimental, deprecated);
-
- accept(ApiVisitor visitor);
-}
-
-/**
- * Description of a named type definition.
- */
-class TypeDefinition extends ApiNode {
- final String name;
- final TypeDecl type;
-
- bool isExternal = false;
-
- TypeDefinition(this.name, this.type, dom.Element html,
- {bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-}
-
-/**
- * Type of an enum. We represent enums in JSON as strings, so this type
- * declaration simply lists the allowed values.
- */
-class TypeEnum extends TypeDecl {
- final List<TypeEnumValue> values;
-
- TypeEnum(this.values, dom.Element html, {bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-
- @override
- accept(ApiVisitor visitor) => visitor.visitTypeEnum(this);
-}
-
-/**
- * Description of a single allowed value for an enum.
- */
-class TypeEnumValue extends ApiNode {
- final String value;
-
- TypeEnumValue(this.value, dom.Element html,
- {bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-}
-
-/**
- * Type of a JSON list.
- */
-class TypeList extends TypeDecl {
- final TypeDecl itemType;
-
- TypeList(this.itemType, dom.Element html, {bool experimental})
- : super(html, experimental, false);
-
- @override
- accept(ApiVisitor visitor) => visitor.visitTypeList(this);
-}
-
-/**
- * Type of a JSON map.
- */
-class TypeMap extends TypeDecl {
- /**
- * Type of map keys. Note that since JSON map keys must always be strings,
- * this must either be a [TypeReference] for [String], or a [TypeReference]
- * to a type which is defined in the API as an enum or a synonym for [String].
- */
- final TypeReference keyType;
-
- /**
- * Type of map values.
- */
- final TypeDecl valueType;
-
- TypeMap(this.keyType, this.valueType, dom.Element html, {bool experimental})
- : super(html, experimental, false);
-
- @override
- accept(ApiVisitor visitor) => visitor.visitTypeMap(this);
-}
-
-/**
- * Type of a JSON object with specified fields, some of which may be optional.
- */
-class TypeObject extends TypeDecl {
- final List<TypeObjectField> fields;
-
- TypeObject(this.fields, dom.Element html,
- {bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-
- @override
- accept(ApiVisitor visitor) => visitor.visitTypeObject(this);
-
- /**
- * Return the field with the given [name], or null if there is no such field.
- */
- TypeObjectField getField(String name) {
- for (TypeObjectField field in fields) {
- if (field.name == name) {
- return field;
- }
- }
- return null;
- }
-}
-
-/**
- * Description of a single field in a [TypeObject].
- */
-class TypeObjectField extends ApiNode {
- final String name;
- final TypeDecl type;
- final bool optional;
-
- /**
- * Value that the field is required to contain, or null if it may vary.
- */
- final Object value;
-
- TypeObjectField(this.name, this.type, dom.Element html,
- {this.optional: false, this.value, bool experimental, bool deprecated})
- : super(html, experimental, deprecated);
-}
-
-/**
- * A reference to a type which is either defined elsewhere in the API or which
- * is built-in ([String], [bool], or [int]).
- */
-class TypeReference extends TypeDecl {
- final String typeName;
-
- TypeReference(this.typeName, dom.Element html, {bool experimental})
- : super(html, experimental, false) {
- if (typeName.isEmpty) {
- throw new Exception('Empty type name');
- }
- }
-
- @override
- accept(ApiVisitor visitor) => visitor.visitTypeReference(this);
-}
-
-/**
- * A collection of type definitions.
- */
-class Types extends ApiNode with IterableMixin<TypeDefinition> {
- final Map<String, TypeDefinition> types;
-
- List<String> importUris = <String>[];
-
- Types(this.types, dom.Element html, {bool experimental})
- : super(html, experimental, false);
-
- @override
- Iterator<TypeDefinition> get iterator => types.values.iterator;
-
- Iterable<String> get keys => types.keys;
-
- TypeDefinition operator [](String typeName) => types[typeName];
-
- bool containsKey(String typeName) => types.containsKey(typeName);
-}
-
-/**
- * Type which represents a union among multiple choices.
- */
-class TypeUnion extends TypeDecl {
- final List<TypeDecl> choices;
-
- /**
- * The field that is used to disambiguate this union
- */
- final String field;
-
- TypeUnion(this.choices, this.field, dom.Element html, {bool experimental})
- : super(html, experimental, false);
-
- @override
- accept(ApiVisitor visitor) => visitor.visitTypeUnion(this);
-}
diff --git a/analyzer_plugin/tool/spec/check_all_test.dart b/analyzer_plugin/tool/spec/check_all_test.dart
deleted file mode 100644
index 9de2a71..0000000
--- a/analyzer_plugin/tool/spec/check_all_test.dart
+++ /dev/null
@@ -1,23 +0,0 @@
-// 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:analysis_tool/tools.dart';
-import 'package:path/path.dart';
-
-import 'generate_all.dart';
-
-/**
- * Check that all targets have been code generated. If they haven't tell the
- * user to run generate_all.dart.
- */
-main() async {
- String script = Platform.script.toFilePath(windows: Platform.isWindows);
- List<String> components = split(script);
- int index = components.indexOf('analyzer_plugin');
- String pkgPath = joinAll(components.sublist(0, index + 1));
- await GeneratedContent.checkAll(
- pkgPath, join(pkgPath, 'tool', 'spec', 'generate_all.dart'), allTargets);
-}
diff --git a/analyzer_plugin/tool/spec/codegen_dart.dart b/analyzer_plugin/tool/spec/codegen_dart.dart
deleted file mode 100644
index f6d1533..0000000
--- a/analyzer_plugin/tool/spec/codegen_dart.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// 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 'api.dart';
-
-/**
- * Visitor specialized for generating Dart code.
- */
-class DartCodegenVisitor extends HierarchicalApiVisitor {
- /**
- * Type references in the spec that are named something else in Dart.
- */
- static const Map<String, String> _typeRenames = const {
- 'long': 'int',
- 'object': 'Map',
- };
-
- DartCodegenVisitor(Api api) : super(api);
-
- /**
- * Convert the given [TypeDecl] to a Dart type.
- */
- String dartType(TypeDecl type) {
- if (type is TypeReference) {
- String typeName = type.typeName;
- TypeDefinition referencedDefinition = api.types[typeName];
- if (_typeRenames.containsKey(typeName)) {
- return _typeRenames[typeName];
- }
- if (referencedDefinition == null) {
- return typeName;
- }
- TypeDecl referencedType = referencedDefinition.type;
- if (referencedType is TypeObject || referencedType is TypeEnum) {
- return typeName;
- }
- return dartType(referencedType);
- } else if (type is TypeList) {
- return 'List<${dartType(type.itemType)}>';
- } else if (type is TypeMap) {
- return 'Map<${dartType(type.keyType)}, ${dartType(type.valueType)}>';
- } else if (type is TypeUnion) {
- return 'dynamic';
- } else {
- throw new Exception("Can't convert to a dart type");
- }
- }
-}
diff --git a/analyzer_plugin/tool/spec/codegen_dart_protocol.dart b/analyzer_plugin/tool/spec/codegen_dart_protocol.dart
deleted file mode 100644
index 0f4e2eb..0000000
--- a/analyzer_plugin/tool/spec/codegen_dart_protocol.dart
+++ /dev/null
@@ -1,1324 +0,0 @@
-// 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:convert';
-
-import 'package:analysis_tool/tools.dart';
-import 'package:html/dom.dart' as dom;
-import 'package:path/path.dart' as path;
-
-import 'api.dart';
-import 'codegen_dart.dart';
-import 'from_html.dart';
-import 'implied_types.dart';
-import 'to_html.dart';
-
-/**
- * Special flags that need to be inserted into the declaration of the Element
- * class.
- */
-const Map<String, String> specialElementFlags = const {
- 'abstract': '0x01',
- 'const': '0x02',
- 'final': '0x04',
- 'static': '0x08',
- 'private': '0x10',
- 'deprecated': '0x20'
-};
-
-GeneratedFile target(bool responseRequiresRequestTime) {
- return new GeneratedFile('lib/protocol/protocol_generated.dart',
- (String pkgPath) async {
- CodegenProtocolVisitor visitor = new CodegenProtocolVisitor(
- path.basename(pkgPath), responseRequiresRequestTime, readApi(pkgPath));
- return visitor.collectCode(visitor.visitApi);
- });
-}
-
-/**
- * Callback type used to represent arbitrary code generation.
- */
-typedef void CodegenCallback();
-
-typedef String FromJsonSnippetCallback(String jsonPath, String json);
-
-typedef String ToJsonSnippetCallback(String value);
-
-/**
- * Visitor which produces Dart code representing the API.
- */
-class CodegenProtocolVisitor extends DartCodegenVisitor with CodeGenerator {
- /**
- * Class members for which the constructor argument should be optional, even
- * if the member is not an optional part of the protocol. For list types,
- * the constructor will default the member to the empty list.
- */
- static const Map<String, List<String>> _optionalConstructorArguments = const {
- 'AnalysisErrorFixes': const ['fixes'],
- 'SourceChange': const ['edits', 'linkedEditGroups'],
- 'SourceFileEdit': const ['edits'],
- 'TypeHierarchyItem': const ['interfaces', 'mixins', 'subclasses'],
- };
-
- /**
- * The disclaimer added to the documentation comment for each of the classes
- * that are generated.
- */
- static const String disclaimer =
- 'Clients may not extend, implement or mix-in this class.';
-
- /**
- * The name of the package into which code is being generated.
- */
- final String packageName;
-
- /**
- * A flag indicating whether the class [Response] requires a `requestTime`
- * parameter.
- */
- final bool responseRequiresRequestTime;
-
- /**
- * Visitor used to produce doc comments.
- */
- final ToHtmlVisitor toHtmlVisitor;
-
- /**
- * Types implied by the API. This includes types explicitly named in the
- * API as well as those implied by the definitions of requests, responses,
- * notifications, etc.
- */
- final Map<String, ImpliedType> impliedTypes;
-
- CodegenProtocolVisitor(
- this.packageName, this.responseRequiresRequestTime, Api api)
- : toHtmlVisitor = new ToHtmlVisitor(api),
- impliedTypes = computeImpliedTypes(api),
- super(api) {
- codeGeneratorSettings.commentLineLength = 79;
- codeGeneratorSettings.languageName = 'dart';
- }
-
- /**
- * Compute the code necessary to compare two objects for equality.
- */
- String compareEqualsCode(TypeDecl type, String thisVar, String otherVar) {
- TypeDecl resolvedType = resolveTypeReferenceChain(type);
- if (resolvedType is TypeReference ||
- resolvedType is TypeEnum ||
- resolvedType is TypeObject ||
- resolvedType is TypeUnion) {
- return '$thisVar == $otherVar';
- } else if (resolvedType is TypeList) {
- String itemTypeName = dartType(resolvedType.itemType);
- String subComparison = compareEqualsCode(resolvedType.itemType, 'a', 'b');
- String closure = '($itemTypeName a, $itemTypeName b) => $subComparison';
- return 'listEqual($thisVar, $otherVar, $closure)';
- } else if (resolvedType is TypeMap) {
- String valueTypeName = dartType(resolvedType.valueType);
- String subComparison =
- compareEqualsCode(resolvedType.valueType, 'a', 'b');
- String closure = '($valueTypeName a, $valueTypeName b) => $subComparison';
- return 'mapEqual($thisVar, $otherVar, $closure)';
- }
- throw new Exception(
- "Don't know how to compare for equality: $resolvedType");
- }
-
- /**
- * Translate each of the given [types] implied by the API to a class.
- */
- void emitClasses(List<ImpliedType> types) {
- for (ImpliedType impliedType in types) {
- TypeDecl type = impliedType.type;
- String dartTypeName = capitalize(impliedType.camelName);
- if (type == null) {
- writeln();
- emitEmptyObjectClass(dartTypeName, impliedType);
- } else if (type is TypeObject) {
- writeln();
- emitObjectClass(dartTypeName, type, impliedType);
- } else if (type is TypeEnum) {
- writeln();
- emitEnumClass(dartTypeName, type, impliedType);
- }
- }
- }
-
- /**
- * Emit a convenience constructor for decoding a piece of protocol, if
- * appropriate. Return true if a constructor was emitted.
- */
- bool emitConvenienceConstructor(String className, ImpliedType impliedType) {
- // The type of object from which this piece of protocol should be decoded.
- String inputType;
- // The name of the input object.
- String inputName;
- // The field within the input object to decode.
- String fieldName;
- // Constructor call to create the JsonDecoder object.
- String makeDecoder;
- // Name of the constructor to create.
- String constructorName;
- // Extra arguments for the constructor.
- List<String> extraArgs = <String>[];
- switch (impliedType.kind) {
- case 'requestParams':
- inputType = 'Request';
- inputName = 'request';
- fieldName = 'params';
- makeDecoder = 'new RequestDecoder(request)';
- constructorName = 'fromRequest';
- break;
- case 'requestResult':
- inputType = 'Response';
- inputName = 'response';
- fieldName = 'result';
- makeDecoder =
- 'new ResponseDecoder(REQUEST_ID_REFACTORING_KINDS.remove(response.id))';
- constructorName = 'fromResponse';
- break;
- case 'notificationParams':
- inputType = 'Notification';
- inputName = 'notification';
- fieldName = 'params';
- makeDecoder = 'new ResponseDecoder(null)';
- constructorName = 'fromNotification';
- break;
- case 'refactoringOptions':
- inputType = 'EditGetRefactoringParams';
- inputName = 'refactoringParams';
- fieldName = 'options';
- makeDecoder = 'new RequestDecoder(request)';
- constructorName = 'fromRefactoringParams';
- extraArgs.add('Request request');
- break;
- default:
- return false;
- }
- List<String> args = ['$inputType $inputName'];
- args.addAll(extraArgs);
- writeln('factory $className.$constructorName(${args.join(', ')}) {');
- indent(() {
- String fieldNameString =
- literalString(fieldName.replaceFirst(new RegExp('^_'), ''));
- if (className == 'EditGetRefactoringParams') {
- writeln('var params = new $className.fromJson(');
- writeln(' $makeDecoder, $fieldNameString, $inputName.$fieldName);');
- writeln('REQUEST_ID_REFACTORING_KINDS[request.id] = params.kind;');
- writeln('return params;');
- } else {
- writeln('return new $className.fromJson(');
- writeln(' $makeDecoder, $fieldNameString, $inputName.$fieldName);');
- }
- });
- writeln('}');
- return true;
- }
-
- /**
- * Emit a class representing an data structure that doesn't exist in the
- * protocol because it is empty (e.g. the "params" object for a request that
- * doesn't have any parameters).
- */
- void emitEmptyObjectClass(String className, ImpliedType impliedType) {
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(impliedType.humanReadableName);
- });
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(disclaimer);
- });
- }));
- write('class $className');
- if (impliedType.kind == 'refactoringFeedback') {
- writeln(' extends RefactoringFeedback implements HasToJson {');
- } else if (impliedType.kind == 'refactoringOptions') {
- writeln(' extends RefactoringOptions implements HasToJson {');
- } else if (impliedType.kind == 'requestParams') {
- writeln(' implements RequestParams {');
- } else if (impliedType.kind == 'requestResult') {
- writeln(' implements ResponseResult {');
- } else {
- writeln(' {');
- }
- indent(() {
- if (impliedType.kind == 'requestResult' ||
- impliedType.kind == 'requestParams') {
- emitEmptyToJsonMember();
- writeln();
- }
- if (emitToRequestMember(impliedType)) {
- writeln();
- }
- if (emitToResponseMember(impliedType)) {
- writeln();
- }
- if (emitToNotificationMember(impliedType)) {
- writeln();
- }
- emitObjectEqualsMember(null, className);
- writeln();
- emitObjectHashCode(null, className);
- });
- writeln('}');
- }
-
- /**
- * Emit the toJson() code for an empty class.
- */
- void emitEmptyToJsonMember() {
- writeln('@override');
- writeln('Map<String, dynamic> toJson() => <String, dynamic>{};');
- }
-
- /**
- * Emit a class to encapsulate an enum.
- */
- void emitEnumClass(String className, TypeEnum type, ImpliedType impliedType) {
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(impliedType.humanReadableName);
- });
- if (impliedType.type != null) {
- toHtmlVisitor.showType(null, impliedType.type);
- }
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(disclaimer);
- });
- }));
- writeln('class $className implements Enum {');
- indent(() {
- if (emitSpecialStaticMembers(className)) {
- writeln();
- }
- for (TypeEnumValue value in type.values) {
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.translateHtml(value.html);
- }));
- String valueString = literalString(value.value);
- writeln(
- 'static const $className ${value.value} = const $className._($valueString);');
- writeln();
- }
-
- writeln('/**');
- writeln(' * A list containing all of the enum values that are defined.');
- writeln(' */');
- write('static const List<');
- write(className);
- write('> VALUES = const <');
- write(className);
- write('>[');
- bool first = true;
- for (TypeEnumValue value in type.values) {
- if (first) {
- first = false;
- } else {
- write(', ');
- }
- write(value.value);
- }
- writeln('];');
- writeln();
-
- writeln('@override');
- writeln('final String name;');
- writeln();
- writeln('const $className._(this.name);');
- writeln();
- emitEnumClassConstructor(className, type);
- writeln();
- emitEnumFromJsonConstructor(className, type, impliedType);
- writeln();
- if (emitSpecialConstructors(className)) {
- writeln();
- }
- if (emitSpecialGetters(className)) {
- writeln();
- }
- if (emitSpecialMethods(className)) {
- writeln();
- }
- writeln('@override');
- writeln('String toString() => "$className.\$name";');
- writeln();
- writeln('String toJson() => name;');
- });
- writeln('}');
- }
-
- /**
- * Emit the constructor for an enum class.
- */
- void emitEnumClassConstructor(String className, TypeEnum type) {
- writeln('factory $className(String name) {');
- indent(() {
- writeln('switch (name) {');
- indent(() {
- for (TypeEnumValue value in type.values) {
- String valueString = literalString(value.value);
- writeln('case $valueString:');
- indent(() {
- writeln('return ${value.value};');
- });
- }
- });
- writeln('}');
- writeln(r"throw new Exception('Illegal enum value: $name');");
- });
- writeln('}');
- }
-
- /**
- * Emit the method for decoding an enum from JSON.
- */
- void emitEnumFromJsonConstructor(
- String className, TypeEnum type, ImpliedType impliedType) {
- writeln(
- 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object json) {');
- indent(() {
- writeln('if (json is String) {');
- indent(() {
- writeln('try {');
- indent(() {
- writeln('return new $className(json);');
- });
- writeln('} catch(_) {');
- indent(() {
- writeln('// Fall through');
- });
- writeln('}');
- });
- writeln('}');
- String humanReadableNameString =
- literalString(impliedType.humanReadableName);
- writeln(
- 'throw jsonDecoder.mismatch(jsonPath, $humanReadableNameString, json);');
- });
- writeln('}');
- }
-
- void emitImports() {
- writeln("import 'dart:convert' hide JsonDecoder;");
- writeln();
- writeln("import 'package:analyzer/src/generated/utilities_general.dart';");
- writeln("import 'package:$packageName/protocol/protocol.dart';");
- writeln(
- "import 'package:$packageName/src/protocol/protocol_internal.dart';");
- for (String uri in api.types.importUris) {
- write("import '");
- write(uri);
- writeln("';");
- }
- }
-
- /**
- * Emit the class to encapsulate an object type.
- */
- void emitObjectClass(
- String className, TypeObject type, ImpliedType impliedType) {
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(impliedType.humanReadableName);
- });
- if (impliedType.type != null) {
- toHtmlVisitor.showType(null, impliedType.type);
- }
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(disclaimer);
- });
- }));
- write('class $className');
- if (impliedType.kind == 'refactoringFeedback') {
- writeln(' extends RefactoringFeedback {');
- } else if (impliedType.kind == 'refactoringOptions') {
- writeln(' extends RefactoringOptions {');
- } else if (impliedType.kind == 'requestParams') {
- writeln(' implements RequestParams {');
- } else if (impliedType.kind == 'requestResult') {
- writeln(' implements ResponseResult {');
- } else {
- writeln(' implements HasToJson {');
- }
- indent(() {
- if (emitSpecialStaticMembers(className)) {
- writeln();
- }
- for (TypeObjectField field in type.fields) {
- if (field.value != null) {
- continue;
- }
- writeln('${dartType(field.type)} _${field.name};');
- writeln();
- }
- for (TypeObjectField field in type.fields) {
- if (field.value != null) {
- continue;
- }
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.translateHtml(field.html);
- }));
- writeln('${dartType(field.type)} get ${field.name} => _${field.name};');
- writeln();
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.translateHtml(field.html);
- }));
- writeln('set ${field.name}(${dartType(field.type)} value) {');
- indent(() {
- if (!field.optional) {
- writeln('assert(value != null);');
- }
- writeln('this._${field.name} = value;');
- });
- writeln('}');
- writeln();
- }
- emitObjectConstructor(type, className);
- writeln();
- emitObjectFromJsonConstructor(className, type, impliedType);
- writeln();
- if (emitConvenienceConstructor(className, impliedType)) {
- writeln();
- }
- if (emitSpecialConstructors(className)) {
- writeln();
- }
- if (emitSpecialGetters(className)) {
- writeln();
- }
- emitToJsonMember(type);
- writeln();
- if (emitToRequestMember(impliedType)) {
- writeln();
- }
- if (emitToResponseMember(impliedType)) {
- writeln();
- }
- if (emitToNotificationMember(impliedType)) {
- writeln();
- }
- if (emitSpecialMethods(className)) {
- writeln();
- }
- writeln('@override');
- writeln('String toString() => json.encode(toJson());');
- writeln();
- emitObjectEqualsMember(type, className);
- writeln();
- emitObjectHashCode(type, className);
- });
- writeln('}');
- }
-
- /**
- * Emit the constructor for an object class.
- */
- void emitObjectConstructor(TypeObject type, String className) {
- List<String> args = <String>[];
- List<String> optionalArgs = <String>[];
- List<CodegenCallback> extraInitCode = <CodegenCallback>[];
- for (TypeObjectField field in type.fields) {
- if (field.value != null) {
- continue;
- }
- String arg = '${dartType(field.type)} ${field.name}';
- String setValueFromArg = 'this.${field.name} = ${field.name};';
- if (isOptionalConstructorArg(className, field)) {
- optionalArgs.add(arg);
- if (!field.optional) {
- // Optional constructor arg, but non-optional field. If no arg is
- // given, the constructor should populate with the empty list.
- TypeDecl fieldType = field.type;
- if (fieldType is TypeList) {
- extraInitCode.add(() {
- writeln('if (${field.name} == null) {');
- indent(() {
- writeln(
- 'this.${field.name} = <${dartType(fieldType.itemType)}>[];');
- });
- writeln('} else {');
- indent(() {
- writeln(setValueFromArg);
- });
- writeln('}');
- });
- } else {
- throw new Exception(
- "Don't know how to create default field value.");
- }
- } else {
- extraInitCode.add(() {
- writeln(setValueFromArg);
- });
- }
- } else {
- args.add(arg);
- extraInitCode.add(() {
- writeln(setValueFromArg);
- });
- }
- }
- if (optionalArgs.isNotEmpty) {
- args.add('{${optionalArgs.join(', ')}}');
- }
- write('$className(${args.join(', ')})');
- if (extraInitCode.isEmpty) {
- writeln(';');
- } else {
- writeln(' {');
- indent(() {
- for (CodegenCallback callback in extraInitCode) {
- callback();
- }
- });
- writeln('}');
- }
- }
-
- /**
- * Emit the operator== code for an object class.
- */
- void emitObjectEqualsMember(TypeObject type, String className) {
- writeln('@override');
- writeln('bool operator ==(other) {');
- indent(() {
- writeln('if (other is $className) {');
- indent(() {
- var comparisons = <String>[];
- if (type != null) {
- for (TypeObjectField field in type.fields) {
- if (field.value != null) {
- continue;
- }
- comparisons.add(compareEqualsCode(
- field.type, field.name, 'other.${field.name}'));
- }
- }
- if (comparisons.isEmpty) {
- writeln('return true;');
- } else {
- String concatenated = comparisons.join(' &&\n ');
- writeln('return $concatenated;');
- }
- });
- writeln('}');
- writeln('return false;');
- });
- writeln('}');
- }
-
- /**
- * Emit the method for decoding an object from JSON.
- */
- void emitObjectFromJsonConstructor(
- String className, TypeObject type, ImpliedType impliedType) {
- String humanReadableNameString =
- literalString(impliedType.humanReadableName);
- if (className == 'RefactoringFeedback') {
- writeln('factory RefactoringFeedback.fromJson(JsonDecoder jsonDecoder, '
- 'String jsonPath, Object json, Map responseJson) {');
- indent(() {
- writeln('return refactoringFeedbackFromJson(jsonDecoder, jsonPath, '
- 'json, responseJson);');
- });
- writeln('}');
- return;
- }
- if (className == 'RefactoringOptions') {
- writeln('factory RefactoringOptions.fromJson(JsonDecoder jsonDecoder, '
- 'String jsonPath, Object json, RefactoringKind kind) {');
- indent(() {
- writeln('return refactoringOptionsFromJson(jsonDecoder, jsonPath, '
- 'json, kind);');
- });
- writeln('}');
- return;
- }
- writeln(
- 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object json) {');
- indent(() {
- writeln('if (json == null) {');
- indent(() {
- writeln('json = {};');
- });
- writeln('}');
- writeln('if (json is Map) {');
- indent(() {
- List<String> args = <String>[];
- List<String> optionalArgs = <String>[];
- for (TypeObjectField field in type.fields) {
- String fieldNameString = literalString(field.name);
- String fieldAccessor = 'json[$fieldNameString]';
- String jsonPath = 'jsonPath + ${literalString('.${field.name}')}';
- if (field.value != null) {
- String valueString = literalString(field.value as String);
- writeln('if ($fieldAccessor != $valueString) {');
- indent(() {
- writeln(
- 'throw jsonDecoder.mismatch(jsonPath, "equal " + $valueString, json);');
- });
- writeln('}');
- continue;
- }
- if (isOptionalConstructorArg(className, field)) {
- optionalArgs.add('${field.name}: ${field.name}');
- } else {
- args.add(field.name);
- }
- TypeDecl fieldType = field.type;
- String fieldDartType = dartType(fieldType);
- writeln('$fieldDartType ${field.name};');
- writeln('if (json.containsKey($fieldNameString)) {');
- indent(() {
- String fromJson =
- fromJsonCode(fieldType).asSnippet(jsonPath, fieldAccessor);
- writeln('${field.name} = $fromJson;');
- });
- write('}');
- if (!field.optional) {
- writeln(' else {');
- indent(() {
- writeln(
- "throw jsonDecoder.mismatch(jsonPath, $fieldNameString);");
- });
- writeln('}');
- } else {
- writeln();
- }
- }
- args.addAll(optionalArgs);
- writeln('return new $className(${args.join(', ')});');
- });
- writeln('} else {');
- indent(() {
- writeln(
- 'throw jsonDecoder.mismatch(jsonPath, $humanReadableNameString, json);');
- });
- writeln('}');
- });
- writeln('}');
- }
-
- /**
- * Emit the hashCode getter for an object class.
- */
- void emitObjectHashCode(TypeObject type, String className) {
- writeln('@override');
- writeln('int get hashCode {');
- indent(() {
- if (type == null) {
- writeln('return ${className.hashCode};');
- } else {
- writeln('int hash = 0;');
- for (TypeObjectField field in type.fields) {
- String valueToCombine;
- if (field.value != null) {
- valueToCombine = field.value.hashCode.toString();
- } else {
- valueToCombine = '${field.name}.hashCode';
- }
- writeln('hash = JenkinsSmiHash.combine(hash, $valueToCombine);');
- }
- writeln('return JenkinsSmiHash.finish(hash);');
- }
- });
- writeln('}');
- }
-
- /**
- * If the class named [className] requires special constructors, emit them
- * and return true.
- */
- bool emitSpecialConstructors(String className) {
- switch (className) {
- case 'LinkedEditGroup':
- docComment([new dom.Text('Construct an empty LinkedEditGroup.')]);
- writeln(
- 'LinkedEditGroup.empty() : this(<Position>[], 0, <LinkedEditSuggestion>[]);');
- return true;
- case 'RefactoringProblemSeverity':
- docComment([
- new dom.Text(
- 'Returns the [RefactoringProblemSeverity] with the maximal severity.')
- ]);
- writeln(
- 'static RefactoringProblemSeverity max(RefactoringProblemSeverity a, RefactoringProblemSeverity b) =>');
- writeln(' maxRefactoringProblemSeverity(a, b);');
- return true;
- default:
- return false;
- }
- }
-
- /**
- * If the class named [className] requires special getters, emit them and
- * return true.
- */
- bool emitSpecialGetters(String className) {
- switch (className) {
- case 'Element':
- for (String name in specialElementFlags.keys) {
- String flag = 'FLAG_${name.toUpperCase()}';
- writeln(
- 'bool get ${camelJoin(['is', name])} => (flags & $flag) != 0;');
- }
- return true;
- case 'SourceEdit':
- docComment([new dom.Text('The end of the region to be modified.')]);
- writeln('int get end => offset + length;');
- return true;
- default:
- return false;
- }
- }
-
- /**
- * If the class named [className] requires special methods, emit them and
- * return true.
- */
- bool emitSpecialMethods(String className) {
- switch (className) {
- case 'LinkedEditGroup':
- docComment([new dom.Text('Add a new position and change the length.')]);
- writeln('void addPosition(Position position, int length) {');
- indent(() {
- writeln('positions.add(position);');
- writeln('this.length = length;');
- });
- writeln('}');
- writeln();
- docComment([new dom.Text('Add a new suggestion.')]);
- writeln('void addSuggestion(LinkedEditSuggestion suggestion) {');
- indent(() {
- writeln('suggestions.add(suggestion);');
- });
- writeln('}');
- return true;
- case 'SourceChange':
- docComment([
- new dom.Text('Adds [edit] to the [FileEdit] for the given [file].')
- ]);
- writeln('void addEdit(String file, int fileStamp, SourceEdit edit) =>');
- writeln(' addEditToSourceChange(this, file, fileStamp, edit);');
- writeln();
- docComment([new dom.Text('Adds the given [FileEdit].')]);
- writeln('void addFileEdit(SourceFileEdit edit) {');
- indent(() {
- writeln('edits.add(edit);');
- });
- writeln('}');
- writeln();
- docComment([new dom.Text('Adds the given [LinkedEditGroup].')]);
- writeln('void addLinkedEditGroup(LinkedEditGroup linkedEditGroup) {');
- indent(() {
- writeln('linkedEditGroups.add(linkedEditGroup);');
- });
- writeln('}');
- writeln();
- docComment([
- new dom.Text(
- 'Returns the [FileEdit] for the given [file], maybe `null`.')
- ]);
- writeln('SourceFileEdit getFileEdit(String file) =>');
- writeln(' getChangeFileEdit(this, file);');
- return true;
- case 'SourceEdit':
- docComment([
- new dom.Text(
- 'Get the result of applying the edit to the given [code].')
- ]);
- writeln('String apply(String code) => applyEdit(code, this);');
- return true;
- case 'SourceFileEdit':
- docComment([new dom.Text('Adds the given [Edit] to the list.')]);
- writeln('void add(SourceEdit edit) => addEditForSource(this, edit);');
- writeln();
- docComment([new dom.Text('Adds the given [Edit]s.')]);
- writeln('void addAll(Iterable<SourceEdit> edits) =>');
- writeln(' addAllEditsForSource(this, edits);');
- return true;
- default:
- return false;
- }
- }
-
- /**
- * If the class named [className] requires special static members, emit them
- * and return true.
- */
- bool emitSpecialStaticMembers(String className) {
- switch (className) {
- case 'Element':
- List<String> makeFlagsArgs = <String>[];
- List<String> makeFlagsStatements = <String>[];
- specialElementFlags.forEach((String name, String value) {
- String flag = 'FLAG_${name.toUpperCase()}';
- String camelName = camelJoin(['is', name]);
- writeln('static const int $flag = $value;');
- makeFlagsArgs.add('bool $camelName: false');
- makeFlagsStatements.add('if ($camelName) flags |= $flag;');
- });
- writeln();
- writeln('static int makeFlags({${makeFlagsArgs.join(', ')}}) {');
- indent(() {
- writeln('int flags = 0;');
- for (String statement in makeFlagsStatements) {
- writeln(statement);
- }
- writeln('return flags;');
- });
- writeln('}');
- return true;
- case 'SourceEdit':
- docComment([
- new dom.Text('Get the result of applying a set of ' +
- '[edits] to the given [code]. Edits are applied in the order ' +
- 'they appear in [edits].')
- ]);
- writeln(
- 'static String applySequence(String code, Iterable<SourceEdit> edits) =>');
- writeln(' applySequenceOfEdits(code, edits);');
- return true;
- default:
- return false;
- }
- }
-
- /**
- * Emit the toJson() code for an object class.
- */
- void emitToJsonMember(TypeObject type) {
- writeln('@override');
- writeln('Map<String, dynamic> toJson() {');
- indent(() {
- writeln('Map<String, dynamic> result = {};');
- for (TypeObjectField field in type.fields) {
- String fieldNameString = literalString(field.name);
- if (field.value != null) {
- writeln(
- 'result[$fieldNameString] = ${literalString(field.value as String)};');
- continue;
- }
- String fieldToJson = toJsonCode(field.type).asSnippet(field.name);
- String populateField = 'result[$fieldNameString] = $fieldToJson;';
- if (field.optional) {
- writeln('if (${field.name} != null) {');
- indent(() {
- writeln(populateField);
- });
- writeln('}');
- } else {
- writeln(populateField);
- }
- }
- writeln('return result;');
- });
- writeln('}');
- }
-
- /**
- * Emit the toNotification() code for a class, if appropriate. Returns true
- * if code was emitted.
- */
- bool emitToNotificationMember(ImpliedType impliedType) {
- if (impliedType.kind == 'notificationParams') {
- writeln('Notification toNotification() {');
- indent(() {
- String eventString =
- literalString((impliedType.apiNode as Notification).longEvent);
- String jsonPart = impliedType.type != null ? 'toJson()' : 'null';
- writeln('return new Notification($eventString, $jsonPart);');
- });
- writeln('}');
- return true;
- }
- return false;
- }
-
- /**
- * Emit the toRequest() code for a class, if appropriate. Returns true if
- * code was emitted.
- */
- bool emitToRequestMember(ImpliedType impliedType) {
- if (impliedType.kind == 'requestParams') {
- writeln('@override');
- writeln('Request toRequest(String id) {');
- indent(() {
- String methodString =
- literalString((impliedType.apiNode as Request).longMethod);
- String jsonPart = impliedType.type != null ? 'toJson()' : 'null';
- writeln('return new Request(id, $methodString, $jsonPart);');
- });
- writeln('}');
- return true;
- }
- return false;
- }
-
- /**
- * Emit the toResponse() code for a class, if appropriate. Returns true if
- * code was emitted.
- */
- bool emitToResponseMember(ImpliedType impliedType) {
- if (impliedType.kind == 'requestResult') {
- writeln('@override');
- if (responseRequiresRequestTime) {
- writeln('Response toResponse(String id, int requestTime) {');
- } else {
- writeln('Response toResponse(String id) {');
- }
- indent(() {
- String jsonPart = impliedType.type != null ? 'toJson()' : 'null';
- if (responseRequiresRequestTime) {
- writeln('return new Response(id, requestTime, result: $jsonPart);');
- } else {
- writeln('return new Response(id, result: $jsonPart);');
- }
- });
- writeln('}');
- return true;
- }
- return false;
- }
-
- /**
- * Compute the code necessary to translate [type] from JSON.
- */
- FromJsonCode fromJsonCode(TypeDecl type) {
- if (type is TypeReference) {
- TypeDefinition referencedDefinition = api.types[type.typeName];
- if (referencedDefinition != null) {
- TypeDecl referencedType = referencedDefinition.type;
- if (referencedType is TypeObject || referencedType is TypeEnum) {
- return new FromJsonSnippet((String jsonPath, String json) {
- String typeName = dartType(type);
- if (typeName == 'RefactoringFeedback') {
- return 'new $typeName.fromJson(jsonDecoder, $jsonPath, $json, json)';
- } else if (typeName == 'RefactoringOptions') {
- return 'new $typeName.fromJson(jsonDecoder, $jsonPath, $json, kind)';
- } else {
- return 'new $typeName.fromJson(jsonDecoder, $jsonPath, $json)';
- }
- });
- } else {
- return fromJsonCode(referencedType);
- }
- } else {
- switch (type.typeName) {
- case 'String':
- return new FromJsonFunction('jsonDecoder.decodeString');
- case 'bool':
- return new FromJsonFunction('jsonDecoder.decodeBool');
- case 'int':
- case 'long':
- return new FromJsonFunction('jsonDecoder.decodeInt');
- case 'object':
- return new FromJsonIdentity();
- default:
- throw new Exception('Unexpected type name ${type.typeName}');
- }
- }
- } else if (type is TypeMap) {
- FromJsonCode keyCode;
- if (dartType(type.keyType) != 'String') {
- keyCode = fromJsonCode(type.keyType);
- } else {
- keyCode = new FromJsonIdentity();
- }
- FromJsonCode valueCode = fromJsonCode(type.valueType);
- if (keyCode.isIdentity && valueCode.isIdentity) {
- return new FromJsonFunction('jsonDecoder.decodeMap');
- } else {
- return new FromJsonSnippet((String jsonPath, String json) {
- StringBuffer result = new StringBuffer();
- result.write('jsonDecoder.decodeMap($jsonPath, $json');
- if (!keyCode.isIdentity) {
- result.write(', keyDecoder: ${keyCode.asClosure}');
- }
- if (!valueCode.isIdentity) {
- result.write(', valueDecoder: ${valueCode.asClosure}');
- }
- result.write(')');
- return result.toString();
- });
- }
- } else if (type is TypeList) {
- FromJsonCode itemCode = fromJsonCode(type.itemType);
- if (itemCode.isIdentity) {
- return new FromJsonFunction('jsonDecoder.decodeList');
- } else {
- return new FromJsonSnippet((String jsonPath, String json) =>
- 'jsonDecoder.decodeList($jsonPath, $json, ${itemCode.asClosure})');
- }
- } else if (type is TypeUnion) {
- List<String> decoders = <String>[];
- for (TypeDecl choice in type.choices) {
- TypeDecl resolvedChoice = resolveTypeReferenceChain(choice);
- if (resolvedChoice is TypeObject) {
- TypeObjectField field = resolvedChoice.getField(type.field);
- if (field == null) {
- throw new Exception(
- 'Each choice in the union needs a field named ${type.field}');
- }
- if (field.value == null) {
- throw new Exception(
- 'Each choice in the union needs a constant value for the field ${type.field}');
- }
- String closure = fromJsonCode(choice).asClosure;
- decoders.add('${literalString(field.value as String)}: $closure');
- } else {
- throw new Exception('Union types must be unions of objects.');
- }
- }
- return new FromJsonSnippet((String jsonPath, String json) =>
- 'jsonDecoder.decodeUnion($jsonPath, $json as Map, ${literalString(type.field)}, {${decoders.join(', ')}})');
- } else {
- throw new Exception("Can't convert $type from JSON");
- }
- }
-
- /**
- * Return a list of the classes to be emitted.
- */
- List<ImpliedType> getClassesToEmit() {
- List<ImpliedType> types = impliedTypes.values.where((ImpliedType type) {
- ApiNode node = type.apiNode;
- return !(node is TypeDefinition && node.isExternal);
- }).toList();
- types.sort((first, second) =>
- capitalize(first.camelName).compareTo(capitalize(second.camelName)));
- return types;
- }
-
- /**
- * True if the constructor argument for the given field should be optional.
- */
- bool isOptionalConstructorArg(String className, TypeObjectField field) {
- if (field.optional) {
- return true;
- }
- List<String> forceOptional = _optionalConstructorArguments[className];
- if (forceOptional != null && forceOptional.contains(field.name)) {
- return true;
- }
- return false;
- }
-
- /**
- * Create a string literal that evaluates to [s].
- */
- String literalString(String s) => json.encode(s);
-
- /**
- * Compute the code necessary to convert [type] to JSON.
- */
- ToJsonCode toJsonCode(TypeDecl type) {
- TypeDecl resolvedType = resolveTypeReferenceChain(type);
- if (resolvedType is TypeReference) {
- return new ToJsonIdentity(dartType(type));
- } else if (resolvedType is TypeList) {
- ToJsonCode itemCode = toJsonCode(resolvedType.itemType);
- if (itemCode.isIdentity) {
- return new ToJsonIdentity(dartType(type));
- } else {
- return new ToJsonSnippet(dartType(type),
- (String value) => '$value.map(${itemCode.asClosure}).toList()');
- }
- } else if (resolvedType is TypeMap) {
- ToJsonCode keyCode;
- if (dartType(resolvedType.keyType) != 'String') {
- keyCode = toJsonCode(resolvedType.keyType);
- } else {
- keyCode = new ToJsonIdentity(dartType(resolvedType.keyType));
- }
- ToJsonCode valueCode = toJsonCode(resolvedType.valueType);
- if (keyCode.isIdentity && valueCode.isIdentity) {
- return new ToJsonIdentity(dartType(resolvedType));
- } else {
- return new ToJsonSnippet(dartType(type), (String value) {
- StringBuffer result = new StringBuffer();
- result.write('mapMap($value');
- if (!keyCode.isIdentity) {
- result.write(', keyCallback: ${keyCode.asClosure}');
- }
- if (!valueCode.isIdentity) {
- result.write(', valueCallback: ${valueCode.asClosure}');
- }
- result.write(')');
- return result.toString();
- });
- }
- } else if (resolvedType is TypeUnion) {
- for (TypeDecl choice in resolvedType.choices) {
- if (resolveTypeReferenceChain(choice) is! TypeObject) {
- throw new Exception('Union types must be unions of objects');
- }
- }
- return new ToJsonSnippet(
- dartType(type), (String value) => '$value.toJson()');
- } else if (resolvedType is TypeObject || resolvedType is TypeEnum) {
- return new ToJsonSnippet(
- dartType(type), (String value) => '$value.toJson()');
- } else {
- throw new Exception("Can't convert $resolvedType from JSON");
- }
- }
-
- @override
- visitApi() {
- outputHeader(year: '2017');
- writeln();
- emitImports();
- emitClasses(getClassesToEmit());
- }
-}
-
-/**
- * Container for code that can be used to translate a data type from JSON.
- */
-abstract class FromJsonCode {
- /**
- * Get the translation code in the form of a closure.
- */
- String get asClosure;
-
- /**
- * True if the data type is already in JSON form, so the translation is the
- * identity function.
- */
- bool get isIdentity;
-
- /**
- * Get the translation code in the form of a code snippet, where [jsonPath]
- * is the variable holding the JSON path, and [json] is the variable holding
- * the raw JSON.
- */
- String asSnippet(String jsonPath, String json);
-}
-
-/**
- * Representation of FromJsonCode for a function defined elsewhere.
- */
-class FromJsonFunction extends FromJsonCode {
- @override
- final String asClosure;
-
- FromJsonFunction(this.asClosure);
-
- @override
- bool get isIdentity => false;
-
- @override
- String asSnippet(String jsonPath, String json) =>
- '$asClosure($jsonPath, $json)';
-}
-
-/**
- * Representation of FromJsonCode for the identity transformation.
- */
-class FromJsonIdentity extends FromJsonSnippet {
- FromJsonIdentity() : super((String jsonPath, String json) => json);
-
- @override
- bool get isIdentity => true;
-}
-
-/**
- * Representation of FromJsonCode for a snippet of inline code.
- */
-class FromJsonSnippet extends FromJsonCode {
- /**
- * Callback that can be used to generate the code snippet, once the names
- * of the [jsonPath] and [json] variables are known.
- */
- final FromJsonSnippetCallback callback;
-
- FromJsonSnippet(this.callback);
-
- @override
- String get asClosure =>
- '(String jsonPath, Object json) => ${callback('jsonPath', 'json')}';
-
- @override
- bool get isIdentity => false;
-
- @override
- String asSnippet(String jsonPath, String json) => callback(jsonPath, json);
-}
-
-/**
- * Container for code that can be used to translate a data type to JSON.
- */
-abstract class ToJsonCode {
- /**
- * Get the translation code in the form of a closure.
- */
- String get asClosure;
-
- /**
- * True if the data type is already in JSON form, so the translation is the
- * identity function.
- */
- bool get isIdentity;
-
- /**
- * Get the translation code in the form of a code snippet, where [value]
- * is the variable holding the object to be translated.
- */
- String asSnippet(String value);
-}
-
-/**
- * Representation of ToJsonCode for a function defined elsewhere.
- */
-class ToJsonFunction extends ToJsonCode {
- @override
- final String asClosure;
-
- ToJsonFunction(this.asClosure);
-
- @override
- bool get isIdentity => false;
-
- @override
- String asSnippet(String value) => '$asClosure($value)';
-}
-
-/**
- * Representation of FromJsonCode for the identity transformation.
- */
-class ToJsonIdentity extends ToJsonSnippet {
- ToJsonIdentity(String type) : super(type, (String value) => value);
-
- @override
- bool get isIdentity => true;
-}
-
-/**
- * Representation of ToJsonCode for a snippet of inline code.
- */
-class ToJsonSnippet extends ToJsonCode {
- /**
- * Callback that can be used to generate the code snippet, once the name
- * of the [value] variable is known.
- */
- final ToJsonSnippetCallback callback;
-
- /**
- * Dart type of the [value] variable.
- */
- final String type;
-
- ToJsonSnippet(this.type, this.callback);
-
- @override
- String get asClosure => '($type value) => ${callback('value')}';
-
- @override
- bool get isIdentity => false;
-
- @override
- String asSnippet(String value) => callback(value);
-}
diff --git a/analyzer_plugin/tool/spec/codegen_inttest_methods.dart b/analyzer_plugin/tool/spec/codegen_inttest_methods.dart
deleted file mode 100644
index 924e5c3..0000000
--- a/analyzer_plugin/tool/spec/codegen_inttest_methods.dart
+++ /dev/null
@@ -1,274 +0,0 @@
-// 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.
-
-/**
- * Code generation for the file "integration_test_methods.dart".
- */
-import 'dart:convert';
-
-import 'package:analysis_tool/tools.dart';
-import 'package:path/path.dart' as path;
-
-import 'api.dart';
-import 'codegen_dart.dart';
-import 'from_html.dart';
-import 'to_html.dart';
-
-final GeneratedFile target =
- new GeneratedFile('test/integration/support/integration_test_methods.dart',
- (String pkgPath) async {
- CodegenInttestMethodsVisitor visitor = new CodegenInttestMethodsVisitor(
- path.basename(pkgPath), readApi(pkgPath));
- return visitor.collectCode(visitor.visitApi);
-});
-
-/**
- * Visitor that generates the code for integration_test_methods.dart
- */
-class CodegenInttestMethodsVisitor extends DartCodegenVisitor
- with CodeGenerator {
- /**
- * The name of the package into which code is being generated.
- */
- final String packageName;
-
- /**
- * Visitor used to produce doc comments.
- */
- final ToHtmlVisitor toHtmlVisitor;
-
- /**
- * Code snippets concatenated to initialize all of the class fields.
- */
- List<String> fieldInitializationCode = <String>[];
-
- /**
- * Code snippets concatenated to produce the contents of the switch statement
- * for dispatching notifications.
- */
- List<String> notificationSwitchContents = <String>[];
-
- CodegenInttestMethodsVisitor(this.packageName, Api api)
- : toHtmlVisitor = new ToHtmlVisitor(api),
- super(api) {
- codeGeneratorSettings.commentLineLength = 79;
- codeGeneratorSettings.languageName = 'dart';
- }
-
- /**
- * Generate a function argument for the given parameter field.
- */
- String formatArgument(TypeObjectField field) =>
- '${dartType(field.type)} ${field.name}';
-
- /**
- * Figure out the appropriate Dart type for data having the given API
- * protocol [type].
- */
- String jsonType(TypeDecl type) {
- type = resolveTypeReferenceChain(type);
- if (type is TypeEnum) {
- return 'String';
- } else if (type is TypeList) {
- return 'List<${jsonType(type.itemType)}>';
- } else if (type is TypeMap) {
- return 'Map<String, ${jsonType(type.valueType)}>';
- } else if (type is TypeObject) {
- return 'Map<String, dynamic>';
- } else if (type is TypeReference) {
- switch (type.typeName) {
- case 'String':
- case 'int':
- case 'bool':
- // These types correspond exactly to Dart types
- return type.typeName;
- case 'object':
- return 'Map<String, dynamic>';
- default:
- throw new Exception(type.typeName);
- }
- } else if (type is TypeUnion) {
- return 'Object';
- } else {
- throw new Exception('Unexpected kind of TypeDecl');
- }
- }
-
- @override
- visitApi() {
- outputHeader(year: '2017');
- writeln();
- writeln('/**');
- writeln(' * Convenience methods for running integration tests');
- writeln(' */');
- writeln("import 'dart:async';");
- writeln();
- writeln("import 'package:$packageName/protocol/protocol_generated.dart';");
- writeln(
- "import 'package:$packageName/src/protocol/protocol_internal.dart';");
- writeln("import 'package:test/test.dart';");
- writeln();
- writeln("import 'integration_tests.dart';");
- writeln("import 'protocol_matchers.dart';");
- for (String uri in api.types.importUris) {
- write("import '");
- write(uri);
- writeln("';");
- }
- writeln();
- writeln('/**');
- writeln(' * Convenience methods for running integration tests');
- writeln(' */');
- writeln('abstract class IntegrationTestMixin {');
- indent(() {
- writeln('Server get server;');
- super.visitApi();
- writeln();
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.writeln('Initialize the fields in InttestMixin, and');
- toHtmlVisitor.writeln('ensure that notifications will be handled.');
- }));
- writeln('void initializeInttestMixin() {');
- indent(() {
- write(fieldInitializationCode.join());
- });
- writeln('}');
- writeln();
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.writeln('Dispatch the notification named [event], and');
- toHtmlVisitor.writeln('containing parameters [params], to the');
- toHtmlVisitor.writeln('appropriate stream.');
- }));
- writeln('void dispatchNotification(String event, params) {');
- indent(() {
- writeln('ResponseDecoder decoder = new ResponseDecoder(null);');
- writeln('switch (event) {');
- indent(() {
- write(notificationSwitchContents.join());
- writeln('default:');
- indent(() {
- writeln("fail('Unexpected notification: \$event');");
- writeln('break;');
- });
- });
- writeln('}');
- });
- writeln('}');
- });
- writeln('}');
- }
-
- @override
- visitNotification(Notification notification) {
- String streamName =
- camelJoin(['on', notification.domainName, notification.event]);
- String className = camelJoin(
- [notification.domainName, notification.event, 'params'],
- doCapitalize: true);
- writeln();
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.translateHtml(notification.html);
- toHtmlVisitor.describePayload(notification.params, 'Parameters');
- }));
- writeln('Stream<$className> $streamName;');
- writeln();
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.write('Stream controller for [$streamName].');
- }));
- writeln('StreamController<$className> _$streamName;');
- fieldInitializationCode.add(collectCode(() {
- writeln('_$streamName = new StreamController<$className>(sync: true);');
- writeln('$streamName = _$streamName.stream.asBroadcastStream();');
- }));
- notificationSwitchContents.add(collectCode(() {
- writeln('case ${json.encode(notification.longEvent)}:');
- indent(() {
- String paramsValidator = camelJoin(
- ['is', notification.domainName, notification.event, 'params']);
- writeln('outOfTestExpect(params, $paramsValidator);');
- String constructorCall;
- if (notification.params == null) {
- constructorCall = 'new $className()';
- } else {
- constructorCall =
- "new $className.fromJson(decoder, 'params', params)";
- }
- writeln('_$streamName.add($constructorCall);');
- writeln('break;');
- });
- }));
- }
-
- @override
- visitRequest(Request request) {
- String methodName = camelJoin(['send', request.domainName, request.method]);
- List<String> args = <String>[];
- List<String> optionalArgs = <String>[];
- if (request.params != null) {
- for (TypeObjectField field in request.params.fields) {
- if (field.optional) {
- optionalArgs.add(formatArgument(field));
- } else {
- args.add(formatArgument(field));
- }
- }
- }
- if (optionalArgs.isNotEmpty) {
- args.add('{${optionalArgs.join(', ')}}');
- }
- writeln();
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.translateHtml(request.html);
- toHtmlVisitor.describePayload(request.params, 'Parameters');
- toHtmlVisitor.describePayload(request.result, 'Returns');
- }));
- if (request.deprecated) {
- writeln('@deprecated');
- }
- String resultClass;
- String futureClass;
- if (request.result == null) {
- futureClass = 'Future';
- } else {
- resultClass = camelJoin([request.domainName, request.method, 'result'],
- doCapitalize: true);
- futureClass = 'Future<$resultClass>';
- }
- writeln('$futureClass $methodName(${args.join(', ')}) async {');
- indent(() {
- String requestClass = camelJoin(
- [request.domainName, request.method, 'params'],
- doCapitalize: true);
- String paramsVar = 'null';
- if (request.params != null) {
- paramsVar = 'params';
- List<String> args = <String>[];
- List<String> optionalArgs = <String>[];
- for (TypeObjectField field in request.params.fields) {
- if (field.optional) {
- optionalArgs.add('${field.name}: ${field.name}');
- } else {
- args.add(field.name);
- }
- }
- args.addAll(optionalArgs);
- writeln('var params = new $requestClass(${args.join(', ')}).toJson();');
- }
- String methodJson = json.encode(request.longMethod);
- writeln('var result = await server.send($methodJson, $paramsVar);');
- if (request.result != null) {
- String kind = 'null';
- if (requestClass == 'EditGetRefactoringParams') {
- kind = 'kind';
- }
- writeln('ResponseDecoder decoder = new ResponseDecoder($kind);');
- writeln("return new $resultClass.fromJson(decoder, 'result', result);");
- } else {
- writeln('outOfTestExpect(result, isNull);');
- writeln('return null;');
- }
- });
- writeln('}');
- }
-}
diff --git a/analyzer_plugin/tool/spec/codegen_matchers.dart b/analyzer_plugin/tool/spec/codegen_matchers.dart
deleted file mode 100644
index bd6c7e1..0000000
--- a/analyzer_plugin/tool/spec/codegen_matchers.dart
+++ /dev/null
@@ -1,190 +0,0 @@
-// 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.
-
-/**
- * Code generation for the file "matchers.dart".
- */
-import 'dart:convert';
-
-import 'package:analysis_tool/tools.dart';
-
-import 'api.dart';
-import 'from_html.dart';
-import 'implied_types.dart';
-import 'to_html.dart';
-
-final GeneratedFile target = new GeneratedFile(
- 'test/integration/support/protocol_matchers.dart', (String pkgPath) async {
- CodegenMatchersVisitor visitor = new CodegenMatchersVisitor(readApi(pkgPath));
- return visitor.collectCode(visitor.visitApi);
-});
-
-class CodegenMatchersVisitor extends HierarchicalApiVisitor with CodeGenerator {
- /**
- * Visitor used to produce doc comments.
- */
- final ToHtmlVisitor toHtmlVisitor;
-
- /**
- * Short human-readable string describing the context of the matcher being
- * created.
- */
- String context;
-
- CodegenMatchersVisitor(Api api)
- : toHtmlVisitor = new ToHtmlVisitor(api),
- super(api) {
- codeGeneratorSettings.commentLineLength = 79;
- codeGeneratorSettings.languageName = 'dart';
- }
-
- /**
- * Create a matcher for the part of the API called [name], optionally
- * clarified by [nameSuffix]. The matcher should verify that its input
- * matches the given [type].
- */
- void makeMatcher(ImpliedType impliedType) {
- context = impliedType.humanReadableName;
- docComment(toHtmlVisitor.collectHtml(() {
- toHtmlVisitor.p(() {
- toHtmlVisitor.write(context);
- });
- if (impliedType.type != null) {
- toHtmlVisitor.showType(null, impliedType.type);
- }
- }));
- write('final Matcher ${camelJoin(['is', impliedType.camelName])} = ');
- if (impliedType.type == null) {
- write('isNull');
- } else {
- visitTypeDecl(impliedType.type);
- }
- writeln(';');
- writeln();
- }
-
- /**
- * Generate a map describing the given set of fields, for use as the
- * 'requiredFields' or 'optionalFields' argument to the [MatchesJsonObject]
- * constructor.
- */
- void outputObjectFields(Iterable<TypeObjectField> fields) {
- if (fields.isEmpty) {
- write('null');
- return;
- }
- writeln('{');
- indent(() {
- bool commaNeeded = false;
- for (TypeObjectField field in fields) {
- if (commaNeeded) {
- writeln(',');
- }
- write('${json.encode(field.name)}: ');
- if (field.value != null) {
- write('equals(${json.encode(field.value)})');
- } else {
- visitTypeDecl(field.type);
- }
- commaNeeded = true;
- }
- writeln();
- });
- write('}');
- }
-
- @override
- visitApi() {
- outputHeader(year: '2017');
- writeln();
- writeln('/**');
- writeln(' * Matchers for data types defined in the analysis server API');
- writeln(' */');
- writeln("import 'package:test/test.dart';");
- writeln();
- writeln("import 'integration_tests.dart';");
- writeln();
- List<ImpliedType> impliedTypes = computeImpliedTypes(api).values.toList();
- impliedTypes.sort((ImpliedType first, ImpliedType second) =>
- first.camelName.compareTo(second.camelName));
- for (ImpliedType impliedType in impliedTypes) {
- makeMatcher(impliedType);
- }
- }
-
- @override
- visitTypeEnum(TypeEnum typeEnum) {
- writeln('new MatchesEnum(${json.encode(context)}, [');
- indent(() {
- bool commaNeeded = false;
- for (TypeEnumValue value in typeEnum.values) {
- if (commaNeeded) {
- writeln(',');
- }
- write('${json.encode(value.value)}');
- commaNeeded = true;
- }
- writeln();
- });
- write('])');
- }
-
- @override
- visitTypeList(TypeList typeList) {
- write('isListOf(');
- visitTypeDecl(typeList.itemType);
- write(')');
- }
-
- @override
- visitTypeMap(TypeMap typeMap) {
- write('isMapOf(');
- visitTypeDecl(typeMap.keyType);
- write(', ');
- visitTypeDecl(typeMap.valueType);
- write(')');
- }
-
- @override
- void visitTypeObject(TypeObject typeObject) {
- writeln('new LazyMatcher(() => new MatchesJsonObject(');
- indent(() {
- write('${json.encode(context)}, ');
- Iterable<TypeObjectField> requiredFields =
- typeObject.fields.where((TypeObjectField field) => !field.optional);
- outputObjectFields(requiredFields);
- List<TypeObjectField> optionalFields = typeObject.fields
- .where((TypeObjectField field) => field.optional)
- .toList();
- if (optionalFields.isNotEmpty) {
- write(', optionalFields: ');
- outputObjectFields(optionalFields);
- }
- });
- write('))');
- }
-
- @override
- void visitTypeReference(TypeReference typeReference) {
- String typeName = typeReference.typeName;
- if (typeName == 'long') {
- typeName = 'int';
- }
- write(camelJoin(['is', typeName]));
- }
-
- @override
- void visitTypeUnion(TypeUnion typeUnion) {
- bool commaNeeded = false;
- write('isOneOf([');
- for (TypeDecl choice in typeUnion.choices) {
- if (commaNeeded) {
- write(', ');
- }
- visitTypeDecl(choice);
- commaNeeded = true;
- }
- write('])');
- }
-}
diff --git a/analyzer_plugin/tool/spec/codegen_protocol_common.dart b/analyzer_plugin/tool/spec/codegen_protocol_common.dart
deleted file mode 100644
index 0798d31..0000000
--- a/analyzer_plugin/tool/spec/codegen_protocol_common.dart
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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:analysis_tool/tools.dart';
-import 'package:path/path.dart' as path;
-
-import 'api.dart';
-import 'codegen_dart_protocol.dart';
-import 'from_html.dart';
-import 'implied_types.dart';
-
-GeneratedFile target(bool responseRequiresRequestTime) =>
- new GeneratedFile('lib/protocol/protocol_common.dart',
- (String pkgPath) async {
- CodegenCommonVisitor visitor = new CodegenCommonVisitor(
- path.basename(pkgPath),
- responseRequiresRequestTime,
- readApi(pkgPath));
- return visitor.collectCode(visitor.visitApi);
- });
-
-/**
- * A visitor that produces Dart code defining the common types associated with
- * the API.
- */
-class CodegenCommonVisitor extends CodegenProtocolVisitor {
- /**
- * Initialize a newly created visitor to generate code in the package with the
- * given [packageName] corresponding to the types in the given [api] that are
- * common to multiple protocols.
- */
- CodegenCommonVisitor(
- String packageName, bool responseRequiresRequestTime, Api api)
- : super(packageName, responseRequiresRequestTime, api);
-
- @override
- void emitImports() {
- writeln("import 'dart:convert' hide JsonDecoder;");
- writeln();
- writeln("import 'package:analyzer/src/generated/utilities_general.dart';");
- writeln("import 'package:$packageName/protocol/protocol.dart';");
- writeln(
- "import 'package:$packageName/src/protocol/protocol_internal.dart';");
- }
-
- @override
- List<ImpliedType> getClassesToEmit() {
- List<ImpliedType> types = impliedTypes.values.where((ImpliedType type) {
- ApiNode node = type.apiNode;
- return node is TypeDefinition && node.isExternal;
- }).toList();
- types.sort((first, second) =>
- capitalize(first.camelName).compareTo(capitalize(second.camelName)));
- return types;
- }
-}
diff --git a/analyzer_plugin/tool/spec/codegen_protocol_constants.dart b/analyzer_plugin/tool/spec/codegen_protocol_constants.dart
deleted file mode 100644
index 7ff2570..0000000
--- a/analyzer_plugin/tool/spec/codegen_protocol_constants.dart
+++ /dev/null
@@ -1,169 +0,0 @@
-// 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:analysis_tool/tools.dart';
-
-import 'api.dart';
-import 'codegen_dart.dart';
-import 'from_html.dart';
-
-final GeneratedFile target = new GeneratedFile(
- 'lib/protocol/protocol_constants.dart', (String pkgPath) async {
- CodegenVisitor visitor = new CodegenVisitor(readApi(pkgPath));
- return visitor.collectCode(visitor.visitApi);
-});
-
-/**
- * A visitor that produces Dart code defining constants associated with the API.
- */
-class CodegenVisitor extends DartCodegenVisitor with CodeGenerator {
- CodegenVisitor(Api api) : super(api) {
- codeGeneratorSettings.commentLineLength = 79;
- codeGeneratorSettings.languageName = 'dart';
- }
-
- /**
- * Generate all of the constants associates with the [api].
- */
- void generateConstants() {
- _ConstantVisitor visitor = new _ConstantVisitor(api);
- visitor.visitApi();
- List<_Constant> constants = visitor.constants;
- constants.sort((first, second) => first.name.compareTo(second.name));
- for (_Constant constant in constants) {
- generateContant(constant);
- }
- }
-
- /**
- * Generate the given [constant].
- */
- void generateContant(_Constant constant) {
- write('const String ');
- write(constant.name);
- write(' = ');
- write(constant.value);
- writeln(';');
- }
-
- @override
- visitApi() {
- outputHeader(year: '2017');
- writeln();
- generateConstants();
- }
-}
-
-/**
- * A representation of a constant that is to be generated.
- */
-class _Constant {
- /**
- * The name of the constant.
- */
- final String name;
-
- /**
- * The value of the constant.
- */
- final String value;
-
- /**
- * Initialize a newly created constant.
- */
- _Constant(this.name, this.value);
-}
-
-/**
- * A visitor that visits an API to compute a list of constants to be generated.
- */
-class _ConstantVisitor extends HierarchicalApiVisitor {
- /**
- * The list of constants to be generated.
- */
- List<_Constant> constants = <_Constant>[];
-
- /**
- * Initialize a newly created visitor to visit the given [api].
- */
- _ConstantVisitor(Api api) : super(api);
-
- @override
- void visitNotification(Notification notification) {
- String domainName = notification.domainName;
- String event = notification.event;
-
- String constantName = _generateName(domainName, 'notification', event);
- constants.add(new _Constant(constantName, "'$domainName.$event'"));
- _addFieldConstants(constantName, notification.params);
- }
-
- @override
- void visitRequest(Request request) {
- String domainName = request.domainName;
- String method = request.method;
-
- String requestConstantName = _generateName(domainName, 'request', method);
- constants.add(new _Constant(requestConstantName, "'$domainName.$method'"));
- _addFieldConstants(requestConstantName, request.params);
-
- String responseConstantName = _generateName(domainName, 'response', method);
- _addFieldConstants(responseConstantName, request.result);
- }
-
- /**
- * Generate a constant for each of the fields in the given [type], where the
- * name of each constant will be composed from the [parentName] and the name
- * of the field.
- */
- void _addFieldConstants(String parentName, TypeObject type) {
- if (type == null) {
- return;
- }
- type.fields.forEach((TypeObjectField field) {
- String name = field.name;
- List<String> components = <String>[];
- components.add(parentName);
- components.addAll(_split(name));
- String fieldConstantName = _fromComponents(components);
- constants.add(new _Constant(fieldConstantName, "'$name'"));
- });
- }
-
- /**
- * Return a name generated by converting each of the given [components] to an
- * uppercase equivalent, then joining them with underscores.
- */
- String _fromComponents(List<String> components) =>
- components.map((String component) => component.toUpperCase()).join('_');
-
- /**
- * Generate a name from the [domainName], [kind] and [name] components.
- */
- String _generateName(String domainName, String kind, String name) {
- List<String> components = <String>[];
- components.addAll(_split(domainName));
- components.add(kind);
- components.addAll(_split(name));
- return _fromComponents(components);
- }
-
- /**
- * Return the components of the given [string] that are indicated by an upper
- * case letter.
- */
- Iterable<String> _split(String first) {
- RegExp regExp = new RegExp('[A-Z]');
- List<String> components = <String>[];
- int start = 1;
- int index = first.indexOf(regExp, start);
- while (index >= 0) {
- components.add(first.substring(start - 1, index));
- start = index + 1;
- index = first.indexOf(regExp, start);
- }
- components.add(first.substring(start - 1));
- return components;
- }
-}
diff --git a/analyzer_plugin/tool/spec/from_html.dart b/analyzer_plugin/tool/spec/from_html.dart
deleted file mode 100644
index fe9cf69..0000000
--- a/analyzer_plugin/tool/spec/from_html.dart
+++ /dev/null
@@ -1,606 +0,0 @@
-// 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.
-
-/**
- * Code for reading an HTML API description.
- */
-import 'dart:io';
-
-import 'package:analysis_tool/html.dart';
-import 'package:html/dom.dart' as dom;
-import 'package:html/parser.dart' as parser;
-import 'package:path/path.dart';
-
-import 'api.dart';
-
-/**
- * Read the API description from the file 'plugin_spec.html'. [pkgPath] is the
- * path to the current package.
- */
-Api readApi(String pkgPath) {
- ApiReader reader =
- new ApiReader(join(pkgPath, 'tool', 'spec', 'plugin_spec.html'));
- return reader.readApi();
-}
-
-typedef void ElementProcessor(dom.Element element);
-
-typedef void TextProcessor(dom.Text text);
-
-class ApiReader {
- static const List<String> specialElements = const [
- 'domain',
- 'feedback',
- 'object',
- 'refactorings',
- 'refactoring',
- 'type',
- 'types',
- 'request',
- 'notification',
- 'params',
- 'result',
- 'field',
- 'list',
- 'map',
- 'enum',
- 'key',
- 'value',
- 'options',
- 'ref',
- 'code',
- 'version',
- 'union',
- 'index',
- 'include'
- ];
-
- /**
- * The absolute and normalized path to the file being read.
- */
- final String filePath;
-
- /**
- * Initialize a newly created API reader to read from the file with the given
- * [filePath].
- */
- ApiReader(this.filePath);
-
- /**
- * Create an [Api] object from an HTML representation such as:
- *
- * <html>
- * ...
- * <body>
- * ... <version>1.0</version> ...
- * <domain name="...">...</domain> <!-- zero or more -->
- * <types>...</types>
- * <refactorings>...</refactorings>
- * </body>
- * </html>
- *
- * Child elements of <api> can occur in any order.
- */
- Api apiFromHtml(dom.Element html) {
- Api api;
- List<String> versions = <String>[];
- List<Domain> domains = <Domain>[];
- Types types = null;
- Refactorings refactorings = null;
- recurse(html, 'api', {
- 'domain': (dom.Element element) {
- domains.add(domainFromHtml(element));
- },
- 'refactorings': (dom.Element element) {
- refactorings = refactoringsFromHtml(element);
- },
- 'types': (dom.Element element) {
- types = typesFromHtml(element);
- },
- 'version': (dom.Element element) {
- versions.add(innerText(element));
- },
- 'index': (dom.Element element) {
- /* Ignore; generated dynamically. */
- }
- });
- if (versions.length != 1) {
- throw new Exception('The API must contain exactly one <version> element');
- }
- api = new Api(versions[0], domains, types, refactorings, html);
- return api;
- }
-
- /**
- * Check that the given [element] has all of the attributes in
- * [requiredAttributes], possibly some of the attributes in
- * [optionalAttributes], and no others.
- */
- void checkAttributes(
- dom.Element element, List<String> requiredAttributes, String context,
- {List<String> optionalAttributes: const []}) {
- Set<String> attributesFound = new Set<String>();
- element.attributes.forEach((name, value) {
- if (!requiredAttributes.contains(name) &&
- !optionalAttributes.contains(name)) {
- throw new Exception(
- '$context: Unexpected attribute in ${element.localName}: $name');
- }
- attributesFound.add(name as String);
- });
- for (String expectedAttribute in requiredAttributes) {
- if (!attributesFound.contains(expectedAttribute)) {
- throw new Exception(
- '$context: ${element.localName} must contain attribute $expectedAttribute');
- }
- }
- }
-
- /**
- * Check that the given [element] has the given [expectedName].
- */
- void checkName(dom.Element element, String expectedName, [String context]) {
- if (element.localName != expectedName) {
- if (context == null) {
- context = element.localName;
- }
- throw new Exception(
- '$context: Expected $expectedName, found ${element.localName}');
- }
- }
-
- /**
- * Create a [Domain] object from an HTML representation such as:
- *
- * <domain name="domainName">
- * <request method="...">...</request> <!-- zero or more -->
- * <notification event="...">...</notification> <!-- zero or more -->
- * </domain>
- *
- * Child elements can occur in any order.
- */
- Domain domainFromHtml(dom.Element html) {
- checkName(html, 'domain');
- String name = html.attributes['name'];
- String context = name ?? 'domain';
- bool experimental = html.attributes['experimental'] == 'true';
- checkAttributes(html, ['name'], context,
- optionalAttributes: ['experimental']);
- List<Request> requests = <Request>[];
- List<Notification> notifications = <Notification>[];
- recurse(html, context, {
- 'request': (dom.Element child) {
- requests.add(requestFromHtml(child, context));
- },
- 'notification': (dom.Element child) {
- notifications.add(notificationFromHtml(child, context));
- }
- });
- return new Domain(name, requests, notifications, html,
- experimental: experimental);
- }
-
- dom.Element getAncestor(dom.Element html, String name, String context) {
- dom.Element ancestor = html.parent;
- while (ancestor != null) {
- if (ancestor.localName == name) {
- return ancestor;
- }
- ancestor = ancestor.parent;
- }
- throw new Exception(
- '$context: <${html.localName}> must be nested within <$name>');
- }
-
- /**
- * Create a [Notification] object from an HTML representation such as:
- *
- * <notification event="methodName">
- * <params>...</params> <!-- optional -->
- * </notification>
- *
- * Note that the event name should not include the domain name.
- *
- * <params> has the same form as <object>, as described in [typeDeclFromHtml].
- *
- * Child elements can occur in any order.
- */
- Notification notificationFromHtml(dom.Element html, String context) {
- String domainName = getAncestor(html, 'domain', context).attributes['name'];
- checkName(html, 'notification', context);
- String event = html.attributes['event'];
- context = '$context.${event != null ? event : 'event'}';
- checkAttributes(html, ['event'], context);
- TypeObject params;
- recurse(html, context, {
- 'params': (dom.Element child) {
- params = typeObjectFromHtml(child, '$context.params');
- }
- });
- return new Notification(domainName, event, params, html);
- }
-
- /**
- * Create a single of [TypeDecl] corresponding to the type defined inside the
- * given HTML element.
- */
- TypeDecl processContentsAsType(dom.Element html, String context) {
- List<TypeDecl> types = processContentsAsTypes(html, context);
- if (types.length != 1) {
- throw new Exception('$context: Exactly one type must be specified');
- }
- return types[0];
- }
-
- /**
- * Create a list of [TypeDecl]s corresponding to the types defined inside the
- * given HTML element. The following forms are supported.
- *
- * To refer to a type declared elsewhere (or a built-in type):
- *
- * <ref>typeName</ref>
- *
- * For a list: <list>ItemType</list>
- *
- * For a map: <map><key>KeyType</key><value>ValueType</value></map>
- *
- * For a JSON object:
- *
- * <object>
- * <field name="...">...</field> <!-- zero or more -->
- * </object>
- *
- * For an enum:
- *
- * <enum>
- * <value>...</value> <!-- zero or more -->
- * </enum>
- *
- * For a union type:
- * <union>
- * TYPE <!-- zero or more -->
- * </union>
- */
- List<TypeDecl> processContentsAsTypes(dom.Element html, String context) {
- List<TypeDecl> types = <TypeDecl>[];
- recurse(html, context, {
- 'object': (dom.Element child) {
- types.add(typeObjectFromHtml(child, context));
- },
- 'list': (dom.Element child) {
- checkAttributes(child, [], context);
- types.add(new TypeList(processContentsAsType(child, context), child));
- },
- 'map': (dom.Element child) {
- checkAttributes(child, [], context);
- TypeDecl keyType;
- TypeDecl valueType;
- recurse(child, context, {
- 'key': (dom.Element child) {
- if (keyType != null) {
- throw new Exception('$context: Key type already specified');
- }
- keyType = processContentsAsType(child, '$context.key');
- },
- 'value': (dom.Element child) {
- if (valueType != null) {
- throw new Exception('$context: Value type already specified');
- }
- valueType = processContentsAsType(child, '$context.value');
- }
- });
- if (keyType == null) {
- throw new Exception('$context: Key type not specified');
- }
- if (valueType == null) {
- throw new Exception('$context: Value type not specified');
- }
- types.add(new TypeMap(keyType as TypeReference, valueType, child));
- },
- 'enum': (dom.Element child) {
- types.add(typeEnumFromHtml(child, context));
- },
- 'ref': (dom.Element child) {
- checkAttributes(child, [], context);
- types.add(new TypeReference(innerText(child), child));
- },
- 'union': (dom.Element child) {
- checkAttributes(child, ['field'], context);
- String field = child.attributes['field'];
- types.add(new TypeUnion(
- processContentsAsTypes(child, context), field, child));
- }
- });
- return types;
- }
-
- /**
- * Read the API description from file with the given [filePath].
- */
- Api readApi() {
- String htmlContents = new File(filePath).readAsStringSync();
- dom.Document document = parser.parse(htmlContents);
- dom.Element htmlElement = document.children
- .singleWhere((element) => element.localName.toLowerCase() == 'html');
- return apiFromHtml(htmlElement);
- }
-
- void recurse(dom.Element parent, String context,
- Map<String, ElementProcessor> elementProcessors) {
- for (String key in elementProcessors.keys) {
- if (!specialElements.contains(key)) {
- throw new Exception('$context: $key is not a special element');
- }
- }
- for (dom.Node node in parent.nodes) {
- if (node is dom.Element) {
- if (elementProcessors.containsKey(node.localName)) {
- elementProcessors[node.localName](node);
- } else if (specialElements.contains(node.localName)) {
- throw new Exception(
- '$context: Unexpected use of <${node.localName}>');
- } else {
- recurse(node, context, elementProcessors);
- }
- }
- }
- }
-
- /**
- * Create a [Refactoring] object from an HTML representation such as:
- *
- * <refactoring kind="refactoringKind">
- * <feedback>...</feedback> <!-- optional -->
- * <options>...</options> <!-- optional -->
- * </refactoring>
- *
- * <feedback> and <options> have the same form as <object>, as described in
- * [typeDeclFromHtml].
- *
- * Child elements can occur in any order.
- */
- Refactoring refactoringFromHtml(dom.Element html) {
- checkName(html, 'refactoring');
- String kind = html.attributes['kind'];
- String context = kind != null ? kind : 'refactoring';
- checkAttributes(html, ['kind'], context);
- TypeObject feedback;
- TypeObject options;
- recurse(html, context, {
- 'feedback': (dom.Element child) {
- feedback = typeObjectFromHtml(child, '$context.feedback');
- },
- 'options': (dom.Element child) {
- options = typeObjectFromHtml(child, '$context.options');
- }
- });
- return new Refactoring(kind, feedback, options, html);
- }
-
- /**
- * Create a [Refactorings] object from an HTML representation such as:
- *
- * <refactorings>
- * <refactoring kind="...">...</refactoring> <!-- zero or more -->
- * </refactorings>
- */
- Refactorings refactoringsFromHtml(dom.Element html) {
- checkName(html, 'refactorings');
- String context = 'refactorings';
- checkAttributes(html, [], context);
- List<Refactoring> refactorings = <Refactoring>[];
- recurse(html, context, {
- 'refactoring': (dom.Element child) {
- refactorings.add(refactoringFromHtml(child));
- }
- });
- return new Refactorings(refactorings, html);
- }
-
- /**
- * Create a [Request] object from an HTML representation such as:
- *
- * <request method="methodName">
- * <params>...</params> <!-- optional -->
- * <result>...</result> <!-- optional -->
- * </request>
- *
- * Note that the method name should not include the domain name.
- *
- * <params> and <result> have the same form as <object>, as described in
- * [typeDeclFromHtml].
- *
- * Child elements can occur in any order.
- */
- Request requestFromHtml(dom.Element html, String context) {
- String domainName = getAncestor(html, 'domain', context).attributes['name'];
- checkName(html, 'request', context);
- String method = html.attributes['method'];
- context = '$context.${method != null ? method : 'method'}';
- checkAttributes(html, ['method'], context,
- optionalAttributes: ['experimental', 'deprecated']);
- bool experimental = html.attributes['experimental'] == 'true';
- bool deprecated = html.attributes['deprecated'] == 'true';
- TypeObject params;
- TypeObject result;
- recurse(html, context, {
- 'params': (dom.Element child) {
- params = typeObjectFromHtml(child, '$context.params');
- },
- 'result': (dom.Element child) {
- result = typeObjectFromHtml(child, '$context.result');
- }
- });
- return new Request(domainName, method, params, result, html,
- experimental: experimental, deprecated: deprecated);
- }
-
- /**
- * Create a [TypeDefinition] object from an HTML representation such as:
- *
- * <type name="typeName">
- * TYPE
- * </type>
- *
- * Where TYPE is any HTML that can be parsed by [typeDeclFromHtml].
- *
- * Child elements can occur in any order.
- */
- TypeDefinition typeDefinitionFromHtml(dom.Element html) {
- checkName(html, 'type');
- String name = html.attributes['name'];
- String context = name != null ? name : 'type';
- checkAttributes(html, ['name'], context,
- optionalAttributes: ['experimental', 'deprecated']);
- TypeDecl type = processContentsAsType(html, context);
- bool experimental = html.attributes['experimental'] == 'true';
- bool deprecated = html.attributes['deprecated'] == 'true';
- return new TypeDefinition(name, type, html,
- experimental: experimental, deprecated: deprecated);
- }
-
- /**
- * Create a [TypeEnum] from an HTML description.
- */
- TypeEnum typeEnumFromHtml(dom.Element html, String context) {
- checkName(html, 'enum', context);
- checkAttributes(html, [], context);
- List<TypeEnumValue> values = <TypeEnumValue>[];
- recurse(html, context, {
- 'value': (dom.Element child) {
- values.add(typeEnumValueFromHtml(child, context));
- }
- });
- return new TypeEnum(values, html);
- }
-
- /**
- * Create a [TypeEnumValue] from an HTML description such as:
- *
- * <enum>
- * <code>VALUE</code>
- * </enum>
- *
- * Where VALUE is the text of the enumerated value.
- *
- * Child elements can occur in any order.
- */
- TypeEnumValue typeEnumValueFromHtml(dom.Element html, String context) {
- checkName(html, 'value', context);
- checkAttributes(html, [], context, optionalAttributes: ['deprecated']);
- bool deprecated = html.attributes['deprecated'] == 'true';
- List<String> values = <String>[];
- recurse(html, context, {
- 'code': (dom.Element child) {
- String text = innerText(child).trim();
- values.add(text);
- }
- });
- if (values.length != 1) {
- throw new Exception('$context: Exactly one value must be specified');
- }
- return new TypeEnumValue(values[0], html, deprecated: deprecated);
- }
-
- /**
- * Create a [TypeObjectField] from an HTML description such as:
- *
- * <field name="fieldName">
- * TYPE
- * </field>
- *
- * Where TYPE is any HTML that can be parsed by [typeDeclFromHtml].
- *
- * In addition, the attribute optional="true" may be used to specify that the
- * field is optional, and the attribute value="..." may be used to specify that
- * the field is required to have a certain value.
- *
- * Child elements can occur in any order.
- */
- TypeObjectField typeObjectFieldFromHtml(dom.Element html, String context) {
- checkName(html, 'field', context);
- String name = html.attributes['name'];
- context = '$context.${name != null ? name : 'field'}';
- checkAttributes(html, ['name'], context,
- optionalAttributes: ['optional', 'value', 'deprecated']);
- bool deprecated = html.attributes['deprecated'] == 'true';
- bool optional = false;
- String optionalString = html.attributes['optional'];
- if (optionalString != null) {
- switch (optionalString) {
- case 'true':
- optional = true;
- break;
- case 'false':
- optional = false;
- break;
- default:
- throw new Exception(
- '$context: field contains invalid "optional" attribute: "$optionalString"');
- }
- }
- String value = html.attributes['value'];
- TypeDecl type = processContentsAsType(html, context);
- return new TypeObjectField(name, type, html,
- optional: optional, value: value, deprecated: deprecated);
- }
-
- /**
- * Create a [TypeObject] from an HTML description.
- */
- TypeObject typeObjectFromHtml(dom.Element html, String context) {
- checkAttributes(html, [], context, optionalAttributes: ['experimental']);
- List<TypeObjectField> fields = <TypeObjectField>[];
- recurse(html, context, {
- 'field': (dom.Element child) {
- fields.add(typeObjectFieldFromHtml(child, context));
- }
- });
- bool experimental = html.attributes['experimental'] == 'true';
- return new TypeObject(fields, html, experimental: experimental);
- }
-
- /**
- * Create a [Types] object from an HTML representation such as:
- *
- * <types>
- * <type name="...">...</type> <!-- zero or more -->
- * </types>
- */
- Types typesFromHtml(dom.Element html) {
- checkName(html, 'types');
- String context = 'types';
- checkAttributes(html, [], context);
- List<String> importUris = <String>[];
- Map<String, TypeDefinition> typeMap = <String, TypeDefinition>{};
- List<dom.Element> childElements = <dom.Element>[];
- recurse(html, context, {
- 'include': (dom.Element child) {
- String importUri = child.attributes['import'];
- if (importUri != null) {
- importUris.add(importUri);
- }
- String relativePath = child.attributes['path'];
- String path = normalize(join(dirname(filePath), relativePath));
- ApiReader reader = new ApiReader(path);
- Api api = reader.readApi();
- for (TypeDefinition typeDefinition in api.types) {
- typeDefinition.isExternal = true;
- childElements.add(typeDefinition.html);
- typeMap[typeDefinition.name] = typeDefinition;
- }
- },
- 'type': (dom.Element child) {
- TypeDefinition typeDefinition = typeDefinitionFromHtml(child);
- typeMap[typeDefinition.name] = typeDefinition;
- }
- });
- for (dom.Element element in childElements) {
- html.append(element);
- }
- Types types = new Types(typeMap, html);
- types.importUris.addAll(importUris);
- return types;
- }
-}
diff --git a/analyzer_plugin/tool/spec/generate_all.dart b/analyzer_plugin/tool/spec/generate_all.dart
deleted file mode 100644
index f959c85..0000000
--- a/analyzer_plugin/tool/spec/generate_all.dart
+++ /dev/null
@@ -1,38 +0,0 @@
-// 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:analysis_tool/tools.dart';
-import 'package:path/path.dart';
-
-import 'codegen_dart_protocol.dart' as codegen_dart_protocol;
-import 'codegen_inttest_methods.dart' as codegen_inttest_methods;
-import 'codegen_matchers.dart' as codegen_matchers;
-import 'codegen_protocol_common.dart' as codegen_protocol_common;
-import 'codegen_protocol_constants.dart' as codegen_protocol_constants;
-import 'to_html.dart' as to_html;
-
-/**
- * Generate all targets.
- */
-main() async {
- String script = Platform.script.toFilePath(windows: Platform.isWindows);
- String pkgPath = normalize(join(dirname(script), '..', '..'));
- await GeneratedContent.generateAll(pkgPath, allTargets);
-}
-
-/**
- * Get a list of all generated targets.
- */
-List<GeneratedContent> get allTargets {
- List<GeneratedContent> targets = <GeneratedContent>[];
- targets.add(codegen_dart_protocol.target(true));
- targets.add(codegen_inttest_methods.target);
- targets.add(codegen_matchers.target);
- targets.add(codegen_protocol_common.target(true));
- targets.add(codegen_protocol_constants.target);
- targets.add(to_html.target);
- return targets;
-}
diff --git a/analyzer_plugin/tool/spec/generate_files b/analyzer_plugin/tool/spec/generate_files
deleted file mode 100755
index da36490..0000000
--- a/analyzer_plugin/tool/spec/generate_files
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env bash
-# 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 script generates the following files, based on the contents of
-# spec_input.html:
-#
-# - ../../doc/api.html: The human-readable API spec.
-#
-# - ../../test/integration/protocol_matchers.dart: matchers to be used by
-# integration tests.
-#
-# - ../../test/integration/integration_test_methods.dart: convenience methods
-# to be used by integration tests.
-
-set -e
-
-function follow_links() {
- file="$1"
- while [ -h "$file" ]; do
- # On Mac OS, readlink -f doesn't work.
- file="$(readlink "$file")"
- done
- echo "$file"
-}
-
-# Unlike $0, $BASH_SOURCE points to the absolute path of this file.
-PROG_NAME="$(follow_links "$BASH_SOURCE")"
-
-SCRIPT_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
-
-ROOT_DIR="$(cd "${SCRIPT_DIR}/../../../.." ; pwd -P)"
-
-if [[ $1 == '--arch' && $2 == 'x64' ]];
-then
- DART_CONFIGURATION="ReleaseX64"
-elif [ -z "$DART_CONFIGURATION" ];
-then
- DART_CONFIGURATION="ReleaseIA32"
-fi
-
-if [[ `uname` == 'Darwin' ]];
-then
- BUILD_DIR="${ROOT_DIR}/xcodebuild/$DART_CONFIGURATION"
-fi
-
-PKG_FILE="${ROOT_DIR}/.packages"
-if [[ !(-e $PKG_FILE) ]];
-then
- PKG_FILE="${ROOT_DIR}/.packages"
-fi
-
-DART="${BUILD_DIR}/dart-sdk/bin/dart"
-
-declare -a VM_OPTIONS
-VM_OPTIONS+=("--enable-asserts")
-VM_OPTIONS+=("--packages=${PKG_FILE}")
-
-cd "${SCRIPT_DIR}"
-"${DART}" "${VM_OPTIONS[@]}" "generate_all.dart"
diff --git a/analyzer_plugin/tool/spec/implied_types.dart b/analyzer_plugin/tool/spec/implied_types.dart
deleted file mode 100644
index 2cf1c8b..0000000
--- a/analyzer_plugin/tool/spec/implied_types.dart
+++ /dev/null
@@ -1,89 +0,0 @@
-// 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.
-
-/**
- * Code for enumerating the set of types implied by the API.
- */
-import 'package:analysis_tool/tools.dart';
-
-import 'api.dart';
-
-Map<String, ImpliedType> computeImpliedTypes(Api api) {
- _ImpliedTypesVisitor visitor = new _ImpliedTypesVisitor(api);
- visitor.visitApi();
- return visitor.impliedTypes;
-}
-
-class ImpliedType {
- final String camelName;
- final String humanReadableName;
- final TypeDecl type;
-
- /**
- * Kind of implied type this is. One of:
- * - 'requestParams'
- * - 'requestResult'
- * - 'notificationParams'
- * - 'refactoringFeedback'
- * - 'refactoringOptions'
- * - 'typeDefinition'
- */
- final String kind;
-
- /**
- * API node from which this type was inferred.
- */
- final ApiNode apiNode;
-
- ImpliedType(this.camelName, this.humanReadableName, this.type, this.kind,
- this.apiNode);
-}
-
-class _ImpliedTypesVisitor extends HierarchicalApiVisitor {
- Map<String, ImpliedType> impliedTypes = <String, ImpliedType>{};
-
- _ImpliedTypesVisitor(Api api) : super(api);
-
- void storeType(String name, String nameSuffix, TypeDecl type, String kind,
- ApiNode apiNode) {
- String humanReadableName = name;
- List<String> camelNameParts = name.split('.');
- if (nameSuffix != null) {
- humanReadableName += ' $nameSuffix';
- camelNameParts.add(nameSuffix);
- }
- String camelName = camelJoin(camelNameParts);
- impliedTypes[camelName] =
- new ImpliedType(camelName, humanReadableName, type, kind, apiNode);
- }
-
- @override
- visitNotification(Notification notification) {
- storeType(notification.longEvent, 'params', notification.params,
- 'notificationParams', notification);
- }
-
- @override
- visitRefactoring(Refactoring refactoring) {
- String camelKind = camelJoin(refactoring.kind.toLowerCase().split('_'));
- storeType(camelKind, 'feedback', refactoring.feedback,
- 'refactoringFeedback', refactoring);
- storeType(camelKind, 'options', refactoring.options, 'refactoringOptions',
- refactoring);
- }
-
- @override
- visitRequest(Request request) {
- storeType(
- request.longMethod, 'params', request.params, 'requestParams', request);
- storeType(
- request.longMethod, 'result', request.result, 'requestResult', request);
- }
-
- @override
- visitTypeDefinition(TypeDefinition typeDefinition) {
- storeType(typeDefinition.name, null, typeDefinition.type, 'typeDefinition',
- typeDefinition);
- }
-}
diff --git a/analyzer_plugin/tool/spec/to_html.dart b/analyzer_plugin/tool/spec/to_html.dart
deleted file mode 100644
index 5a519e0..0000000
--- a/analyzer_plugin/tool/spec/to_html.dart
+++ /dev/null
@@ -1,827 +0,0 @@
-// 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.
-
-/**
- * Code for displaying the API as HTML. This is used both for generating a
- * full description of the API as a web page, and for generating doc comments
- * in generated code.
- */
-import 'dart:convert';
-
-import 'package:analysis_tool/html.dart';
-import 'package:analysis_tool/tools.dart';
-import 'package:html/dom.dart' as dom;
-
-import 'api.dart';
-import 'from_html.dart';
-
-/**
- * Embedded stylesheet
- */
-final String stylesheet = '''
-body {
- font-family: 'Roboto', sans-serif;
- max-width: 800px;
- margin: 0 auto;
- padding: 0 16px;
- font-size: 16px;
- line-height: 1.5;
- color: #111;
- background-color: #fdfdfd;
- font-weight: 300;
- -webkit-font-smoothing: auto;
-}
-
-h2, h3, h4, h5 {
- margin-bottom: 0;
-}
-
-h2.domain {
- border-bottom: 1px solid rgb(200, 200, 200);
- margin-bottom: 0.5em;
-}
-
-h4 {
- font-size: 18px;
-}
-
-h5 {
- font-size: 16px;
-}
-
-p {
- margin-top: 0;
-}
-
-pre {
- margin: 0;
- font-family: 'Source Code Pro', monospace;
- font-size: 15px;
-}
-
-div.box {
- background-color: rgb(240, 245, 240);
- border-radius: 4px;
- padding: 4px 12px;
- margin: 16px 0;
-}
-
-div.hangingIndent {
- padding-left: 3em;
- text-indent: -3em;
-}
-
-dl dt {
- font-weight: bold;
-}
-
-dl dd {
- margin-left: 16px;
-}
-
-dt {
- margin-top: 1em;
-}
-
-dt.notification {
- font-weight: bold;
-}
-
-dt.refactoring {
- font-weight: bold;
-}
-
-dt.request {
- font-weight: bold;
-}
-
-dt.typeDefinition {
- font-weight: bold;
-}
-
-a {
- text-decoration: none;
-}
-
-a:focus, a:hover {
- text-decoration: underline;
-}
-
-.deprecated {
- text-decoration: line-through;
-}
-
-/* Styles for index */
-
-.subindex ul {
- padding-left: 0;
- margin-left: 0;
-
- -webkit-margin-before: 0;
- -webkit-margin-start: 0;
- -webkit-padding-start: 0;
-
- list-style-type: none;
-}
-'''
- .trim();
-
-final GeneratedFile target =
- new GeneratedFile('doc/api.html', (String pkgPath) async {
- ToHtmlVisitor visitor = new ToHtmlVisitor(readApi(pkgPath));
- dom.Document document = new dom.Document();
- document.append(new dom.DocumentType('html', null, null));
- for (dom.Node node in visitor.collectHtml(visitor.visitApi)) {
- document.append(node);
- }
- return document.outerHtml;
-});
-
-String _toTitleCase(String str) {
- if (str.isEmpty) return str;
- return str.substring(0, 1).toUpperCase() + str.substring(1);
-}
-
-/**
- * Visitor that records the mapping from HTML elements to various kinds of API
- * nodes.
- */
-class ApiMappings extends HierarchicalApiVisitor {
- Map<dom.Element, Domain> domains = <dom.Element, Domain>{};
-
- ApiMappings(Api api) : super(api);
-
- @override
- void visitDomain(Domain domain) {
- domains[domain.html] = domain;
- }
-}
-
-/**
- * Helper methods for creating HTML elements.
- */
-abstract class HtmlMixin {
- void anchor(String id, void callback()) {
- element('a', {'name': id}, callback);
- }
-
- void b(void callback()) => element('b', {}, callback);
- void body(void callback()) => element('body', {}, callback);
- void box(void callback()) {
- element('div', {'class': 'box'}, callback);
- }
-
- void br() => element('br', {});
- void dd(void callback()) => element('dd', {}, callback);
- void dl(void callback()) => element('dl', {}, callback);
- void dt(String cls, void callback()) =>
- element('dt', {'class': cls}, callback);
- void element(String name, Map<dynamic, String> attributes, [void callback()]);
- void gray(void callback()) =>
- element('span', {'style': 'color:#999999'}, callback);
- void h1(void callback()) => element('h1', {}, callback);
- void h2(String cls, void callback()) {
- if (cls == null) {
- return element('h2', {}, callback);
- }
- return element('h2', {'class': cls}, callback);
- }
-
- void h3(void callback()) => element('h3', {}, callback);
- void h4(void callback()) => element('h4', {}, callback);
- void h5(void callback()) => element('h5', {}, callback);
- void hangingIndent(void callback()) =>
- element('div', {'class': 'hangingIndent'}, callback);
- void head(void callback()) => element('head', {}, callback);
- void html(void callback()) => element('html', {}, callback);
- void i(void callback()) => element('i', {}, callback);
- void li(void callback()) => element('li', {}, callback);
- void link(String id, void callback(), [Map<dynamic, String> attributes]) {
- attributes ??= {};
- attributes['href'] = '#$id';
- element('a', attributes, callback);
- }
-
- void p(void callback()) => element('p', {}, callback);
- void pre(void callback()) => element('pre', {}, callback);
- void span(String cls, void callback()) =>
- element('span', {'class': cls}, callback);
- void title(void callback()) => element('title', {}, callback);
- void tt(void callback()) => element('tt', {}, callback);
- void ul(void callback()) => element('ul', {}, callback);
-}
-
-/**
- * Visitor that generates HTML documentation of the API.
- */
-class ToHtmlVisitor extends HierarchicalApiVisitor
- with HtmlMixin, HtmlGenerator {
- /**
- * Set of types defined in the API.
- */
- Set<String> definedTypes = new Set<String>();
-
- /**
- * Mappings from HTML elements to API nodes.
- */
- ApiMappings apiMappings;
-
- ToHtmlVisitor(Api api)
- : apiMappings = new ApiMappings(api),
- super(api) {
- apiMappings.visitApi();
- }
-
- /**
- * Describe the payload of request, response, notification, refactoring
- * feedback, or refactoring options.
- *
- * If [force] is true, then a section is inserted even if the payload is
- * null.
- */
- void describePayload(TypeObject subType, String name, {bool force: false}) {
- if (force || subType != null) {
- h4(() {
- write(name);
- });
- if (subType == null) {
- p(() {
- write('none');
- });
- } else {
- visitTypeDecl(subType);
- }
- }
- }
-
- void generateDomainIndex(Domain domain) {
- h4(() {
- write(domain.name);
- write(' (');
- link('domain_${domain.name}', () => write('\u2191'));
- write(')');
- });
- if (domain.requests.length > 0) {
- element('div', {'class': 'subindex'}, () {
- generateRequestsIndex(domain.requests);
- if (domain.notifications.length > 0) {
- generateNotificationsIndex(domain.notifications);
- }
- });
- } else if (domain.notifications.length > 0) {
- element('div', {'class': 'subindex'}, () {
- generateNotificationsIndex(domain.notifications);
- });
- }
- }
-
- void generateDomainsHeader() {
- h1(() {
- write('Domains');
- });
- }
-
- void generateIndex() {
- h3(() => write('Domains'));
- for (var domain in api.domains) {
- if (domain.experimental ||
- (domain.requests.length == 0 && domain.notifications == 0)) {
- continue;
- }
- generateDomainIndex(domain);
- }
-
- generateTypesIndex(definedTypes);
- generateRefactoringsIndex(api.refactorings);
- }
-
- void generateNotificationsIndex(Iterable<Notification> notifications) {
- h5(() => write("Notifications"));
- element('div', {'class': 'subindex'}, () {
- element('ul', {}, () {
- for (var notification in notifications) {
- element(
- 'li',
- {},
- () => link('notification_${notification.longEvent}',
- () => write(notification.event)));
- }
- });
- });
- }
-
- void generateRefactoringsIndex(Iterable<Refactoring> refactorings) {
- if (refactorings == null) {
- return;
- }
- h3(() {
- write("Refactorings");
- write(' (');
- link('refactorings', () => write('\u2191'));
- write(')');
- });
- // TODO: Individual refactorings are not yet hyperlinked.
- element('div', {'class': 'subindex'}, () {
- element('ul', {}, () {
- for (var refactoring in refactorings) {
- element(
- 'li',
- {},
- () => link('refactoring_${refactoring.kind}',
- () => write(refactoring.kind)));
- }
- });
- });
- }
-
- void generateRequestsIndex(Iterable<Request> requests) {
- h5(() => write("Requests"));
- element('ul', {}, () {
- for (var request in requests) {
- if (!request.experimental) {
- element(
- 'li',
- {},
- () => link('request_${request.longMethod}',
- () => write(request.method)));
- }
- }
- });
- }
-
- void generateTableOfContents() {
- for (var domain in api.domains.where((domain) => !domain.experimental)) {
- if (domain.experimental) continue;
-
- writeln();
-
- p(() {
- link('domain_${domain.name}', () {
- write(_toTitleCase(domain.name));
- });
- });
-
- ul(() {
- for (Request request in domain.requests) {
- if (request.experimental) continue;
-
- li(() {
- link('request_${request.longMethod}', () {
- write(request.longMethod);
- }, request.deprecated ? {'class': 'deprecated'} : null);
- });
- writeln();
- }
- });
-
- writeln();
- }
- }
-
- void generateTypesIndex(Set<String> types) {
- h3(() {
- write("Types");
- write(' (');
- link('types', () => write('\u2191'));
- write(')');
- });
- List<String> sortedTypes = types.toList();
- sortedTypes.sort();
- element('div', {'class': 'subindex'}, () {
- element('ul', {}, () {
- for (var type in sortedTypes) {
- element('li', {}, () => link('type_$type', () => write(type)));
- }
- });
- });
- }
-
- void javadocParams(TypeObject typeObject) {
- if (typeObject != null) {
- for (TypeObjectField field in typeObject.fields) {
- hangingIndent(() {
- write('@param ${field.name} ');
- translateHtml(field.html, squashParagraphs: true);
- });
- }
- }
- }
-
- /**
- * Generate a description of [type] using [TypeVisitor].
- *
- * If [shortDesc] is non-null, the output is prefixed with this string
- * and a colon.
- *
- * If [typeForBolding] is supplied, then fields in this type are shown in
- * boldface.
- */
- void showType(String shortDesc, TypeDecl type, [TypeObject typeForBolding]) {
- Set<String> fieldsToBold = new Set<String>();
- if (typeForBolding != null) {
- for (TypeObjectField field in typeForBolding.fields) {
- fieldsToBold.add(field.name);
- }
- }
- pre(() {
- if (shortDesc != null) {
- write('$shortDesc: ');
- }
- TypeVisitor typeVisitor =
- new TypeVisitor(api, fieldsToBold: fieldsToBold);
- addAll(typeVisitor.collectHtml(() {
- typeVisitor.visitTypeDecl(type);
- }));
- });
- }
-
- /**
- * Copy the contents of the given HTML element, translating the special
- * elements that define the API appropriately.
- */
- void translateHtml(dom.Element html, {bool squashParagraphs: false}) {
- for (dom.Node node in html.nodes) {
- if (node is dom.Element) {
- if (squashParagraphs && node.localName == 'p') {
- translateHtml(node, squashParagraphs: squashParagraphs);
- continue;
- }
- switch (node.localName) {
- case 'domains':
- generateDomainsHeader();
- break;
- case 'domain':
- visitDomain(apiMappings.domains[node]);
- break;
- case 'head':
- head(() {
- translateHtml(node, squashParagraphs: squashParagraphs);
- element('link', {
- 'rel': 'stylesheet',
- 'href':
- 'https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400',
- 'type': 'text/css'
- });
- element('style', {}, () {
- writeln(stylesheet);
- });
- });
- break;
- case 'refactorings':
- visitRefactorings(api.refactorings);
- break;
- case 'types':
- visitTypes(api.types);
- break;
- case 'version':
- translateHtml(node, squashParagraphs: squashParagraphs);
- break;
- case 'toc':
- generateTableOfContents();
- break;
- case 'index':
- generateIndex();
- break;
- default:
- if (!ApiReader.specialElements.contains(node.localName)) {
- element(node.localName, node.attributes, () {
- translateHtml(node, squashParagraphs: squashParagraphs);
- });
- }
- }
- } else if (node is dom.Text) {
- String text = node.text;
- write(text);
- }
- }
- }
-
- @override
- void visitApi() {
- Iterable<TypeDefinition> apiTypes =
- api.types.where((TypeDefinition td) => !td.experimental);
- definedTypes = apiTypes.map((TypeDefinition td) => td.name).toSet();
-
- html(() {
- translateHtml(api.html);
- });
- }
-
- @override
- void visitDomain(Domain domain) {
- if (domain.experimental) {
- return;
- }
- h2('domain', () {
- anchor('domain_${domain.name}', () {
- write('${domain.name} domain');
- });
- });
- translateHtml(domain.html);
- if (domain.requests.isNotEmpty) {
- h3(() {
- write('Requests');
- });
- dl(() {
- domain.requests.forEach(visitRequest);
- });
- }
- if (domain.notifications.isNotEmpty) {
- h3(() {
- write('Notifications');
- });
- dl(() {
- domain.notifications.forEach(visitNotification);
- });
- }
- }
-
- @override
- void visitNotification(Notification notification) {
- dt('notification', () {
- anchor('notification_${notification.longEvent}', () {
- write(notification.longEvent);
- });
- });
- dd(() {
- box(() {
- showType(
- 'notification', notification.notificationType, notification.params);
- });
- translateHtml(notification.html);
- describePayload(notification.params, 'parameters:');
- });
- }
-
- @override
- visitRefactoring(Refactoring refactoring) {
- dt('refactoring', () {
- write(refactoring.kind);
- });
- dd(() {
- translateHtml(refactoring.html);
- describePayload(refactoring.feedback, 'Feedback:', force: true);
- describePayload(refactoring.options, 'Options:', force: true);
- });
- }
-
- @override
- void visitRefactorings(Refactorings refactorings) {
- translateHtml(refactorings.html);
- dl(() {
- super.visitRefactorings(refactorings);
- });
- }
-
- @override
- void visitRequest(Request request) {
- if (request.experimental) {
- return;
- }
- dt(request.deprecated ? 'request deprecated' : 'request', () {
- anchor('request_${request.longMethod}', () {
- write(request.longMethod);
- });
- });
- dd(() {
- box(() {
- showType('request', request.requestType, request.params);
- br();
- showType('response', request.responseType, request.result);
- });
- translateHtml(request.html);
- describePayload(request.params, 'parameters:');
- describePayload(request.result, 'returns:');
- });
- }
-
- @override
- void visitTypeDefinition(TypeDefinition typeDefinition) {
- if (typeDefinition.experimental) {
- return;
- }
- dt(
- typeDefinition.deprecated
- ? 'typeDefinition deprecated'
- : 'typeDefinition', () {
- anchor('type_${typeDefinition.name}', () {
- write('${typeDefinition.name}: ');
- TypeVisitor typeVisitor = new TypeVisitor(api, short: true);
- addAll(typeVisitor.collectHtml(() {
- typeVisitor.visitTypeDecl(typeDefinition.type);
- }));
- });
- });
- dd(() {
- translateHtml(typeDefinition.html);
- visitTypeDecl(typeDefinition.type);
- });
- }
-
- @override
- void visitTypeEnum(TypeEnum typeEnum) {
- dl(() {
- super.visitTypeEnum(typeEnum);
- });
- }
-
- @override
- void visitTypeEnumValue(TypeEnumValue typeEnumValue) {
- bool isDocumented = false;
- for (dom.Node node in typeEnumValue.html.nodes) {
- if ((node is dom.Element && node.localName != 'code') ||
- (node is dom.Text && node.text.trim().isNotEmpty)) {
- isDocumented = true;
- break;
- }
- }
- dt(typeEnumValue.deprecated ? 'value deprecated' : 'value', () {
- write(typeEnumValue.value);
- });
- if (isDocumented) {
- dd(() {
- translateHtml(typeEnumValue.html);
- });
- }
- }
-
- @override
- void visitTypeList(TypeList typeList) {
- visitTypeDecl(typeList.itemType);
- }
-
- @override
- void visitTypeMap(TypeMap typeMap) {
- visitTypeDecl(typeMap.valueType);
- }
-
- @override
- void visitTypeObject(TypeObject typeObject) {
- dl(() {
- super.visitTypeObject(typeObject);
- });
- }
-
- @override
- void visitTypeObjectField(TypeObjectField typeObjectField) {
- dt('field', () {
- b(() {
- if (typeObjectField.deprecated) {
- span('deprecated', () {
- write(typeObjectField.name);
- });
- } else {
- write(typeObjectField.name);
- }
- if (typeObjectField.value != null) {
- write(' = ${json.encode(typeObjectField.value)}');
- } else {
- write(': ');
- TypeVisitor typeVisitor = new TypeVisitor(api, short: true);
- addAll(typeVisitor.collectHtml(() {
- typeVisitor.visitTypeDecl(typeObjectField.type);
- }));
- if (typeObjectField.optional) {
- gray(() => write(' (optional)'));
- }
- }
- });
- });
- dd(() {
- translateHtml(typeObjectField.html);
- });
- }
-
- @override
- void visitTypeReference(TypeReference typeReference) {}
-
- @override
- void visitTypes(Types types) {
- translateHtml(types.html);
- dl(() {
- List<TypeDefinition> sortedTypes = types.toList();
- sortedTypes.sort((TypeDefinition first, TypeDefinition second) =>
- first.name.compareTo(second.name));
- sortedTypes.forEach(visitTypeDefinition);
- });
- }
-}
-
-/**
- * Visitor that generates a compact representation of a type, such as:
- *
- * {
- * "id": String
- * "error": optional Error
- * "result": {
- * "version": String
- * }
- * }
- */
-class TypeVisitor extends HierarchicalApiVisitor
- with HtmlMixin, HtmlCodeGenerator {
- /**
- * Set of fields which should be shown in boldface, or null if no field
- * should be shown in boldface.
- */
- final Set<String> fieldsToBold;
-
- /**
- * True if a short description should be generated. In a short description,
- * objects are shown as simply "object", and enums are shown as "String".
- */
- final bool short;
-
- TypeVisitor(Api api, {this.fieldsToBold, this.short: false}) : super(api);
-
- @override
- void visitTypeEnum(TypeEnum typeEnum) {
- if (short) {
- write('String');
- return;
- }
- writeln('enum {');
- indent(() {
- for (TypeEnumValue value in typeEnum.values) {
- writeln(value.value);
- }
- });
- write('}');
- }
-
- @override
- void visitTypeList(TypeList typeList) {
- write('List<');
- visitTypeDecl(typeList.itemType);
- write('>');
- }
-
- @override
- void visitTypeMap(TypeMap typeMap) {
- write('Map<');
- visitTypeDecl(typeMap.keyType);
- write(', ');
- visitTypeDecl(typeMap.valueType);
- write('>');
- }
-
- @override
- void visitTypeObject(TypeObject typeObject) {
- if (short) {
- write('object');
- return;
- }
- writeln('{');
- indent(() {
- for (TypeObjectField field in typeObject.fields) {
- write('"');
- if (fieldsToBold != null && fieldsToBold.contains(field.name)) {
- b(() {
- write(field.name);
- });
- } else {
- write(field.name);
- }
- write('": ');
- if (field.value != null) {
- write(json.encode(field.value));
- } else {
- if (field.optional) {
- gray(() {
- write('optional');
- });
- write(' ');
- }
- visitTypeDecl(field.type);
- }
- writeln();
- }
- });
- write('}');
- }
-
- @override
- void visitTypeReference(TypeReference typeReference) {
- String displayName = typeReference.typeName;
- if (api.types.containsKey(typeReference.typeName)) {
- link('type_${typeReference.typeName}', () {
- write(displayName);
- });
- } else {
- write(displayName);
- }
- }
-
- @override
- void visitTypeUnion(TypeUnion typeUnion) {
- bool verticalBarNeeded = false;
- for (TypeDecl choice in typeUnion.choices) {
- if (verticalBarNeeded) {
- write(' | ');
- }
- visitTypeDecl(choice);
- verticalBarNeeded = true;
- }
- }
-}
diff --git a/build/BUILD.gn b/build/BUILD.gn
index 5b679d1..633bca4 100644
--- a/build/BUILD.gn
+++ b/build/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for build-1.2.1
+# This file is generated by importer.py for build-1.2.0
import("//build/dart/dart_library.gni")
diff --git a/build/CHANGELOG.md b/build/CHANGELOG.md
index 7d53894..1ff0302 100644
--- a/build/CHANGELOG.md
+++ b/build/CHANGELOG.md
@@ -1,7 +1,3 @@
-## 1.2.1
-
-- Allow analyzer `0.39.x`.
-
## 1.2.0
- Add the `void reportUnusedAssets(Iterable<AssetId> ids)` method to the
diff --git a/build/lib/src/analyzer/resolver.dart b/build/lib/src/analyzer/resolver.dart
index 838c981..8f68a6c 100644
--- a/build/lib/src/analyzer/resolver.dart
+++ b/build/lib/src/analyzer/resolver.dart
@@ -62,7 +62,7 @@
/// this [Resolvers].
///
/// In between calls to [reset] no Assets should change, so every call to
- /// `BuildStep.readAsString` for a given AssetId should return identical
+ /// [BuildStep.readAsString] for a given AssetId should return identical
/// contents. Any time an Asset's contents may change [reset] must be called.
void reset() {}
}
diff --git a/build/mono_pkg.yaml b/build/mono_pkg.yaml
index dc1b387..66e63e4 100644
--- a/build/mono_pkg.yaml
+++ b/build/mono_pkg.yaml
@@ -11,9 +11,6 @@
- 2.3.0
- unit_test:
- command: pub run build_runner test
- os:
- - linux
- - windows
cache:
directories:
diff --git a/build/pubspec.yaml b/build/pubspec.yaml
index 0272de7..e56c9e6 100644
--- a/build/pubspec.yaml
+++ b/build/pubspec.yaml
@@ -1,14 +1,14 @@
name: build
-version: 1.2.1
+version: 1.2.0
description: A build system for Dart.
author: Dart Team <misc@dartlang.org>
homepage: https://github.com/dart-lang/build/tree/master/build
environment:
- sdk: ">=2.3.0 <3.0.0"
+ sdk: ">=2.2.2 <3.0.0"
dependencies:
- analyzer: '>=0.35.0 <0.40.0'
+ analyzer: '>=0.35.0 <0.39.0'
async: ">=1.13.3 <3.0.0"
convert: ^2.0.0
crypto: ">=0.9.2 <3.0.0"
diff --git a/build_modules/BUILD.gn b/build_modules/BUILD.gn
index 3364eb2..a3cdc5c 100644
--- a/build_modules/BUILD.gn
+++ b/build_modules/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for build_modules-2.6.3
+# This file is generated by importer.py for build_modules-2.6.2
import("//build/dart/dart_library.gni")
diff --git a/build_modules/CHANGELOG.md b/build_modules/CHANGELOG.md
index d0a1679..037fe72 100644
--- a/build_modules/CHANGELOG.md
+++ b/build_modules/CHANGELOG.md
@@ -1,12 +1,3 @@
-## 2.6.3
-
-- Keep cached deserialized module instances in more cases. This may improve
- performance of incremental builds in watch mode.
-- **Deprecated**: The package specific unsupported module whitelist option
- provided by `computeTransitiveDependencies`. The only known uses are being
- removed.
-- Allow analyzer version `0.39.x`.
-
## 2.6.2
Republish of `2.6.0` with the proper min sdk contraint.
diff --git a/build_modules/lib/src/module_cache.dart b/build_modules/lib/src/module_cache.dart
index 5a91108..452046d 100644
--- a/build_modules/lib/src/module_cache.dart
+++ b/build_modules/lib/src/module_cache.dart
@@ -6,7 +6,6 @@
import 'package:async/async.dart';
import 'package:build/build.dart';
-import 'package:crypto/crypto.dart';
import 'meta_module.dart';
import 'modules.dart';
@@ -38,19 +37,14 @@
Resource<DecodingCache<T>>(() => DecodingCache._(fromBytes, toBytes),
dispose: (c) => c._dispose());
- final _cached = <AssetId, _Entry<T>>{};
+ final _cached = <AssetId, Future<Result<T>>>{};
final T Function(List<int>) _fromBytes;
final List<int> Function(T) _toBytes;
DecodingCache._(this._fromBytes, this._toBytes);
- void _dispose() {
- _cached.removeWhere((_, entry) => entry.digest == null);
- for (var entry in _cached.values) {
- entry.needsCheck = true;
- }
- }
+ void _dispose() => _cached.clear();
/// Find and deserialize a [T] stored in [id].
///
@@ -59,29 +53,9 @@
/// content dependencies will be tracked through [reader].
Future<T> find(AssetId id, AssetReader reader) async {
if (!await reader.canRead(id)) return null;
- _Entry<T> entry;
- if (!_cached.containsKey(id)) {
- entry = _cached[id] = _Entry()
- ..needsCheck = false
- ..value = Result.capture(reader.readAsBytes(id).then(_fromBytes))
- ..digest = Result.capture(reader.digest(id));
- } else {
- entry = _cached[id];
- if (entry.needsCheck) {
- await (entry.onGoingCheck ??= () async {
- var previousDigest = await Result.release(entry.digest);
- entry.digest = Result.capture(reader.digest(id));
- if (await Result.release(entry.digest) != previousDigest) {
- entry.value =
- Result.capture(reader.readAsBytes(id).then(_fromBytes));
- }
- entry
- ..needsCheck = false
- ..onGoingCheck = null;
- }());
- }
- }
- return Result.release(entry.value);
+ var result = _cached.putIfAbsent(
+ id, () => Result.capture(reader.readAsBytes(id).then(_fromBytes)));
+ return Result.release(result);
}
/// Serialized and write a [T] to [id].
@@ -90,15 +64,6 @@
/// instances without deserializing it.
Future<void> write(AssetId id, AssetWriter writer, T instance) async {
await writer.writeAsBytes(id, _toBytes(instance));
- _cached[id] = _Entry()
- ..needsCheck = false
- ..value = Result.capture(Future.value(instance));
+ _cached[id] = Result.capture(Future.value(instance));
}
}
-
-class _Entry<T> {
- bool needsCheck = false;
- Future<Result<T>> value;
- Future<Result<Digest>> digest;
- Future<void> onGoingCheck;
-}
diff --git a/build_modules/lib/src/modules.dart b/build_modules/lib/src/modules.dart
index 439c08d..b135f8e 100644
--- a/build_modules/lib/src/modules.dart
+++ b/build_modules/lib/src/modules.dart
@@ -139,7 +139,7 @@
/// will be thrown if there are any modules that are not supported.
Future<List<Module>> computeTransitiveDependencies(BuildStep buildStep,
{bool throwIfUnsupported = false,
- @deprecated Set<String> skipPlatformCheckPackages = const {}}) async {
+ Set<String> skipPlatformCheckPackages = const {}}) async {
throwIfUnsupported ??= false;
skipPlatformCheckPackages ??= const {};
final modules = await buildStep.fetchResource(moduleCache);
diff --git a/build_modules/mono_pkg.yaml b/build_modules/mono_pkg.yaml
index 3d1ec9e..96dfc46 100644
--- a/build_modules/mono_pkg.yaml
+++ b/build_modules/mono_pkg.yaml
@@ -1,5 +1,5 @@
dart:
- - dev
+ - dev/release/2.6.0-dev.1.0
stages:
- analyze_and_format:
@@ -13,9 +13,6 @@
# Run the script directly - running from snapshot has issues for packages
# that are depended on by build_runner itself.
- command: dart $(pub run build_runner generate-build-script) test --delete-conflicting-outputs -- -P presubmit
- os:
- - linux
- - windows
cache:
directories:
diff --git a/build_modules/pubspec.yaml b/build_modules/pubspec.yaml
index a637ef7..d61ce8b 100644
--- a/build_modules/pubspec.yaml
+++ b/build_modules/pubspec.yaml
@@ -1,5 +1,5 @@
name: build_modules
-version: 2.6.3
+version: 2.6.2
description: Builders for Dart modules
author: Dart Team <misc@dartlang.org>
homepage: https://github.com/dart-lang/build/tree/master/build_modules
@@ -8,7 +8,7 @@
sdk: ">=2.5.0 <3.0.0"
dependencies:
- analyzer: ">0.35.0 <0.40.0"
+ analyzer: ">0.30.0 <0.39.0"
async: ^2.0.0
bazel_worker: ^0.1.20
build: ">=1.2.0 <2.0.0"
@@ -28,12 +28,9 @@
build_runner: ^1.0.0
build_test: ^0.10.9
build_vm_compilers: ^1.0.0
+ json_serializable: ^3.1.0
test: ^1.6.0
a:
path: test/fixtures/a
b:
path: test/fixtures/b
-
-dependency_overrides:
- build_vm_compilers:
- path: ../build_vm_compilers
diff --git a/build_web_compilers/BUILD.gn b/build_web_compilers/BUILD.gn
index 53b8d98..ad95387 100644
--- a/build_web_compilers/BUILD.gn
+++ b/build_web_compilers/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for build_web_compilers-2.7.1
+# This file is generated by importer.py for build_web_compilers-2.7.0
import("//build/dart/dart_library.gni")
diff --git a/build_web_compilers/CHANGELOG.md b/build_web_compilers/CHANGELOG.md
index 3518c63..3f3c852 100644
--- a/build_web_compilers/CHANGELOG.md
+++ b/build_web_compilers/CHANGELOG.md
@@ -1,7 +1,3 @@
-## 2.7.1
-
-- Allow analyzer version `0.39.x`.
-
## 2.7.0
- Added an `environment` option to the `DevCompilerBuilder`.
diff --git a/build_web_compilers/pubspec.yaml b/build_web_compilers/pubspec.yaml
index 44253c6..e10f532 100644
--- a/build_web_compilers/pubspec.yaml
+++ b/build_web_compilers/pubspec.yaml
@@ -1,5 +1,5 @@
name: build_web_compilers
-version: 2.7.1
+version: 2.7.0
description: Builder implementations wrapping Dart compilers.
author: Dart Team <misc@dartlang.org>
homepage: https://github.com/dart-lang/build/tree/master/build_web_compilers
@@ -8,7 +8,7 @@
sdk: ">=2.5.0 <3.0.0"
dependencies:
- analyzer: ">=0.30.0 <0.40.0"
+ analyzer: ">=0.30.0 <0.39.0"
archive: ^2.0.0
bazel_worker: ^0.1.18
build: ">=1.2.0 <2.0.0"
diff --git a/built_value/BUILD.gn b/built_value/BUILD.gn
index 4a1eb53..33ad906 100644
--- a/built_value/BUILD.gn
+++ b/built_value/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for built_value-6.8.2
+# This file is generated by importer.py for built_value-6.7.1
import("//build/dart/dart_library.gni")
diff --git a/built_value/CHANGELOG.md b/built_value/CHANGELOG.md
index ee70872..3d28bb1 100644
--- a/built_value/CHANGELOG.md
+++ b/built_value/CHANGELOG.md
@@ -1,31 +1,5 @@
# Changelog
-# 6.8.2
-
-- Fix `_finalizeBuilder` generation so it uses the correct class name.
-
-# 6.8.1
-
-- Fix missing `README.md` in `package:built_value`.
-
-# 6.8.0
-
-- Support `_initializeBuilder` hook in value types. If found, it's executed
- when a `Builder` is created and can be used to set defaults.
-- Support `_finalizeBuilder` hook in value types. If found, it's executed
- when `build` is called and can be used to apply processing to fields.
-- Add `defaultCompare` and `defaultSerialize` to `@BuiltValue`. They
- control the defaults for `compare` and `serialize` in `@BuiltValueField`.
-- Add facility to merge `Serializers` instances via `Serializers.merge`,
- `SerializersBuilder.merge` and `SerializersBuilder.mergeAll`.
-- Bug fix: fix generated code with polymorphism and more than one level of
- non-instantiable classes.
-- Bug fix: fix generated `operator==` when a field is called `other`.
-- Fix `num` deserialization so it does not always convert to `double`.
-- Bump version of `analyzer`.
-- Internal: replace analyzer's `DartType.displayName` with custom code
- generator.
-
# 6.7.1
- Fix codegen for custom builders when fields use types that have an import
diff --git a/built_value/README.md b/built_value/README.md
index c960618..6ef2c81 100644
--- a/built_value/README.md
+++ b/built_value/README.md
@@ -2,7 +2,7 @@
[![Build Status](https://travis-ci.org/google/built_value.dart.svg?branch=master)](https://travis-ci.org/google/built_value.dart)
## Introduction
-Built Value provides:
+Built Values provides:
- Immutable value types;
- EnumClass, classes that behave like enums;
@@ -11,8 +11,6 @@
Immutable collections are from
[built_collection](https://github.com/google/built_collection.dart#built-collections-for-dart).
-See the [API docs](https://pub.dev/documentation/built_value/latest/built_value/built_value-library.html).
-
## Articles
- [`built_value` for Immutable Object Models](https://medium.com/@davidmorgan_14314/darts-built-value-for-immutable-object-models-83e2497922d4#.48dyezxcl)
@@ -169,6 +167,9 @@
the classes the server knows. Most other libraries are monolithic, requiring all
endpoints to know all types.
+It's _multi language_. Support will be come first for Dart, Java and
+Java/GWT. Many other libraries support a single language only.
+
It _has first class support for validation_ via Built Values. An important
part of a powerful data model is ensuring it's valid, so classes can make
guarantees about what they can do. Other libraries also support validation
@@ -180,12 +181,6 @@
interoperate with other tools or to add hand coded high performance serializers
for specific classes. Some other libraries are not so extensible.
-It was designed to be _multi language_, mapping to equivalent object models in
-Java and other languages. Currently only Dart is supported. The need for other
-languages didn't materialize as servers are typically either written in Dart
-or owned by third parties. Please open an issue if you'd like to explore
-support in more languages.
-
## Common Usage
While full, compiled examples are available in
diff --git a/built_value/lib/built_value.dart b/built_value/lib/built_value.dart
index 985a744..8b3033d 100644
--- a/built_value/lib/built_value.dart
+++ b/built_value/lib/built_value.dart
@@ -25,10 +25,9 @@
B toBuilder();
}
-/// Every [Built] class has a corresponding [Builder] class.
+/// Every Built Value must have a [Builder] class.
///
-/// Usually you don't need to create one by hand; it will be generated
-/// for you.
+/// Use it to set defaults, if needed, and to do validation.
///
/// See <https://github.com/google/built_value.dart/tree/master/example>
abstract class Builder<V extends Built<V, B>, B extends Builder<V, B>> {
@@ -105,25 +104,13 @@
/// indicates that the name is to be taken from the literal class name.
final String wireName;
- /// The default for [BuiltValueField.compare]. Set to `false` if you want to
- /// ignore most fields when comparing, then mark the ones you do want to
- /// compare on with `@BuiltValueField(compare: true)`.
- final bool defaultCompare;
-
- /// The default for [BuiltValueField.serialize]. Set to `false` if you want
- /// to ignore most fields when serializing, then mark the ones you do want
- /// to serialize with `@BuiltValueField(serialize: true)`.
- final bool defaultSerialize;
-
const BuiltValue(
{this.instantiable = true,
this.nestedBuilders = true,
this.autoCreateNestedBuilders = true,
this.comparableBuilders = false,
this.generateBuilderOnSetField = false,
- this.wireName,
- this.defaultCompare = true,
- this.defaultSerialize = true});
+ this.wireName});
}
/// Nullable annotation for Built Value fields.
@@ -134,15 +121,13 @@
/// Optionally, annotate a Built Value field with this to specify settings.
/// This is only needed for advanced use.
class BuiltValueField {
- /// Whether the field is compared and hashed. Defaults to `null` which means
- /// [BuiltValue.defaultCompare] is used.
+ /// Whether the field is compared and hashed. Defaults to `true`.
///
/// Set to `false` to ignore the field when calculating `hashCode` and when
/// comparing with `operator==`.
final bool compare;
- /// Whether the field is serialized. Defaults to `null` which means
- /// [BuiltValue.defaultSerialize] is used.
+ /// Whether the field is serialized. Defaults to `true`.
///
/// If a field is not serialized, it must either be `@nullable` or specify a
/// default for deserialization to succeed.
@@ -152,7 +137,8 @@
/// indicates the name is to be taken from the literal field name.
final String wireName;
- const BuiltValueField({this.compare, this.serialize, this.wireName});
+ const BuiltValueField(
+ {this.compare = true, this.serialize = true, this.wireName});
}
/// Optionally, annotate a Built Value `Serializer` getters with this to
diff --git a/built_value/lib/serializer.dart b/built_value/lib/serializer.dart
index 07ff2c9..f54f95e 100644
--- a/built_value/lib/serializer.dart
+++ b/built_value/lib/serializer.dart
@@ -89,12 +89,6 @@
.build();
}
- /// Merges iterable of [Serializers] into a single [Serializers].
- ///
- /// [Serializer] and builder factories are accumulated. Plugins are not.
- static Serializers merge(Iterable<Serializers> serializersIterable) =>
- (Serializers().toBuilder()..mergeAll(serializersIterable)).build();
-
/// The installed [Serializer]s.
Iterable<Serializer> get serializers;
@@ -180,16 +174,9 @@
/// via its `types` property.
void add(Serializer serializer);
- /// Merges a [Serializers], adding all of its [Serializer] instances and
- /// builder factories. Does _not_ add plugins.
- void merge(Serializers serializers);
-
/// Adds an iterable of [Serializer].
void addAll(Iterable<Serializer> serializers);
- /// Merges an iterable of [Serializers].
- void mergeAll(Iterable<Serializers> serializersIterable);
-
/// Adds a builder factory.
///
/// Builder factories are needed when deserializing to types that use
diff --git a/built_value/lib/src/built_json_serializers.dart b/built_value/lib/src/built_json_serializers.dart
index dc356c5..0891614 100644
--- a/built_value/lib/src/built_json_serializers.dart
+++ b/built_value/lib/src/built_json_serializers.dart
@@ -257,19 +257,6 @@
}
@override
- void merge(Serializers serializers) {
- addAll(serializers.serializers);
- _builderFactories.addAll(serializers.builderFactories.asMap());
- }
-
- @override
- void mergeAll(Iterable<Serializers> serializersIterable) {
- for (var serializers in serializersIterable) {
- merge(serializers);
- }
- }
-
- @override
void addPlugin(SerializerPlugin plugin) {
_plugins.add(plugin);
}
diff --git a/built_value/lib/src/num_serializer.dart b/built_value/lib/src/num_serializer.dart
index b9a0173..f4eecc6 100644
--- a/built_value/lib/src/num_serializer.dart
+++ b/built_value/lib/src/num_serializer.dart
@@ -37,7 +37,7 @@
} else if (serialized == DoubleSerializer.infinity) {
return double.infinity;
} else {
- return serialized as num;
+ return (serialized as num).toDouble();
}
}
}
diff --git a/built_value/pubspec.yaml b/built_value/pubspec.yaml
index d976635..7320cf1 100644
--- a/built_value/pubspec.yaml
+++ b/built_value/pubspec.yaml
@@ -1,5 +1,5 @@
name: built_value
-version: 6.8.2
+version: 6.7.1
description: >
Value types with builders, Dart classes as enums, and serialization.
This library is the runtime dependency.
@@ -12,10 +12,6 @@
dependencies:
built_collection: '>=2.0.0 <5.0.0'
- # `built_value` 6.8.0 changed default of `BuiltValueField.compare` and
- # `BuiltValueField.serialize` to `null`, which breaks older
- # `built_value_generator`.
- built_value_generator: ^6.8.2
collection: ^1.0.0
fixnum: ^0.10.0
quiver: '>=0.21.0 <3.0.0'
diff --git a/built_value_generator/AUTHORS b/built_value_generator/AUTHORS
deleted file mode 100644
index be0c30e..0000000
--- a/built_value_generator/AUTHORS
+++ /dev/null
@@ -1,10 +0,0 @@
-# Below is a list of people and organizations that have contributed
-# to the project. Names should be added to the list like so:
-#
-# Name/Organization <email address>
-
-Abhijeeth Padarthi <rkinabhi@gmail.com>
-David Morgan/Google Inc. <davidmorgan@google.com>
-Ivan Inozemtsev/Google Inc. <iinozemtsev@google.com>
-John Dengis <jadengis@gmail.com>
-Resul Alkan/MetGlobal <me@resulalkan.com>
diff --git a/built_value_generator/BUILD.gn b/built_value_generator/BUILD.gn
deleted file mode 100644
index 8f92598..0000000
--- a/built_value_generator/BUILD.gn
+++ /dev/null
@@ -1,24 +0,0 @@
-# This file is generated by importer.py for built_value_generator-6.8.2
-
-import("//build/dart/dart_library.gni")
-
-dart_library("built_value_generator") {
- package_name = "built_value_generator"
-
- # This parameter is left empty as we don't care about analysis or exporting
- # these sources outside of the tree.
- sources = []
-
- disable_analysis = true
-
- deps = [
- "//third_party/dart-pkg/pub/built_collection",
- "//third_party/dart-pkg/pub/quiver",
- "//third_party/dart-pkg/pub/analyzer_plugin",
- "//third_party/dart-pkg/pub/analyzer",
- "//third_party/dart-pkg/pub/build",
- "//third_party/dart-pkg/pub/build_config",
- "//third_party/dart-pkg/pub/built_value",
- "//third_party/dart-pkg/pub/source_gen",
- ]
-}
diff --git a/built_value_generator/CHANGELOG.md b/built_value_generator/CHANGELOG.md
deleted file mode 100644
index ee70872..0000000
--- a/built_value_generator/CHANGELOG.md
+++ /dev/null
@@ -1,650 +0,0 @@
-# Changelog
-
-# 6.8.2
-
-- Fix `_finalizeBuilder` generation so it uses the correct class name.
-
-# 6.8.1
-
-- Fix missing `README.md` in `package:built_value`.
-
-# 6.8.0
-
-- Support `_initializeBuilder` hook in value types. If found, it's executed
- when a `Builder` is created and can be used to set defaults.
-- Support `_finalizeBuilder` hook in value types. If found, it's executed
- when `build` is called and can be used to apply processing to fields.
-- Add `defaultCompare` and `defaultSerialize` to `@BuiltValue`. They
- control the defaults for `compare` and `serialize` in `@BuiltValueField`.
-- Add facility to merge `Serializers` instances via `Serializers.merge`,
- `SerializersBuilder.merge` and `SerializersBuilder.mergeAll`.
-- Bug fix: fix generated code with polymorphism and more than one level of
- non-instantiable classes.
-- Bug fix: fix generated `operator==` when a field is called `other`.
-- Fix `num` deserialization so it does not always convert to `double`.
-- Bump version of `analyzer`.
-- Internal: replace analyzer's `DartType.displayName` with custom code
- generator.
-
-# 6.7.1
-
-- Fix codegen for custom builders when fields use types that have an import
- prefix.
-- Bump version of `analyzer_plugin`.
-
-# 6.7.0
-
-- Generate code compatible with 'no raw types'.
-
-# 6.6.0
-
-- Allow providing your own `toString` via a mixin.
-- Fix `BuiltValueSerializer(serializeNulls: true)` for non-primitive fields.
-- Stop using old analyzer API; require analyzer `0.34.0`.
-
-# 6.5.0
-
-- Add `Iso8601DurationSerializer` for use when you want ISO8601 serialization
- instead of the default microseconds serialization.
-- Bump versions of `analyzer`, `analyzer_plugin` and `build_config`.
-
-# 6.4.0
-
-- Add `@BuiltValue(generateBuilderOnSetField: true)` which provides a way to
- listen for `set` calls on generated builders.
-- Add `@BuiltValueEnumConst(fallback: true)` as a way to mark an enum const
- as the fallback when `valueOf` or deserialization fails.
-- Add `@BuiltValueSerializer(serializeNulls: true` as a way to modify the wire
- format to explicitly contain `null` values.
-- Make it possible to merge `Serializers` instances: add a `builderFactories`
- getter that returns installed builder factories.
-- Use new `Function` syntax everywhere.
-- Bug fix: only generate builder factories for fields that are `Built`
- types or `built_collection` collections.
-
-# 6.3.2
-
-- Allow `analyzer` 0.35.0.
-
-# 6.3.1
-
-- Fix `BuiltList` serialization when using `StandardJsonPlugin` with
- unspecified type and when list length is 1.
-
-# 6.3.0
-
-- Allow custom builders to use setter/getter pairs instead of normal fields.
-- Add an option to `@BuiltValue` to turn off auto instantiation of nested
- builders.
-- Add `@BuiltValueSerializer` annotation which gives the option to specify a
- custom serializer for a class.
-- Make it possible to merge `Serializers` instances: add a `serializers`
- getter that returns the installed serializers.
-- Add serializer for `RegExp` fields.
-- Allow `analyzer` 0.34.0.
-
-# 6.2.0
-
-New features:
-
-- Add an option to `@BuiltValue` to generate comparable builders.
-- Add serializer for `Duration` fields.
-- Add `serializerForType` and `serializerForWireName` methods to `Serializers`.
-
-Improvements:
-
-- Add ignore for `avoid_as` lint to generated code.
-- Put ignored lints on a single line at the end of the generated output.
-- Stop checking for import of `built_value.dart` when `EnumClass` is used; this
- was expensive.
-
-Fixes:
-
-- Fix tests following changes to source_gen error output.
-- Fix generation when new `mixin` declarations are used.
-- Support dollar signs in enum value names.
-- Fix nested collections when using a custom builder.
-
-# 6.1.6
-
-- Switch to new analyzer API in version `0.33.3`.
-
-# 6.1.5
-
-- Bump versions of `analyzer`, `analyzer_plugin`, `build`, `build_runner`.
-
-# 6.1.4
-
-- Allow polymorphic base classes to omit implementing `Built` while still
- implementing any other interface(s).
-- Allow the dollar character in `wireName` settings.
-- Allow `build` version 1.0.
-
-# 6.1.3
-
-- Add `built_value_test` support for remaining built collections.
-
-# 6.1.2
-
-- Fix generated `operator==` when a type uses generic functions.
-- Fix generated code for `curly_braces_in_control_flow` lint.
-
-# 6.1.1
-
-- Allow `build_runner` 0.10.0.
-
-# 6.1.0
-
-- Improve generation for `operator==`, don't use `dynamic`.
-- Improve error message and documentation for missing builder factory.
-- Allow built_collection 4.0.0.
-- Fix code generation stack overflow when there is a loop in serializable
- types.
-- Fix library name output in generation error messages.
-- Add ignores for lints 'unnecessary_const' and 'unnecessary_new' to generated
- code.
-
-# 6.0.0
-
-- Update to the latest `source_gen`. This generator can now be used with other
- generators that want to write to `.g.dart` files without a manual build
- script.
-- Breaking change: The "header" configuration on this builder is now ignored.
-
-# 5.5.5
-
-- Allow SDK 2.0.0.
-
-# 5.5.4
-
-- Add ignores for lints 'lines_longer_than_80_chars' and
- 'avoid_catches_without_on_clauses' to generated code.
-- Bump version of quiver.
-
-# 5.5.3
-
-- Bump versions of build_runner, build_config and shelf.
-
-# 5.5.2
-
-- Fix violations of `prefer_equal_for_default_values` lint.
-
-# 5.5.1
-
-- Bump versions of `analyzer`, `analyzer_plugin`.
-
-# 5.5.0
-
-- Support serializing `BuiltSet` with `StandardJsonPlugin`. It's serialized to
- a JSON list.
-- Add `Iso8601DateTimeSerializer` for use when you want ISO8601 serialization
- instead of microseconds since epoch.
-- Fix code generation when inherited generic fields are made non-generic.
-
-# 5.4.5
-
-- Improve error message on failure to deserialize.
-- Move check forbidding instantiation with `dynamic` type parameters from
- builder to value class. Previously, you could avoid the check by using the
- generated constructor called `_`.
-
-# 5.4.4
-
-- Removed dependency on `build_config` from `built_value` and added it to
- `built_value_generator`.
-
-# 5.4.3
-
-- Allow source_gen 0.8.0.
-
-# 5.4.2
-
-- Make `StandardJsonPlugin` return `Map<String, Object>`, as the firebase
- libraries expect, instead of `Map<Object, Object>`.
-
-# 5.4.1
-
-- Fix analyzer plugin loading. It should now work, provided you modify your
- `analysis_options.yaml` as suggested.
-
-# 5.4.0
-
-- Add an experimental analyzer plugin that surfaces compile time generation
- errors as suggestions in your IDE. Turn it on by modifying your
- `analysis_options.yaml` file to add `plugins` entries,
- [example](https://github.com/google/built_value.dart/blob/master/analysis_options.yaml).
-
-# 5.3.0
-
-- Support serializing `BigInt`.
-- Add support for setting the generated header in a `build.yaml` file in your
- project. See `example/build.yaml` for an example.
-- Explicitly forbid serialization of `Function` and `typedef` types; these
- fields need to be marked `@BuiltValueField(serialize: false)`.
-- Fix generation when a field picked up via inheritance is a function type
- defined in another source file.
-- Fail with a helpful error message if `@SerializersFor` annotation list
- contains an undefined symbol.
-
-# 5.2.2
-
-- Fix built_value_generator/build.yaml to run generator on self package.
-- Fix end_to_end_test/pubspec.yaml to include build_runner.
-- Fix internal use of deprecated SDK constants.
-- Remove polymorphism examples that no longer work in Dart 2. Proper fix to come.
-- Allow quiver 0.29.
-
-# 5.2.1
-
-- Type fixes for DDC.
-
-# 5.2.0
-
-- Upgrade to latest `built_runner`. You no longer need `build.dart` or
- `watch.dart`. Instead, make sure you have a dev dependency on
- `built_value_generator` and `build_runner`, then run
- `pub run build_runner build` or `pub run build_runner watch`.
-- Note: this version requires the pre release of the Dart 2 SDK.
-
-# 5.1.3
-
-- Generate simpler deserialization code for `built_collection` instances.
-
-# 5.1.2
-
-- Fix generated serialization code when a manually declared builder causes
- a field to not use a nested builder.
-
-# 5.1.1
-
-- Workaround for analyzer issue when `implement`ing multiple classes that
- use `@BuiltValue(instantiable: false)`.
-
-## 5.1.0
-
-- Relax restriction on `extends` to allow for one special case: sharing of
- code between `built_value` and `const` classes. The base class in question
- must be abstract, have no fields, have no abstract getters and must not
- implement `operator==`, `hashCode` or `toString`.
-
-## 5.0.1
-
-- Allow quiver 0.28.
-
-## 5.0.0
-
-Introduce restrictions on using `built_value` in unsupported ways:
-
-- Prohibit use of `extends` in `built_value` classes. Classes should inherit
- API using `implements` and API+implementation using `extends Object with`.
-- Prohibit use of `show` or `as` when importing
- 'package:built_value/built_value.dart'. The generated code needs access to
- all symbols in the package with no import prefix.
-- Prohibit use of the mutable collection types `List`, `Set`, `Map`,
- `ListMultimap` and `SetMultimap`. Suggest `built_collection` equivalents
- instead.
-
-If any of these restrictions causes problem for you, please file an issue
-on github: https://github.com/google/built_value.dart/issues
-
-## 4.6.1
-
-- Allow hand-coded base builders, that is, builders for classes with
- `@BuiltValue(instantaible: false)`. They are now allowed to not
- implement `Builder` (as a workaround for a dart2js issue); they are
- allowed to omit fields; and they must omit constructor and factory.
-
-## 4.6.0
-
-- Add custom `Error` classes: `BuiltValueNullFieldError`,
- `BuiltValueMissingGenericsError` and `BuiltValueNestedFieldError`. These
- provide clearer error messages on failure. In particular, errors in nested
- builders now report the enclosing class and field name, making them much
- more useful.
-- Fix serialization when using polymorphism with StandardJsonPlugin.
-
-## 4.5.2
-
-- Allow built_collection 3.0.0.
-- Allow quiver 0.27.
-
-## 4.5.1
-
-- Fix generation when analyzing using summaries.
-
-## 4.5.0
-
-New features:
-
-- Add `serialize` field to `@BuiltValueField`. Use this to tag fields to skip
- when serializing.
-- Add `wireName` field to `@BuiltValue` and `@BuiltValueField`. Use this to
- override the wire name for classes and fields when serializing.
-- Add `@BuiltValueEnum` and `@BuiltValueEnumConst` annotations for specifying
- settings for enums. Add `wireName` field to these to override the wire names
- in enums when serializing.
-- Add support for polymorphism to `StandardJsonPlugin`. It will now specify
- type names as needed via a `discriminator` field, which by defualt is
- called `$`. This can be changed in the `StandardJsonPlugin` constructor.
-- Add `BuiltListAsyncDeserializer`. It provides a way to deserialize large
- responses without blocking, provided the top level serialized type is
- `BuiltList`.
-- Add built in serializer for `Uri`.
-
-Improvements:
-
-- Allow declaration of multiple `Serializers` in the same file.
-- Explicitly disallow private fields; fail with an error during generation if
- one is found.
-- Improve error message for field without type.
-
-Fixes:
-
-- Fix generated builder when fields hold function types.
-- Fix checks and generated builder when manually maintained builder has
- generics.
-- Fix name of classes generated from a private class.
-- Fix builder and serializer generation when importing with a prefix.
-
-## 4.4.1
-
-- Use build 0.11.1 and build_runner 0.6.0.
-
-## 4.4.0
-
-- New annotation, `BuiltValueField`, for configuring fields. First
- setting available is `compare`. Set to `false` to ignore a particular field
- for `operator==` and `hashCode`.
-- Generator now has a `const` constructor.
-
-## 4.3.4
-
-- Fix for built_collection 2.0.0.
-
-## 4.3.3
-
-- Allow quiver 0.26.
-
-## 4.3.2
-
-- Fix generation when a field is found via two levels of inheritance.
-
-## 4.3.1
-
-- Fix generation when a field comes from an interface but is also implemented
- by a mixin.
-
-## 4.3.0
-
-- Support serializing Int64.
-
-## 4.2.1
-
-- Correct handling of import prefixes; fixes some corner cases in
- generation.
-
-## 4.2.0
-
-- Generated code ignores more lints.
-- Add a workaround so "polymorphism" features can be used with dart2js.
- See example/lib/polymorphism.dart.
-- Deal explicitly with the user defining their own operator==, hashCode
- and/or toString(). Previously, they would just not work. Now, custom
- operator== and hashCode are forbidden at compile time, but custom
- toString() is supported.
-
-## 4.1.1
-
-- Generated code now tells the analyzer to ignore
- prefer_expression_function_bodies and sort_constructors_first.
-- Remove an unneeded use of computeNode in generator; improves generator
- performance.
-
-## 4.1.0
-
-- Improved annotation handling for corner cases.
-- Pick up field declarations from mixins as well as interfaces.
-
-## 4.0.0
-
-- Fix generated polymorphic builders for the analyzer. Mark the `rebuild`
- method with `covariant` so the analyzer knows that, for example, a
- `CatBuilder` cannot accept an `Animal`.
-- Update to build 0.10.0 and build_runner 0.4.0. Please update your
- `build.dart` and `watch.dart` as shown in the examples.
-
-## 3.0.0
-
-- Fix DateTime serialization; include microseconds. This is a breaking change
- to the JSON format.
-- Add SerializersFor annotation. Classes to serialize are no longer found by
- scanning all available libraries, as this was slow and hard to control.
- Instead, specify which classes you need to serialize using the new
- annotation on your "serializers" declaration. You only need to specify the
- "root" classes; the classes needed for the fields of classes you specify
- are included, transitively.
-
-## 2.1.0
-
-- Add "nestedBuilders" setting. Defaults to true; set to false to stop
- using nested builders by default in fully generated builders.
-- Allow fields to be called 'result'.
-- Fix generation when a field is a noninstantiable built value: don't try to
- instantiate the abstract builder.
-
-## 2.0.0
-
-- Update to source_gen 0.7.0.
-- Please make the following trivial update to your `build.dart` and
- `watch.dart`: replace the string `GeneratorBuilder` with `PartBuilder`.
-
-## 1.2.1
-
-- Fix generated code when implementing generic non-instantiable Built class.
-
-## 1.2.0
-
-- Fix depending on a fully generated builder from a manually maintained builder.
-- Pick up fields on implemented interfaces, so you don't have to @override them.
-- Add BuiltValue annotation for specifying settings.
-- Add "instantiable" setting. When false, no implementation is generated, only
- a builder interface.
-- Polymorphism support: you can now "implement" a non-instantiable Built class.
- The generated builder will implement its builder, so the types all work.
-
-## 1.1.4
-
-- Require SDK 1.21 and use the non-comment syntax for generics again.
-
-## 1.1.3
-
-- Removed dependency on now-unneeded package:meta.
-- Fixed a few lints/hints in enum generated code.
-- Use comment syntax for generics; using the non-comment syntax requires
- SDK 1.21 which is not specified in pubspec.yaml.
-
-## 1.1.2
-
-- Significantly improve build performance by using @memoized instead of
- precomputed fields.
-
-## 1.1.1
-
-- Update analyzer and build dependencies.
-
-## 1.1.0
-
-- Add "built_value_test" library. It provides a matcher which gives good
- mismatch messages for built_value instances.
-
-## 1.0.1
-
-- Allow quiver 0.25.
-
-## 1.0.0
-
-- Version bump to 1.0.0. Three minor features are marked as experimental and
- may change without a major version increase: BuiltValueToStringHelper,
- JsonObject and SerializerPlugin.
-- Made toString() output customizable.
-- Made the default toString() output use indentation and omit nulls.
-- Sort serializers in generated output.
-
-## 0.5.7
-
-- Ignore nulls when deserializing with StandardJsonPlugin.
-
-## 0.5.6
-
-- Add serializer for "DateTime" fields.
-- Add JsonObject class and serializer.
-- Add convenience methods Seralizers.serializeWith and deserializeWith.
-- Add example for using StandardJsonPlugin.
-- Support serializing NaN, INF and -INF for double and num.
-
-## 0.5.5
-
-- Add serializer for "num" fields.
-- Better error message for missing serializer.
-- Fix generation when there are nested multi-parameter generics.
-- Use cascades in generated code as suggested by lint.
-- Allow users to define any factory that references the generated
- implementation.
-- Add example of a simpler factory for a one-field class.
-
-## 0.5.4
-
-- Enforce that serializer declarations refer to the right generated name.
-- Streamline generation for classes with no fields.
-- Add identical check to generated operator==.
-- Make generated code compatible with strong mode implicit-dynamic:false
- and implicit-cast:false.
-
-## 0.5.3
-
-- Add null check to generated builder "replace" methods.
-- Fail with error on abstract enum classes.
-- Update to `build` 0.7.0 , `build_runner` 0.3.0, and `build_test` 0.4.0.
-
-## 0.5.2
-
-- Support "import ... as" for field types.
-
-## 0.5.1
-
-- Add @memoized. Annotate getters on built_value classes with @memoized
- to memoize their result. That means it's computed on first access then
- stored in the instance.
-- Support generics, in value types and in serialization.
-- Add support for "standard" JSON via StandardJsonPlugin.
-
-## 0.5.0
-
-- Update dependency on analyzer, build, quiver.
-- Breaking change: your build.dart and watch.dart now need to import
- build_runner/build_runner.dart instead of build/build.dart.
-
-## 0.4.3
-
-- Fix builder getters to be available before a set is used.
-
-## 0.4.2
-
-- Fix lints.
-- Allow "updates" in value type factory to have explicit void return type.
-
-## 0.4.1
-
-- Fix some analyzer hints.
-- Fix exception from serializer generator if builder field is incorrect.
-
-## 0.4.0
-
-- Add benchmark for updating deeply nested data structures.
-- Make builders copy lazily. This makes updates to deeply nested structures
- much faster: only the classes on the path to the update are copied, instead
- of the entire tree.
-- Breaking change: if you hand-code the builder then you must mark the fields
- @virtual so they can be overriden in the generated code.
-- Auto-create nested nullable builders when they're accessed. Fixes
- deserialization with nested nullable builder.
-
-## 0.3.0
-
-- Merged built_json and built_json_generator into built_value and
- built_value_generator. These are intended to be used together, and make
- more sense as a single package.
-- Fix generation when class extends multiple interfaces.
-- Add serialization of BuiltListMultimap and BuiltSetMultimap.
-
-## 0.2.0
-
-- Merged enum_class and enum_class_generator into built_value and
- built_value_generator. These are intended to be used together, and make
- more sense as a single package.
-
-## 0.1.6
-
-- Add checking for correct type arguments for Built and Builder interfaces.
-- Generate empty constructor with semicolon instead of {}.
-- Use ArgumentError.notNull for null errors.
-- Reject dynamic fields.
-- Add simple benchmark for hashing. Improve hashing performance.
-
-## 0.1.5
-
-- Allow quiver 0.23.
-
-## 0.1.4
-
-- Upgrade analyzer, build and source_gen dependencies.
-
-## 0.1.3
-
-- Generate builder if it's not written by hand.
-- Make toString append commas for improved clarity.
-- Improve examples and tests.
-- Fix double null checking.
-
-## 0.1.2
-
-- Refactor generator to split into logical classes.
-
-## 0.1.1
-
-- Improve error output on failure to generate.
-
-## 0.1.0
-
-- Upgrade to source_gen 0.5.0.
-- Breaking change; see example for required changes to build.dart.
-
-## 0.0.6
-
-- Move null checks to "build" method for compatibility with Strong Mode
- analyzer.
-- Allow (and ignore) setters.
-- Allow custom factories on value classes.
-
-## 0.0.5
-
-- Fix for changes to analyzer library.
-
-## 0.0.4
-
-- Support @nullable for fields using builders.
-- Fix constraints for source_gen.
-
-## 0.0.3
-
-- Allow static fields in value class.
-- Allow custom setters in builder.
-
-## 0.0.2
-
-- Fix error message for missing builder class.
-- Allow non-abstract getters in value class.
-
-## 0.0.1
-
-- Generator, tests and example.
diff --git a/built_value_generator/CONTRIBUTING.md b/built_value_generator/CONTRIBUTING.md
deleted file mode 100644
index f1322f8..0000000
--- a/built_value_generator/CONTRIBUTING.md
+++ /dev/null
@@ -1,34 +0,0 @@
-Want to contribute? Great! First, read this page (including the small print at
-the end).
-
-### Before you contribute
-Before we can use your code, you must sign the
-[Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual)
-(CLA), which you can do online. The CLA is necessary mainly because you own the
-copyright to your changes, even after your contribution becomes part of our
-codebase, so we need your permission to use and distribute your code. We also
-need to be sure of various other things—for instance that you'll tell us if you
-know that your code infringes on other people's patents. You don't have to sign
-the CLA until after you've submitted your code for review and a member has
-approved it, but you must do it before we can put your code into our codebase.
-
-Before you start working on a larger contribution, you should get in touch with
-us first through the issue tracker with your idea so that we can help out and
-possibly guide you. Coordinating up front makes it much easier to avoid
-frustration later on.
-
-### Code reviews
-All submissions, including submissions by project members, require review. We
-use Github pull requests for this purpose.
-
-### File headers
-All files in the project must start with the following header.
-
- // Copyright (c) 2015, Google Inc. 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 small print
-Contributions made by corporations are covered by a different agreement than the
-one above, the
-[Software Grant and Corporate Contributor License Agreement](https://developers.google.com/open-source/cla/corporate).
diff --git a/built_value_generator/LICENSE b/built_value_generator/LICENSE
deleted file mode 100644
index ec8a981..0000000
--- a/built_value_generator/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright 2015, Google Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/built_value_generator/README.md b/built_value_generator/README.md
deleted file mode 100644
index c960618..0000000
--- a/built_value_generator/README.md
+++ /dev/null
@@ -1,254 +0,0 @@
-# Built Values for Dart
-[![Build Status](https://travis-ci.org/google/built_value.dart.svg?branch=master)](https://travis-ci.org/google/built_value.dart)
-## Introduction
-
-Built Value provides:
-
-- Immutable value types;
-- EnumClass, classes that behave like enums;
-- JSON serialization.
-
-Immutable collections are from
-[built_collection](https://github.com/google/built_collection.dart#built-collections-for-dart).
-
-See the [API docs](https://pub.dev/documentation/built_value/latest/built_value/built_value-library.html).
-
-## Articles
-
-- [`built_value` for Immutable Object Models](https://medium.com/@davidmorgan_14314/darts-built-value-for-immutable-object-models-83e2497922d4#.48dyezxcl)
-- [`built_value` for Serialization](https://medium.com/@davidmorgan_14314/darts-built-value-for-serialization-f5db9d0f4159#.h12y94wu7)
-- [Building a Chat App in Dart](https://medium.com/@davidmorgan_14314/building-a-chat-app-in-dart-815fcd0e5a31#.ku4vtbmk2)
-- [End to End Testing in One Short Second with Dart](https://medium.com/@davidmorgan_14314/end-to-end-testing-in-one-short-second-with-dart-e699c8146fd6#.c7xfxohg4)
-- [Moving Fast with Dart Immutable Values](https://medium.com/@davidmorgan_14314/moving-fast-with-dart-immutable-values-1e717925fafb)
-- [Flutter JSON Serialization](https://aloisdeniel.github.io/flutter-json-serialization/)
-- [Flutter TODO App Example](https://gitlab.com/brianegan/flutter_architecture_samples/tree/master/example/built_redux)
- using `built_value`, [built_redux](https://pub.dartlang.org/packages/built_redux), and [flutter_built_redux](https://pub.dartlang.org/packages/flutter_built_redux)
-- [Building a (large) Flutter app with Redux](https://hillelcoren.com/2018/06/01/building-a-large-flutter-app-with-redux/)
-- [Some Options for Deserializing JSON with Flutter](https://medium.com/flutter-io/some-options-for-deserializing-json-with-flutter-7481325a4450)
-
-## Tutorials
-
- - [Custom Serializers](https://medium.com/@solid.goncalo/creating-custom-built-value-serializers-with-builtvalueserializer-46a52c75d4c5)
- - [Flutter + built_value + Reddit Tutorial](https://steemit.com/utopian-io/@tensor/building-immutable-models-with-built-value-and-built-collection-in-dart-s-flutter-framework);
- [video](https://www.youtube.com/watch?v=hNbOSSgpneI);
- [source code](https://github.com/tensor-programming/built_flutter_tutorial)
-
-## Tools
-
- - The [Json to Dart built_value class converter](https://charafau.github.io/json2builtvalue/) creates classes for you that correspond to a snippet of JSON
-
-## Examples
-
-For an end to end example see the
-[chat example](https://github.com/google/built_value.dart/tree/master/chat_example), which was
-[demoed](https://www.youtube.com/watch?v=TMeJxWltoVo) at the Dart Summit 2016.
-The
-[data model](https://github.com/google/built_value.dart/blob/master/chat_example/lib/data_model/data_model.dart),
-used both client and server side, uses value types, enums and serialization from
-built_value.
-
-Simple examples are
-[here](https://github.com/google/built_value.dart/tree/master/example/lib/example.dart).
-
-Since `v5.2.0` codegen is triggered by running `pub run build_runner build` to
-do a one-off build or `pub run build_runner watch` to continuously watch your
-source and update the generated output when it changes. Note that you need a
-dev dependency on `built_value_generator` and `build_runner`. See the example
-[pubspec.yaml](https://github.com/google/built_value.dart/blob/master/example/pubspec.yaml).
-
-If using Flutter, the equivalent command is `flutter packages pub run build_runner build`.
-Alternatively, put your `built_value` classes in a separate Dart package with no dependency
-on Flutter. You can then use `built_value` as normal.
-
-If using a version before v5.2.0, codegen is triggered via either a
-[build.dart](https://github.com/google/built_value.dart/blob/92783c27a08ac3c73f28bb08736b9d4a30fa3b7e/example/tool/build.dart)
-to do a one-off build or a
-[watch.dart](https://github.com/google/built_value.dart/blob/92783c27a08ac3c73f28bb08736b9d4a30fa3b7e/example/tool/watch.dart)
-to continuously watch your source and update generated output.
-
-## Value Types
-
-Value types are, for our purposes, classes that are considered
-interchangeable if their fields have the same values.
-
-Common examples include `Date`, `Money` and `Url`. Most code introduces
-its own value types. For example, every web app probably has some
-version of `Account` and `User`.
-
-Value types are very commonly sent by RPC and/or stored for later
-retrieval.
-
-The problems that led to the creation of the Built Value library have
-been
-[discussed at great length](https://docs.google.com/presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/edit)
-in the context of
-[AutoValue](https://github.com/google/auto/tree/master/value#autovalue)
-for Java.
-
-In short: creating and maintaining value types by hand requires a lot of
-boilerplate. It's boring to write, and if you make a mistake, you very
-likely create a bug that's hard to track down.
-
-Any solution for value types needs to allow them to participate in object
-oriented design. `Date`, for example, is the right place for code that
-does simple date manipulation.
-
-[AutoValue](https://github.com/google/auto/tree/master/value#autovalue)
-solves the problem for Java with code generation, and Built Values does
-the same for Dart. The boilerplate is generated for you, leaving you to
-specify which fields you need and to add code for the behaviour of the
-class.
-
-### Generating boilerplate for Value Types
-
-Value types require a bit of boilerplate in order to connect it to generated
-code. Luckily, even this bit of boilerplate can be got automated using code
-snippets support in your favourite text editor. For example, in IntelliJ you
-can use following live template:
-
-```dart
-abstract class $CLASS_NAME$ implements Built<$CLASS_NAME$, $CLASS_NAME$Builder> {
- $CLASS_NAME$._();
- factory $CLASS_NAME$([void Function($CLASS_NAME$Builder) updates]) = _$$$CLASS_NAME$;
-}
-```
-
-Using this template you would only have to manually enter a name of your data
-class name which is something that can't be automated.
-
-## Enum Class
-
-Enum Classes provide classes with enum features.
-
-Enums are very helpful in modelling the real world: whenever there are a
-small fixed set of options, an enum is a natural choice. For an object
-oriented design, though, enums need to be classes. Dart falls short here,
-so Enum Classes provide what's missing!
-
-Design:
-
-- Constants have `name` and `toString`, can be used in `switch` statements,
- and are real classes that can hold code and implement interfaces
-- Generated `values` method that returns all the enum values in a `BuiltSet` (immutable set)
-- Generated `valueOf` method that takes a `String`
-
-## Serialization
-
-Built Values comes with JSON serialization support which allows you to
-serialize a complete data model of Built Values, Enum Classes and
-Built Collections. The
-[chat example](https://github.com/google/built_value.dart/tree/master/chat_example) shows
-how easy this makes building a full application with Dart on the server and
-client.
-
-Here are the major features of the serialization support:
-
-It _fully supports object oriented design_: any object model that you can
-design can be serialized, including full use of generics and interfaces.
-Some other libraries require concrete types or do not fully support generics.
-
-It _allows different object oriented models over the same data_. For
-example, in a client server application, it's likely that the client and server
-want different functionality from their data model. So, they are allowed to have
-different classes that map to the same data. Most other libraries enforce a 1:1
-mapping between classes and types on the wire.
-
-It _requires well behaved types_. They must be immutable, can use
-interface but not concrete inheritance, must have predictable nullability,
-`hashCode`, `equals` and `toString`. In fact, they must be Enum Classes, Built
-Collections or Built Values. Some other libraries allow badly behaved types to
-be serialized.
-
-It _supports changes to the data model_. Optional fields can be added or
-removed, and fields can be switched from optional to required, allowing your
-data model to evolve without breaking compatbility. Some other libraries break
-compatibility on any change to any serializable class.
-
-It's _modular_. Each endpoint can choose which classes to know about;
-for example, you can have multiple clients that each know about only a subset of
-the classes the server knows. Most other libraries are monolithic, requiring all
-endpoints to know all types.
-
-It _has first class support for validation_ via Built Values. An important
-part of a powerful data model is ensuring it's valid, so classes can make
-guarantees about what they can do. Other libraries also support validation
-but usually in a less prominent way.
-
-It's _pluggable_. You can add serializers for your own types, and you can add
-[plugins](https://github.com/google/built_value.dart/blob/master/built_value/lib/standard_json_plugin.dart)
-which run before and after all serializers. This could be used to
-interoperate with other tools or to add hand coded high performance serializers
-for specific classes. Some other libraries are not so extensible.
-
-It was designed to be _multi language_, mapping to equivalent object models in
-Java and other languages. Currently only Dart is supported. The need for other
-languages didn't materialize as servers are typically either written in Dart
-or owned by third parties. Please open an issue if you'd like to explore
-support in more languages.
-
-## Common Usage
-
-While full, compiled examples are available in
-[`example/lib`](https://github.com/google/built_value.dart/tree/master/example/lib),
-a common usage example is shown here. This example assumes that you are writing
-a client for a JSON API representing a person that looks like the following:
-
-```json
-{
- "id": 12345,
- "age": 35,
- "first_name": "Jimmy",
- "hobbies": ["jumping", "basketball"]
-}
-```
-
-The corresponding dart class employing `built_value` might look like this. Note
-that it is using the
-[`@nullable`](https://pub.dartlang.org/documentation/built_value/latest/built_value/nullable-constant.html)
-annotation to indicate that the field does not have to be present on the
-response, as well as the
-[`@BuiltValueField`](https://pub.dartlang.org/documentation/built_value/latest/built_value/BuiltValueField-class.html)
-annotation to map between the property name on the response and the name of the
-member variable in the `Person` class.
-
-```dart
-import 'package:built_value/built_value.dart';
-import 'package:built_value/serializer.dart';
-import 'package:built_collection/built_collection.dart';
-
-part 'person.g.dart';
-
-abstract class Person implements Built<Person, PersonBuilder> {
- static Serializer<Person> get serializer => _$personSerializer;
-
- // Can never be null.
- int get id;
-
- @nullable
- int get age;
-
- @nullable
- @BuiltValueField(wireName: 'first_name')
- String get firstName;
-
- @nullable
- BuiltList<String> get hobbies;
-
- Person._();
- factory Person([void Function(PersonBuilder) updates]) = _$Person;
-}
-```
-
-## FAQ
-
-### Should I check in and/or publish in the generated `.g.dart` files?
-
-See the [build_runner](https://pub.dartlang.org/packages/build_runner#source-control)
-docs. You usually should not check in generated files, but you _do_ need to publish
-them.
-
-## Features and bugs
-
-Please file feature requests and bugs at the [issue tracker][tracker].
-
-[tracker]: https://github.com/google/built_value.dart/issues
diff --git a/built_value_generator/analysis_options.yaml b/built_value_generator/analysis_options.yaml
deleted file mode 100644
index 108d105..0000000
--- a/built_value_generator/analysis_options.yaml
+++ /dev/null
@@ -1 +0,0 @@
-include: package:pedantic/analysis_options.yaml
diff --git a/built_value_generator/build.yaml b/built_value_generator/build.yaml
deleted file mode 100644
index cb16bb0..0000000
--- a/built_value_generator/build.yaml
+++ /dev/null
@@ -1,15 +0,0 @@
-targets:
- $default:
- builders:
- built_value_generator|built_value:
- enabled: true
-
-builders:
- built_value:
- target: ":built_value_generator"
- import: "package:built_value_generator/builder.dart"
- builder_factories: ["builtValue"]
- build_extensions: {".dart": [".built_value.g.part"]}
- auto_apply: dependents
- build_to: cache
- applies_builders: ["source_gen|combining_builder"]
diff --git a/built_value_generator/lib/builder.dart b/built_value_generator/lib/builder.dart
deleted file mode 100644
index d33c3b8..0000000
--- a/built_value_generator/lib/builder.dart
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright (c) 2018, Google Inc. 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:build/build.dart';
-
-import 'package:built_value_generator/built_value_generator.dart';
-import 'package:source_gen/source_gen.dart';
-
-Builder builtValue(BuilderOptions _) =>
- SharedPartBuilder([BuiltValueGenerator()], 'built_value');
diff --git a/built_value_generator/lib/built_value_generator.dart b/built_value_generator/lib/built_value_generator.dart
deleted file mode 100644
index c2add2d..0000000
--- a/built_value_generator/lib/built_value_generator.dart
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details.
-// All rights reserved. Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:build/build.dart';
-import 'package:built_value_generator/src/enum_source_library.dart';
-import 'package:built_value_generator/src/value_source_class.dart';
-import 'package:built_value_generator/src/serializer_source_library.dart';
-import 'package:source_gen/source_gen.dart';
-
-/// Generator for Enum Class and Built Values.
-///
-/// See https://github.com/google/built_value.dart/tree/master/example
-class BuiltValueGenerator extends Generator {
- // Allow creating via `const` as well as enforces immutability here.
- const BuiltValueGenerator();
-
- @override
- Future<String> generate(LibraryReader library, BuildStep buildStep) async {
- var result = StringBuffer();
-
- try {
- final enumCode = EnumSourceLibrary(library.element).generateCode();
- if (enumCode != null) result.writeln(enumCode);
- final serializerSourceLibrary = SerializerSourceLibrary(library.element);
- if (serializerSourceLibrary.needsBuiltJson ||
- serializerSourceLibrary.hasSerializers) {
- result.writeln(serializerSourceLibrary.generateCode());
- }
- } on InvalidGenerationSourceError catch (e, st) {
- result.writeln(_error(e.message));
- log.severe(
- 'Error in BuiltValueGenerator for '
- '${library.element.source.fullName}.',
- e,
- st);
- } catch (e, st) {
- result.writeln(_error(e.toString()));
- log.severe(
- 'Unknown error in BuiltValueGenerator for '
- '${library.element.source.fullName}.',
- e,
- st);
- }
-
- for (var element in library.allElements) {
- if (element is ClassElement &&
- ValueSourceClass.needsBuiltValue(element)) {
- try {
- result.writeln(ValueSourceClass(element).generateCode() ?? '');
- } catch (e, st) {
- result.writeln(_error(e));
- log.severe('Error in BuiltValueGenerator for $element.', e, st);
- }
- }
- }
-
- if (result.isNotEmpty) {
- return '$result'
- '\n'
- '// ignore_for_file: '
- 'always_put_control_body_on_new_line,'
- 'always_specify_types,'
- 'annotate_overrides,'
- 'avoid_annotating_with_dynamic,'
- 'avoid_as,'
- 'avoid_catches_without_on_clauses,'
- 'avoid_returning_this,'
- 'lines_longer_than_80_chars,'
- 'omit_local_variable_types,'
- 'prefer_expression_function_bodies,'
- 'sort_constructors_first,'
- 'test_types_in_equals,'
- 'unnecessary_const,'
- 'unnecessary_new';
- } else {
- return null;
- }
- }
-}
-
-String _error(Object error) {
- var lines = '$error'.split('\n');
- var indented = lines.skip(1).map((l) => '// $l'.trim()).join('\n');
- return '// Error: ${lines.first}\n$indented';
-}
diff --git a/built_value_generator/lib/plugin_starter.dart b/built_value_generator/lib/plugin_starter.dart
deleted file mode 100644
index 0a4a356..0000000
--- a/built_value_generator/lib/plugin_starter.dart
+++ /dev/null
@@ -1,11 +0,0 @@
-import 'dart:isolate';
-
-import 'package:analyzer/file_system/physical_file_system.dart';
-import 'package:analyzer_plugin/starter.dart';
-import 'package:built_value_generator/src/plugin/plugin.dart';
-
-void start(List<String> args, SendPort sendPort) {
- ServerPluginStarter(
- BuiltValueAnalyzerPlugin(PhysicalResourceProvider.INSTANCE))
- .start(sendPort);
-}
diff --git a/built_value_generator/lib/src/dart_types.dart b/built_value_generator/lib/src/dart_types.dart
deleted file mode 100644
index 15d86ef..0000000
--- a/built_value_generator/lib/src/dart_types.dart
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright (c) 2017, Google Inc. 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/type.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value_generator/src/value_source_class.dart';
-
-BuiltSet<String> _builtCollectionNames = BuiltSet<String>([
- 'BuiltList',
- 'BuiltListMultimap',
- 'BuiltMap',
- 'BuiltSet',
- 'BuiltSetMultimap',
-]);
-
-class DartTypes {
- static bool needsNestedBuilder(DartType type) {
- return isInstantiableBuiltValue(type) || isBuiltCollection(type);
- }
-
- static bool isInstantiableBuiltValue(DartType type) {
- return isBuiltValue(type) &&
- ValueSourceClass(type.element as ClassElement).settings.instantiable;
- }
-
- static bool isBuiltValue(DartType type) {
- if (type.element is! ClassElement) return false;
- return (type.element as ClassElement)
- .allSupertypes
- .any((interfaceType) => interfaceType.name == 'Built');
- }
-
- static bool isBuiltCollection(DartType type) {
- return _builtCollectionNames
- .any((name) => getName(type).startsWith('$name<'));
- }
-
- static bool isBuilt(DartType type) =>
- isBuiltValue(type) || isBuiltCollection(type);
-
- static bool isBuiltCollectionTypeName(String name) =>
- _builtCollectionNames.contains(name);
-
- /// Gets the name of a `DartType`. Supports `Function` types, which will
- /// be returned using the `Function()` syntax.
- static String getName(DartType dartType) {
- if (dartType == null) {
- return null;
- } else if (dartType.isDynamic) {
- return 'dynamic';
- } else if (dartType is FunctionType) {
- return getName(dartType.returnType) +
- ' Function(' +
- dartType.parameters.map((p) => getName(p.type)).join(', ') +
- ')';
- } else if (dartType is InterfaceType) {
- var typeArguments = dartType.typeArguments;
- if (typeArguments.isEmpty || typeArguments.every((t) => t.isDynamic)) {
- return dartType.element.name;
- } else {
- final typeArgumentsStr = typeArguments.map(getName).join(', ');
- return '${dartType.element.name}<$typeArgumentsStr>';
- }
- } else if (dartType is TypeParameterType) {
- return dartType.element.name;
- } else if (dartType.isVoid) {
- return 'void';
- } else {
- throw UnimplementedError('(${dartType.runtimeType}) $dartType');
- }
- }
-
- /// Turns a type name, optionally with generics, into just the type name.
- static String stripGenerics(String name) {
- var genericsStart = name.indexOf('<');
- return genericsStart == -1 ? name : name.substring(0, genericsStart);
- }
-}
diff --git a/built_value_generator/lib/src/enum_source_class.dart b/built_value_generator/lib/src/enum_source_class.dart
deleted file mode 100644
index aef2204..0000000
--- a/built_value_generator/lib/src/enum_source_class.dart
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright (c) 2016, Google Inc. 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 built_value_generator.enum_source_class;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/dart_types.dart';
-import 'package:built_value_generator/src/enum_source_field.dart';
-import 'package:built_value_generator/src/strings.dart';
-import 'package:quiver/iterables.dart';
-
-part 'enum_source_class.g.dart';
-
-abstract class EnumSourceClass
- implements Built<EnumSourceClass, EnumSourceClassBuilder> {
- ClassElement get element;
-
- factory EnumSourceClass(
- ParsedLibraryResult parsedLibrary, ClassElement element) =>
- _$EnumSourceClass._(element: element);
- EnumSourceClass._();
-
- @memoized
- ParsedLibraryResult get parsedLibrary =>
- element.library.session.getParsedLibraryByElement(element.library);
-
- @memoized
- String get name => element.name;
-
- @memoized
- String get wireName => settings.wireName ?? name;
-
- @memoized
- BuiltValueEnum get settings {
- var annotations = element.metadata
- .map((annotation) => annotation.computeConstantValue())
- .where((value) => DartTypes.getName(value?.type) == 'BuiltValueEnum');
- if (annotations.isEmpty) return const BuiltValueEnum();
- var annotation = annotations.single;
- return BuiltValueEnum(
- wireName: annotation.getField('wireName').toStringValue());
- }
-
- @memoized
- bool get isAbstract => element.isAbstract;
-
- @memoized
- BuiltList<EnumSourceField> get fields =>
- EnumSourceField.fromClassElement(parsedLibrary, element);
-
- @memoized
- BuiltList<String> get constructors =>
- BuiltList<String>(element.constructors.map((element) {
- final declaration = parsedLibrary.getElementDeclaration(element);
- return declaration?.node?.toSource() ?? '';
- }));
-
- @memoized
- String get valuesIdentifier {
- var getter = element.getGetter('values');
- if (getter == null) return null;
- var source = parsedLibrary.getElementDeclaration(getter).node.toSource();
- var matches = RegExp(r'static BuiltSet<' +
- element.displayName +
- r'> get values => (_\$\w+)\;')
- .allMatches(source);
- return matches.isEmpty ? null : matches.first.group(1);
- }
-
- @memoized
- String get valueOfIdentifier {
- var getter = element.getMethod('valueOf');
- if (getter == null) return null;
- var source = parsedLibrary.getElementDeclaration(getter).node.toSource();
- var matches = RegExp(r'static ' +
- element.displayName +
- r' valueOf\(String name\) \=\> (\_\$\w+)\(name\)\;')
- .allMatches(source);
- return matches.isEmpty ? null : matches.first.group(1);
- }
-
- @memoized
- bool get usesMixin => element.library.getType(name + 'Mixin') != null;
-
- @memoized
- String get mixinDeclaration {
- var mixinElement = element.library.getType(name + 'Mixin');
- if (mixinElement == null) return null;
- return parsedLibrary.getElementDeclaration(mixinElement).node.toSource();
- }
-
- @memoized
- Iterable<String> get identifiers {
- return concat([
- [valuesIdentifier, valueOfIdentifier],
- fields.map((field) => field.generatedIdentifier)
- ]);
- }
-
- static bool needsEnumClass(ClassElement classElement) {
- // `Object` and mixins return `null` for `supertype`.
- return DartTypes.getName(classElement.supertype) == 'EnumClass';
- }
-
- Iterable<String> computeErrors() {
- return concat([
- _checkAbstract(),
- _checkFields(),
- _checkFallbackFields(),
- _checkConstructor(),
- _checkValuesGetter(),
- _checkValueOf(),
- _checkMixin(),
- ]).toList();
- }
-
- Iterable<String> _checkAbstract() {
- return isAbstract ? ['Make $name concrete; remove "abstract".'] : [];
- }
-
- Iterable<String> _checkFields() {
- return concat(fields.map((field) => field.errors));
- }
-
- Iterable<String> _checkFallbackFields() {
- var result = <String>[];
-
- var fallbackFields =
- fields.where((field) => field.settings.fallback).toList();
- if (fallbackFields.length > 1) {
- result.add('Remove `fallback = true` '
- 'so that at most one constant is the fallback. '
- 'Currently on "$name" fields '
- '${fallbackFields.map((field) => '"${field.name}"').join(', ')}.');
- }
- return result;
- }
-
- Iterable<String> _checkConstructor() {
- var expectedCode = 'const $name._(String name) : super(name);';
- return constructors.length == 1 && constructors.single == expectedCode
- ? <String>[]
- : <String>['Have exactly one constructor: $expectedCode'];
- }
-
- Iterable<String> _checkValuesGetter() {
- var result = <String>[];
- if (valuesIdentifier == null) {
- result.add('Add getter: static BuiltSet<$name> get values => _\$values');
- }
- return result;
- }
-
- Iterable<String> _checkValueOf() {
- var result = <String>[];
- if (valueOfIdentifier == null) {
- result.add('Add method: '
- 'static $name valueOf(String name) => _\$valueOf(name)');
- }
- return result;
- }
-
- Iterable<String> _checkMixin() {
- if (usesMixin) {
- final expectedCode =
- 'abstract class ${name}Mixin = Object with _\$${name}Mixin;';
- if (!mixinDeclaration.contains(expectedCode)) {
- return ['Remove mixin or declare using exactly: $expectedCode'];
- }
- }
- return [];
- }
-
- String generateCode() {
- var result = StringBuffer();
-
- for (var field in fields) {
- result.writeln('const $name ${field.generatedIdentifier} = '
- 'const $name._(\'${escapeString(field.name)}\');');
- }
-
- result.writeln('');
-
- result.writeln('$name $valueOfIdentifier(String name) {'
- 'switch (name) {');
- for (var field in fields) {
- result.writeln("case '${escapeString(field.name)}':"
- ' return ${field.generatedIdentifier};');
- }
-
- var fallback = fields.firstWhere((field) => field.settings.fallback,
- orElse: () => null);
- if (fallback == null) {
- result.writeln('default: throw new ArgumentError(name);');
- } else {
- result.writeln('default: return ${fallback.generatedIdentifier};');
- }
- result.writeln('}}');
-
- result.writeln('');
-
- result.writeln('final BuiltSet<$name> $valuesIdentifier ='
- 'new BuiltSet<$name>(const <$name>[');
- for (var field in fields) {
- result.writeln('${field.generatedIdentifier},');
- }
- result.writeln(']);');
-
- if (usesMixin) {
- result.write(_generateMixin());
- }
-
- return result.toString();
- }
-
- String _generateMixin() {
- var result = StringBuffer();
-
- result
- ..writeln('class _\$${name}Meta {')
- ..writeln('const _\$${name}Meta();');
- for (var field in fields) {
- result
- .writeln('$name get ${field.name} => ${field.generatedIdentifier};');
- }
- result
- ..writeln('$name valueOf(String name) => $valueOfIdentifier(name);')
- ..writeln('BuiltSet<$name> get values => $valuesIdentifier;')
- ..writeln('}')
- ..writeln('abstract class _\$${name}Mixin {')
- ..writeln(' // ignore: non_constant_identifier_names')
- ..writeln('_\$${name}Meta get $name => const _\$${name}Meta();')
- ..writeln('}');
-
- return result.toString();
- }
-}
diff --git a/built_value_generator/lib/src/enum_source_class.g.dart b/built_value_generator/lib/src/enum_source_class.g.dart
deleted file mode 100644
index 794856c..0000000
--- a/built_value_generator/lib/src/enum_source_class.g.dart
+++ /dev/null
@@ -1,138 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.enum_source_class;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$EnumSourceClass extends EnumSourceClass {
- @override
- final ClassElement element;
- ParsedLibraryResult __parsedLibrary;
- String __name;
- String __wireName;
- BuiltValueEnum __settings;
- bool __isAbstract;
- BuiltList<EnumSourceField> __fields;
- BuiltList<String> __constructors;
- String __valuesIdentifier;
- String __valueOfIdentifier;
- bool __usesMixin;
- String __mixinDeclaration;
- Iterable<String> __identifiers;
-
- factory _$EnumSourceClass([void Function(EnumSourceClassBuilder) updates]) =>
- (new EnumSourceClassBuilder()..update(updates)).build();
-
- _$EnumSourceClass._({this.element}) : super._() {
- if (element == null) {
- throw new BuiltValueNullFieldError('EnumSourceClass', 'element');
- }
- }
-
- @override
- ParsedLibraryResult get parsedLibrary =>
- __parsedLibrary ??= super.parsedLibrary;
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get wireName => __wireName ??= super.wireName;
-
- @override
- BuiltValueEnum get settings => __settings ??= super.settings;
-
- @override
- bool get isAbstract => __isAbstract ??= super.isAbstract;
-
- @override
- BuiltList<EnumSourceField> get fields => __fields ??= super.fields;
-
- @override
- BuiltList<String> get constructors => __constructors ??= super.constructors;
-
- @override
- String get valuesIdentifier => __valuesIdentifier ??= super.valuesIdentifier;
-
- @override
- String get valueOfIdentifier =>
- __valueOfIdentifier ??= super.valueOfIdentifier;
-
- @override
- bool get usesMixin => __usesMixin ??= super.usesMixin;
-
- @override
- String get mixinDeclaration => __mixinDeclaration ??= super.mixinDeclaration;
-
- @override
- Iterable<String> get identifiers => __identifiers ??= super.identifiers;
-
- @override
- EnumSourceClass rebuild(void Function(EnumSourceClassBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- EnumSourceClassBuilder toBuilder() =>
- new EnumSourceClassBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is EnumSourceClass && element == other.element;
- }
-
- @override
- int get hashCode {
- return $jf($jc(0, element.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('EnumSourceClass')
- ..add('element', element))
- .toString();
- }
-}
-
-class EnumSourceClassBuilder
- implements Builder<EnumSourceClass, EnumSourceClassBuilder> {
- _$EnumSourceClass _$v;
-
- ClassElement _element;
- ClassElement get element => _$this._element;
- set element(ClassElement element) => _$this._element = element;
-
- EnumSourceClassBuilder();
-
- EnumSourceClassBuilder get _$this {
- if (_$v != null) {
- _element = _$v.element;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(EnumSourceClass other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$EnumSourceClass;
- }
-
- @override
- void update(void Function(EnumSourceClassBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$EnumSourceClass build() {
- final _$result = _$v ?? new _$EnumSourceClass._(element: element);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/enum_source_field.dart b/built_value_generator/lib/src/enum_source_field.dart
deleted file mode 100644
index e01f2f7..0000000
--- a/built_value_generator/lib/src/enum_source_field.dart
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright (c) 2016, Google Inc. 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 built_value_generator.enum_source_field;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-
-import 'dart_types.dart';
-
-part 'enum_source_field.g.dart';
-
-abstract class EnumSourceField
- implements Built<EnumSourceField, EnumSourceFieldBuilder> {
- ParsedLibraryResult get parsedLibrary;
- FieldElement get element;
-
- factory EnumSourceField(
- ParsedLibraryResult parsedLibrary, FieldElement element) =>
- _$EnumSourceField._(parsedLibrary: parsedLibrary, element: element);
- EnumSourceField._();
-
- @memoized
- String get name => element.displayName;
-
- @memoized
- String get type => DartTypes.getName(element.getter.returnType);
-
- @memoized
- BuiltValueEnumConst get settings {
- var annotations = element.metadata
- .map((annotation) => annotation.computeConstantValue())
- .where(
- (value) => DartTypes.getName(value?.type) == 'BuiltValueEnumConst');
- if (annotations.isEmpty) return const BuiltValueEnumConst();
- var annotation = annotations.single;
- return BuiltValueEnumConst(
- fallback: annotation.getField('fallback')?.toBoolValue() ?? false,
- wireName: annotation.getField('wireName').toStringValue());
- }
-
- @memoized
- String get generatedIdentifier {
- var fieldName = element.displayName;
- return parsedLibrary
- .getElementDeclaration(element)
- .node
- .toSource()
- .substring('$fieldName = '.length);
- }
-
- @memoized
- bool get isConst => element.isConst;
-
- @memoized
- bool get isStatic => element.isStatic;
-
- static BuiltList<EnumSourceField> fromClassElement(
- ParsedLibraryResult parsedLibrary, ClassElement classElement) {
- var result = ListBuilder<EnumSourceField>();
-
- var enumName = classElement.displayName;
- for (var fieldElement in classElement.fields) {
- final type = DartTypes.getName(fieldElement.getter.returnType);
- if (!fieldElement.isSynthetic &&
- (type == enumName || type == 'dynamic')) {
- result.add(EnumSourceField(parsedLibrary, fieldElement));
- }
- }
-
- return result.build();
- }
-
- Iterable<String> get errors {
- var result = <String>[];
-
- if (type == 'dynamic') {
- result.add('Specify a type for field "$name".');
- } else if (!isConst && !isStatic) {
- result.add('Make field "$name" static const.');
- } else if (!isConst) {
- result.add('Make field "$name" const.');
- } else if (!generatedIdentifier.startsWith('_\$')) {
- result.add('Initialize field "$name" with a value starting "_\$".');
- }
-
- return result;
- }
-}
diff --git a/built_value_generator/lib/src/enum_source_field.g.dart b/built_value_generator/lib/src/enum_source_field.g.dart
deleted file mode 100644
index aa1d7ca..0000000
--- a/built_value_generator/lib/src/enum_source_field.g.dart
+++ /dev/null
@@ -1,128 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.enum_source_field;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$EnumSourceField extends EnumSourceField {
- @override
- final ParsedLibraryResult parsedLibrary;
- @override
- final FieldElement element;
- String __name;
- String __type;
- BuiltValueEnumConst __settings;
- String __generatedIdentifier;
- bool __isConst;
- bool __isStatic;
-
- factory _$EnumSourceField([void Function(EnumSourceFieldBuilder) updates]) =>
- (new EnumSourceFieldBuilder()..update(updates)).build();
-
- _$EnumSourceField._({this.parsedLibrary, this.element}) : super._() {
- if (parsedLibrary == null) {
- throw new BuiltValueNullFieldError('EnumSourceField', 'parsedLibrary');
- }
- if (element == null) {
- throw new BuiltValueNullFieldError('EnumSourceField', 'element');
- }
- }
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get type => __type ??= super.type;
-
- @override
- BuiltValueEnumConst get settings => __settings ??= super.settings;
-
- @override
- String get generatedIdentifier =>
- __generatedIdentifier ??= super.generatedIdentifier;
-
- @override
- bool get isConst => __isConst ??= super.isConst;
-
- @override
- bool get isStatic => __isStatic ??= super.isStatic;
-
- @override
- EnumSourceField rebuild(void Function(EnumSourceFieldBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- EnumSourceFieldBuilder toBuilder() =>
- new EnumSourceFieldBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is EnumSourceField &&
- parsedLibrary == other.parsedLibrary &&
- element == other.element;
- }
-
- @override
- int get hashCode {
- return $jf($jc($jc(0, parsedLibrary.hashCode), element.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('EnumSourceField')
- ..add('parsedLibrary', parsedLibrary)
- ..add('element', element))
- .toString();
- }
-}
-
-class EnumSourceFieldBuilder
- implements Builder<EnumSourceField, EnumSourceFieldBuilder> {
- _$EnumSourceField _$v;
-
- ParsedLibraryResult _parsedLibrary;
- ParsedLibraryResult get parsedLibrary => _$this._parsedLibrary;
- set parsedLibrary(ParsedLibraryResult parsedLibrary) =>
- _$this._parsedLibrary = parsedLibrary;
-
- FieldElement _element;
- FieldElement get element => _$this._element;
- set element(FieldElement element) => _$this._element = element;
-
- EnumSourceFieldBuilder();
-
- EnumSourceFieldBuilder get _$this {
- if (_$v != null) {
- _parsedLibrary = _$v.parsedLibrary;
- _element = _$v.element;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(EnumSourceField other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$EnumSourceField;
- }
-
- @override
- void update(void Function(EnumSourceFieldBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$EnumSourceField build() {
- final _$result = _$v ??
- new _$EnumSourceField._(parsedLibrary: parsedLibrary, element: element);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/enum_source_library.dart b/built_value_generator/lib/src/enum_source_library.dart
deleted file mode 100644
index 50d3f1e..0000000
--- a/built_value_generator/lib/src/enum_source_library.dart
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright (c) 2016, Google Inc. 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 built_value_generator.enum_source_library;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/enum_source_class.dart';
-import 'package:built_value_generator/src/library_elements.dart';
-import 'package:quiver/iterables.dart';
-import 'package:source_gen/source_gen.dart';
-
-part 'enum_source_library.g.dart';
-
-abstract class EnumSourceLibrary
- implements Built<EnumSourceLibrary, EnumSourceLibraryBuilder> {
- LibraryElement get element;
-
- factory EnumSourceLibrary(LibraryElement element) =>
- _$EnumSourceLibrary._(element: element);
- EnumSourceLibrary._();
-
- @memoized
- ParsedLibraryResult get parsedLibrary =>
- element.library.session.getParsedLibraryByElement(element.library);
-
- @memoized
- String get name => element.name;
-
- @memoized
- String get fileName => element.source.shortName.replaceAll('.dart', '');
-
- @memoized
- String get source => element.source.contents.data;
-
- @memoized
- BuiltList<EnumSourceClass> get classes {
- var result = ListBuilder<EnumSourceClass>();
-
- for (var classElement in LibraryElements.getClassElements(element)) {
- if (EnumSourceClass.needsEnumClass(classElement)) {
- result.add(EnumSourceClass(parsedLibrary, classElement));
- }
- }
- return result.build();
- }
-
- String generateCode() {
- if (classes.isEmpty) return null;
-
- var errors = _computeErrors();
- if (errors.isNotEmpty) throw _makeError(errors);
-
- return classes.map((c) => c.generateCode()).join('\n');
- }
-
- Iterable<String> _computeErrors() {
- return concat([
- _checkPart(),
- _checkIdentifiers(),
- concat(classes.map((c) => c.computeErrors()))
- ]);
- }
-
- Iterable<String> _checkPart() {
- var expectedCode = "part '$fileName.g.dart';";
- var alternativeExpectedCode = 'part "$fileName.g.dart";';
- return source.contains(expectedCode) ||
- source.contains(alternativeExpectedCode)
- ? <String>[]
- : <String>['Import generated part: $expectedCode'];
- }
-
- Iterable<String> _checkIdentifiers() {
- var result = <String>[];
- var seenIdentifiers = Set<String>();
- var reportedIdentifiers = Set<String>();
-
- for (var sourceClass in classes) {
- for (var identifier in sourceClass.identifiers) {
- if (seenIdentifiers.contains(identifier) &&
- !reportedIdentifiers.contains(identifier)) {
- reportedIdentifiers.add(identifier);
- result.add(
- 'Generated identifier "$identifier" is used multiple times in'
- ' $name, change to something else.');
- }
- seenIdentifiers.add(identifier);
- }
- }
-
- return result;
- }
-}
-
-InvalidGenerationSourceError _makeError(Iterable<String> todos) {
- final message =
- StringBuffer('Please make the following changes to use EnumClass:\n');
- for (var i = 0; i != todos.length; ++i) {
- message.write('\n${i + 1}. ${todos.elementAt(i)}');
- }
-
- return InvalidGenerationSourceError(message.toString());
-}
diff --git a/built_value_generator/lib/src/enum_source_library.g.dart b/built_value_generator/lib/src/enum_source_library.g.dart
deleted file mode 100644
index d15452d..0000000
--- a/built_value_generator/lib/src/enum_source_library.g.dart
+++ /dev/null
@@ -1,110 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.enum_source_library;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$EnumSourceLibrary extends EnumSourceLibrary {
- @override
- final LibraryElement element;
- ParsedLibraryResult __parsedLibrary;
- String __name;
- String __fileName;
- String __source;
- BuiltList<EnumSourceClass> __classes;
-
- factory _$EnumSourceLibrary(
- [void Function(EnumSourceLibraryBuilder) updates]) =>
- (new EnumSourceLibraryBuilder()..update(updates)).build();
-
- _$EnumSourceLibrary._({this.element}) : super._() {
- if (element == null) {
- throw new BuiltValueNullFieldError('EnumSourceLibrary', 'element');
- }
- }
-
- @override
- ParsedLibraryResult get parsedLibrary =>
- __parsedLibrary ??= super.parsedLibrary;
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get fileName => __fileName ??= super.fileName;
-
- @override
- String get source => __source ??= super.source;
-
- @override
- BuiltList<EnumSourceClass> get classes => __classes ??= super.classes;
-
- @override
- EnumSourceLibrary rebuild(void Function(EnumSourceLibraryBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- EnumSourceLibraryBuilder toBuilder() =>
- new EnumSourceLibraryBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is EnumSourceLibrary && element == other.element;
- }
-
- @override
- int get hashCode {
- return $jf($jc(0, element.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('EnumSourceLibrary')
- ..add('element', element))
- .toString();
- }
-}
-
-class EnumSourceLibraryBuilder
- implements Builder<EnumSourceLibrary, EnumSourceLibraryBuilder> {
- _$EnumSourceLibrary _$v;
-
- LibraryElement _element;
- LibraryElement get element => _$this._element;
- set element(LibraryElement element) => _$this._element = element;
-
- EnumSourceLibraryBuilder();
-
- EnumSourceLibraryBuilder get _$this {
- if (_$v != null) {
- _element = _$v.element;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(EnumSourceLibrary other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$EnumSourceLibrary;
- }
-
- @override
- void update(void Function(EnumSourceLibraryBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$EnumSourceLibrary build() {
- final _$result = _$v ?? new _$EnumSourceLibrary._(element: element);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/fields.dart b/built_value_generator/lib/src/fields.dart
deleted file mode 100644
index cfc5abf..0000000
--- a/built_value_generator/lib/src/fields.dart
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2017, Google Inc. 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/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:built_collection/built_collection.dart';
-
-/// Gets fields, including from interfaces. Fields from interfaces are only
-/// returned if they are not also implemented by a mixin.
-///
-/// If a field is overridden then just the closest (overriding) field is
-/// returned.
-BuiltList<FieldElement> collectFields(ClassElement element) =>
- collectFieldsForType(element.type);
-
-/// Gets fields, including from interfaces. Fields from interfaces are only
-/// returned if they are not also implemented by a mixin.
-///
-/// If a field is overridden then just the closest (overriding) field is
-/// returned.
-BuiltList<FieldElement> collectFieldsForType(InterfaceType type) {
- var fields = <FieldElement>[];
- // Add fields from this class before interfaces, so they're added to the set
- // first below. Re-added fields from interfaces are ignored.
- fields.addAll(_fieldElementsForType(type));
-
- Set<InterfaceType>.from(type.interfaces)
- ..addAll(type.mixins)
- ..forEach((interface) => fields.addAll(collectFieldsForType(interface)));
-
- // Overridden fields have multiple declarations, so deduplicate by adding
- // to a set that compares on field name.
- var fieldSet = LinkedHashSet<FieldElement>(
- equals: (a, b) => a.displayName == b.displayName,
- hashCode: (a) => a.displayName.hashCode);
- fieldSet.addAll(fields);
-
- // Filter to fields that are not implemented by a mixin.
- return BuiltList<FieldElement>.build((b) => b
- ..addAll(fieldSet)
- ..where((field) =>
- type.lookUpInheritedGetter(field.name, thisType: false)?.isAbstract ??
- true));
-}
-
-BuiltList<FieldElement> _fieldElementsForType(InterfaceType type) {
- var result = ListBuilder<FieldElement>();
- for (var accessor in type.accessors) {
- if (accessor.isSetter) continue;
- result.add(accessor.variable as FieldElement);
- }
- return result.build();
-}
diff --git a/built_value_generator/lib/src/fixes.dart b/built_value_generator/lib/src/fixes.dart
deleted file mode 100644
index ad3ba1a..0000000
--- a/built_value_generator/lib/src/fixes.dart
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2018, Google Inc. 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:built_value/built_value.dart';
-
-part 'fixes.g.dart';
-
-/// An error in input source detected by the generator.
-///
-/// Optionally specifies the location of the error and the source code to
-/// replace it to fix the error.
-abstract class GeneratorError
- implements Built<GeneratorError, GeneratorErrorBuilder> {
- /// Error message for the user.
- String get message;
-
- /// Optionally, the offset of the incorrect code.
- @nullable
- int get offset;
-
- /// Optionally, the length of the incorrect code.
- @nullable
- int get length;
-
- /// Optionally, the fix for the incorrect code.
- @nullable
- String get fix;
-
- factory GeneratorError([void Function(GeneratorErrorBuilder) updates]) =
- _$GeneratorError;
- GeneratorError._() {
- if (((offset == null) != (length == null)) ||
- ((offset == null) != (fix == null))) {
- throw ArgumentError(
- 'Offset, length and fix must either all be null or all non-null. '
- 'Got: offset $offset, length $length, fix $fix');
- }
- }
-}
diff --git a/built_value_generator/lib/src/fixes.g.dart b/built_value_generator/lib/src/fixes.g.dart
deleted file mode 100644
index 4fb8a3e..0000000
--- a/built_value_generator/lib/src/fixes.g.dart
+++ /dev/null
@@ -1,121 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of 'fixes.dart';
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$GeneratorError extends GeneratorError {
- @override
- final String message;
- @override
- final int offset;
- @override
- final int length;
- @override
- final String fix;
-
- factory _$GeneratorError([void Function(GeneratorErrorBuilder) updates]) =>
- (new GeneratorErrorBuilder()..update(updates)).build();
-
- _$GeneratorError._({this.message, this.offset, this.length, this.fix})
- : super._() {
- if (message == null) {
- throw new BuiltValueNullFieldError('GeneratorError', 'message');
- }
- }
-
- @override
- GeneratorError rebuild(void Function(GeneratorErrorBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- GeneratorErrorBuilder toBuilder() =>
- new GeneratorErrorBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is GeneratorError &&
- message == other.message &&
- offset == other.offset &&
- length == other.length &&
- fix == other.fix;
- }
-
- @override
- int get hashCode {
- return $jf($jc(
- $jc($jc($jc(0, message.hashCode), offset.hashCode), length.hashCode),
- fix.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('GeneratorError')
- ..add('message', message)
- ..add('offset', offset)
- ..add('length', length)
- ..add('fix', fix))
- .toString();
- }
-}
-
-class GeneratorErrorBuilder
- implements Builder<GeneratorError, GeneratorErrorBuilder> {
- _$GeneratorError _$v;
-
- String _message;
- String get message => _$this._message;
- set message(String message) => _$this._message = message;
-
- int _offset;
- int get offset => _$this._offset;
- set offset(int offset) => _$this._offset = offset;
-
- int _length;
- int get length => _$this._length;
- set length(int length) => _$this._length = length;
-
- String _fix;
- String get fix => _$this._fix;
- set fix(String fix) => _$this._fix = fix;
-
- GeneratorErrorBuilder();
-
- GeneratorErrorBuilder get _$this {
- if (_$v != null) {
- _message = _$v.message;
- _offset = _$v.offset;
- _length = _$v.length;
- _fix = _$v.fix;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(GeneratorError other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$GeneratorError;
- }
-
- @override
- void update(void Function(GeneratorErrorBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$GeneratorError build() {
- final _$result = _$v ??
- new _$GeneratorError._(
- message: message, offset: offset, length: length, fix: fix);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/library_elements.dart b/built_value_generator/lib/src/library_elements.dart
deleted file mode 100644
index 6ff7bcc..0000000
--- a/built_value_generator/lib/src/library_elements.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) 2016, Google Inc. 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/visitor.dart';
-import 'package:built_collection/built_collection.dart';
-
-/// Tools for [LibraryElement]s.
-class LibraryElements {
- static BuiltList<ClassElement> getClassElements(
- LibraryElement libraryElement) {
- var result = _GetClassesVisitor();
- libraryElement.visitChildren(result);
- return BuiltList<ClassElement>(result.classElements);
- }
-}
-
-/// Visitor that gets all [ClassElement]s.
-class _GetClassesVisitor extends SimpleElementVisitor {
- final List<ClassElement> classElements = List<ClassElement>();
-
- @override
- void visitClassElement(ClassElement element) {
- classElements.add(element);
- }
-
- @override
- void visitCompilationUnitElement(CompilationUnitElement element) {
- element.visitChildren(this);
- }
-}
diff --git a/built_value_generator/lib/src/memoized_getter.dart b/built_value_generator/lib/src/memoized_getter.dart
deleted file mode 100644
index 54eefa2..0000000
--- a/built_value_generator/lib/src/memoized_getter.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-library built_value_generator.memoized_getter;
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/dart_types.dart';
-import 'package:built_value_generator/src/metadata.dart'
- show metadataToStringValue;
-
-part 'memoized_getter.g.dart';
-
-abstract class MemoizedGetter
- implements Built<MemoizedGetter, MemoizedGetterBuilder> {
- String get returnType;
- String get name;
-
- factory MemoizedGetter([void Function(MemoizedGetterBuilder) updates]) =
- _$MemoizedGetter;
- MemoizedGetter._();
-
- static Iterable<MemoizedGetter> fromClassElement(ClassElement classElement) {
- return classElement.fields
- .where((field) =>
- field.getter != null &&
- !field.getter.isAbstract &&
- field.getter.metadata.any(
- (metadata) => metadataToStringValue(metadata) == 'memoized'))
- .map((field) => MemoizedGetter((b) => b
- ..returnType = DartTypes.getName(field.getter.returnType)
- ..name = field.displayName))
- .toList();
- }
-}
diff --git a/built_value_generator/lib/src/memoized_getter.g.dart b/built_value_generator/lib/src/memoized_getter.g.dart
deleted file mode 100644
index c503097..0000000
--- a/built_value_generator/lib/src/memoized_getter.g.dart
+++ /dev/null
@@ -1,102 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.memoized_getter;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$MemoizedGetter extends MemoizedGetter {
- @override
- final String returnType;
- @override
- final String name;
-
- factory _$MemoizedGetter([void Function(MemoizedGetterBuilder) updates]) =>
- (new MemoizedGetterBuilder()..update(updates)).build();
-
- _$MemoizedGetter._({this.returnType, this.name}) : super._() {
- if (returnType == null) {
- throw new BuiltValueNullFieldError('MemoizedGetter', 'returnType');
- }
- if (name == null) {
- throw new BuiltValueNullFieldError('MemoizedGetter', 'name');
- }
- }
-
- @override
- MemoizedGetter rebuild(void Function(MemoizedGetterBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- MemoizedGetterBuilder toBuilder() =>
- new MemoizedGetterBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is MemoizedGetter &&
- returnType == other.returnType &&
- name == other.name;
- }
-
- @override
- int get hashCode {
- return $jf($jc($jc(0, returnType.hashCode), name.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('MemoizedGetter')
- ..add('returnType', returnType)
- ..add('name', name))
- .toString();
- }
-}
-
-class MemoizedGetterBuilder
- implements Builder<MemoizedGetter, MemoizedGetterBuilder> {
- _$MemoizedGetter _$v;
-
- String _returnType;
- String get returnType => _$this._returnType;
- set returnType(String returnType) => _$this._returnType = returnType;
-
- String _name;
- String get name => _$this._name;
- set name(String name) => _$this._name = name;
-
- MemoizedGetterBuilder();
-
- MemoizedGetterBuilder get _$this {
- if (_$v != null) {
- _returnType = _$v.returnType;
- _name = _$v.name;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(MemoizedGetter other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$MemoizedGetter;
- }
-
- @override
- void update(void Function(MemoizedGetterBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$MemoizedGetter build() {
- final _$result =
- _$v ?? new _$MemoizedGetter._(returnType: returnType, name: name);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/metadata.dart b/built_value_generator/lib/src/metadata.dart
deleted file mode 100644
index 545aefa..0000000
--- a/built_value_generator/lib/src/metadata.dart
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright (c) 2017, Google Inc. 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/constant/value.dart';
-import 'package:source_gen/source_gen.dart';
-
-DartObject getConstantValueFromAnnotation(ElementAnnotation annotation) {
- final value = annotation.computeConstantValue();
- if (value == null) {
- throw InvalidGenerationSourceError(
- 'Can’t process annotation “${annotation.toSource()}” in '
- '“${annotation.librarySource.uri}”. Please check for a missing import.');
- }
- return value;
-}
-
-/// Gets the `String` value of an annotation. Throws a descriptive
-/// [InvalidGenerationSourceError] if the annotation can't be resolved.
-String metadataToStringValue(ElementAnnotation annotation) {
- final value = getConstantValueFromAnnotation(annotation);
- return value.toStringValue();
-}
-
-/// Gets a field from an annotation. Throws a descriptive
-/// [InvalidGenerationSourceError] if the annotation can't be resolved.
-DartObject getMetadataField(ElementAnnotation annotation, String name) {
- final value = getConstantValueFromAnnotation(annotation);
- return value.getField(name);
-}
diff --git a/built_value_generator/lib/src/plugin/checker.dart b/built_value_generator/lib/src/plugin/checker.dart
deleted file mode 100644
index 76064ae..0000000
--- a/built_value_generator/lib/src/plugin/checker.dart
+++ /dev/null
@@ -1,82 +0,0 @@
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:analyzer_plugin/protocol/protocol_generated.dart';
-import 'package:built_value_generator/src/value_source_class.dart';
-
-/// Checks a library for errors related to built_value generation. Returns
-/// the errors and, where possible, corresponding fixes.
-class Checker {
- Map<AnalysisError, PrioritizedSourceChange> check(
- LibraryElement libraryElement) {
- var result = <AnalysisError, PrioritizedSourceChange>{};
-
- for (var compilationUnit in libraryElement.units) {
- // Don't analyze if there's no source; there's nothing to do.
- if (compilationUnit.source == null) continue;
- // Don't analyze generated source; there's nothing to do.
- if (compilationUnit.source.fullName.endsWith('.g.dart')) continue;
-
- for (var type in compilationUnit.types) {
- if (!type.interfaces.any((i) => i.displayName.startsWith('Built'))) {
- continue;
- }
-
- final ValueSourceClass sourceClass = ValueSourceClass(type);
- final errors = sourceClass.computeErrors();
-
- if (errors.isNotEmpty) {
- final lineInfo = compilationUnit.lineInfo;
-
- // Report one error on the 'Built' interface. Bundle together all the
- // necessary fixes.
-
- // TODO(davidmorgan): split error message and example; only show
- // example in the build error, not in the IDE.
- final builtNode = sourceClass
- .classDeclaration.implementsClause.interfaces
- .singleWhere((typeName) => typeName.name.name == 'Built');
- final offset = builtNode.offset;
- final length = builtNode.length;
- final offsetLineLocation = lineInfo.getLocation(offset);
- final error = AnalysisError(
- AnalysisErrorSeverity.ERROR,
- AnalysisErrorType.LINT,
- Location(
- compilationUnit.source.fullName,
- offset,
- length,
- offsetLineLocation.lineNumber,
- offsetLineLocation.columnNumber),
- 'Class needs fixes for built_value: ' +
- errors.map((error) => error.message).join(' '),
- 'BUILT_VALUE_NEEDS_FIXES');
-
- // Fix consists of all the individual fixes, sorted so they apply
- // from the end of the file backwards, so each fix does not
- // invalidate the line numbers for the following fixes.
- final edits = errors
- .where((error) => error.fix != null)
- .map((error) => SourceEdit(error.offset, error.length, error.fix))
- .toList();
- edits.sort((left, right) => right.offset.compareTo(left.offset));
-
- final fix = PrioritizedSourceChange(
- 1000000,
- SourceChange(
- 'Apply fixes for built_value.',
- edits: [
- SourceFileEdit(
- compilationUnit.source.fullName,
- compilationUnit.source.modificationStamp,
- edits: edits,
- )
- ],
- ));
- result[error] = fix;
- }
- }
- }
-
- return result;
- }
-}
diff --git a/built_value_generator/lib/src/plugin/plugin.dart b/built_value_generator/lib/src/plugin/plugin.dart
deleted file mode 100644
index ac57af9..0000000
--- a/built_value_generator/lib/src/plugin/plugin.dart
+++ /dev/null
@@ -1,116 +0,0 @@
-import 'dart:async';
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/file_system/file_system.dart';
-// ignore: implementation_imports
-import 'package:analyzer/src/context/builder.dart';
-// ignore: implementation_imports
-import 'package:analyzer/src/context/context_root.dart';
-// ignore: implementation_imports
-import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer_plugin/plugin/plugin.dart';
-import 'package:analyzer_plugin/protocol/protocol_common.dart' as plugin;
-import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
-import 'package:built_value_generator/src/plugin/checker.dart';
-
-/// Analyzer plugin for built_value.
-///
-/// Surfaces the same errors as the generator at compile time, with fixes
-/// where possible.
-class BuiltValueAnalyzerPlugin extends ServerPlugin {
- final Checker checker = Checker();
-
- BuiltValueAnalyzerPlugin(ResourceProvider provider) : super(provider);
-
- @override
- AnalysisDriverGeneric createAnalysisDriver(plugin.ContextRoot contextRoot) {
- var root = ContextRoot(contextRoot.root, contextRoot.exclude,
- pathContext: resourceProvider.pathContext)
- ..optionsFilePath = contextRoot.optionsFile;
- var contextBuilder = ContextBuilder(resourceProvider, sdkManager, null)
- ..analysisDriverScheduler = analysisDriverScheduler
- ..byteStore = byteStore
- ..performanceLog = performanceLog
- ..fileContentOverlay = fileContentOverlay;
- var result = contextBuilder.buildDriver(root);
- result.results.listen(_processResult);
- return result;
- }
-
- @override
- List<String> get fileGlobsToAnalyze => const ['*.dart'];
-
- @override
- String get name => 'Built Value';
-
- // This is the protocol version, not the plugin version. It must match the
- // version of the `analyzer_plugin` package.
- @override
- String get version => '1.0.0-alpha.0';
-
- @override
- String get contactInfo => 'https://github.com/google/built_value.dart/issues';
-
- /// Computes errors based on an analysis result and notifies the analyzer.
- // ignore: deprecated_member_use
- void _processResult(ResolveResult analysisResult) {
- try {
- // If there is no relevant analysis result, notify the analyzer of no errors.
- if (analysisResult.unit == null ||
- analysisResult.libraryElement == null) {
- channel.sendNotification(
- plugin.AnalysisErrorsParams(analysisResult.path, [])
- .toNotification());
- } else {
- // If there is something to analyze, do so and notify the analyzer.
- // Note that notifying with an empty set of errors is important as
- // this clears errors if they were fixed.
- final checkResult = checker.check(analysisResult.libraryElement);
- channel.sendNotification(plugin.AnalysisErrorsParams(
- analysisResult.path, checkResult.keys.toList())
- .toNotification());
- }
- } catch (e, stackTrace) {
- // Notify the analyzer that an exception happened.
- channel.sendNotification(
- plugin.PluginErrorParams(false, e.toString(), stackTrace.toString())
- .toNotification());
- }
- }
-
- @override
- void contentChanged(String path) {
- super.driverForPath(path).addFile(path);
- }
-
- @override
- Future<plugin.EditGetFixesResult> handleEditGetFixes(
- plugin.EditGetFixesParams parameters) async {
- try {
- final analysisResult =
- await (driverForPath(parameters.file) as AnalysisDriver)
- .getResult(parameters.file);
-
- // Get errors and fixes for the file.
- final checkResult = checker.check(analysisResult.libraryElement);
-
- // Return any fixes that are for the expected file.
- final fixes = <plugin.AnalysisErrorFixes>[];
- for (var error in checkResult.keys) {
- if (error.location.file == parameters.file &&
- checkResult[error].change.edits.single.edits.isNotEmpty) {
- fixes.add(
- plugin.AnalysisErrorFixes(error, fixes: [checkResult[error]]));
- }
- }
-
- return plugin.EditGetFixesResult(fixes);
- } catch (e, stackTrace) {
- // Notify the analyzer that an exception happened.
- channel.sendNotification(
- plugin.PluginErrorParams(false, e.toString(), stackTrace.toString())
- .toNotification());
- return plugin.EditGetFixesResult([]);
- }
- }
-}
diff --git a/built_value_generator/lib/src/serializer_source_class.dart b/built_value_generator/lib/src/serializer_source_class.dart
deleted file mode 100644
index 85654cd..0000000
--- a/built_value_generator/lib/src/serializer_source_class.dart
+++ /dev/null
@@ -1,502 +0,0 @@
-// Copyright (c) 2015, Google Inc. 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 built_value_generator.source_class;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/enum_source_class.dart';
-import 'package:built_value_generator/src/enum_source_field.dart';
-import 'package:built_value_generator/src/fields.dart' show collectFields;
-import 'package:built_value_generator/src/serializer_source_field.dart';
-import 'package:built_value_generator/src/strings.dart';
-import 'package:built_value_generator/src/value_source_class.dart';
-
-import 'dart_types.dart';
-
-part 'serializer_source_class.g.dart';
-
-abstract class SerializerSourceClass
- implements Built<SerializerSourceClass, SerializerSourceClassBuilder> {
- ClassElement get element;
- @nullable
- ClassElement get builderElement;
-
- factory SerializerSourceClass(ClassElement element) =>
- _$SerializerSourceClass._(
- element: element,
- builderElement:
- element.library.getType(element.displayName + 'Builder'));
- SerializerSourceClass._();
-
- @memoized
- ParsedLibraryResult get parsedLibrary =>
- element.library.session.getParsedLibraryByElement(element.library);
-
- // TODO(davidmorgan): share common code in a nicer way.
- @memoized
- BuiltValue get builtValueSettings => ValueSourceClass(element).settings;
-
- @memoized
- BuiltValueSerializer get serializerSettings {
- var serializerFields =
- element.fields.where((field) => field.name == 'serializer').toList();
- if (serializerFields.isEmpty) return const BuiltValueSerializer();
- var serializerField = serializerFields.single;
- if (serializerField.getter == null) return const BuiltValueSerializer();
-
- var annotations = serializerField.getter.metadata
- .map((annotation) => annotation.computeConstantValue())
- .where((value) =>
- DartTypes.getName(value?.type) == 'BuiltValueSerializer');
- if (annotations.isEmpty) return const BuiltValueSerializer();
-
- var annotation = annotations.single;
- // If a field does not exist, that means an old `built_value` version; use
- // the default.
- return BuiltValueSerializer(
- custom: annotation.getField('custom')?.toBoolValue() ?? false,
- serializeNulls:
- annotation.getField('serializeNulls')?.toBoolValue() ?? false);
- }
-
- // TODO(davidmorgan): share common code in a nicer way.
- @memoized
- BuiltValueEnum get enumClassSettings =>
- EnumSourceClass(parsedLibrary, element).settings;
-
- @memoized
- String get name => element.name;
-
- @memoized
- String get wireName {
- if (isBuiltValue) {
- return builtValueSettings.wireName ?? name;
- } else if (isEnumClass) {
- return enumClassSettings.wireName ?? name;
- } else {
- return name;
- }
- }
-
- @memoized
- String get serializerDeclaration {
- var serializerFields =
- element.fields.where((field) => field.name == 'serializer').toList();
- if (serializerFields.isEmpty) return '';
- var serializerField = serializerFields.single;
- var result = parsedLibrary
- .getElementDeclaration(serializerField.getter)
- ?.node
- ?.toSource() ??
- '';
- // Strip off annotations.
- if (result.startsWith('@')) {
- // First thing after the annotations should be `static`.
- if (result.contains(' static ')) {
- result = result.substring(result.indexOf(' static ') + 1);
- }
- }
- return result;
- }
-
- @memoized
- BuiltList<String> get genericParameters =>
- BuiltList<String>(element.typeParameters.map((e) => e.name));
-
- @memoized
- BuiltList<String> get genericBounds =>
- BuiltList<String>(element.typeParameters
- .map((element) => (element.bound ?? '').toString()));
-
- // TODO(davidmorgan): better check.
- @memoized
- bool get isBuiltValue =>
- element.allSupertypes
- .map((type) => type.name)
- .any((name) => name.startsWith('Built')) &&
- !element.name.startsWith(r'_$') &&
- element.fields.any((field) => field.name == 'serializer');
-
- // TODO(davidmorgan): better check.
- @memoized
- bool get isEnumClass =>
- element.allSupertypes
- .map((type) => type.name)
- .any((name) => name == 'EnumClass') &&
- !element.name.startsWith(r'_$') &&
- element.fields.any((field) => field.name == 'serializer');
-
- @memoized
- BuiltList<SerializerSourceField> get fields {
- var result = ListBuilder<SerializerSourceField>();
- for (var fieldElement in collectFields(element)) {
- final builderFieldElement =
- builderElement?.getField(fieldElement.displayName);
- final sourceField = SerializerSourceField(
- builtValueSettings, parsedLibrary, fieldElement, builderFieldElement);
- if (sourceField.isSerializable) {
- result.add(sourceField);
- }
- }
- return result.build();
- }
-
- /// Returns all the serializable classes used, transitively, by fields of
- /// this class.
- @memoized
- BuiltSet<SerializerSourceClass> get fieldClasses =>
- _fieldClassesWith(BuiltSet<SerializerSourceClass>());
-
- /// Returns all the serializable classes used, transitively, by fields of
- /// this class.
- ///
- /// [initialClasses] may be empty, or may include classes that are already
- /// being evaluated. These will not be re-evaluated, preventing infinite
- /// recursion when there is a loop in field types. For example, when `FooA`
- /// has a field of type `FooB`, and `FooB `has a field of type `FooA`.
- BuiltSet<SerializerSourceClass> _fieldClassesWith(
- BuiltSet<SerializerSourceClass> initialClasses) {
- var result = initialClasses.toBuilder();
- for (var fieldElement in collectFields(element)) {
- if (fieldElement.isStatic) continue;
- if (fieldElement.setter != null) continue;
-
- // Type is not fully specified, ignore.
- if (fieldElement.type.element is! ClassElement) continue;
-
- // Also find classes used as generic parameters; for example a field
- // of type List<Foo> means we need to be able to serialize Foo.
- if (fieldElement.type is ParameterizedType) {
- for (var type
- in (fieldElement.type as ParameterizedType).typeArguments) {
- // Type is not fully specified, ignore.
- if (type.element is! ClassElement) continue;
-
- final sourceClass =
- SerializerSourceClass(type.element as ClassElement);
-
- if (sourceClass != this &&
- !result.build().contains(sourceClass) &&
- sourceClass.isSerializable) {
- result.add(sourceClass);
- result.replace(sourceClass._fieldClassesWith(result.build()));
- }
- }
- }
-
- final sourceClass =
- SerializerSourceClass(fieldElement.type.element as ClassElement);
- if (sourceClass != this &&
- !result.build().contains(sourceClass) &&
- sourceClass.isSerializable) {
- result.add(sourceClass);
- result.replace(sourceClass._fieldClassesWith(result.build()));
- }
- }
-
- return result.build();
- }
-
- @memoized
- CompilationUnitElement get compilationUnit =>
- element.library.definingCompilationUnit;
-
- Iterable<String> computeErrors() {
- var result = <String>[];
-
- if (!serializerSettings.custom) {
- final camelCaseName =
- name.substring(0, 1).toLowerCase() + name.substring(1);
-
- final expectedSerializerDeclaration =
- 'static Serializer<$name> get serializer => '
- '_\$${camelCaseName}Serializer;';
- if (serializerDeclaration != expectedSerializerDeclaration) {
- result.add('Declare $name.serializer as: '
- '$expectedSerializerDeclaration got $serializerDeclaration');
- }
- }
-
- for (var field in fields) {
- result.addAll(field.computeErrors());
- }
-
- return result;
- }
-
- @memoized
- bool get isSerializable => isBuiltValue || isEnumClass;
-
- @memoized
- bool get needsGeneratedSerializer => !serializerSettings.custom;
-
- String generateTransitiveSerializerAdder() {
- return '..add($name.serializer)';
- }
-
- /// Returns a string with `addBuilderFactory` calls to add the needed builder
- /// factories. Specify the [compilationUnit] the code will run in, so the
- /// code can be generated correctly (with or without import prefixes).
- String generateBuilderFactoryAdders(CompilationUnitElement compilationUnit) {
- return fields
- .where((field) =>
- field.needsBuilder &&
- field
- .generateFullType(
- compilationUnit, genericParameters.toBuiltSet())
- .startsWith('const '))
- .map((field) =>
- '..addBuilderFactory(${field.generateFullType(compilationUnit)}, '
- ' () => ${field.generateBuilder()})')
- .join('\n');
- }
-
- String generateSerializerDeclaration() {
- var camelCaseName = _toCamelCase(name);
- return 'Serializer<$name> '
- '_\$${camelCaseName}Serializer = '
- 'new _\$${name}Serializer();';
- }
-
- String generateSerializer() {
- if (isBuiltValue) {
- return '''
-class _\$${name}Serializer implements StructuredSerializer<$name> {
- @override
- final Iterable<Type> types = const [$name, _\$$name];
- @override
- final String wireName = '${escapeString(wireName)}';
-
- @override
- Iterable<Object> serialize(Serializers serializers, $name object,
- {FullType specifiedType = FullType.unspecified}) {
- ${fields.isEmpty ? 'return <Object>[];' : '''
- ${_generateGenericsSerializerPreamble()}
- final result = <Object>[${_generateRequiredFieldSerializers()}];
- ${_generateNullableFieldSerializers()}
- return result;
- '''}
- }
-
- @override
- $name deserialize(Serializers serializers, Iterable<Object> serialized,
- {FullType specifiedType = FullType.unspecified}) {
- ${_generateGenericsSerializerPreamble()}
- ${fields.isEmpty ? 'return ${_generateNewBuilder()}.build();' : '''
- final result = ${_generateNewBuilder()};
-
- final iterator = serialized.iterator;
- while (iterator.moveNext()) {
- final key = iterator.current as String;
- iterator.moveNext();
- final dynamic value = iterator.current;
- ${serializerSettings.serializeNulls ? 'if (value == null) continue;' : ''}'''
- '''switch (key) {
- ${_generateFieldDeserializers()}
- }
- }
-
- return result.build();
- '''}
- }
-}
-''';
- } else if (isEnumClass) {
- final wireNameMapping = BuiltMap<String, String>.build((b) => element
- .fields
- .where((field) => field.isConst && field.isStatic)
- .forEach((field) {
- final enumSourceField = EnumSourceField(parsedLibrary, field);
- if (enumSourceField.settings.wireName != null) {
- b[field.name] = enumSourceField.settings.wireName;
- }
- }));
-
- if (wireNameMapping.isEmpty) {
- // No wire names. Just use the enum names directly.
- return '''
-class _\$${name}Serializer implements PrimitiveSerializer<$name> {
- @override
- final Iterable<Type> types = const <Type>[$name];
- @override
- final String wireName = '${escapeString(wireName)}';
-
- @override
- Object serialize(Serializers serializers, $name object,
- {FullType specifiedType = FullType.unspecified}) =>
- object.name;
-
- @override
- $name deserialize(Serializers serializers, Object serialized,
- {FullType specifiedType = FullType.unspecified}) =>
- $name.valueOf(serialized as String);
-}''';
- } else {
- // Generate maps between enum names and wire names.
- final toWire = '''
- static const Map<String, String> _toWire = const <String, String>{
- ${wireNameMapping.keys.map((key) => "'$key': '${wireNameMapping[key]}',").join('\n')}
- };''';
- final fromWire = '''
- static const Map<String, String> _fromWire = const <String, String>{
- ${wireNameMapping.keys.map((key) => "'${wireNameMapping[key]}': '$key',").join('\n')}
- };''';
-
- return '''
-class _\$${name}Serializer implements PrimitiveSerializer<$name> {
- $toWire
- $fromWire
-
- @override
- final Iterable<Type> types = const <Type>[$name];
- @override
- final String wireName = '${escapeString(wireName)}';
-
- @override
- Object serialize(Serializers serializers, $name object,
- {FullType specifiedType = FullType.unspecified}) =>
- _toWire[object.name] ?? object.name;
-
- @override
- $name deserialize(Serializers serializers, Object serialized,
- {FullType specifiedType = FullType.unspecified}) =>
- $name.valueOf(_fromWire[serialized] ?? serialized as String);
-}''';
- }
- } else {
- throw UnsupportedError('not serializable');
- }
- }
-
- String _generateNewBuilder() {
- var parameters = _genericParametersUsedInFields;
- if (parameters.isEmpty) return 'new ${name}Builder()';
- var boundsOrObject = genericBounds
- .map((bound) => bound.isEmpty ? 'Object' : bound)
- .join(', ');
- return 'isUnderspecified ? '
- 'new ${name}Builder<$boundsOrObject>() : '
- 'serializers.newBuilder(specifiedType) as ${name}Builder';
- }
-
- BuiltList<String> get _genericParametersUsedInFields => BuiltList<String>(
- genericParameters.where((parameter) => fields.any((field) =>
- field.rawType == parameter ||
- field.type.contains(RegExp('[<, \n]$parameter[>, \n]')))));
-
- String _generateGenericsSerializerPreamble() {
- var parameters = _genericParametersUsedInFields;
- if (parameters.isEmpty) return '';
- var result = StringBuffer();
- result.writeln('final isUnderspecified = specifiedType.isUnspecified || '
- 'specifiedType.parameters.isEmpty;');
- result.writeln(
- 'if (!isUnderspecified) serializers.expectBuilder(specifiedType);');
- for (var parameter in parameters) {
- final index = genericParameters.indexOf(parameter);
- result.writeln('final parameter$parameter = '
- 'isUnderspecified '
- '? FullType.object : '
- 'specifiedType.parameters[$index];');
- }
- result.writeln();
- return result.toString();
- }
-
- String _generateRequiredFieldSerializers() {
- return fields
- .where((field) => !field.isNullable)
- .map((field) => "'${escapeString(field.wireName)}', "
- 'serializers.serialize(object.${field.name}, '
- 'specifiedType: '
- '${field.generateFullType(compilationUnit, genericParameters.toBuiltSet())}),')
- .join('');
- }
-
- String _generateNullableFieldSerializers() {
- return fields.where((field) => field.isNullable).map((field) {
- var serializeField = '''serializers.serialize(
- object.${field.name},
- specifiedType:
- ${field.generateFullType(compilationUnit, genericParameters.toBuiltSet())})''';
-
- // By default, omit nulls; but if we were asked to include nulls, just
- // write them.
- if (serializerSettings.serializeNulls) {
- return '''
- result.add('${escapeString(field.wireName)}');
- if (object.${field.name} == null) {
- result.add(null);
- } else {
- result.add($serializeField);
- }''';
- } else {
- return '''
- if (object.${field.name} != null) {
- result
- ..add('${escapeString(field.wireName)}')
- ..add($serializeField);
- }''';
- }
- }).join('');
- }
-
- /// Gets a map from generic parameter to its bound.
- ///
- /// 'Object' is substituted where there is no bound.
- BuiltMap<String, String> get _genericBoundsAsMap {
- var genericBoundsOrObject =
- genericBounds.map((bound) => bound.isEmpty ? 'Object' : bound).toList();
- var result = MapBuilder<String, String>();
- for (var i = 0; i != genericParameters.length; ++i) {
- result[genericParameters[i]] = genericBoundsOrObject[i];
- }
- return result.build();
- }
-
- String _generateFieldDeserializers() {
- return fields.map((field) {
- final fullType = field.generateFullType(
- compilationUnit, genericParameters.toBuiltSet());
- final cast = field.generateCast(compilationUnit, _genericBoundsAsMap);
- if (field.builderFieldUsesNestedBuilder) {
- return '''
-case '${escapeString(field.wireName)}':
- result.${field.name}.replace(serializers.deserialize(
- value, specifiedType: $fullType) $cast);
- break;
-''';
- } else {
- return '''
-case '${escapeString(field.wireName)}':
- result.${field.name} = serializers.deserialize(
- value, specifiedType: $fullType) $cast;
- break;
-''';
- }
- }).join('');
- }
-
- static String _toCamelCase(String name) {
- var result = '';
- var upperCase = false;
- var firstCharacter = true;
- for (var char in name.split('')) {
- if (char == '_') {
- upperCase = true;
- } else {
- result += firstCharacter
- ? char.toLowerCase()
- : (upperCase ? char.toUpperCase() : char);
- upperCase = false;
- firstCharacter = false;
- }
- }
- return result;
- }
-}
diff --git a/built_value_generator/lib/src/serializer_source_class.g.dart b/built_value_generator/lib/src/serializer_source_class.g.dart
deleted file mode 100644
index 5476978..0000000
--- a/built_value_generator/lib/src/serializer_source_class.g.dart
+++ /dev/null
@@ -1,177 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.source_class;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$SerializerSourceClass extends SerializerSourceClass {
- @override
- final ClassElement element;
- @override
- final ClassElement builderElement;
- ParsedLibraryResult __parsedLibrary;
- BuiltValue __builtValueSettings;
- BuiltValueSerializer __serializerSettings;
- BuiltValueEnum __enumClassSettings;
- String __name;
- String __wireName;
- String __serializerDeclaration;
- BuiltList<String> __genericParameters;
- BuiltList<String> __genericBounds;
- bool __isBuiltValue;
- bool __isEnumClass;
- BuiltList<SerializerSourceField> __fields;
- BuiltSet<SerializerSourceClass> __fieldClasses;
- CompilationUnitElement __compilationUnit;
- bool __isSerializable;
- bool __needsGeneratedSerializer;
-
- factory _$SerializerSourceClass(
- [void Function(SerializerSourceClassBuilder) updates]) =>
- (new SerializerSourceClassBuilder()..update(updates)).build();
-
- _$SerializerSourceClass._({this.element, this.builderElement}) : super._() {
- if (element == null) {
- throw new BuiltValueNullFieldError('SerializerSourceClass', 'element');
- }
- }
-
- @override
- ParsedLibraryResult get parsedLibrary =>
- __parsedLibrary ??= super.parsedLibrary;
-
- @override
- BuiltValue get builtValueSettings =>
- __builtValueSettings ??= super.builtValueSettings;
-
- @override
- BuiltValueSerializer get serializerSettings =>
- __serializerSettings ??= super.serializerSettings;
-
- @override
- BuiltValueEnum get enumClassSettings =>
- __enumClassSettings ??= super.enumClassSettings;
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get wireName => __wireName ??= super.wireName;
-
- @override
- String get serializerDeclaration =>
- __serializerDeclaration ??= super.serializerDeclaration;
-
- @override
- BuiltList<String> get genericParameters =>
- __genericParameters ??= super.genericParameters;
-
- @override
- BuiltList<String> get genericBounds =>
- __genericBounds ??= super.genericBounds;
-
- @override
- bool get isBuiltValue => __isBuiltValue ??= super.isBuiltValue;
-
- @override
- bool get isEnumClass => __isEnumClass ??= super.isEnumClass;
-
- @override
- BuiltList<SerializerSourceField> get fields => __fields ??= super.fields;
-
- @override
- BuiltSet<SerializerSourceClass> get fieldClasses =>
- __fieldClasses ??= super.fieldClasses;
-
- @override
- CompilationUnitElement get compilationUnit =>
- __compilationUnit ??= super.compilationUnit;
-
- @override
- bool get isSerializable => __isSerializable ??= super.isSerializable;
-
- @override
- bool get needsGeneratedSerializer =>
- __needsGeneratedSerializer ??= super.needsGeneratedSerializer;
-
- @override
- SerializerSourceClass rebuild(
- void Function(SerializerSourceClassBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- SerializerSourceClassBuilder toBuilder() =>
- new SerializerSourceClassBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is SerializerSourceClass &&
- element == other.element &&
- builderElement == other.builderElement;
- }
-
- @override
- int get hashCode {
- return $jf($jc($jc(0, element.hashCode), builderElement.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('SerializerSourceClass')
- ..add('element', element)
- ..add('builderElement', builderElement))
- .toString();
- }
-}
-
-class SerializerSourceClassBuilder
- implements Builder<SerializerSourceClass, SerializerSourceClassBuilder> {
- _$SerializerSourceClass _$v;
-
- ClassElement _element;
- ClassElement get element => _$this._element;
- set element(ClassElement element) => _$this._element = element;
-
- ClassElement _builderElement;
- ClassElement get builderElement => _$this._builderElement;
- set builderElement(ClassElement builderElement) =>
- _$this._builderElement = builderElement;
-
- SerializerSourceClassBuilder();
-
- SerializerSourceClassBuilder get _$this {
- if (_$v != null) {
- _element = _$v.element;
- _builderElement = _$v.builderElement;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(SerializerSourceClass other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$SerializerSourceClass;
- }
-
- @override
- void update(void Function(SerializerSourceClassBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$SerializerSourceClass build() {
- final _$result = _$v ??
- new _$SerializerSourceClass._(
- element: element, builderElement: builderElement);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/serializer_source_field.dart b/built_value_generator/lib/src/serializer_source_field.dart
deleted file mode 100644
index e2a14c3..0000000
--- a/built_value_generator/lib/src/serializer_source_field.dart
+++ /dev/null
@@ -1,266 +0,0 @@
-// Copyright (c) 2015, Google Inc. 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 built_value_generator.source_field;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/dart_types.dart';
-import 'package:built_value_generator/src/metadata.dart'
- show metadataToStringValue;
-
-part 'serializer_source_field.g.dart';
-
-abstract class SerializerSourceField
- implements Built<SerializerSourceField, SerializerSourceFieldBuilder> {
- static final BuiltMap<String, String> typesWithBuilder =
- BuiltMap<String, String>({
- 'BuiltList': 'ListBuilder',
- 'BuiltListMultimap': 'ListMultimapBuilder',
- 'BuiltMap': 'MapBuilder',
- 'BuiltSet': 'SetBuilder',
- 'BuiltSetMultimap': 'SetMultimapBuilder',
- });
- BuiltValue get settings;
- ParsedLibraryResult get parsedLibrary;
- FieldElement get element;
- @nullable
- FieldElement get builderElement;
-
- factory SerializerSourceField(
- BuiltValue settings,
- ParsedLibraryResult parsedLibrary,
- FieldElement element,
- FieldElement builderElement) =>
- _$SerializerSourceField._(
- settings: settings,
- parsedLibrary: parsedLibrary,
- element: element,
- builderElement: builderElement);
- SerializerSourceField._();
-
- @memoized
- bool get isSerializable =>
- element.getter != null &&
- element.getter.isAbstract &&
- !element.isStatic &&
- (builtValueField.serialize ?? settings.defaultSerialize);
-
- @memoized
- BuiltValueField get builtValueField {
- var annotations = element.getter.metadata
- .map((annotation) => annotation.computeConstantValue())
- .where((value) => DartTypes.getName(value?.type) == 'BuiltValueField');
- if (annotations.isEmpty) return const BuiltValueField();
- var annotation = annotations.single;
- return BuiltValueField(
- compare: annotation.getField('compare').toBoolValue(),
- serialize: annotation.getField('serialize').toBoolValue(),
- wireName: annotation.getField('wireName').toStringValue());
- }
-
- @memoized
- bool get isNullable => element.getter.metadata
- .any((metadata) => metadataToStringValue(metadata) == 'nullable');
-
- @memoized
- String get name => element.displayName;
-
- @memoized
- String get wireName => builtValueField.wireName ?? name;
-
- @memoized
- String get type => DartTypes.getName(element.getter.returnType);
-
- /// The [type] plus any import prefix.
- @memoized
- String get typeWithPrefix {
- var declaration = parsedLibrary.getElementDeclaration(element.getter);
- var typeFromAst =
- (declaration.node as MethodDeclaration)?.returnType?.toString() ??
- 'dynamic';
- var typeFromElement = type;
-
- // If the type is a function, we can't use the element result; it is
- // formatted incorrectly.
- if (typeFromElement.contains('(')) return typeFromAst;
-
- // If the type does not have an import prefix, prefer the element result.
- // It handles inherited generics correctly.
- if (!typeFromAst.contains('.')) return typeFromElement;
-
- return typeFromAst;
- }
-
- /// Returns the type with import prefix if the compilation unit matches,
- /// otherwise the type with no import prefix.
- String typeInCompilationUnit(CompilationUnitElement compilationUnitElement) {
- return compilationUnitElement == element.library.definingCompilationUnit
- ? typeWithPrefix
- : type;
- }
-
- @memoized
- bool get builderFieldUsesNestedBuilder {
- var builderFieldElementIsValid =
- (builderElement?.getter?.isAbstract == false) &&
- !builderElement.isStatic;
-
- // If the builder is present, check it to determine whether a nested
- // builder is needed. Otherwise, use the same logic as built_value when
- // it decides whether to use a nested builder.
- return builderFieldElementIsValid
- ? DartTypes.getName(element.getter.returnType) !=
- DartTypes.getName(builderElement.getter.returnType)
- : settings.nestedBuilders &&
- DartTypes.needsNestedBuilder(element.getter.returnType);
- }
-
- @memoized
- String get rawType => _getBareType(type);
-
- String generateFullType(CompilationUnitElement compilationUnit,
- [BuiltSet<String> classGenericParameters]) {
- return _generateFullType(typeInCompilationUnit(compilationUnit),
- classGenericParameters ?? BuiltSet<String>());
- }
-
- @memoized
- bool get needsBuilder =>
- DartTypes.getName(element.getter.returnType).contains('<') &&
- DartTypes.isBuilt(element.getter.returnType);
-
- Iterable<String> computeErrors() {
- if (isSerializable && element.getter.returnType is FunctionType) {
- return [
- 'Function fields are not serializable. '
- 'Remove "$name" or mark it "@BuiltValueField(serialize: false)".'
- ];
- }
-
- return [];
- }
-
- /// Generates a cast using 'as' to this field type.
- ///
- /// Generics are cast to the bound of the generic. If there is no bound,
- /// no cast is needed, and an empty string is returned.
- String generateCast(CompilationUnitElement compilationUnit,
- BuiltMap<String, String> classGenericBounds) {
- var result = _generateCast(
- typeInCompilationUnit(compilationUnit), classGenericBounds);
- return result == 'Object' ? '' : 'as $result';
- }
-
- String generateBuilder() {
- var bareType = _getBareType(type);
- if (typesWithBuilder.containsKey(bareType)) {
- return 'new ${typesWithBuilder[bareType]}<${_getGenerics(type)}>()';
- } else {
- return 'new ${bareType}Builder<${_getGenerics(type)}>()';
- }
- }
-
- static String _generateFullType(
- String type, BuiltSet<String> classGenericParameters) {
- var bareType = _getBareType(type);
- var generics = _getGenerics(type);
- var genericItems = _splitOnTopLevelCommas(generics);
-
- if (generics.isEmpty) {
- if (classGenericParameters.contains(bareType)) {
- return 'parameter$bareType';
- }
- return 'const FullType($bareType)';
- } else {
- final parameterFullTypes = genericItems
- .map((item) => _generateFullType(item, classGenericParameters))
- .join(', ');
- final canUseConst = parameterFullTypes.startsWith('const ');
- final constOrNew = canUseConst ? 'const' : 'new';
- final constOrEmpty = canUseConst ? 'const' : '';
- return '$constOrNew FullType($bareType, $constOrEmpty [$parameterFullTypes])';
- }
- }
-
- static String _generateCast(
- String type, BuiltMap<String, String> classGenericBounds,
- {bool topLevel = true}) {
- var bareType = _getBareType(type);
-
- // For built collections we can cast to the dynamic type when deserializing,
- // instead of the actual generic type. This is because the `replace` method
- // checks the generic type and copies if needed.
- String generics;
- if (topLevel && DartTypes.isBuiltCollectionTypeName(bareType)) {
- if (bareType == 'BuiltList' || bareType == 'BuiltSet') {
- generics = 'dynamic';
- } else if (bareType == 'BuiltMap' ||
- bareType == 'BuiltListMultimap' ||
- bareType == 'BuiltSetMultimap') {
- generics = 'dynamic, dynamic';
- } else {
- throw UnsupportedError('Bare type is a built_collection type, but not '
- 'one of the known built_collection types: $bareType.');
- }
- } else {
- generics = _getGenerics(type);
- }
- var genericItems = _splitOnTopLevelCommas(generics);
-
- if (generics.isEmpty) {
- if (classGenericBounds.keys.contains(bareType)) {
- return classGenericBounds[bareType];
- }
- return bareType;
- } else {
- final parameterFullTypes = genericItems
- .map((item) =>
- _generateCast(item, classGenericBounds, topLevel: false))
- .join(', ');
- return '$bareType<$parameterFullTypes>';
- }
- }
-
- static String _getBareType(String name) {
- var genericsStart = name.indexOf('<');
- return genericsStart == -1 ? name : name.substring(0, genericsStart);
- }
-
- static String _getGenerics(String name) {
- var genericsStart = name.indexOf('<');
- return genericsStart == -1
- ? ''
- : name
- .substring(genericsStart + 1)
- .substring(0, name.length - genericsStart - 2);
- }
-
- /// Splits a generic parameter string on top level commas; that means
- /// commas nested inside '<' and '>' are ignored.
- static BuiltList<String> _splitOnTopLevelCommas(String string) {
- var result = ListBuilder<String>();
- var accumulator = StringBuffer();
- var depth = 0;
- for (var i = 0; i != string.length; ++i) {
- if (string[i] == '<') ++depth;
- if (string[i] == '>') --depth;
-
- if (string[i] == ',' && depth == 0) {
- result.add(accumulator.toString().trim());
- accumulator.clear();
- } else {
- accumulator.write(string[i]);
- }
- }
- if (accumulator.isNotEmpty) {
- result.add(accumulator.toString().trim());
- }
- return result.build();
- }
-}
diff --git a/built_value_generator/lib/src/serializer_source_field.g.dart b/built_value_generator/lib/src/serializer_source_field.g.dart
deleted file mode 100644
index 9e11783..0000000
--- a/built_value_generator/lib/src/serializer_source_field.g.dart
+++ /dev/null
@@ -1,179 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.source_field;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$SerializerSourceField extends SerializerSourceField {
- @override
- final BuiltValue settings;
- @override
- final ParsedLibraryResult parsedLibrary;
- @override
- final FieldElement element;
- @override
- final FieldElement builderElement;
- bool __isSerializable;
- BuiltValueField __builtValueField;
- bool __isNullable;
- String __name;
- String __wireName;
- String __type;
- String __typeWithPrefix;
- bool __builderFieldUsesNestedBuilder;
- String __rawType;
- bool __needsBuilder;
-
- factory _$SerializerSourceField(
- [void Function(SerializerSourceFieldBuilder) updates]) =>
- (new SerializerSourceFieldBuilder()..update(updates)).build();
-
- _$SerializerSourceField._(
- {this.settings, this.parsedLibrary, this.element, this.builderElement})
- : super._() {
- if (settings == null) {
- throw new BuiltValueNullFieldError('SerializerSourceField', 'settings');
- }
- if (parsedLibrary == null) {
- throw new BuiltValueNullFieldError(
- 'SerializerSourceField', 'parsedLibrary');
- }
- if (element == null) {
- throw new BuiltValueNullFieldError('SerializerSourceField', 'element');
- }
- }
-
- @override
- bool get isSerializable => __isSerializable ??= super.isSerializable;
-
- @override
- BuiltValueField get builtValueField =>
- __builtValueField ??= super.builtValueField;
-
- @override
- bool get isNullable => __isNullable ??= super.isNullable;
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get wireName => __wireName ??= super.wireName;
-
- @override
- String get type => __type ??= super.type;
-
- @override
- String get typeWithPrefix => __typeWithPrefix ??= super.typeWithPrefix;
-
- @override
- bool get builderFieldUsesNestedBuilder =>
- __builderFieldUsesNestedBuilder ??= super.builderFieldUsesNestedBuilder;
-
- @override
- String get rawType => __rawType ??= super.rawType;
-
- @override
- bool get needsBuilder => __needsBuilder ??= super.needsBuilder;
-
- @override
- SerializerSourceField rebuild(
- void Function(SerializerSourceFieldBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- SerializerSourceFieldBuilder toBuilder() =>
- new SerializerSourceFieldBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is SerializerSourceField &&
- settings == other.settings &&
- parsedLibrary == other.parsedLibrary &&
- element == other.element &&
- builderElement == other.builderElement;
- }
-
- @override
- int get hashCode {
- return $jf($jc(
- $jc($jc($jc(0, settings.hashCode), parsedLibrary.hashCode),
- element.hashCode),
- builderElement.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('SerializerSourceField')
- ..add('settings', settings)
- ..add('parsedLibrary', parsedLibrary)
- ..add('element', element)
- ..add('builderElement', builderElement))
- .toString();
- }
-}
-
-class SerializerSourceFieldBuilder
- implements Builder<SerializerSourceField, SerializerSourceFieldBuilder> {
- _$SerializerSourceField _$v;
-
- BuiltValue _settings;
- BuiltValue get settings => _$this._settings;
- set settings(BuiltValue settings) => _$this._settings = settings;
-
- ParsedLibraryResult _parsedLibrary;
- ParsedLibraryResult get parsedLibrary => _$this._parsedLibrary;
- set parsedLibrary(ParsedLibraryResult parsedLibrary) =>
- _$this._parsedLibrary = parsedLibrary;
-
- FieldElement _element;
- FieldElement get element => _$this._element;
- set element(FieldElement element) => _$this._element = element;
-
- FieldElement _builderElement;
- FieldElement get builderElement => _$this._builderElement;
- set builderElement(FieldElement builderElement) =>
- _$this._builderElement = builderElement;
-
- SerializerSourceFieldBuilder();
-
- SerializerSourceFieldBuilder get _$this {
- if (_$v != null) {
- _settings = _$v.settings;
- _parsedLibrary = _$v.parsedLibrary;
- _element = _$v.element;
- _builderElement = _$v.builderElement;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(SerializerSourceField other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$SerializerSourceField;
- }
-
- @override
- void update(void Function(SerializerSourceFieldBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$SerializerSourceField build() {
- final _$result = _$v ??
- new _$SerializerSourceField._(
- settings: settings,
- parsedLibrary: parsedLibrary,
- element: element,
- builderElement: builderElement);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/serializer_source_library.dart b/built_value_generator/lib/src/serializer_source_library.dart
deleted file mode 100644
index 2a33b45..0000000
--- a/built_value_generator/lib/src/serializer_source_library.dart
+++ /dev/null
@@ -1,181 +0,0 @@
-// Copyright (c) 2015, Google Inc. 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 built_value_generator.source_library;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/library_elements.dart';
-import 'package:built_value_generator/src/serializer_source_class.dart';
-import 'package:quiver/iterables.dart';
-import 'package:source_gen/source_gen.dart';
-
-import 'dart_types.dart';
-
-part 'serializer_source_library.g.dart';
-
-abstract class SerializerSourceLibrary
- implements Built<SerializerSourceLibrary, SerializerSourceLibraryBuilder> {
- LibraryElement get element;
-
- factory SerializerSourceLibrary(LibraryElement element) =>
- _$SerializerSourceLibrary._(element: element);
- SerializerSourceLibrary._();
-
- @memoized
- ParsedLibraryResult get parsedLibrary =>
- element.library.session.getParsedLibraryByElement(element.library);
-
- @memoized
- bool get hasSerializers => serializersForAnnotations.isNotEmpty;
-
- /// Returns a map of `Serializers` declarations; the keys are field names
- /// and the values are the `@SerializersFor` annotations.
- @memoized
- BuiltMap<String, ElementAnnotation> get serializersForAnnotations {
- var result = MapBuilder<String, ElementAnnotation>();
- var accessors = element.definingCompilationUnit.accessors
- .where((element) =>
- element.isGetter &&
- DartTypes.getName(element.returnType) == 'Serializers')
- .toList();
-
- for (var accessor in accessors) {
- final annotations = accessor.variable.metadata
- .where((annotation) =>
- DartTypes.getName(annotation.computeConstantValue()?.type) ==
- 'SerializersFor')
- .toList();
- if (annotations.isEmpty) continue;
-
- result[accessor.name] = annotations.single;
- }
-
- return result.build();
- }
-
- /// Returns the set of serializable classes in this library. A serializer
- /// needs to be installed for each of these. A serialized needs to be
- /// generated for each, except where the serializer is marked `custom`.
- @memoized
- BuiltSet<SerializerSourceClass> get sourceClasses {
- var result = SetBuilder<SerializerSourceClass>();
- var classElements = LibraryElements.getClassElements(element);
- for (var classElement in classElements) {
- final sourceClass = SerializerSourceClass(classElement);
- if (sourceClass.isSerializable) {
- result.add(sourceClass);
- }
- }
- return result.build();
- }
-
- /// Returns a map from `Serializers` declaration field names to the classes
- /// that each serializer is required to be able to serialize.
- @memoized
- BuiltSetMultimap<String, SerializerSourceClass> get serializeForClasses {
- var result = SetMultimapBuilder<String, SerializerSourceClass>();
-
- for (var field in serializersForAnnotations.keys) {
- final serializersForAnnotation = serializersForAnnotations[field];
-
- final types = serializersForAnnotation
- .computeConstantValue()
- .getField('types')
- .toListValue()
- ?.map((dartObject) => dartObject.toTypeValue());
-
- if (types == null) {
- // This only happens if the source code is invalid.
- throw InvalidGenerationSourceError(
- 'Broken @SerializersFor annotation. Are all the types imported?');
- }
-
- result.addValues(
- field,
- types.map(
- (type) => SerializerSourceClass(type.element as ClassElement)));
- }
- return result.build();
- }
-
- /// Returns a map from `Serializers` declaration field names to the
- /// transitive set of serializable classes implied by `serializeForClasses`.
- @memoized
- BuiltSetMultimap<String, SerializerSourceClass>
- get serializeForTransitiveClasses {
- var result = SetMultimapBuilder<String, SerializerSourceClass>();
-
- for (var field in serializersForAnnotations.keys) {
- var currentResult = BuiltSet<SerializerSourceClass>(
- serializeForClasses[field].where(
- (serializerSourceClass) => serializerSourceClass.isSerializable));
- BuiltSet<SerializerSourceClass> expandedResult;
-
- while (currentResult != expandedResult) {
- currentResult = expandedResult ?? currentResult;
- expandedResult = currentResult.rebuild((b) => b
- ..addAll(currentResult.expand((sourceClass) => sourceClass
- .fieldClasses
- .where((fieldClass) => fieldClass.isSerializable))));
- }
-
- result.addValues(field, currentResult);
- }
-
- return result.build();
- }
-
- bool get needsBuiltJson => sourceClasses.isNotEmpty;
-
- /// Generates serializer source for this library.
- String generateCode() {
- var errors = concat(sourceClasses
- .map((sourceClass) => sourceClass.computeErrors())
- .toList());
-
- if (errors.isNotEmpty) throw _makeError(errors);
-
- return _generateSerializersTopLevelFields() +
- sourceClasses
- .where((sourceClass) => sourceClass.needsGeneratedSerializer)
- .map((sourceClass) => sourceClass.generateSerializerDeclaration())
- .join('\n') +
- sourceClasses
- .where((sourceClass) => sourceClass.needsGeneratedSerializer)
- .map((sourceClass) => sourceClass.generateSerializer())
- .join('\n');
- }
-
- String _generateSerializersTopLevelFields() => serializersForAnnotations.keys
- .map((field) =>
- 'Serializers _\$$field = (new Serializers().toBuilder()' +
- (serializeForTransitiveClasses[field]
- .map((sourceClass) =>
- sourceClass.generateTransitiveSerializerAdder())
- .toList()
- ..sort())
- .join('\n') +
- (serializeForTransitiveClasses[field]
- .map((sourceClass) =>
- sourceClass.generateBuilderFactoryAdders(
- element.definingCompilationUnit))
- .toList()
- ..sort())
- .join('\n') +
- ').build();')
- .join('\n');
-}
-
-InvalidGenerationSourceError _makeError(Iterable<String> todos) {
- var message = StringBuffer(
- 'Please make the following changes to use built_value serialization:\n');
- for (var i = 0; i != todos.length; ++i) {
- message.write('\n${i + 1}. ${todos.elementAt(i)}');
- }
-
- return InvalidGenerationSourceError(message.toString());
-}
diff --git a/built_value_generator/lib/src/serializer_source_library.g.dart b/built_value_generator/lib/src/serializer_source_library.g.dart
deleted file mode 100644
index c16e911..0000000
--- a/built_value_generator/lib/src/serializer_source_library.g.dart
+++ /dev/null
@@ -1,122 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.source_library;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$SerializerSourceLibrary extends SerializerSourceLibrary {
- @override
- final LibraryElement element;
- ParsedLibraryResult __parsedLibrary;
- bool __hasSerializers;
- BuiltMap<String, ElementAnnotation> __serializersForAnnotations;
- BuiltSet<SerializerSourceClass> __sourceClasses;
- BuiltSetMultimap<String, SerializerSourceClass> __serializeForClasses;
- BuiltSetMultimap<String, SerializerSourceClass>
- __serializeForTransitiveClasses;
-
- factory _$SerializerSourceLibrary(
- [void Function(SerializerSourceLibraryBuilder) updates]) =>
- (new SerializerSourceLibraryBuilder()..update(updates)).build();
-
- _$SerializerSourceLibrary._({this.element}) : super._() {
- if (element == null) {
- throw new BuiltValueNullFieldError('SerializerSourceLibrary', 'element');
- }
- }
-
- @override
- ParsedLibraryResult get parsedLibrary =>
- __parsedLibrary ??= super.parsedLibrary;
-
- @override
- bool get hasSerializers => __hasSerializers ??= super.hasSerializers;
-
- @override
- BuiltMap<String, ElementAnnotation> get serializersForAnnotations =>
- __serializersForAnnotations ??= super.serializersForAnnotations;
-
- @override
- BuiltSet<SerializerSourceClass> get sourceClasses =>
- __sourceClasses ??= super.sourceClasses;
-
- @override
- BuiltSetMultimap<String, SerializerSourceClass> get serializeForClasses =>
- __serializeForClasses ??= super.serializeForClasses;
-
- @override
- BuiltSetMultimap<String, SerializerSourceClass>
- get serializeForTransitiveClasses => __serializeForTransitiveClasses ??=
- super.serializeForTransitiveClasses;
-
- @override
- SerializerSourceLibrary rebuild(
- void Function(SerializerSourceLibraryBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- SerializerSourceLibraryBuilder toBuilder() =>
- new SerializerSourceLibraryBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is SerializerSourceLibrary && element == other.element;
- }
-
- @override
- int get hashCode {
- return $jf($jc(0, element.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('SerializerSourceLibrary')
- ..add('element', element))
- .toString();
- }
-}
-
-class SerializerSourceLibraryBuilder
- implements
- Builder<SerializerSourceLibrary, SerializerSourceLibraryBuilder> {
- _$SerializerSourceLibrary _$v;
-
- LibraryElement _element;
- LibraryElement get element => _$this._element;
- set element(LibraryElement element) => _$this._element = element;
-
- SerializerSourceLibraryBuilder();
-
- SerializerSourceLibraryBuilder get _$this {
- if (_$v != null) {
- _element = _$v.element;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(SerializerSourceLibrary other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$SerializerSourceLibrary;
- }
-
- @override
- void update(void Function(SerializerSourceLibraryBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$SerializerSourceLibrary build() {
- final _$result = _$v ?? new _$SerializerSourceLibrary._(element: element);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/strings.dart b/built_value_generator/lib/src/strings.dart
deleted file mode 100644
index 5b444d1..0000000
--- a/built_value_generator/lib/src/strings.dart
+++ /dev/null
@@ -1,2 +0,0 @@
-/// Escapes dollar signs in a string with backslashes.
-String escapeString(String string) => string.replaceAll(r'$', r'\$');
diff --git a/built_value_generator/lib/src/value_source_class.dart b/built_value_generator/lib/src/value_source_class.dart
deleted file mode 100644
index 4f51186..0000000
--- a/built_value_generator/lib/src/value_source_class.dart
+++ /dev/null
@@ -1,1082 +0,0 @@
-// Copyright (c) 2016, Google Inc. 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 built_value_generator.source_class;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/fixes.dart';
-import 'package:built_value_generator/src/memoized_getter.dart';
-import 'package:built_value_generator/src/value_source_field.dart';
-import 'package:quiver/iterables.dart';
-import 'package:source_gen/source_gen.dart';
-
-import 'dart_types.dart';
-
-part 'value_source_class.g.dart';
-
-const String _importWithSingleQuotes =
- "import 'package:built_value/built_value.dart'";
-const String _importWithDoubleQuotes =
- 'import "package:built_value/built_value.dart"';
-
-abstract class ValueSourceClass
- implements Built<ValueSourceClass, ValueSourceClassBuilder> {
- ClassElement get element;
-
- factory ValueSourceClass(ClassElement element) =>
- _$ValueSourceClass._(element: element);
- ValueSourceClass._();
-
- @memoized
- ParsedLibraryResult get parsedLibrary =>
- element.library.session.getParsedLibraryByElement(element.library);
-
- @memoized
- String get name => element.displayName;
-
- /// Returns the class name for the generated implementation. If the manually
- /// maintained class is private then we ignore the underscore here, to avoid
- /// returning a class name starting `_$_`.
- @memoized
- String get implName =>
- name.startsWith('_') ? '_\$${name.substring(1)}' : '_\$$name';
-
- @memoized
- ClassElement get builderElement {
- var result = element.library.getType(name + 'Builder');
- if (result == null) return null;
- // If the builder is in a generated file, then we're analyzing _after_ code
- // generation. Ignore it. This happens when running as an analyzer plugin.
- if (result.source.fullName.endsWith('.g.dart')) return null;
- return result;
- }
-
- @memoized
- bool get implementsBuilt => element.allSupertypes
- .any((interfaceType) => interfaceType.name == 'Built');
-
- @memoized
- bool get extendsIsAllowed {
- // Usually `extends` is not allowed. But, allow one special case:
- //
- // A `built_value` class may share code with a `const` class by extending
- // a `const` base class. There's no other way to do this sharing because
- // a `const` class is not allowed to use a mixin.
- //
- // To avoid causing problems for `built_value` the base class must be
- // abstract, must have no fields, must have no abstract getters, and
- // must not implement `operator==`, `hashCode` or `toString`.
- // This means it _is_ allowed to have concrete getters as well as
- // concrete and abstract methods.
-
- for (var supertype in [element.supertype]
- ..addAll(element.supertype.element.allSupertypes)) {
- if (DartTypes.getName(supertype) == 'Object') continue;
-
- // Base class must be abstract.
- if (!supertype.element.isAbstract) return false;
-
- // Base class must have no fields.
- if (supertype.element.fields
- .any((field) => !field.isStatic && !field.isSynthetic)) {
- return false;
- }
-
- // Base class must have no abstract getters.
- if (supertype.accessors.any((accessor) =>
- !accessor.isStatic && accessor.isGetter && accessor.isAbstract)) {
- return false;
- }
-
- // Base class must not implement operator==, hashCode or toString.
- if (supertype.element.getMethod('hashCode') != null) return false;
- if (supertype.element.getMethod('==') != null) return false;
- if (supertype.element.getMethod('toString') != null) return false;
- }
-
- return true;
- }
-
- @memoized
- BuiltValue get settings {
- var annotations = element.metadata
- .map((annotation) => annotation.computeConstantValue())
- .where((value) => DartTypes.getName(value?.type) == 'BuiltValue');
- if (annotations.isEmpty) return const BuiltValue();
- var annotation = annotations.single;
- // If a field does not exist, that means an old `built_value` version; use
- // the default.
- return BuiltValue(
- comparableBuilders:
- annotation.getField('comparableBuilders')?.toBoolValue() ?? false,
- instantiable:
- annotation.getField('instantiable')?.toBoolValue() ?? true,
- nestedBuilders:
- annotation.getField('nestedBuilders')?.toBoolValue() ?? true,
- autoCreateNestedBuilders:
- annotation.getField('autoCreateNestedBuilders')?.toBoolValue() ??
- true,
- generateBuilderOnSetField:
- annotation.getField('generateBuilderOnSetField')?.toBoolValue() ??
- false,
- defaultCompare:
- annotation.getField('defaultCompare')?.toBoolValue() ?? true,
- defaultSerialize:
- annotation.getField('defaultSerialize')?.toBoolValue() ?? true,
- wireName: annotation.getField('wireName')?.toStringValue());
- }
-
- @memoized
- BuiltList<String> get genericParameters =>
- BuiltList<String>(element.typeParameters.map((e) => e.name));
-
- @memoized
- BuiltList<String> get genericBounds =>
- BuiltList<String>(element.typeParameters.map((element) {
- var bound = element.bound;
- if (bound == null) return '';
- return DartTypes.getName(bound);
- }));
-
- @memoized
- ClassDeclaration get classDeclaration {
- return parsedLibrary.getElementDeclaration(element).node
- as ClassDeclaration;
- }
-
- @memoized
- bool get hasBuilder => builderElement != null;
-
- @memoized
- bool get hasBuilderInitializer => builderInitializer != null;
-
- @memoized
- MethodElement get builderInitializer =>
- element.getMethod('_initializeBuilder');
-
- @memoized
- bool get hasBuilderFinalizer => builderFinalizer != null;
-
- @memoized
- MethodElement get builderFinalizer => element.getMethod('_finalizeBuilder');
-
- @memoized
- String get builderParameters {
- return builderElement.allSupertypes
- .where((interfaceType) => interfaceType.name == 'Builder')
- .single
- .typeArguments
- .map((type) => DartTypes.getName(type))
- .join(', ');
- }
-
- @memoized
- BuiltList<ValueSourceField> get fields => ValueSourceField.fromClassElements(
- settings, parsedLibrary, element, builderElement);
-
- @memoized
- String get source =>
- element.library.definingCompilationUnit.source.contents.data;
-
- @memoized
- String get partStatement {
- var fileName = element.library.source.shortName.replaceAll('.dart', '');
- return "part '$fileName.g.dart';";
- }
-
- @memoized
- bool get hasPartStatement {
- var expectedCode = partStatement;
- return source.contains(expectedCode);
- }
-
- @memoized
- bool get hasBuiltValueImportWithShow {
- // It would be more accurate to check using the AST, but this is
- // potentially expensive. We already have the source for the "part of"
- // check, use that.
- return source.contains('$_importWithSingleQuotes show') ||
- source.contains('$_importWithDoubleQuotes show');
- }
-
- @memoized
- bool get hasBuiltValueImportWithAs {
- // It would be more accurate to check using the AST, but this is
- // potentially expensive. We already have the source for the "part of"
- // check, use that.
- return source.contains('$_importWithSingleQuotes as') ||
- source.contains('$_importWithDoubleQuotes as');
- }
-
- @memoized
- bool get valueClassIsAbstract => element.isAbstract;
-
- @memoized
- BuiltList<ConstructorDeclaration> get valueClassConstructors =>
- BuiltList<ConstructorDeclaration>(element.constructors
- .where((constructor) =>
- !constructor.isFactory && !constructor.isSynthetic)
- .map((constructor) =>
- parsedLibrary.getElementDeclaration(constructor).node));
-
- @memoized
- BuiltList<ConstructorDeclaration> get valueClassFactories =>
- BuiltList<ConstructorDeclaration>(element.constructors
- .where((constructor) => constructor.isFactory)
- .map((factory) => parsedLibrary.getElementDeclaration(factory).node));
-
- @memoized
- bool get builderClassIsAbstract => builderElement.isAbstract;
-
- @memoized
- BuiltList<String> get builderClassConstructors =>
- BuiltList<String>(builderElement.constructors
- .where((constructor) =>
- !constructor.isFactory && !constructor.isSynthetic)
- .map((constructor) => parsedLibrary
- .getElementDeclaration(constructor)
- .node
- .toSource()));
-
- @memoized
- BuiltList<String> get builderClassFactories =>
- BuiltList<String>(builderElement.constructors
- .where((constructor) => constructor.isFactory)
- .map((factory) =>
- parsedLibrary.getElementDeclaration(factory).node.toSource()));
-
- @memoized
- BuiltList<MemoizedGetter> get memoizedGetters =>
- BuiltList<MemoizedGetter>(MemoizedGetter.fromClassElement(element));
-
- /// Returns the `implements` clause for the builder.
- ///
- /// All builders implement `Builder`.
- ///
- /// Additionally, if the value class implements other value classes, the
- /// builder implements the corresponding builders.
- @memoized
- BuiltList<String> get builderImplements => BuiltList<String>.build((b) => b
- ..add('Builder<$name$_generics, ${name}Builder$_generics>')
- ..addAll(element.interfaces
- .where((interface) => needsBuiltValue(interface.element))
- .map((interface) {
- final displayName = DartTypes.getName(interface);
- if (!displayName.contains('<')) return displayName + 'Builder';
- final index = displayName.indexOf('<');
- return displayName.substring(0, index) +
- 'Builder' +
- displayName.substring(index);
- })));
-
- @memoized
- bool get implementsHashCode => element.getGetter('hashCode') != null;
-
- @memoized
- bool get implementsOperatorEquals => element.getMethod('==') != null;
-
- @memoized
- bool get implementsToString {
- // Check for any `toString` implementation apart from the one defined on
- // `Object`.
- var method = element.lookUpConcreteMethod('toString', element.library);
- var clazz = method.enclosingElement;
- return clazz is! ClassElement || clazz.name != 'Object';
- }
-
- @memoized
- CompilationUnitElement get compilationUnit =>
- element.library.definingCompilationUnit;
-
- static bool needsBuiltValue(ClassElement classElement) {
- // TODO(davidmorgan): more exact type check.
- return !classElement.displayName.startsWith('_\$') &&
- (classElement.allSupertypes
- .any((interfaceType) => interfaceType.name == 'Built') ||
- classElement.metadata
- .map((annotation) => annotation.computeConstantValue())
- .any(
- (value) => DartTypes.getName(value?.type) == 'BuiltValue'));
- }
-
- Iterable<GeneratorError> computeErrors() {
- return concat([
- _checkPart(),
- _checkSettings(),
- _checkValueClass(),
- _checkBuilderClass(),
- _checkFieldList(),
- concat(fields.map((field) => field.computeErrors()))
- ]);
- }
-
- Iterable<GeneratorError> _checkPart() {
- if (hasPartStatement) return [];
-
- var directives = (classDeclaration.parent as CompilationUnit).directives;
- if (directives.isEmpty) {
- return [
- GeneratorError((b) => b
- ..message = 'Import generated part: $partStatement'
- ..offset = 0
- ..length = 0
- ..fix = '$partStatement\n\n')
- ];
- } else {
- return [
- GeneratorError((b) => b
- ..message = 'Import generated part: $partStatement'
- ..offset = directives.last.offset + directives.last.length
- ..length = 0
- ..fix = '\n\n$partStatement\n\n')
- ];
- }
- }
-
- Iterable<GeneratorError> _checkSettings() {
- // Not allowed to have comparable builders with nested builders; this
- // would break comparing because the nested builders may not be comparable.
- // (Collection builders, in particularly, are definitely not comparable).
- if (settings.comparableBuilders && settings.nestedBuilders) {
- return [
- GeneratorError((b) => b
- ..message = 'Set `nestedBuilders: false`'
- ' in order to use `comparableBuilders: true`.')
- ];
- } else {
- return [];
- }
- }
-
- Iterable<GeneratorError> _checkValueClass() {
- var result = <GeneratorError>[];
-
- if (!valueClassIsAbstract) {
- result.add(GeneratorError((b) => b
- ..message = 'Make class abstract.'
- ..offset = classDeclaration.offset
- ..length = 0
- ..fix = 'abstract '));
- }
-
- if (hasBuiltValueImportWithShow) {
- result.add(GeneratorError((b) => b
- ..message = 'Stop using "show" when importing '
- '"package:built_value/built_value.dart". It prevents the '
- 'generated code from finding helper methods.'));
- }
-
- if (hasBuiltValueImportWithAs) {
- result.add(GeneratorError((b) => b
- ..message = 'Stop using "as" when importing '
- '"package:built_value/built_value.dart". It prevents the generated '
- 'code from finding helper methods.'));
- }
-
- var implementsClause = classDeclaration.implementsClause;
- var expectedInterface = 'Built<$name$_generics, ${name}Builder$_generics>';
-
- var implementsClauseIsCorrect = implementsClause != null &&
- implementsClause.interfaces
- .any((type) => type.toSource() == expectedInterface);
-
- // Built parameters need fixing if they are not as expected, unless 1) the
- // class is marked `@BuiltValue(instantiable: false)` and 2) there is no
- // case of the `Built` interface being implemented. This is to allow
- // omitting the `Built` interface to work around having to implement the
- // same interface twice with different type parameters.
- var implementsClauseIsAllowedToBeIncorrect = !settings.instantiable &&
- (implementsClause == null ||
- !implementsClause.interfaces.any((type) =>
- type.toSource() == 'Built' ||
- type.toSource().startsWith('Built<')));
-
- if (!implementsClauseIsCorrect && !implementsClauseIsAllowedToBeIncorrect) {
- if (implementsClause == null) {
- result.add(GeneratorError((b) => b
- ..message = 'Make class implement $expectedInterface.'
- ..offset = classDeclaration.leftBracket.offset - 1
- ..length = 0
- ..fix = 'implements $expectedInterface'));
- } else {
- var found = false;
- final interfaces = implementsClause.interfaces.map((type) {
- if (type.name.name == 'Built') {
- found = true;
- return expectedInterface;
- } else {
- return type.toSource();
- }
- }).toList();
- if (!found) interfaces.add(expectedInterface);
-
- result.add(GeneratorError((b) => b
- ..message = 'Make class implement $expectedInterface.'
- ..offset = implementsClause.offset
- ..length = implementsClause.length
- ..fix = 'implements ${interfaces.join(", ")}'));
- }
- }
-
- if (!extendsIsAllowed) {
- result.add(GeneratorError((b) => b
- ..message = 'Stop class extending other classes. '
- 'Only "implements" and "extends Object with" are allowed.'));
- }
-
- if (settings.instantiable) {
- if (hasBuilderInitializer) {
- if (!builderInitializer.isStatic ||
- !builderInitializer.returnType.isVoid ||
- builderInitializer.parameters.length != 1 ||
- parsedLibrary
- .getElementDeclaration(builderInitializer.parameters[0])
- .node is! SimpleFormalParameter ||
- DartTypes.stripGenerics((parsedLibrary
- .getElementDeclaration(builderInitializer.parameters[0])
- .node as SimpleFormalParameter)
- .type
- ?.toSource()) !=
- '${name}Builder') {
- result.add(GeneratorError((b) => b
- ..message = 'Fix _initializeBuilder signature: '
- 'static void _initializeBuilder(${name}Builder b)'));
- }
- }
- if (hasBuilderFinalizer) {
- if (!builderFinalizer.isStatic ||
- !builderFinalizer.returnType.isVoid ||
- builderFinalizer.parameters.length != 1 ||
- parsedLibrary
- .getElementDeclaration(builderFinalizer.parameters[0])
- .node is! SimpleFormalParameter ||
- DartTypes.stripGenerics((parsedLibrary
- .getElementDeclaration(builderFinalizer.parameters[0])
- .node as SimpleFormalParameter)
- .type
- ?.toSource()) !=
- '${name}Builder') {
- result.add(GeneratorError((b) => b
- ..message = 'Fix _finalizeBuilder signature: '
- 'static void _finalizeBuilder(${name}Builder b)'));
- }
- }
-
- final expectedConstructor = '$name._()';
- if (valueClassConstructors.isEmpty) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make class have exactly one constructor: $expectedConstructor;'
- ..offset = classDeclaration.rightBracket.offset
- ..length = 0
- ..fix = ' $expectedConstructor;\n'));
- } else if (valueClassConstructors.length > 1) {
- var found = false;
- for (var constructor in valueClassConstructors) {
- if (constructor.toSource().startsWith(expectedConstructor)) {
- found = true;
- } else {
- result.add(GeneratorError((b) => b
- ..message = 'Remove invalid constructor.'
- ..offset = constructor.offset
- ..length = constructor.length
- ..fix = ''));
- }
- }
- if (!found) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make class have exactly one constructor: $expectedConstructor;'
- ..offset = classDeclaration.rightBracket.offset
- ..length = 0
- ..fix = ' $expectedConstructor;\n'));
- }
- } else if (!(valueClassConstructors.single
- .toSource()
- .startsWith(expectedConstructor))) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make class have exactly one constructor: $expectedConstructor;'
- ..offset = valueClassConstructors.single.offset
- ..length = valueClassConstructors.single.length
- ..fix = expectedConstructor + ';'));
- }
- } else {
- if (valueClassConstructors.isNotEmpty) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Remove all constructors or remove "instantiable: false".'));
- }
- }
-
- if (settings.instantiable) {
- if (!valueClassFactories.any(
- (factory) => factory.toSource().contains('$implName$_generics'))) {
- final exampleFactory =
- 'factory $name([void Function(${name}Builder$_generics) updates]) = '
- '$implName$_generics;';
- result.add(GeneratorError((b) => b
- ..message =
- 'Add a factory so your class can be instantiated. Example:\n\n'
- '$exampleFactory'
- ..offset = classDeclaration.rightBracket.offset
- ..length = 0
- ..fix = ' $exampleFactory\n'));
- }
- } else {
- if (valueClassFactories.isNotEmpty) {
- result.add(GeneratorError((b) => b
- ..message = 'Remove all factories or remove "instantiable: false".'));
- }
- }
-
- if (implementsHashCode) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Stop implementing hashCode; it will be generated for you.'));
- }
-
- if (implementsOperatorEquals) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Stop implementing operator==; it will be generated for you.'));
- }
-
- return result;
- }
-
- Iterable<GeneratorError> _checkBuilderClass() {
- var result = <GeneratorError>[];
- if (!hasBuilder) return result;
-
- if (!builderClassIsAbstract) {
- result.add(
- GeneratorError((b) => b..message = 'Make builder class abstract.'));
- }
-
- if (settings.instantiable) {
- final expectedBuilderParameters =
- '$name$_generics, ${name}Builder$_generics';
- if (builderParameters != expectedBuilderParameters) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make builder class implement Builder<$expectedBuilderParameters>. '
- 'Currently: Builder<$builderParameters>'));
- }
- }
-
- if (settings.instantiable) {
- final expectedConstructor = '${name}Builder._()';
- if (builderClassConstructors.length != 1 ||
- !(builderClassConstructors.single.startsWith(expectedConstructor))) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make builder class have exactly one constructor: $expectedConstructor;'));
- }
- } else {
- if (builderClassConstructors.isNotEmpty) {
- result.add(GeneratorError((b) => b
- ..message = 'Remove all builder constructors '
- 'or remove "instantiable: false".'));
- }
- }
-
- if (settings.instantiable) {
- final expectedFactory =
- 'factory ${name}Builder() = _\$${name}Builder$_generics;';
- if (builderClassFactories.length != 1 ||
- builderClassFactories.single != expectedFactory) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make builder class have exactly one factory: $expectedFactory'));
- }
- } else {
- if (builderClassFactories.isNotEmpty) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Remove all builder factories or remove "instantiable: false".'));
- }
- }
-
- return result;
- }
-
- Iterable<GeneratorError> _checkFieldList() {
- if (!hasBuilder || !settings.instantiable) return <GeneratorError>[];
- return fields.any((field) => !field.builderFieldExists)
- ? [
- GeneratorError((b) => b
- ..message = 'Make builder have exactly these fields: ' +
- fields.map((field) => field.name).join(', '))
- ]
- : [];
- }
-
- String get _generics =>
- genericParameters.isEmpty ? '' : '<' + genericParameters.join(', ') + '>';
-
- String get _boundedGenerics => genericParameters.isEmpty
- ? ''
- : '<' +
- zip(<Iterable>[genericParameters, genericBounds]).map((zipped) {
- final parameter = zipped[0] as String;
- final bound = zipped[1] as String;
- return bound.isEmpty ? parameter : '$parameter extends $bound';
- }).join(', ') +
- '>';
-
- String generateCode() {
- var errors = computeErrors();
- if (errors.isNotEmpty) throw _makeError(errors);
-
- var result = StringBuffer();
- if (settings.instantiable) result.write(_generateImpl());
- if (settings.instantiable) {
- result.write(_generateBuilder());
- } else if (!hasBuilder) {
- result.write(_generateAbstractBuilder());
- }
- return result.toString();
- }
-
- /// Generates the value class implementation.
- String _generateImpl() {
- var result = StringBuffer();
- result.writeln('class $implName$_boundedGenerics '
- 'extends $name$_generics {');
- for (var field in fields) {
- final type = field.typeInCompilationUnit(compilationUnit);
- result.writeln('@override');
- result.writeln('final $type ${field.name};');
- }
- for (var memoizedGetter in memoizedGetters) {
- result.writeln('${memoizedGetter.returnType} __${memoizedGetter.name};');
- }
- result.writeln();
-
- // If there is a manually maintained builder we have to cast the "build()"
- // result to the generated value class. If the builder is generated, that
- // can return the right type directly and needs no cast.
- var cast = hasBuilder ? 'as _\$$name$_generics' : '';
- result.writeln('factory $implName(['
- 'void Function(${name}Builder$_generics) updates]) '
- '=> (new ${name}Builder$_generics()..update(updates)).build() $cast;');
- result.writeln();
-
- if (fields.isEmpty) {
- result.write('$implName._() : super._()');
- } else {
- result.write('$implName._({');
- result.write(fields.map((field) => 'this.${field.name}').join(', '));
- result.write('}) : super._()');
- }
- var requiredFields = fields.where((field) => !field.isNullable);
- if (requiredFields.isEmpty && genericParameters.isEmpty) {
- result.writeln(';');
- } else {
- result.writeln('{');
- for (var field in requiredFields) {
- result.writeln('if (${field.name} == null) {');
- result.writeln(
- "throw new BuiltValueNullFieldError('$name', '${field.name}');");
- result.writeln('}');
- }
- // If there are generic parameters, check they are not "dynamic".
- if (genericParameters.isNotEmpty) {
- for (var genericParameter in genericParameters) {
- result.writeln('if ($genericParameter == dynamic) {');
- result.writeln('throw new BuiltValueMissingGenericsError('
- "'$name', '$genericParameter');");
- result.writeln('}');
- }
- }
- result.writeln();
- result.writeln('}');
- }
- result.writeln();
-
- for (var memoizedGetter in memoizedGetters) {
- result.writeln('@override');
- result.writeln(
- '${memoizedGetter.returnType} get ${memoizedGetter.name} =>');
- result.writeln(
- '__${memoizedGetter.name} ??= super.${memoizedGetter.name};');
- result.writeln();
- }
-
- result.writeln('@override');
- result.writeln(
- '$name$_generics rebuild(void Function(${name}Builder$_generics) updates) '
- '=> (toBuilder()..update(updates)).build();');
- result.writeln();
-
- result.writeln('@override');
- if (hasBuilder) {
- result.writeln('${implName}Builder$_generics toBuilder() '
- '=> new ${implName}Builder$_generics()..replace(this);');
- } else {
- result.writeln('${name}Builder$_generics toBuilder() '
- '=> new ${name}Builder$_generics()..replace(this);');
- }
- result.writeln();
-
- result.write(_generateEqualsAndHashcode());
-
- // Only generate toString() if there wasn't one already.
- if (!implementsToString) {
- result.writeln('@override');
- result.writeln('String toString() {');
- if (fields.isEmpty) {
- result
- .writeln("return newBuiltValueToStringHelper('$name').toString();");
- } else {
- result.writeln("return (newBuiltValueToStringHelper('$name')");
- result.writeln(fields
- .map((field) => "..add('${field.name}', ${field.name})")
- .join(''));
- result.writeln(").toString();");
- }
- result.writeln('}');
- result.writeln();
- }
-
- result.writeln('}');
- return result.toString();
- }
-
- /// Generates the builder implementation.
- String _generateBuilder() {
- var result = StringBuffer();
- if (hasBuilder) {
- result.writeln('class ${implName}Builder$_boundedGenerics '
- 'extends ${name}Builder$_generics {');
- } else {
- result.writeln('class ${name}Builder$_boundedGenerics '
- 'implements ${builderImplements.join(", ")} {');
- }
-
- // Builder holds a reference to a value, copies from it lazily.
- result.writeln('$implName$_generics _\$v;');
- result.writeln('');
-
- if (hasBuilder) {
- for (var field in fields) {
- final type = field.typeInCompilationUnit(compilationUnit);
- final typeInBuilder = field.builderElementTypeWithPrefix;
- final name = field.name;
-
- if (field.isNestedBuilder) {
- result.writeln('@override');
- result.writeln('$typeInBuilder get $name {'
- '_\$this;');
- if (settings.autoCreateNestedBuilders) {
- result.writeln('return super.$name ??= new $typeInBuilder();');
- } else {
- result.writeln('return super.$name;');
- }
- result.writeln('}');
- result.writeln('@override');
- result.writeln('set $name($typeInBuilder $name) {'
- '_\$this;'
- 'super.$name = $name;'
- '}');
- } else {
- result.writeln('@override');
- result.writeln('$typeInBuilder get $name {'
- '_\$this;'
- 'return super.$name;'
- '}');
- result.writeln('@override');
- result.writeln('set $name($type $name) {'
- '_\$this;'
- 'super.$name = $name;'
- '}');
- }
- result.writeln();
- }
- } else {
- if (settings.generateBuilderOnSetField) {
- result.writeln('void Function() onSet = () {};');
- result.writeln();
- }
-
- for (var field in fields) {
- var type = field.typeInCompilationUnit(compilationUnit);
- var typeInBuilder = field.typeInBuilder(compilationUnit);
- var fieldType = field.isNestedBuilder ? typeInBuilder : type;
- var name = field.name;
-
- // Field.
- result.writeln('$fieldType _$name;');
-
- // Getter.
- result.writeln('$fieldType get $name =>');
- if (field.isNestedBuilder && settings.autoCreateNestedBuilders) {
- result.writeln('_\$this._$name ??= new $typeInBuilder();');
- } else {
- result.writeln('_\$this._$name;');
- }
-
- // Setter.
- if (settings.generateBuilderOnSetField) {
- result.writeln('set $name($fieldType $name) {'
- '_\$this._$name = $name;'
- 'onSet();'
- '}');
- } else {
- result.writeln('set $name($fieldType $name) =>'
- '_\$this._$name = $name;');
- }
-
- result.writeln();
- }
- }
- result.writeln();
-
- if (hasBuilder) {
- result.writeln('${implName}Builder() : super._()');
- } else {
- result.writeln('${name}Builder()');
- }
- if (hasBuilderInitializer) {
- result.writeln('{');
- result.writeln('$name._initializeBuilder(this);');
- result.writeln('}');
- } else {
- result.writeln(';');
- }
- result.writeln('');
-
- // Getter for "this" that does lazy copying if needed.
- if (fields.isNotEmpty) {
- result.writeln('${name}Builder$_generics get _\$this {');
- result.writeln('if (_\$v != null) {');
- for (var field in fields) {
- final name = field.name;
- final nameInBuilder = hasBuilder ? 'super.$name' : '_$name';
- if (field.isNestedBuilder) {
- result.writeln('$nameInBuilder = _\$v.$name?.toBuilder();');
- } else {
- result.writeln('$nameInBuilder = _\$v.$name;');
- }
- }
- result.writeln('_\$v = null;');
- result.writeln('}');
- result.writeln('return this;');
- result.writeln('}');
- }
-
- result.writeln('@override');
- if (builderImplements.length > 1) {
- // If we're overriding `replace` from other builders, tell the analyzer
- // that this builder only accepts values of exactly the right type, by
- // marking the value `covariant`.
-
- if (builderImplements.length > 2) {
- // Add this `ignore` as a workaround for analyzer issue:
- // https://github.com/dart-lang/sdk/issues/32025
- result.writeln('// ignore: override_on_non_overriding_method');
- }
- result.writeln('void replace(covariant $name$_generics other) {');
- } else {
- result.writeln('void replace($name$_generics other) {');
- }
-
- result.writeln('if (other == null) {');
- result.writeln("throw new ArgumentError.notNull('other');");
- result.writeln('}');
- result.writeln('_\$v = other as $implName$_generics;');
- result.writeln('}');
-
- result.writeln('@override');
- result.writeln(
- 'void update(void Function(${name}Builder$_generics) updates) {'
- ' if (updates != null) updates(this); }');
- result.writeln();
-
- result.writeln('@override');
- result.writeln('$implName$_generics build() {');
-
- if (hasBuilderFinalizer) {
- result.writeln('$name._finalizeBuilder(this);');
- }
-
- // Construct a map from field to how it's built. If it's a normal field,
- // this is just the field name; if it's a nested builder, this is an
- // invocation of the nested builder taking into account nullability.
- var fieldBuilders = <String, String>{};
- fields.forEach((field) {
- final name = field.name;
- if (!field.isNestedBuilder) {
- fieldBuilders[name] = name;
- } else if (!field.isNullable) {
- // If not nullable, go via the public accessor, which instantiates
- // if needed.
- fieldBuilders[name] = '$name.build()';
- } else if (hasBuilder) {
- // Otherwise access the private field: in super if there's a manually
- // maintained builder.
- fieldBuilders[name] = 'super.$name?.build()';
- } else {
- // Or, directly if there is no manually maintained builder.
- fieldBuilders[name] = '_$name?.build()';
- }
- });
-
- // If there are nested builders then wrap the build in a try/catch so we
- // can add information should a nested builder fail.
- var needsTryCatchOnBuild =
- fieldBuilders.keys.any((field) => fieldBuilders[field] != field);
-
- if (needsTryCatchOnBuild) {
- result.writeln('$implName$_generics _\$result;');
- result.writeln('try {');
- } else {
- result.write('final ');
- }
- result.writeln('_\$result = _\$v ?? ');
- result.writeln('new $implName$_generics._(');
- result.write(fieldBuilders.keys
- .map((field) => '$field: ${fieldBuilders[field]}')
- .join(','));
- result.writeln(');');
-
- if (needsTryCatchOnBuild) {
- // Handle errors by re-running all nested builders; if there's an error
- // in a nested builder then throw with more information. Otherwise,
- // just rethrow.
- result.writeln('} catch (_) {');
- result.writeln('String _\$failedField;');
- result.writeln('try {');
- result.write(fieldBuilders.keys.map((field) {
- final fieldBuilder = fieldBuilders[field];
- if (fieldBuilder == field) return '';
- return "_\$failedField = '$field'; $fieldBuilder;";
- }).join('\n'));
-
- result.writeln('} catch (e) {');
- result.writeln('throw new BuiltValueNestedFieldError('
- "'$name', _\$failedField, e.toString());");
- result.writeln('}');
- result.writeln('rethrow;');
- result.writeln('}');
- }
-
- // Set _$v to the built value, so it will be lazily copied if needed.
- result.writeln('replace(_\$result);');
- result.writeln('return _\$result;');
- result.writeln('}');
-
- if (settings.comparableBuilders) {
- result.write(_generateEqualsAndHashcode(forBuilder: true));
- }
-
- result.writeln('}');
-
- return result.toString();
- }
-
- String _generateEqualsAndHashcode({bool forBuilder = false}) {
- var result = StringBuffer();
-
- var comparedFields = fields
- .where(
- (field) => field.builtValueField.compare ?? settings.defaultCompare)
- .toList();
- var comparedFunctionFields =
- comparedFields.where((field) => field.isFunctionType).toList();
- result.writeln('@override');
- result.writeln('bool operator==(Object other) {');
- result.writeln(' if (identical(other, this)) return true;');
-
- if (comparedFunctionFields.isNotEmpty) {
- result.writeln(' final _\$dynamicOther = other as dynamic;');
- }
- result.writeln(' return other is $name${forBuilder ? 'Builder' : ''}');
- if (comparedFields.isNotEmpty) {
- result.writeln('&&');
- result.writeln(comparedFields.map((field) {
- var nameOrThisDotName =
- field.name == 'other' ? 'this.other' : field.name;
- return field.isFunctionType
- ? '$nameOrThisDotName == _\$dynamicOther.${field.name}'
- : '$nameOrThisDotName == other.${field.name}';
- }).join('&&'));
- }
- result.writeln(';');
- result.writeln('}');
- result.writeln();
-
- result.writeln('@override');
- result.writeln('int get hashCode {');
-
- if (comparedFields.isEmpty) {
- result.writeln('return ${name.hashCode};');
- } else {
- result.writeln(r'return $jf(');
- result.writeln(r'$jc(' * comparedFields.length);
- // Use a different seed for builders than for values, so they do not have
- // identical hashCodes if the values are identical.
- result.writeln(forBuilder ? '1, ' : '0, ');
- result.write(
- comparedFields.map((field) => '${field.name}.hashCode').join('), '));
- result.writeln('));');
- }
- result.writeln('}');
- result.writeln();
-
- return result.toString();
- }
-
- /// Generates an abstract builder with just abstract setters and getters.
- String _generateAbstractBuilder() {
- var result = StringBuffer();
-
- if (implementsBuilt) {
- result.writeln('abstract class ${name}Builder$_boundedGenerics '
- 'implements ${builderImplements.join(", ")} {');
- } else {
- // The "Built" interface has been omitted to work around dart2js issue
- // https://github.com/dart-lang/sdk/issues/14729. So, we can't implement
- // "Builder". Add the methods explicitly. We can however implement any
- // other built_value interfaces.
- var interfaces = builderImplements.skip(1).toList();
- result.writeln('abstract class ${name}Builder$_boundedGenerics '
- '${interfaces.isEmpty ? '' : 'implements ' + interfaces.join(', ')}'
- '{');
-
- // Add `covariant` if we're implementing one or more parent builders.
- result.writeln('void replace(${interfaces.isEmpty ? '' : 'covariant '}'
- '$name$_generics other);');
- result.writeln(
- 'void update(void Function(${name}Builder$_generics) updates);');
- }
-
- for (var field in fields) {
- final typeInBuilder = field.typeInBuilder(compilationUnit);
- final name = field.name;
-
- result.writeln('$typeInBuilder get $name;');
- result.writeln('set $name($typeInBuilder $name);');
- result.writeln();
- }
-
- result.writeln('}');
- return result.toString();
- }
-}
-
-InvalidGenerationSourceError _makeError(Iterable<GeneratorError> todos) {
- var message =
- StringBuffer('Please make the following changes to use BuiltValue:\n');
- for (var i = 0; i != todos.length; ++i) {
- message.write('\n${i + 1}. ${todos.elementAt(i).message}');
- }
-
- return InvalidGenerationSourceError(message.toString());
-}
diff --git a/built_value_generator/lib/src/value_source_class.g.dart b/built_value_generator/lib/src/value_source_class.g.dart
deleted file mode 100644
index d31d438..0000000
--- a/built_value_generator/lib/src/value_source_class.g.dart
+++ /dev/null
@@ -1,248 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.source_class;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$ValueSourceClass extends ValueSourceClass {
- @override
- final ClassElement element;
- ParsedLibraryResult __parsedLibrary;
- String __name;
- String __implName;
- ClassElement __builderElement;
- bool __implementsBuilt;
- bool __extendsIsAllowed;
- BuiltValue __settings;
- BuiltList<String> __genericParameters;
- BuiltList<String> __genericBounds;
- ClassDeclaration __classDeclaration;
- bool __hasBuilder;
- bool __hasBuilderInitializer;
- MethodElement __builderInitializer;
- bool __hasBuilderFinalizer;
- MethodElement __builderFinalizer;
- String __builderParameters;
- BuiltList<ValueSourceField> __fields;
- String __source;
- String __partStatement;
- bool __hasPartStatement;
- bool __hasBuiltValueImportWithShow;
- bool __hasBuiltValueImportWithAs;
- bool __valueClassIsAbstract;
- BuiltList<ConstructorDeclaration> __valueClassConstructors;
- BuiltList<ConstructorDeclaration> __valueClassFactories;
- bool __builderClassIsAbstract;
- BuiltList<String> __builderClassConstructors;
- BuiltList<String> __builderClassFactories;
- BuiltList<MemoizedGetter> __memoizedGetters;
- BuiltList<String> __builderImplements;
- bool __implementsHashCode;
- bool __implementsOperatorEquals;
- bool __implementsToString;
- CompilationUnitElement __compilationUnit;
-
- factory _$ValueSourceClass(
- [void Function(ValueSourceClassBuilder) updates]) =>
- (new ValueSourceClassBuilder()..update(updates)).build();
-
- _$ValueSourceClass._({this.element}) : super._() {
- if (element == null) {
- throw new BuiltValueNullFieldError('ValueSourceClass', 'element');
- }
- }
-
- @override
- ParsedLibraryResult get parsedLibrary =>
- __parsedLibrary ??= super.parsedLibrary;
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get implName => __implName ??= super.implName;
-
- @override
- ClassElement get builderElement => __builderElement ??= super.builderElement;
-
- @override
- bool get implementsBuilt => __implementsBuilt ??= super.implementsBuilt;
-
- @override
- bool get extendsIsAllowed => __extendsIsAllowed ??= super.extendsIsAllowed;
-
- @override
- BuiltValue get settings => __settings ??= super.settings;
-
- @override
- BuiltList<String> get genericParameters =>
- __genericParameters ??= super.genericParameters;
-
- @override
- BuiltList<String> get genericBounds =>
- __genericBounds ??= super.genericBounds;
-
- @override
- ClassDeclaration get classDeclaration =>
- __classDeclaration ??= super.classDeclaration;
-
- @override
- bool get hasBuilder => __hasBuilder ??= super.hasBuilder;
-
- @override
- bool get hasBuilderInitializer =>
- __hasBuilderInitializer ??= super.hasBuilderInitializer;
-
- @override
- MethodElement get builderInitializer =>
- __builderInitializer ??= super.builderInitializer;
-
- @override
- bool get hasBuilderFinalizer =>
- __hasBuilderFinalizer ??= super.hasBuilderFinalizer;
-
- @override
- MethodElement get builderFinalizer =>
- __builderFinalizer ??= super.builderFinalizer;
-
- @override
- String get builderParameters =>
- __builderParameters ??= super.builderParameters;
-
- @override
- BuiltList<ValueSourceField> get fields => __fields ??= super.fields;
-
- @override
- String get source => __source ??= super.source;
-
- @override
- String get partStatement => __partStatement ??= super.partStatement;
-
- @override
- bool get hasPartStatement => __hasPartStatement ??= super.hasPartStatement;
-
- @override
- bool get hasBuiltValueImportWithShow =>
- __hasBuiltValueImportWithShow ??= super.hasBuiltValueImportWithShow;
-
- @override
- bool get hasBuiltValueImportWithAs =>
- __hasBuiltValueImportWithAs ??= super.hasBuiltValueImportWithAs;
-
- @override
- bool get valueClassIsAbstract =>
- __valueClassIsAbstract ??= super.valueClassIsAbstract;
-
- @override
- BuiltList<ConstructorDeclaration> get valueClassConstructors =>
- __valueClassConstructors ??= super.valueClassConstructors;
-
- @override
- BuiltList<ConstructorDeclaration> get valueClassFactories =>
- __valueClassFactories ??= super.valueClassFactories;
-
- @override
- bool get builderClassIsAbstract =>
- __builderClassIsAbstract ??= super.builderClassIsAbstract;
-
- @override
- BuiltList<String> get builderClassConstructors =>
- __builderClassConstructors ??= super.builderClassConstructors;
-
- @override
- BuiltList<String> get builderClassFactories =>
- __builderClassFactories ??= super.builderClassFactories;
-
- @override
- BuiltList<MemoizedGetter> get memoizedGetters =>
- __memoizedGetters ??= super.memoizedGetters;
-
- @override
- BuiltList<String> get builderImplements =>
- __builderImplements ??= super.builderImplements;
-
- @override
- bool get implementsHashCode =>
- __implementsHashCode ??= super.implementsHashCode;
-
- @override
- bool get implementsOperatorEquals =>
- __implementsOperatorEquals ??= super.implementsOperatorEquals;
-
- @override
- bool get implementsToString =>
- __implementsToString ??= super.implementsToString;
-
- @override
- CompilationUnitElement get compilationUnit =>
- __compilationUnit ??= super.compilationUnit;
-
- @override
- ValueSourceClass rebuild(void Function(ValueSourceClassBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- ValueSourceClassBuilder toBuilder() =>
- new ValueSourceClassBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is ValueSourceClass && element == other.element;
- }
-
- @override
- int get hashCode {
- return $jf($jc(0, element.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('ValueSourceClass')
- ..add('element', element))
- .toString();
- }
-}
-
-class ValueSourceClassBuilder
- implements Builder<ValueSourceClass, ValueSourceClassBuilder> {
- _$ValueSourceClass _$v;
-
- ClassElement _element;
- ClassElement get element => _$this._element;
- set element(ClassElement element) => _$this._element = element;
-
- ValueSourceClassBuilder();
-
- ValueSourceClassBuilder get _$this {
- if (_$v != null) {
- _element = _$v.element;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(ValueSourceClass other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$ValueSourceClass;
- }
-
- @override
- void update(void Function(ValueSourceClassBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$ValueSourceClass build() {
- final _$result = _$v ?? new _$ValueSourceClass._(element: element);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/lib/src/value_source_field.dart b/built_value_generator/lib/src/value_source_field.dart
deleted file mode 100644
index d594fbe..0000000
--- a/built_value_generator/lib/src/value_source_field.dart
+++ /dev/null
@@ -1,263 +0,0 @@
-// Copyright (c) 2016, Google Inc. 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 built_value_generator.source_field;
-
-import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:built_collection/built_collection.dart';
-import 'package:built_value/built_value.dart';
-import 'package:built_value_generator/src/dart_types.dart';
-import 'package:built_value_generator/src/fixes.dart';
-import 'package:built_value_generator/src/fields.dart' show collectFields;
-import 'package:built_value_generator/src/metadata.dart'
- show metadataToStringValue;
-
-part 'value_source_field.g.dart';
-
-const _suggestedTypes = <String, String>{
- 'List': 'BuiltList',
- 'Map': 'BuiltMap',
- 'Set': 'BuiltSet',
- 'ListMultimap': 'BuiltListMultimap',
- 'SetMultimap': 'BuiltSetMultimap',
-};
-
-abstract class ValueSourceField
- implements Built<ValueSourceField, ValueSourceFieldBuilder> {
- BuiltValue get settings;
- ParsedLibraryResult get parsedLibrary;
- FieldElement get element;
- @nullable
- FieldElement get builderElement;
-
- factory ValueSourceField(
- BuiltValue settings,
- ParsedLibraryResult parsedLibrary,
- FieldElement element,
- FieldElement builderElement) =>
- _$ValueSourceField._(
- settings: settings,
- parsedLibrary: parsedLibrary,
- element: element,
- builderElement: builderElement);
- ValueSourceField._();
-
- @memoized
- String get name => element.displayName;
-
- @memoized
- String get type => DartTypes.getName(element.getter.returnType);
-
- @memoized
- bool get isFunctionType => type.contains('(');
-
- /// The [type] plus any import prefix.
- @memoized
- String get typeWithPrefix {
- var typeFromAst = (parsedLibrary.getElementDeclaration(element.getter).node
- as MethodDeclaration)
- ?.returnType
- ?.toSource() ??
- 'dynamic';
- var typeFromElement = type;
-
- // If the type is a function, we can't use the element result; it is
- // formatted incorrectly.
- if (isFunctionType) return typeFromAst;
-
- // If the type does not have an import prefix, prefer the element result.
- // It handles inherited generics correctly.
- if (!typeFromAst.contains('.')) return typeFromElement;
-
- return typeFromAst;
- }
-
- /// Returns the type with import prefix if the compilation unit matches,
- /// otherwise the type with no import prefix.
- String typeInCompilationUnit(CompilationUnitElement compilationUnitElement) {
- return compilationUnitElement == element.library.definingCompilationUnit
- ? typeWithPrefix
- : type;
- }
-
- @memoized
- bool get isGetter => element.getter != null && !element.getter.isSynthetic;
-
- @memoized
- bool get isNullable => element.getter.metadata
- .any((metadata) => metadataToStringValue(metadata) == 'nullable');
-
- @memoized
- BuiltValueField get builtValueField {
- var annotations = element.getter.metadata
- .map((annotation) => annotation.computeConstantValue())
- .where((value) => DartTypes.getName(value?.type) == 'BuiltValueField');
- if (annotations.isEmpty) return const BuiltValueField();
- var annotation = annotations.single;
- return BuiltValueField(
- compare: annotation.getField('compare').toBoolValue(),
- serialize: annotation.getField('serialize').toBoolValue(),
- wireName: annotation.getField('wireName').toStringValue());
- }
-
- @memoized
- bool get builderFieldExists => builderElement != null;
-
- @memoized
- bool get builderFieldIsNormalField =>
- builderFieldExists &&
- builderElement.getter != null &&
- !builderElement.getter.isAbstract &&
- builderElement.getter.isSynthetic;
-
- @memoized
- bool get builderFieldIsGetterSetterPair =>
- builderFieldExists &&
- (builderElement.getter != null && builderElement.setter != null);
-
- @memoized
- String get buildElementType {
- // Try to get a resolved type first, it's faster.
- var result = DartTypes.getName(builderElement.getter?.returnType);
- if (result != null && result != 'dynamic') return result;
- // Go via AST to allow use of unresolvable types not yet generated;
- // this includes generated Builder types.
- result = parsedLibrary
- .getElementDeclaration(builderElement)
- ?.node
- ?.parent
- ?.childEntities
- ?.first
- .toString() ??
- 'dynamic';
- // If we went via the AST there may be an import prefix, but we don't
- // want one here. Strip it off.
- if (result.contains('.')) {
- result = result.substring(result.indexOf('.') + 1);
- }
- return result;
- }
-
- /// The [builderElementType] plus any import prefix.
- @memoized
- String get builderElementTypeWithPrefix {
- // If it's a real field, it's a [VariableDeclaration] which is guaranteed
- // to have parent node [VariableDeclarationList] giving the type.
- var fieldDeclaration = parsedLibrary.getElementDeclaration(builderElement);
- if (fieldDeclaration != null) {
- return (((fieldDeclaration.node as VariableDeclaration).parent)
- as VariableDeclarationList)
- ?.type
- ?.toSource() ??
- 'dynamic';
- } else {
- // Otherwise it's an explicit getter/setter pair; get the type from the getter.
- return (parsedLibrary.getElementDeclaration(builderElement.getter).node
- as MethodDeclaration)
- ?.returnType
- ?.toSource() ??
- 'dynamic';
- }
- }
-
- /// Gets the type name for the builder. Specify the compilation unit to
- /// get the name for as [compilationUnit]; this affects whether an import
- /// prefix is used. Pass `null` for [compilationUnit] to just omit the prefix.
- String typeInBuilder(
- CompilationUnitElement compilationUnit) =>
- builderFieldExists
- ? buildElementType
- : _toBuilderType(element.getter.returnType,
- typeInCompilationUnit(compilationUnit));
-
- @memoized
- bool get isNestedBuilder => builderFieldExists
- ? typeInBuilder(null).contains('Builder') ?? false
- : settings.nestedBuilders &&
- DartTypes.needsNestedBuilder(element.getter.returnType);
-
- static BuiltList<ValueSourceField> fromClassElements(
- BuiltValue settings,
- ParsedLibraryResult parsedLibrary,
- ClassElement classElement,
- ClassElement builderClassElement) {
- var result = ListBuilder<ValueSourceField>();
-
- for (var field in collectFields(classElement)) {
- if (!field.isStatic &&
- field.getter != null &&
- (field.getter.isAbstract || field.getter.isSynthetic)) {
- final builderField = builderClassElement?.getField(field.name);
- result.add(
- ValueSourceField(settings, parsedLibrary, field, builderField));
- }
- }
-
- return result.build();
- }
-
- static String _toBuilderType(DartType type, String displayName) {
- if (DartTypes.isBuiltCollection(type)) {
- return displayName
- .replaceFirst('Built', '')
- .replaceFirst('<', 'Builder<');
- } else if (DartTypes.isInstantiableBuiltValue(type)) {
- return displayName.contains('<')
- ? displayName.replaceFirst('<', 'Builder<')
- : '${displayName}Builder';
- } else {
- return displayName;
- }
- }
-
- Iterable<GeneratorError> computeErrors() {
- var result = <GeneratorError>[];
-
- if (!isGetter) {
- result.add(
- GeneratorError((b) => b..message = 'Make field $name a getter.'));
- }
-
- if (type == 'dynamic') {
- result.add(GeneratorError((b) => b
- ..message = 'Make field $name have non-dynamic type. '
- 'If you are already specifying a type, '
- 'please make sure the type is correctly imported.'));
- }
-
- if (name.startsWith('_')) {
- result.add(GeneratorError((b) =>
- b..message = 'Make field $name public; remove the underscore.'));
- }
-
- if (_suggestedTypes.keys.contains(type)) {
- result.add(GeneratorError((b) => b
- ..message = 'Make field "$name" have type "${_suggestedTypes[type]}". '
- 'The current type, "$type", is not allowed because it is mutable.'));
- }
-
- if (builderFieldExists) {
- if (buildElementType != type &&
- buildElementType != _toBuilderType(element.type, type)) {
- result.add(GeneratorError((b) => b
- ..message = 'Make builder field $name have type: '
- '$type (or, if applicable, builder)'));
- }
- }
-
- if (builderFieldExists &&
- !builderFieldIsNormalField &&
- !builderFieldIsGetterSetterPair) {
- result.add(GeneratorError((b) => b
- ..message =
- 'Make builder field $name a normal field or a getter/setter '
- 'pair.'));
- }
-
- return result;
- }
-}
diff --git a/built_value_generator/lib/src/value_source_field.g.dart b/built_value_generator/lib/src/value_source_field.g.dart
deleted file mode 100644
index 573dd6a..0000000
--- a/built_value_generator/lib/src/value_source_field.g.dart
+++ /dev/null
@@ -1,192 +0,0 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
-
-part of built_value_generator.source_field;
-
-// **************************************************************************
-// BuiltValueGenerator
-// **************************************************************************
-
-class _$ValueSourceField extends ValueSourceField {
- @override
- final BuiltValue settings;
- @override
- final ParsedLibraryResult parsedLibrary;
- @override
- final FieldElement element;
- @override
- final FieldElement builderElement;
- String __name;
- String __type;
- bool __isFunctionType;
- String __typeWithPrefix;
- bool __isGetter;
- bool __isNullable;
- BuiltValueField __builtValueField;
- bool __builderFieldExists;
- bool __builderFieldIsNormalField;
- bool __builderFieldIsGetterSetterPair;
- String __buildElementType;
- String __builderElementTypeWithPrefix;
- bool __isNestedBuilder;
-
- factory _$ValueSourceField(
- [void Function(ValueSourceFieldBuilder) updates]) =>
- (new ValueSourceFieldBuilder()..update(updates)).build();
-
- _$ValueSourceField._(
- {this.settings, this.parsedLibrary, this.element, this.builderElement})
- : super._() {
- if (settings == null) {
- throw new BuiltValueNullFieldError('ValueSourceField', 'settings');
- }
- if (parsedLibrary == null) {
- throw new BuiltValueNullFieldError('ValueSourceField', 'parsedLibrary');
- }
- if (element == null) {
- throw new BuiltValueNullFieldError('ValueSourceField', 'element');
- }
- }
-
- @override
- String get name => __name ??= super.name;
-
- @override
- String get type => __type ??= super.type;
-
- @override
- bool get isFunctionType => __isFunctionType ??= super.isFunctionType;
-
- @override
- String get typeWithPrefix => __typeWithPrefix ??= super.typeWithPrefix;
-
- @override
- bool get isGetter => __isGetter ??= super.isGetter;
-
- @override
- bool get isNullable => __isNullable ??= super.isNullable;
-
- @override
- BuiltValueField get builtValueField =>
- __builtValueField ??= super.builtValueField;
-
- @override
- bool get builderFieldExists =>
- __builderFieldExists ??= super.builderFieldExists;
-
- @override
- bool get builderFieldIsNormalField =>
- __builderFieldIsNormalField ??= super.builderFieldIsNormalField;
-
- @override
- bool get builderFieldIsGetterSetterPair =>
- __builderFieldIsGetterSetterPair ??= super.builderFieldIsGetterSetterPair;
-
- @override
- String get buildElementType => __buildElementType ??= super.buildElementType;
-
- @override
- String get builderElementTypeWithPrefix =>
- __builderElementTypeWithPrefix ??= super.builderElementTypeWithPrefix;
-
- @override
- bool get isNestedBuilder => __isNestedBuilder ??= super.isNestedBuilder;
-
- @override
- ValueSourceField rebuild(void Function(ValueSourceFieldBuilder) updates) =>
- (toBuilder()..update(updates)).build();
-
- @override
- ValueSourceFieldBuilder toBuilder() =>
- new ValueSourceFieldBuilder()..replace(this);
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) return true;
- return other is ValueSourceField &&
- settings == other.settings &&
- parsedLibrary == other.parsedLibrary &&
- element == other.element &&
- builderElement == other.builderElement;
- }
-
- @override
- int get hashCode {
- return $jf($jc(
- $jc($jc($jc(0, settings.hashCode), parsedLibrary.hashCode),
- element.hashCode),
- builderElement.hashCode));
- }
-
- @override
- String toString() {
- return (newBuiltValueToStringHelper('ValueSourceField')
- ..add('settings', settings)
- ..add('parsedLibrary', parsedLibrary)
- ..add('element', element)
- ..add('builderElement', builderElement))
- .toString();
- }
-}
-
-class ValueSourceFieldBuilder
- implements Builder<ValueSourceField, ValueSourceFieldBuilder> {
- _$ValueSourceField _$v;
-
- BuiltValue _settings;
- BuiltValue get settings => _$this._settings;
- set settings(BuiltValue settings) => _$this._settings = settings;
-
- ParsedLibraryResult _parsedLibrary;
- ParsedLibraryResult get parsedLibrary => _$this._parsedLibrary;
- set parsedLibrary(ParsedLibraryResult parsedLibrary) =>
- _$this._parsedLibrary = parsedLibrary;
-
- FieldElement _element;
- FieldElement get element => _$this._element;
- set element(FieldElement element) => _$this._element = element;
-
- FieldElement _builderElement;
- FieldElement get builderElement => _$this._builderElement;
- set builderElement(FieldElement builderElement) =>
- _$this._builderElement = builderElement;
-
- ValueSourceFieldBuilder();
-
- ValueSourceFieldBuilder get _$this {
- if (_$v != null) {
- _settings = _$v.settings;
- _parsedLibrary = _$v.parsedLibrary;
- _element = _$v.element;
- _builderElement = _$v.builderElement;
- _$v = null;
- }
- return this;
- }
-
- @override
- void replace(ValueSourceField other) {
- if (other == null) {
- throw new ArgumentError.notNull('other');
- }
- _$v = other as _$ValueSourceField;
- }
-
- @override
- void update(void Function(ValueSourceFieldBuilder) updates) {
- if (updates != null) updates(this);
- }
-
- @override
- _$ValueSourceField build() {
- final _$result = _$v ??
- new _$ValueSourceField._(
- settings: settings,
- parsedLibrary: parsedLibrary,
- element: element,
- builderElement: builderElement);
- replace(_$result);
- return _$result;
- }
-}
-
-// ignore_for_file: always_put_control_body_on_new_line,always_specify_types,annotate_overrides,avoid_annotating_with_dynamic,avoid_as,avoid_catches_without_on_clauses,avoid_returning_this,lines_longer_than_80_chars,omit_local_variable_types,prefer_expression_function_bodies,sort_constructors_first,test_types_in_equals,unnecessary_const,unnecessary_new
diff --git a/built_value_generator/pubspec.yaml b/built_value_generator/pubspec.yaml
deleted file mode 100644
index c2e5014..0000000
--- a/built_value_generator/pubspec.yaml
+++ /dev/null
@@ -1,28 +0,0 @@
-name: built_value_generator
-version: 6.8.2
-description: >
- Value types with builders, Dart classes as enums, and serialization.
- This library is the dev dependency.
-authors:
-- David Morgan <davidmorgan@google.com>
-homepage: https://github.com/google/built_value.dart
-
-environment:
- sdk: '>=2.0.0 <3.0.0'
-
-dependencies:
- analyzer: '>=0.34.0 <0.39.0'
- analyzer_plugin: '>=0.1.0 <0.3.0'
- build: ^1.0.0
- build_config: '>=0.3.1 <0.5.0'
- built_collection: '>=2.0.0 <5.0.0'
- built_value: '>=5.5.5 <7.0.0'
- source_gen: ^0.9.0
- quiver: '>=0.21.0 <3.0.0'
-
-dev_dependencies:
- build_test: ^0.10.3
- build_runner: ^1.0.0
- logging: ^0.11.0
- pedantic: ^1.4.0
- test: ^1.0.0
diff --git a/built_value_generator/tools/analyzer_plugin/bin/plugin.dart b/built_value_generator/tools/analyzer_plugin/bin/plugin.dart
deleted file mode 100644
index 45fd5e2..0000000
--- a/built_value_generator/tools/analyzer_plugin/bin/plugin.dart
+++ /dev/null
@@ -1,7 +0,0 @@
-import 'dart:isolate';
-
-import 'package:built_value_generator/plugin_starter.dart';
-
-void main(List<String> args, SendPort sendPort) {
- start(args, sendPort);
-}
diff --git a/built_value_generator/tools/analyzer_plugin/pubspec.yaml b/built_value_generator/tools/analyzer_plugin/pubspec.yaml
deleted file mode 100644
index ca80ebb..0000000
--- a/built_value_generator/tools/analyzer_plugin/pubspec.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-name: built_value_generator_plugin_loader
-version: 6.8.2
-description: This pubspec determines the version of the analyzer plugin to load.
-environment:
- sdk: '>=1.24.0-dev.1.0'
-dependencies:
- built_value_generator: ^6.8.2
diff --git a/connectivity/BUILD.gn b/connectivity/BUILD.gn
index cec2711..61cafaf 100644
--- a/connectivity/BUILD.gn
+++ b/connectivity/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for connectivity-0.4.5+2
+# This file is generated by importer.py for connectivity-0.4.5+1
import("//build/dart/dart_library.gni")
diff --git a/connectivity/CHANGELOG.md b/connectivity/CHANGELOG.md
index 1248200..8ccb04d 100644
--- a/connectivity/CHANGELOG.md
+++ b/connectivity/CHANGELOG.md
@@ -1,8 +1,3 @@
-## 0.4.5+2
-
-* Include lifecycle dependency as a compileOnly one on Android to resolve
- potential version conflicts with other transitive libraries.
-
## 0.4.5+1
* Android: Use android.arch.lifecycle instead of androidx.lifecycle:lifecycle in `build.gradle` to support apps that has not been migrated to AndroidX.
diff --git a/connectivity/android/build.gradle b/connectivity/android/build.gradle
index a562f60..1767ef4 100644
--- a/connectivity/android/build.gradle
+++ b/connectivity/android/build.gradle
@@ -64,9 +64,9 @@
android {
dependencies {
def lifecycle_version = "1.1.1"
- compileOnly "android.arch.lifecycle:runtime:$lifecycle_version"
- compileOnly "android.arch.lifecycle:common:$lifecycle_version"
- compileOnly "android.arch.lifecycle:common-java8:$lifecycle_version"
+ api "android.arch.lifecycle:runtime:$lifecycle_version"
+ api "android.arch.lifecycle:common:$lifecycle_version"
+ api "android.arch.lifecycle:common-java8:$lifecycle_version"
}
}
}
diff --git a/connectivity/pubspec.yaml b/connectivity/pubspec.yaml
index 42c9641..fa90f1a 100644
--- a/connectivity/pubspec.yaml
+++ b/connectivity/pubspec.yaml
@@ -3,7 +3,7 @@
mobile/cellular) connectivity on Android and iOS.
author: Flutter Team <flutter-dev@googlegroups.com>
homepage: https://github.com/flutter/plugins/tree/master/packages/connectivity
-version: 0.4.5+2
+version: 0.4.5+1
flutter:
plugin:
diff --git a/coverage/BUILD.gn b/coverage/BUILD.gn
index 4a9c6ec..c1bd71e 100644
--- a/coverage/BUILD.gn
+++ b/coverage/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for coverage-0.13.3+1
+# This file is generated by importer.py for coverage-0.13.3
import("//build/dart/dart_library.gni")
diff --git a/coverage/CHANGELOG.md b/coverage/CHANGELOG.md
index 51b17f3..a1f8817 100644
--- a/coverage/CHANGELOG.md
+++ b/coverage/CHANGELOG.md
@@ -1,9 +1,3 @@
-## 0.13.3+1 - 2019-10-10
-
-* Loosen the dependency on the `vm_service` package from `^1.0.0` to `>=1.0.0
- <3.0.0`. Ensures dependency version range compatibility with the latest
- versions of package `test`.
-
## 0.13.3 - 2019-09-27
* Adds a new named argument to `collect` to filter coverage results by a set
diff --git a/coverage/pubspec.yaml b/coverage/pubspec.yaml
index 0b2a36b..e4e9a35 100644
--- a/coverage/pubspec.yaml
+++ b/coverage/pubspec.yaml
@@ -1,5 +1,5 @@
name: coverage
-version: 0.13.3+1
+version: 0.13.3
author: Dart Team <misc@dartlang.org>
description: Coverage data manipulation and formatting
homepage: https://github.com/dart-lang/coverage
@@ -13,7 +13,7 @@
package_config: '>=0.1.5 <2.0.0'
path: '>=0.9.0 <2.0.0'
stack_trace: ^1.3.0
- vm_service: '>=1.0.0 <3.0.0'
+ vm_service: ^1.0.0
dev_dependencies:
test: ^1.0.0
diff --git a/device_info/BUILD.gn b/device_info/BUILD.gn
index 91dc28f..7c34845 100644
--- a/device_info/BUILD.gn
+++ b/device_info/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for device_info-0.4.1+1
+# This file is generated by importer.py for device_info-0.4.1
import("//build/dart/dart_library.gni")
diff --git a/device_info/CHANGELOG.md b/device_info/CHANGELOG.md
index 9099e40..1fff8c7 100644
--- a/device_info/CHANGELOG.md
+++ b/device_info/CHANGELOG.md
@@ -1,8 +1,3 @@
-## 0.4.1+1
-
-* Include lifecycle dependency as a compileOnly one on Android to resolve
- potential version conflicts with other transitive libraries.
-
## 0.4.1
* Support the v2 Android embedding.
diff --git a/device_info/android/build.gradle b/device_info/android/build.gradle
index 68ffcf9..7dfea2d 100644
--- a/device_info/android/build.gradle
+++ b/device_info/android/build.gradle
@@ -64,9 +64,9 @@
android {
dependencies {
def lifecycle_version = "1.1.1"
- compileOnly "android.arch.lifecycle:runtime:$lifecycle_version"
- compileOnly "android.arch.lifecycle:common:$lifecycle_version"
- compileOnly "android.arch.lifecycle:common-java8:$lifecycle_version"
+ api "android.arch.lifecycle:runtime:$lifecycle_version"
+ api "android.arch.lifecycle:common:$lifecycle_version"
+ api "android.arch.lifecycle:common-java8:$lifecycle_version"
}
}
}
diff --git a/device_info/example/android/app/gradle.properties b/device_info/example/android/app/gradle.properties
new file mode 100644
index 0000000..5465fec
--- /dev/null
+++ b/device_info/example/android/app/gradle.properties
@@ -0,0 +1,2 @@
+android.enableJetifier=true
+android.useAndroidX=true
\ No newline at end of file
diff --git a/device_info/pubspec.yaml b/device_info/pubspec.yaml
index 94e0c64..580df14 100644
--- a/device_info/pubspec.yaml
+++ b/device_info/pubspec.yaml
@@ -3,7 +3,7 @@
(make, model, etc.), and Android or iOS version the app is running on.
author: Flutter Team <flutter-dev@googlegroups.com>
homepage: https://github.com/flutter/plugins/tree/master/packages/device_info
-version: 0.4.1+1
+version: 0.4.1
flutter:
plugin:
diff --git a/dwds/BUILD.gn b/dwds/BUILD.gn
index 472d3fb..024849d 100644
--- a/dwds/BUILD.gn
+++ b/dwds/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for dwds-0.7.6
+# This file is generated by importer.py for dwds-0.7.5
import("//build/dart/dart_library.gni")
diff --git a/dwds/CHANGELOG.md b/dwds/CHANGELOG.md
index 54be826..25c306c 100644
--- a/dwds/CHANGELOG.md
+++ b/dwds/CHANGELOG.md
@@ -1,9 +1,3 @@
-## 0.7.6
-
-- Fix issue with source map logic for the legacy module system.
-- Allow setting breakpoints multiple times and just return the old breakpoint.
-- Fix a bug with Maps that contain lists of simple types.
-
## 0.7.5
- The injected client's connection is now based off the request URI.
diff --git a/dwds/lib/src/debugging/classes.dart b/dwds/lib/src/debugging/classes.dart
deleted file mode 100644
index 25d30f3..0000000
--- a/dwds/lib/src/debugging/classes.dart
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.import 'dart:async';
-
-import '../utilities/domain.dart';
-import '../utilities/shared.dart';
-import '../utilities/wrapped_service.dart';
-import 'inspector.dart';
-import 'metadata.dart';
-
-/// A hard-coded ClassRef for the Closure class.
-final classRefForClosure = classRefFor('dart:core', 'Closure');
-
-/// A hard-coded ClassRef for the String class.
-final classRefForString = classRefFor('dart:core', InstanceKind.kString);
-
-/// A hard-coded ClassRef for a (non-existent) class called Unknown.
-final classRefForUnknown = classRefFor('dart:core', 'Unknown');
-
-/// Returns a [ClassRef] for the provided library ID and class name.
-ClassRef classRefFor(String libraryId, String name) =>
- ClassRef(id: 'classes|$libraryId|$name', name: name);
-
-/// Keeps track of Dart classes available in the running application.
-class ClassHelper extends Domain {
- /// Map of class ID to [Class].
- final _classes = <String, Class>{};
-
- ClassHelper(AppInspector Function() provider) : super(provider) {
- var staticClasses = [
- classRefForClosure,
- classRefForString,
- classRefForUnknown
- ];
- for (var classRef in staticClasses) {
- _classes[classRef.id] = Class(
- name: classRef.name,
- isAbstract: false,
- isConst: false,
- library: null,
- interfaces: [],
- fields: [],
- functions: [],
- subclasses: [],
- id: classRef.id);
- }
- }
-
- /// Returns the [Class] that corresponds to the provided [objectId].
- ///
- /// If a corresponding class does not exist it will return null.
- Future<Class> forObjectId(String objectId) async {
- if (!objectId.startsWith('classes|')) return null;
- var clazz = _classes[objectId];
- if (clazz != null) return clazz;
- var splitId = objectId.split('|');
- var libraryId = splitId[1];
- var libraryRef = await inspector.libraryHelper.libraryRefFor(libraryId);
- var classRef = classRefFor(libraryId, splitId.last);
- clazz = await _constructClass(libraryRef, classRef);
- return _classes[objectId] = clazz;
- }
-
- /// Constructs a [Class] instance for the provided [LibraryRef] and
- /// [ClassRef].
- Future<Class> _constructClass(
- LibraryRef libraryRef, ClassRef classRef) async {
- var expression = '''
- (function() {
- ${getLibrarySnippet(libraryRef.uri)}
- var result = {};
- var clazz = library["${classRef.name}"];
- var descriptor = {
- 'name': clazz.name,
- 'dartName': sdkUtils.typeName(clazz)
- };
- // TODO(jakemac): static methods once ddc supports them
- var methods = sdkUtils.getMethods(clazz);
- var methodNames = methods ? Object.keys(methods) : [];
- descriptor['methods'] = {};
- for (var name of methodNames) {
- var method = methods[name];
- descriptor['methods'][name] = {
- // TODO(jakemac): how can we get actual const info?
- "isConst": false,
- "isStatic": false,
- }
- }
- // TODO(jakemac): static fields once ddc supports them
- var fields = sdkUtils.getFields(clazz);
- var fieldNames = fields ? Object.keys(fields) : [];
- descriptor['fields'] = {};
- for (var name of fieldNames) {
- var field = fields[name];
- var libraryUri = Object.getOwnPropertySymbols(fields[name]["type"])
- .find(x => x.description == "libraryUri");
- descriptor['fields'][name] = {
- // TODO(jakemac): how can we get actual const info?
- "isConst": false,
- "isFinal": field.isFinal,
- "isStatic": false,
- "classRefName": fields[name]["type"]["name"],
- "classRefDartName": sdkUtils.typeName(fields[name]["type"]),
- "classRefLibraryId" : field["type"][libraryUri],
- }
- }
- return descriptor;
- })()
- ''';
- var result = await inspector.remoteDebugger.sendCommand('Runtime.evaluate',
- params: {'expression': expression, 'returnByValue': true});
- handleErrorIfPresent(result, evalContents: expression);
- var classDescriptor = result.result['result']['value'];
- var classMetaData = ClassMetaData(
- jsName: classDescriptor['name'],
- libraryId: libraryRef.id,
- dartName: classDescriptor['dartName']);
-
- var methodRefs = <FuncRef>[];
- var methodDescriptors = classDescriptor['methods'] as Map<String, dynamic>;
- methodDescriptors.forEach((name, descriptor) {
- var methodId = '${classMetaData.id}:$name';
- methodRefs.add(FuncRef(
- id: methodId,
- name: name,
- owner: classRef,
- isConst: descriptor['isConst'] as bool,
- isStatic: descriptor['isStatic'] as bool));
- });
- var fieldRefs = <FieldRef>[];
- var fieldDescriptors = classDescriptor['fields'] as Map<String, dynamic>;
- fieldDescriptors.forEach((name, descriptor) async {
- var classMetaData = ClassMetaData(
- jsName: descriptor['classRefName'],
- libraryId: descriptor['classRefLibraryId'],
- dartName: descriptor['classRefDartName']);
- fieldRefs.add(FieldRef(
- name: name,
- owner: classRef,
- declaredType: InstanceRef(
- id: createId(),
- kind: InstanceKind.kType,
- classRef: classMetaData.classRef),
- isConst: descriptor['isConst'] as bool,
- isFinal: descriptor['isFinal'] as bool,
- isStatic: descriptor['isStatic'] as bool,
- id: createId()));
- });
-
- // TODO: Implement the rest of these
- // https://github.com/dart-lang/webdev/issues/176.
- return Class(
- name: classMetaData.jsName,
- isAbstract: false,
- isConst: false,
- library: libraryRef,
- interfaces: [],
- fields: fieldRefs,
- functions: methodRefs,
- subclasses: [],
- id: classMetaData.id);
- }
-}
diff --git a/dwds/lib/src/debugging/dart_scope.dart b/dwds/lib/src/debugging/dart_scope.dart
index be8afa7..d4615e6 100644
--- a/dwds/lib/src/debugging/dart_scope.dart
+++ b/dwds/lib/src/debugging/dart_scope.dart
@@ -29,13 +29,6 @@
await debugger.getProperties(scope['object']['objectId'] as String))
.toList();
var allProperties = [for (var list in propertyLists) ...await list];
- // We should never see a raw JS class. The only case where this happens is a
- // Dart generic function, where the type arguments get passed in as
- // parameters. Hide those.
- // TODO(#786) Handle these correctly rather than just suppressing them.
- allProperties.removeWhere((each) =>
- each.value.type == 'function' &&
- each.value.description.startsWith('class '));
var existingThis =
allProperties.firstWhere((x) => x.name == 'this', orElse: () => null);
if (existingThis == null) {
diff --git a/dwds/lib/src/debugging/debugger.dart b/dwds/lib/src/debugging/debugger.dart
index 8f3cd81..6711027 100644
--- a/dwds/lib/src/debugging/debugger.dart
+++ b/dwds/lib/src/debugging/debugger.dart
@@ -5,7 +5,6 @@
import 'dart:async';
import 'package:logging/logging.dart';
-import 'package:meta/meta.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
hide StackTrace;
@@ -39,6 +38,8 @@
final RemoteDebugger _remoteDebugger;
+ /// The root URI from which the application is served.
+ final String _root;
final StreamNotify _streamNotify;
final Sources _sources;
final Modules _modules;
@@ -51,18 +52,17 @@
this._sources,
this._modules,
this._locations,
- String root,
- ) : _breakpoints = _Breakpoints(
- locations: _locations,
- provider: provider,
- remoteDebugger: _remoteDebugger,
- root: root),
+ this._root,
+ ) : _breakpoints = _Breakpoints(provider),
super(provider);
/// The breakpoints we have set so far, indexable by either
/// Dart or JS ID.
final _Breakpoints _breakpoints;
+ /// Allocates Dart breakpoint IDs
+ int _nextBreakpointId = 1;
+
Stack _pausedStack;
PauseState _pauseState = PauseState.none;
@@ -250,15 +250,41 @@
Future<Breakpoint> addBreakpoint(String isolateId, String scriptId, int line,
{int column}) async {
checkIsolate(isolateId);
- return _breakpoints.add(scriptId, line, ifNew: (breakpoint) async {
- _streamNotify(
- 'Debug',
- Event(
- kind: EventKind.kBreakpointAdded,
- timestamp: DateTime.now().millisecondsSinceEpoch,
- isolate: inspector.isolateRef)
- ..breakpoint = breakpoint);
- });
+ var dartScript = await inspector.scriptWithId(scriptId);
+ var dartUri = DartUri(dartScript.uri, _root);
+ var location = await _locations.locationForDart(dartUri, line);
+ // TODO: Handle cases where a breakpoint can't be set exactly at that line.
+ if (location == null) {
+ // ignore: only_throw_errors
+ throw RPCError(
+ 'addBreakpoint',
+ 102,
+ 'The VM is unable to add a breakpoint '
+ 'at the specified line or function');
+ }
+
+ var jsBreakpointId = await _setBreakpoint(location);
+ var dartBreakpoint = _dartBreakpoint(dartScript, location);
+ _breakpoints.noteBreakpoint(js: jsBreakpointId, bp: dartBreakpoint);
+ return dartBreakpoint;
+ }
+
+ /// Create a Dart breakpoint at [location] in [dartScript].
+ Breakpoint _dartBreakpoint(ScriptRef dartScript, Location location) {
+ var breakpoint = Breakpoint()
+ ..resolved = true
+ ..id = '${_nextBreakpointId++}'
+ ..location = (SourceLocation()
+ ..script = dartScript
+ ..tokenPos = location.tokenPos);
+ _streamNotify(
+ 'Debug',
+ Event(
+ kind: EventKind.kBreakpointAdded,
+ timestamp: DateTime.now().millisecondsSinceEpoch,
+ isolate: inspector.isolateRef)
+ ..breakpoint = breakpoint);
+ return breakpoint;
}
/// Remove a Dart breakpoint.
@@ -269,7 +295,7 @@
throw ArgumentError.notNull('breakpointId');
}
var jsId = _breakpoints.jsId(breakpointId);
- var bp = await _breakpoints.remove(js: jsId, dartId: breakpointId);
+ var bp = _breakpoints.removeBreakpoint(js: jsId, dartId: breakpointId);
if (bp == null) {
throw ArgumentError.value(
breakpointId, 'Breakpoint not found with this id.');
@@ -285,6 +311,21 @@
return Success();
}
+ /// Call the Chrome protocol setBreakpoint and return the breakpoint ID.
+ Future<String> _setBreakpoint(Location location) async {
+ // Location is 0 based according to:
+ // https://chromedevtools.github.io/devtools-protocol/tot/Debugger#type-Location
+ var response =
+ await _remoteDebugger.sendCommand('Debugger.setBreakpoint', params: {
+ 'location': {
+ 'scriptId': location.jsLocation.scriptId,
+ 'lineNumber': location.jsLocation.line - 1,
+ }
+ });
+ handleErrorIfPresent(response);
+ return response.result['breakpointId'] as String;
+ }
+
/// Call the Chrome protocol removeBreakpoint.
Future<void> _removeBreakpoint(String breakpointId) async {
var response = await _remoteDebugger.sendCommand(
@@ -418,7 +459,7 @@
var jsBreakpointIds = (params['hitBreakpoints'] as List).toSet();
if (jsBreakpointIds.isNotEmpty) {
var breakpointIds = jsBreakpointIds
- .map((id) => _breakpoints._dartIdByJsId[id])
+ .map((id) => _breakpoints._byJsId[id])
// In case the breakpoint was set in Chrome DevTools outside of
// package:dwds.
.where((entry) => entry != null)
@@ -516,103 +557,39 @@
/// Keeps track of the Dart and JS breakpoint Ids that correspond.
class _Breakpoints extends Domain {
- final Map<String, String> _dartIdByJsId = {};
- final Map<String, String> _jsIdByDartId = {};
+ final Map<String, String> _byJsId = {};
+ final Map<String, String> _byDartId = {};
- final Map<String, Future<Breakpoint>> _bpByDartId = {};
+ _Breakpoints(AppInspectorProvider provider) : super(provider);
- final Locations locations;
- final RemoteDebugger remoteDebugger;
-
- /// The root URI from which the application is served.
- final String root;
-
- _Breakpoints({
- @required this.locations,
- @required AppInspectorProvider provider,
- @required this.remoteDebugger,
- @required this.root,
- }) : super(provider);
-
- /// Adds a breakpoint at [scriptId] and [line] or returns an existing one
- /// if present.
+ /// Record the breakpoint.
///
- /// If a new breakpoint is created then [ifNew] is invoked with the
- /// breakpoint.
- Future<Breakpoint> add(String scriptId, int line,
- {void Function(Breakpoint) ifNew}) async {
- var id = 'bp/$scriptId#$line';
- var bp = await _bpByDartId.putIfAbsent(id, () async {
- var dartScript = await inspector.scriptWithId(scriptId);
- var dartUri = DartUri(dartScript.uri, root);
- var location = await locations.locationForDart(dartUri, line);
- // TODO: Handle cases where a breakpoint can't be set exactly at that line.
- if (location == null) {
- // ignore: only_throw_errors
- throw RPCError(
- 'addBreakpoint',
- 102,
- 'The VM is unable to add a breakpoint '
- 'at the specified line or function');
- }
-
- var dartBreakpoint = _dartBreakpoint(dartScript, location, id);
- var jsBreakpointId = await _setJsBreakpoint(location);
- _note(jsId: jsBreakpointId, bp: dartBreakpoint);
- ifNew(dartBreakpoint);
- return dartBreakpoint;
- });
- assert(bp.id == id);
- return bp;
- }
-
- /// Create a Dart breakpoint at [location] in [dartScript] with [id].
- Breakpoint _dartBreakpoint(
- ScriptRef dartScript, Location location, String id) {
- var breakpoint = Breakpoint()
- ..resolved = true
- ..id = id
- ..location = (SourceLocation()
- ..script = dartScript
- ..tokenPos = location.tokenPos);
- return breakpoint;
- }
-
- /// Calls the Chrome protocol setBreakpoint and returns the remote ID.
- Future<String> _setJsBreakpoint(Location location) async {
- // Location is 0 based according to:
- // https://chromedevtools.github.io/devtools-protocol/tot/Debugger#type-Location
- var response =
- await remoteDebugger.sendCommand('Debugger.setBreakpoint', params: {
- 'location': {
- 'scriptId': location.jsLocation.scriptId,
- 'lineNumber': location.jsLocation.line - 1,
- }
- });
- handleErrorIfPresent(response);
- return response.result['breakpointId'] as String;
- }
-
- /// Records the internal Dart <=> JS breakpoint id mapping and adds the
- /// breakpoint to the current isolates list of breakpoints.
- void _note({Breakpoint bp, String jsId}) {
- _dartIdByJsId[jsId] = bp.id;
- _jsIdByDartId[bp.id] = jsId;
+ /// Either [dartId] or the Dart breakpoint [bp] must be provided.
+ void noteBreakpoint({String js, String dartId, Breakpoint bp}) {
+ _byJsId[js] = dartId ?? bp?.id;
+ _byDartId[dartId ?? bp?.id] = js;
var isolate = inspector.isolate;
- isolate?.breakpoints?.add(bp);
+ if (bp != null) {
+ isolate?.breakpoints?.add(bp);
+ }
}
- Future<Breakpoint> remove({String js, String dartId}) async {
+ Breakpoint removeBreakpoint({String js, String dartId, Breakpoint bp}) {
var isolate = inspector.isolate;
- _dartIdByJsId.remove(js);
- _jsIdByDartId.remove(dartId);
- isolate?.breakpoints?.removeWhere((b) => b.id == dartId);
- return await _bpByDartId.remove(dartId);
+ _byJsId.remove(js);
+ _byDartId.remove(dartId ?? bp?.id);
+ Breakpoint dartBp;
+ // TODO: Do something better than the default throw when it's not found.
+ dartBp = bp ??
+ isolate.breakpoints
+ .firstWhere((b) => b.id == dartId, orElse: () => null);
+ isolate?.breakpoints?.remove(dartBp);
+ return dartBp;
}
- String dartId(String jsId) => _dartIdByJsId[jsId];
+ String dartId(String jsId) => _byJsId[jsId];
- String jsId(String dartId) => _jsIdByDartId[dartId];
+ String jsId(String dartId) => _byDartId[dartId];
}
final escapedPipe = '\$124';
diff --git a/dwds/lib/src/debugging/inspector.dart b/dwds/lib/src/debugging/inspector.dart
index 2148f7d..255c31c 100644
--- a/dwds/lib/src/debugging/inspector.dart
+++ b/dwds/lib/src/debugging/inspector.dart
@@ -6,23 +6,22 @@
import 'dart:convert';
import 'dart:io';
-import 'package:dwds/src/debugging/debugger.dart';
+import 'package:dwds/src/connections/app_connection.dart';
+import 'package:dwds/src/debugging/location.dart';
+import 'package:dwds/src/debugging/remote_debugger.dart';
import 'package:path/path.dart' as p;
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
import '../../asset_handler.dart';
-import '../connections/app_connection.dart';
-import '../debugging/location.dart';
-import '../debugging/remote_debugger.dart';
+import '../services/chrome_proxy_service.dart';
import '../utilities/conversions.dart';
import '../utilities/dart_uri.dart';
import '../utilities/domain.dart';
import '../utilities/shared.dart';
import '../utilities/wrapped_service.dart';
-import 'classes.dart';
import 'exceptions.dart';
import 'instance.dart';
-import 'libraries.dart';
+import 'metadata.dart';
/// An inspector for a running Dart application contained in the
/// [WipConnection].
@@ -30,9 +29,13 @@
/// Provides information about currently loaded scripts and objects and support
/// for eval.
class AppInspector extends Domain {
+ /// Map of class ID to [Class].
+ final _classes = <String, Class>{};
+
Future<List<ScriptRef>> _cachedScriptRefs;
- Future<List<ScriptRef>> get scriptRefs => _cachedScriptRefs ??= _getScripts();
+ Future<List<ScriptRef>> get _scriptRefs =>
+ _cachedScriptRefs ??= _getScripts();
/// Map of scriptRef ID to [ScriptRef].
final _scriptRefsById = <String, ScriptRef>{};
@@ -40,21 +43,22 @@
/// Map of Dart server path to [ScriptRef].
final _serverPathToScriptRef = <String, ScriptRef>{};
+ /// Map of library ID to [Library].
+ final _libraries = <String, Library>{};
+
+ /// Map of libraryRef ID to [LibraryRef].
+ final _libraryRefs = <String, LibraryRef>{};
+
/// Map of [ScriptRef] id to containing [LibraryRef] id.
final _scriptIdToLibraryId = <String, String>{};
- final RemoteDebugger remoteDebugger;
- final Debugger debugger;
- final Isolate isolate;
- final IsolateRef isolateRef;
- final AppConnection appConnection;
-
- final LibraryHelper libraryHelper;
- final ClassHelper classHelper;
- final InstanceHelper instanceHelper;
-
+ final RemoteDebugger _remoteDebugger;
final AssetHandler _assetHandler;
final Locations _locations;
+ final Isolate isolate;
+ final IsolateRef isolateRef;
+ final InstanceHelper instanceHelper;
+ final AppConnection appConnection;
/// The root URI from which the application is served.
final String _root;
@@ -62,14 +66,11 @@
AppInspector._(
this.appConnection,
this.isolate,
- this.remoteDebugger,
- this.debugger,
- this.libraryHelper,
- this.classHelper,
- this.instanceHelper,
this._assetHandler,
this._locations,
this._root,
+ this._remoteDebugger,
+ this.instanceHelper,
) : isolateRef = _toIsolateRef(isolate),
super.forInspector();
@@ -79,7 +80,7 @@
AppInspector get inspector => this;
Future<void> _initialize() async {
- var libraries = await libraryHelper.libraryRefs;
+ var libraries = await _getLibraryRefs();
isolate.libraries.addAll(libraries);
await DartUri.recordAbsoluteUris(libraries.map((lib) => lib.uri));
@@ -94,13 +95,13 @@
IsolateRef(id: isolate.id, name: isolate.name, number: isolate.number);
static Future<AppInspector> initialize(
- AppConnection appConnection,
- RemoteDebugger remoteDebugger,
- AssetHandler assetHandler,
- Locations locations,
- String root,
- Debugger debugger,
- ) async {
+ AppConnection appConnection,
+ RemoteDebugger remoteDebugger,
+ AssetHandler assetHandler,
+ Locations locations,
+ String root,
+ InstanceHelper instanceHelper,
+ String pauseMode) async {
var id = createId();
var time = DateTime.now().millisecondsSinceEpoch;
var name = '$root:main()';
@@ -118,27 +119,19 @@
livePorts: 0,
libraries: [],
breakpoints: [],
- exceptionPauseMode: debugger.pauseState)
+ exceptionPauseMode: pauseMode)
..extensionRPCs = [];
- AppInspector appInspector;
- var provider = () => appInspector;
- var libraryHelper = LibraryHelper(provider);
- var classHelper = ClassHelper(provider);
- var instanceHelper = InstanceHelper(provider);
- appInspector = AppInspector._(
+ var inspector = AppInspector._(
appConnection,
isolate,
- remoteDebugger,
- debugger,
- libraryHelper,
- classHelper,
- instanceHelper,
assetHandler,
locations,
root,
+ remoteDebugger,
+ instanceHelper,
);
- await appInspector._initialize();
- return appInspector;
+ await inspector._initialize();
+ return inspector;
}
/// Get the value of the field named [fieldName] from [receiver].
@@ -180,7 +173,7 @@
{bool returnByValue = false}) async {
var jsArguments = arguments.map(callArgumentFor).toList();
var result =
- await remoteDebugger.sendCommand('Runtime.callFunctionOn', params: {
+ await _remoteDebugger.sendCommand('Runtime.callFunctionOn', params: {
'functionDeclaration': evalExpression,
'arguments': jsArguments,
'objectId': receiver.objectId,
@@ -246,7 +239,7 @@
String expression, String libraryUri) {
var evalExpression = '''
(function() {
- ${getLibrarySnippet(libraryUri)};
+ ${_getLibrarySnippet(libraryUri)};
return library.$expression;
})();
''';
@@ -257,7 +250,7 @@
Future<RemoteObject> jsEvaluate(String expression) async {
// TODO(alanknight): Support a version with arguments if needed.
WipResponse result;
- result = await remoteDebugger
+ result = await _remoteDebugger
.sendCommand('Runtime.evaluate', params: {'expression': expression});
handleErrorIfPresent(result, evalContents: expression, additionalDetails: {
'Dart expression': expression,
@@ -271,7 +264,7 @@
Library library, String jsFunction, List<RemoteObject> arguments) async {
var findLibrary = '''
(function() {
- ${getLibrarySnippet(library.uri)};
+ ${_getLibrarySnippet(library.uri)};
return library;
})();
''';
@@ -287,7 +280,7 @@
var arguments = scope.values.map(remoteObjectFor).toList();
var evalExpression = '''
function($argsString) {
- ${getLibrarySnippet(library.uri)};
+ ${_getLibrarySnippet(library.uri)};
return library.$expression;
}
''';
@@ -296,16 +289,20 @@
Future<Library> _getLibrary(String isolateId, String objectId) async {
if (isolateId != isolate.id) return null;
- var libraryRef = await libraryHelper.libraryRefFor(objectId);
+ var libraryRef = _libraryRefs[objectId];
if (libraryRef == null) return null;
- return libraryHelper.libraryFor(libraryRef);
+ var library = _libraries[objectId];
+ if (library != null) return library;
+ library = await _constructLibrary(libraryRef);
+ _libraries[objectId] = library;
+ return library;
}
Future getObject(String isolateId, String objectId,
{int offset, int count}) async {
var library = await _getLibrary(isolateId, objectId);
if (library != null) return library;
- var clazz = await classHelper.forObjectId(objectId);
+ var clazz = _classes[objectId];
if (clazz != null) return clazz;
var scriptRef = _scriptRefsById[objectId];
if (scriptRef != null) return await _getScript(isolateId, scriptRef);
@@ -316,6 +313,132 @@
'are supported for getObject');
}
+ Future<Library> _constructLibrary(LibraryRef libraryRef) async {
+ // Fetch information about all the classes in this library.
+ var expression = '''
+ (function() {
+ ${_getLibrarySnippet(libraryRef.uri)}
+ var result = {};
+ var classes = Object.values(Object.getOwnPropertyDescriptors(library))
+ .filter((p) => 'value' in p)
+ .map((p) => p.value)
+ .filter((l) => l && sdkUtils.isType(l));
+ var classList = classes.map(function(clazz) {
+ var descriptor = {
+ 'name': clazz.name,
+ 'dartName': sdkUtils.typeName(clazz)
+ };
+ // TODO(jakemac): static methods once ddc supports them
+ var methods = sdkUtils.getMethods(clazz);
+ var methodNames = methods ? Object.keys(methods) : [];
+ descriptor['methods'] = {};
+ for (var name of methodNames) {
+ var method = methods[name];
+ descriptor['methods'][name] = {
+ // TODO(jakemac): how can we get actual const info?
+ "isConst": false,
+ "isStatic": false,
+ }
+ }
+
+ // TODO(jakemac): static fields once ddc supports them
+ var fields = sdkUtils.getFields(clazz);
+ var fieldNames = fields ? Object.keys(fields) : [];
+ descriptor['fields'] = {};
+ for (var name of fieldNames) {
+ var field = fields[name];
+ var libraryUri = Object.getOwnPropertySymbols(fields[name]["type"])
+ .find(x => x.description == "libraryUri");
+ descriptor['fields'][name] = {
+ // TODO(jakemac): how can we get actual const info?
+ "isConst": false,
+ "isFinal": field.isFinal,
+ "isStatic": false,
+ "classRefName": fields[name]["type"]["name"],
+ "classRefDartName": sdkUtils.typeName(fields[name]["type"]),
+ "classRefLibraryId" : field["type"][libraryUri],
+ }
+ }
+
+ return descriptor;
+ });
+ result['classes'] = classList;
+ return result;
+ })()
+ ''';
+ var result = await _remoteDebugger.sendCommand('Runtime.evaluate',
+ params: {'expression': expression, 'returnByValue': true});
+ handleErrorIfPresent(result, evalContents: expression);
+ var classDescriptors = (result.result['result']['value']['classes'] as List)
+ .cast<Map<String, Object>>();
+ var classRefs = <ClassRef>[];
+ for (var classDescriptor in classDescriptors) {
+ var classMetaData = ClassMetaData(
+ jsName: classDescriptor['name'] as String,
+ libraryId: libraryRef.id,
+ dartName: classDescriptor['dartName'] as String);
+ var classRef = ClassRef(name: classMetaData.jsName, id: classMetaData.id);
+ classRefs.add(classRef);
+
+ var methodRefs = <FuncRef>[];
+ var methodDescriptors =
+ classDescriptor['methods'] as Map<String, dynamic>;
+ methodDescriptors.forEach((name, descriptor) {
+ var methodId = '${classMetaData.id}:$name';
+ methodRefs.add(FuncRef(
+ id: methodId,
+ name: name,
+ owner: classRef,
+ isConst: descriptor['isConst'] as bool,
+ isStatic: descriptor['isStatic'] as bool));
+ });
+
+ var fieldRefs = <FieldRef>[];
+ var fieldDescriptors = classDescriptor['fields'] as Map<String, dynamic>;
+ fieldDescriptors.forEach((name, descriptor) async {
+ var classMetaData = ClassMetaData(
+ jsName: descriptor['classRefName'],
+ libraryId: descriptor['classRefLibraryId'],
+ dartName: descriptor['classRefDartName']);
+ fieldRefs.add(FieldRef(
+ name: name,
+ owner: classRef,
+ declaredType: InstanceRef(
+ id: createId(),
+ kind: InstanceKind.kType,
+ classRef:
+ ClassRef(name: classMetaData.jsName, id: classMetaData.id)),
+ isConst: descriptor['isConst'] as bool,
+ isFinal: descriptor['isFinal'] as bool,
+ isStatic: descriptor['isStatic'] as bool,
+ id: createId()));
+ });
+
+ // TODO: Implement the rest of these
+ // https://github.com/dart-lang/webdev/issues/176.
+ _classes[classMetaData.id] = Class(
+ name: classMetaData.jsName,
+ isAbstract: false,
+ isConst: false,
+ library: libraryRef,
+ interfaces: [],
+ fields: fieldRefs,
+ functions: methodRefs,
+ subclasses: [],
+ id: classMetaData.id);
+ }
+ return Library(
+ name: libraryRef.name,
+ uri: libraryRef.uri,
+ debuggable: true,
+ dependencies: [],
+ scripts: await _scriptRefs,
+ variables: [],
+ functions: [],
+ classes: classRefs,
+ id: libraryRef.id);
+ }
+
Future<Script> _getScript(String isolateId, ScriptRef scriptRef) async {
var libraryId = _scriptIdToLibraryId[scriptRef.id];
var serverPath = DartUri(scriptRef.uri, _root).serverPath;
@@ -325,9 +448,10 @@
}
var script = await response.readAsString();
return Script(
- uri: scriptRef.uri,
- library: await libraryHelper.libraryRefFor(libraryId),
- id: scriptRef.id)
+ uri: scriptRef.uri,
+ library: _libraryRefs[libraryId],
+ id: scriptRef.id,
+ )
..tokenPosTable = await _locations.tokenPosTableFor(serverPath)
..source = script;
}
@@ -344,7 +468,7 @@
/// All the scripts in the isolate.
Future<ScriptList> getScripts(String isolateId) async {
checkIsolate(isolateId);
- return ScriptList()..scripts = await scriptRefs;
+ return ScriptList()..scripts = await _scriptRefs;
}
Future<List<ScriptRef>> _getScripts() async {
@@ -374,7 +498,7 @@
return allScripts;
})()
''';
- var result = await remoteDebugger.sendCommand('Runtime.evaluate',
+ var result = await _remoteDebugger.sendCommand('Runtime.evaluate',
params: {'expression': expression, 'returnByValue': true});
handleErrorIfPresent(result, evalContents: expression);
var allScripts = result.result['result']['value'];
@@ -390,7 +514,7 @@
for (var part in parts)
ScriptRef(uri: p.url.join(parent, part), id: createId())
];
- var libraryRef = await libraryHelper.libraryRefFor(uri);
+ var libraryRef = _libraryRefs[uri];
for (var scriptRef in scriptRefs) {
_scriptRefsById[scriptRef.id] = scriptRef;
_scriptIdToLibraryId[scriptRef.id] = libraryRef.id;
@@ -404,13 +528,56 @@
Future<ScriptRef> scriptWithId(String scriptId) async =>
_scriptRefsById[scriptId];
+ /// Returns all libraryRefs in the app.
+ ///
+ /// Note this can return a cached result.
+ Future<List<LibraryRef>> _getLibraryRefs() async {
+ if (_libraryRefs.isNotEmpty) return _libraryRefs.values.toList();
+ var expression = '''
+ (function() {
+ $getLibraries
+ return libs;
+ })()
+ ''';
+ var librariesResult = await _remoteDebugger.sendCommand('Runtime.evaluate',
+ params: {'expression': expression, 'returnByValue': true});
+ handleErrorIfPresent(librariesResult, evalContents: expression);
+ var libraries =
+ List<String>.from(librariesResult.result['result']['value'] as List);
+ // Filter out any non-Dart libraries, which basically means the .bootstrap
+ // library from build_web_runners.
+ var dartLibraries = libraries
+ .where((name) => name.startsWith('dart:') || name.endsWith('.dart'));
+ for (var library in dartLibraries) {
+ var ref = LibraryRef(id: library, name: library, uri: library);
+ _libraryRefs[ref.id] = ref;
+ }
+ return _libraryRefs.values.toList();
+ }
+
/// Runs an eval on the page to compute all existing registered extensions.
Future<List<String>> _getExtensionRpcs() async {
var expression =
"$loadModule('dart_sdk').developer._extensions.keys.toList();";
- var extensionsResult = await remoteDebugger.sendCommand('Runtime.evaluate',
+ var extensionsResult = await _remoteDebugger.sendCommand('Runtime.evaluate',
params: {'expression': expression, 'returnByValue': true});
handleErrorIfPresent(extensionsResult, evalContents: expression);
return List.from(extensionsResult.result['result']['value'] as List);
}
}
+
+/// Creates a snippet of JS code that initializes a `library` variable that has
+/// the actual library object in DDC for [libraryUri].
+///
+/// In DDC we have module libraries indexed by names of the form
+/// 'packages/package/mainFile' with no .dart suffix on the file, or
+/// 'directory/packageName/mainFile', also with no .dart suffix, and relative to
+/// the serving root, normally /web within the package. These modules have a map
+/// from the URI with a Dart-specific scheme (package: or org-dartlang-app:) to
+/// the library objects. The [libraryUri] parameter should be one of these
+/// Dart-specific scheme URIs, and we set `library` the corresponding library.
+String _getLibrarySnippet(String libraryUri) => '''
+ var sdkUtils = $loadModule('dart_sdk').dart;
+ var library = sdkUtils.getLibrary('$libraryUri');
+ if (!library) throw 'cannot find library for $libraryUri';
+ ''';
diff --git a/dwds/lib/src/debugging/instance.dart b/dwds/lib/src/debugging/instance.dart
index 7c02960..2952cec 100644
--- a/dwds/lib/src/debugging/instance.dart
+++ b/dwds/lib/src/debugging/instance.dart
@@ -9,26 +9,48 @@
import '../utilities/objects.dart';
import '../utilities/shared.dart';
import '../utilities/wrapped_service.dart';
-import 'classes.dart';
+import 'debugger.dart';
import 'inspector.dart';
import 'metadata.dart';
+import 'remote_debugger.dart';
/// Creates an [InstanceRef] for a primitive [RemoteObject].
InstanceRef _primitiveInstance(String kind, RemoteObject remoteObject) {
- var classRef = classRefFor('dart:core', kind);
+ var classRef = ClassRef(
+ // TODO(grouma) - is this ID correct?
+ id: 'dart:core:${remoteObject?.type}',
+ name: kind);
return InstanceRef(
kind: kind, classRef: classRef, id: dartIdFor(remoteObject?.value))
..valueAsString = '${remoteObject?.value}';
}
+/// A hard-coded ClassRef for the String class.
+final _classRefForString =
+ ClassRef(id: 'dart:core:String', name: InstanceKind.kString);
+
+/// A hard-coded ClassRef for the Closure class.
+// TODO(grouma) - orgnaize our static classRefs better.
+final _classRefForClosure = ClassRef(name: 'Closure', id: createId());
+
+/// A hard-coded ClassRef for a (non-existent) class called Unknown.
+final _classRefForUnknown = ClassRef(name: 'Unknown', id: createId());
+
/// Contains a set of methods for getting [Instance]s and [InstanceRef]s.
class InstanceHelper extends Domain {
- InstanceHelper(AppInspector Function() provider) : super(provider);
+ final Debugger _debugger;
+ final RemoteDebugger _remoteDebugger;
+
+ InstanceHelper(
+ this._debugger, this._remoteDebugger, AppInspector Function() provider)
+ : super(provider);
Future<Instance> _stringInstanceFor(RemoteObject remoteObject) async {
var actualString = stringFromDartId(remoteObject.objectId);
return Instance(
- kind: InstanceKind.kString, classRef: classRefForString, id: createId())
+ kind: InstanceKind.kString,
+ classRef: _classRefForString,
+ id: createId())
..valueAsString = actualString
..length = actualString.length;
}
@@ -37,7 +59,7 @@
var result = Instance(
kind: InstanceKind.kClosure,
id: remoteObject.objectId,
- classRef: classRefForClosure);
+ classRef: _classRefForClosure);
return result;
}
@@ -50,13 +72,12 @@
return _stringInstanceFor(remoteObject);
}
var metaData = await ClassMetaData.metaDataFor(
- inspector.remoteDebugger, remoteObject, inspector);
+ _remoteDebugger, remoteObject, inspector);
var classRef = metaData.classRef;
if (metaData.jsName == 'Function') {
return _closureInstanceFor(remoteObject);
}
- var properties =
- await inspector.debugger.getProperties(remoteObject.objectId);
+ var properties = await _debugger.getProperties(remoteObject.objectId);
if (metaData.jsName == 'JSArray') {
return await _listInstanceFor(classRef, remoteObject, properties);
} else if (metaData.jsName == 'LinkedMap' ||
@@ -106,38 +127,28 @@
/// The associations for a Dart Map or IdentityMap.
Future<List<MapAssociation>> _mapAssociations(RemoteObject map) async {
- // We do this in in awkward way because we want the keys and values, but we
- // can't return things by value or some Dart objects will come back as
- // values that we need to be RemoteObject, e.g. a List of int.
var expression = '''
function() {
var sdkUtils = $loadModule('dart_sdk').dart;
var entries = sdkUtils.dloadRepl(this, "entries");
entries = sdkUtils.dsendRepl(entries, "toList", []);
- function asKey(entry) {
- return sdkUtils.dloadRepl(entry, "key");
+ function asKeyValue(entry) {
+ return {
+ key: sdkUtils.dloadRepl(entry, "key"),
+ value: sdkUtils.dloadRepl(entry, "value")
+ }
}
- function asValue(entry) {
- return sdkUtils.dloadRepl(entry, "value");
- }
- return {
- keys: entries.map(asKey),
- values: entries.map(asValue)
- };
+ return entries.map(asKeyValue);
}
''';
- var keysAndValues = await inspector.jsCallFunctionOn(map, expression, []);
- var keys = await inspector.loadField(keysAndValues, 'keys');
- var values = await inspector.loadField(keysAndValues, 'values');
- var keysInstance = await instanceFor(keys);
- var valuesInstance = await instanceFor(values);
+ var keysAndValues = await inspector.jsCallFunctionOn(map, expression, [],
+ returnByValue: true);
var associations = <MapAssociation>[];
- Map.fromIterables(keysInstance.elements, valuesInstance.elements)
- .forEach((key, value) {
+ for (var each in keysAndValues.value as List) {
associations.add(MapAssociation()
- ..key = key
- ..value = value);
- });
+ ..key = await instanceRefFor(each['key'])
+ ..value = await instanceRefFor(each['value']));
+ }
return associations;
}
@@ -194,12 +205,12 @@
const sdk = $loadModule("dart_sdk");
const sdk_utils = sdk.dart;
const fields = sdk_utils.getFields(sdk_utils.getType(this)) || [];
- if (!fields && (dart_sdk._interceptors.JSArray.is(this) ||
+ if (!fields && (dart_sdk._interceptors.JSArray.is(this) ||
dart_sdk._js_helper.InternalMap.is(this))) {
// Trim off the 'length' property.
const fields = allJsProperties.slice(0, allJsProperties.length -1);
return fields.join(',');
- }
+ }
const privateFields = sdk_utils.getOwnPropertySymbols(fields);
const nonSymbolNames = privateFields.map(sym => sym.description);
const publicFieldNames = sdk_utils.getOwnPropertyNames(fields);
@@ -246,7 +257,7 @@
case 'string':
return InstanceRef(
id: dartIdFor(remoteObject.value),
- classRef: classRefForString,
+ classRef: _classRefForString,
kind: InstanceKind.kString)
..valueAsString = remoteObject.value as String;
case 'number':
@@ -260,7 +271,7 @@
return _primitiveInstance(InstanceKind.kNull, remoteObject);
}
var metaData = await ClassMetaData.metaDataFor(
- inspector.remoteDebugger, remoteObject, inspector);
+ _remoteDebugger, remoteObject, inspector);
if (metaData == null) return null;
if (metaData.jsName == 'JSArray') {
return InstanceRef(
@@ -282,18 +293,18 @@
id: remoteObject.objectId,
classRef: metaData.classRef);
case 'function':
- var functionMetaData = await FunctionMetaData.metaDataFor(
- inspector.remoteDebugger, remoteObject);
+ var functionMetaData =
+ await FunctionMetaData.metaDataFor(_remoteDebugger, remoteObject);
return InstanceRef(
kind: InstanceKind.kClosure,
id: remoteObject.objectId,
- classRef: classRefForClosure)
+ classRef: _classRefForClosure)
// TODO(grouma) - fill this in properly.
..closureFunction = FuncRef(
name: functionMetaData.name,
id: createId(),
// TODO(alanknight): The right ClassRef
- owner: classRefForUnknown,
+ owner: _classRefForUnknown,
isConst: false,
isStatic: false)
..closureContext = (ContextRef()..length = 0);
diff --git a/dwds/lib/src/debugging/libraries.dart b/dwds/lib/src/debugging/libraries.dart
deleted file mode 100644
index 1fab235..0000000
--- a/dwds/lib/src/debugging/libraries.dart
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.import 'dart:async';
-
-import 'package:dwds/src/debugging/inspector.dart';
-
-import '../utilities/domain.dart';
-import '../utilities/shared.dart';
-import '../utilities/wrapped_service.dart';
-import 'metadata.dart';
-
-/// Keeps track of Dart libraries available in the running application.
-class LibraryHelper extends Domain {
- /// Map of library ID to [Library].
- final _librariesById = <String, Library>{};
-
- /// Map of libraryRef ID to [LibraryRef].
- final _libraryRefsById = <String, LibraryRef>{};
-
- LibraryHelper(AppInspector Function() provider) : super(provider);
-
- /// Returns all libraryRefs in the app.
- ///
- /// Note this can return a cached result.
- Future<List<LibraryRef>> get libraryRefs async {
- if (_libraryRefsById.isNotEmpty) return _libraryRefsById.values.toList();
- var expression = '''
- (function() {
- $getLibraries
- return libs;
- })()
- ''';
- var result = await inspector.remoteDebugger.sendCommand('Runtime.evaluate',
- params: {'expression': expression, 'returnByValue': true});
- handleErrorIfPresent(result, evalContents: expression);
- var libraries = List<String>.from(result.result['result']['value'] as List);
- // Filter out any non-Dart libraries, which basically means the .bootstrap
- // library from build_web_runners.
- var dartLibraries = libraries
- .where((name) => name.startsWith('dart:') || name.endsWith('.dart'));
- for (var library in dartLibraries) {
- var ref = LibraryRef(id: library, name: library, uri: library);
- _libraryRefsById[ref.id] = ref;
- }
- return _libraryRefsById.values.toList();
- }
-
- Future<Library> libraryFor(LibraryRef libraryRef) async {
- var library = _librariesById[libraryRef.id];
- if (library != null) return library;
- return _librariesById[libraryRef.id] = await _constructLibrary(libraryRef);
- }
-
- Future<LibraryRef> libraryRefFor(String objectId) async {
- if (_libraryRefsById.isEmpty) await libraryRefs;
- return _libraryRefsById[objectId];
- }
-
- Future<Library> _constructLibrary(LibraryRef libraryRef) async {
- // Fetch information about all the classes in this library.
- var expression = '''
- (function() {
- ${getLibrarySnippet(libraryRef.uri)}
- var result = {};
- var classes = Object.values(Object.getOwnPropertyDescriptors(library))
- .filter((p) => 'value' in p)
- .map((p) => p.value)
- .filter((l) => l && sdkUtils.isType(l));
- var classList = classes.map(function(clazz) {
- var descriptor = {
- 'name': clazz.name,
- 'dartName': sdkUtils.typeName(clazz)
- };
- return descriptor;
- });
- result['classes'] = classList;
- return result;
- })()
- ''';
- var result = await inspector.remoteDebugger.sendCommand('Runtime.evaluate',
- params: {'expression': expression, 'returnByValue': true});
- handleErrorIfPresent(result, evalContents: expression);
- var classDescriptors = (result.result['result']['value']['classes'] as List)
- .cast<Map<String, Object>>();
- var classRefs = classDescriptors.map<ClassRef>((classDescriptor) {
- var classMetaData = ClassMetaData(
- jsName: classDescriptor['name'],
- libraryId: libraryRef.id,
- dartName: classDescriptor['dartName']);
- return classMetaData.classRef;
- }).toList();
- return Library(
- name: libraryRef.name,
- uri: libraryRef.uri,
- debuggable: true,
- dependencies: [],
- scripts: await inspector.scriptRefs,
- variables: [],
- functions: [],
- classes: classRefs,
- id: libraryRef.id);
- }
-}
diff --git a/dwds/lib/src/debugging/metadata.dart b/dwds/lib/src/debugging/metadata.dart
index ebc14b8..16c04dc 100644
--- a/dwds/lib/src/debugging/metadata.dart
+++ b/dwds/lib/src/debugging/metadata.dart
@@ -4,7 +4,6 @@
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
-import '../debugging/classes.dart';
import '../debugging/inspector.dart';
import '../services/chrome_proxy_service.dart';
import '../utilities/shared.dart';
@@ -55,7 +54,7 @@
const classObject = sdkUtils.getReifiedType(arg);
const isFunction = sdkUtils.AbstractFunctionType.is(classObject);
const result = {};
- result['name'] = isFunction ? 'Function' : classObject.name;
+ result['name'] = isFunction ? 'Function' : classObject.name;
result['dartName'] = sdkUtils.typeName(classObject);
result['length'] = arg['length'];
result['libraryId'] = sdkUtils.getLibraryUri(classObject);
@@ -77,7 +76,7 @@
}
/// Return a [ClassRef] appropriate to this metadata.
- ClassRef get classRef => classRefFor(libraryId, dartName);
+ ClassRef get classRef => ClassRef(name: dartName, id: id);
}
/// Meta data for a remote Dart function in Chrome.
diff --git a/dwds/lib/src/debugging/modules.dart b/dwds/lib/src/debugging/modules.dart
index cdfa9a5..f43f9c5 100644
--- a/dwds/lib/src/debugging/modules.dart
+++ b/dwds/lib/src/debugging/modules.dart
@@ -6,8 +6,8 @@
import 'package:path/path.dart' as p;
+import '../services/chrome_proxy_service.dart';
import '../utilities/dart_uri.dart';
-import '../utilities/shared.dart';
import 'remote_debugger.dart';
/// Contains meta data and helpful methods for DDC modules.
@@ -25,6 +25,8 @@
final _moduleExtensionCompleter = Completer<String>();
+ var _initializedCompleter = Completer();
+
Modules(this._remoteDebugger, this._root);
/// Completes with the module extension i.e. `.ddc.js` or `.ddk.js`.
@@ -38,9 +40,8 @@
/// Intended to be called multiple times throughout the development workflow,
/// e.g. after a hot-reload.
void initialize() {
- // We only clear the source to module mapping as script IDs may persist
- // across hot reloads.
- _sourceToModule.clear();
+ _initializedCompleter = Completer();
+ _initializeMapping();
}
/// Returns the module for the Chrome script ID.
@@ -53,32 +54,29 @@
/// Returns the containing module for the provided Dart server path.
Future<String> moduleForSource(String serverPath) async {
- if (_sourceToModule.isEmpty) {
- await _initializeMapping();
- }
+ await _initializedCompleter.future;
return _sourceToModule[serverPath];
}
/// Checks if the [url] correspond to a module and stores meta data.
Future<Null> noteModule(String url, String scriptId) async {
- var path = Uri.parse(url).path;
- if (path == null ||
- !(path.endsWith('.ddc.js') || path.endsWith('.ddk.js'))) {
+ if (url == null || !(url.endsWith('.ddc.js') || url.endsWith('.ddk.js'))) {
return;
}
// TODO(grouma) - This is wonky. Find a better way.
if (!_moduleExtensionCompleter.isCompleted) {
- if (path.endsWith('.ddc.js')) {
+ if (url.endsWith('.ddc.js')) {
_moduleExtensionCompleter.complete('.ddc.js');
} else {
_moduleExtensionCompleter.complete('.ddk.js');
}
}
- var module =
- // Remove the DDC extension (e.g. .ddc.js) from the path.
- _moduleFor(p.withoutExtension(p.withoutExtension(path)));
+ // Remove the DDC extension (e.g. .ddc.js) from the path.
+ var module = p
+ .withoutExtension(p.withoutExtension(Uri.parse(url).path))
+ .substring(1);
_scriptIdToModule[scriptId] = module;
_moduleToScriptId[module] = scriptId;
@@ -88,7 +86,7 @@
Future<void> _initializeMapping() async {
var expression = '''
(function() {
- var dart = $loadModule('dart_sdk').dart;
+ var dart = require('dart_sdk').dart;
var result = {};
dart.getModuleNames().forEach(function(module){
Object.keys(dart.getModuleLibraries(module)).forEach(
@@ -105,38 +103,20 @@
var value = response.result['result']['value'] as Map<String, dynamic>;
for (var dartScript in value.keys) {
if (!dartScript.endsWith('.dart')) continue;
- _sourceToModule[DartUri(dartScript, _root).serverPath] = _moduleFor(
- value[dartScript] as String,
- skipRoot: dartScript.startsWith('org-dartlang-app:///'));
- }
- }
-
- /// Returns the module for the provided path.
- ///
- /// Module are of the following form:
- ///
- /// packages/foo/bar/module
- /// some/root/bar/module
- ///
- String _moduleFor(String path, {bool skipRoot}) {
- skipRoot ??= false;
- var result = '';
- if (path.contains('/packages/')) {
- result = 'packages/${path.split('/packages/').last}';
- } else if (path.contains('/lib/')) {
- var splitModule = path.split('/lib/').first.substring(1).split('/');
- // Special case third_party/dart for Google3.
- if (path.startsWith('/third_party/dart/')) {
- splitModule = splitModule.skip(2).toList();
+ var scriptUri = Uri.parse(dartScript);
+ var moduleUri = Uri.parse(value[dartScript] as String);
+ // The module uris returned by the expression contain the root. Rewrite
+ // the uris so that DartUri properly accounts for this fact.
+ if (scriptUri.scheme == 'org-dartlang-app') {
+ moduleUri = moduleUri.replace(scheme: 'org-dartlang-app');
+ } else if (scriptUri.scheme == 'package') {
+ moduleUri = moduleUri.replace(
+ scheme: 'package', path: moduleUri.path.split('/packages/').last);
}
- result = 'packages/${splitModule.join(".")}/${p.basename(path)}';
- } else if (path.startsWith('/')) {
- path = path.substring(1);
- if (skipRoot) {
- path = path.split('/').skip(1).join('/');
- }
- result = path;
+ // TODO(grouma) - handle G3 scheme.
+ _sourceToModule[DartUri(dartScript, _root).serverPath] =
+ DartUri(moduleUri.toString()).serverPath;
}
- return result;
+ _initializedCompleter.complete();
}
}
diff --git a/dwds/lib/src/services/chrome_proxy_service.dart b/dwds/lib/src/services/chrome_proxy_service.dart
index 3796e54..1796714 100644
--- a/dwds/lib/src/services/chrome_proxy_service.dart
+++ b/dwds/lib/src/services/chrome_proxy_service.dart
@@ -15,6 +15,7 @@
import '../connections/app_connection.dart';
import '../debugging/debugger.dart';
import '../debugging/inspector.dart';
+import '../debugging/instance.dart';
import '../debugging/location.dart';
import '../debugging/modules.dart';
import '../debugging/remote_debugger.dart';
@@ -53,7 +54,7 @@
final RemoteDebugger remoteDebugger;
/// Provides debugger-related functionality.
- Future<Debugger> get _debugger => _debuggerCompleter.future;
+ Future<Debugger> get debugger => _debuggerCompleter.future;
final AssetHandler _assetHandler;
@@ -127,7 +128,10 @@
_locations.clearCache();
_modules.initialize();
- (await _debugger).notifyPausedAtStart();
+ (await debugger).notifyPausedAtStart();
+
+ var instanceHelper =
+ InstanceHelper(await debugger, remoteDebugger, appInspectorProvider);
_inspector = await AppInspector.initialize(
appConnection,
@@ -135,11 +139,12 @@
_assetHandler,
_locations,
uri,
- await _debugger,
+ instanceHelper,
+ (await debugger).pauseState,
);
unawaited(appConnection.onStart.then((_) async {
- await (await _debugger).resumeFromStart();
+ await (await debugger).resumeFromStart();
}));
var isolateRef = _inspector.isolateRef;
@@ -201,8 +206,7 @@
@override
Future<Breakpoint> addBreakpoint(String isolateId, String scriptId, int line,
{int column}) async =>
- (await _debugger)
- .addBreakpoint(isolateId, scriptId, line, column: column);
+ (await debugger).addBreakpoint(isolateId, scriptId, line, column: column);
@override
Future<Breakpoint> addBreakpointAtEntry(String isolateId, String functionId) {
@@ -215,7 +219,7 @@
{int column}) async {
var dartUri = DartUri(scriptUri, uri);
var ref = await _inspector.scriptRefFor(dartUri.serverPath);
- return (await _debugger)
+ return (await debugger)
.addBreakpoint(isolateId, ref.id, line, column: column);
}
@@ -325,7 +329,7 @@
/// Returns null if the corresponding isolate is not paused.
@override
Future<Stack> getStack(String isolateId) async =>
- (await _debugger).getStack(isolateId);
+ (await debugger).getStack(isolateId);
@override
Future<VM> getVM() async {
@@ -405,7 +409,7 @@
}
@override
- Future<Success> pause(String isolateId) async => (await _debugger).pause();
+ Future<Success> pause(String isolateId) async => (await debugger).pause();
@override
Future<Success> registerService(String service, String alias) async {
@@ -421,13 +425,13 @@
@override
Future<Success> removeBreakpoint(
String isolateId, String breakpointId) async =>
- (await _debugger).removeBreakpoint(isolateId, breakpointId);
+ (await debugger).removeBreakpoint(isolateId, breakpointId);
@override
Future<Success> resume(String isolateId,
{String step, int frameIndex}) async {
if (_inspector.appConnection.isStarted) {
- return await (await _debugger)
+ return await (await debugger)
.resume(isolateId, step: step, frameIndex: frameIndex);
} else {
_inspector.appConnection.runMain();
@@ -437,7 +441,7 @@
@override
Future<Success> setExceptionPauseMode(String isolateId, String mode) async =>
- (await _debugger).setExceptionPauseMode(isolateId, mode);
+ (await debugger).setExceptionPauseMode(isolateId, mode);
@override
Future<Success> setFlag(String name, String value) {
@@ -630,6 +634,19 @@
/// The `type`s of [ConsoleAPIEvent]s that are treated as `stdout` logs.
const _stdoutTypes = ['log', 'info', 'warning'];
+/// Throws an [ExceptionDetails] object if `exceptionDetails` is present on the
+/// result.
+void handleErrorIfPresent(WipResponse response,
+ {String evalContents, Object additionalDetails}) {
+ if (response == null) return;
+ if (response.result.containsKey('exceptionDetails')) {
+ throw ChromeDebugException(
+ response.result['exceptionDetails'] as Map<String, dynamic>,
+ evalContents: evalContents,
+ additionalDetails: additionalDetails);
+ }
+}
+
class ChromeDebugException extends ExceptionDetails implements Exception {
/// Optional, additional information about the exception.
final Object additionalDetails;
diff --git a/dwds/lib/src/utilities/shared.dart b/dwds/lib/src/utilities/shared.dart
index c0f802b..7a9a881 100644
--- a/dwds/lib/src/utilities/shared.dart
+++ b/dwds/lib/src/utilities/shared.dart
@@ -4,9 +4,8 @@
import 'dart:io';
-import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
+import 'package:dwds/dwds.dart' show ModuleStrategy;
-import '../../dwds.dart' show ChromeDebugException, ModuleStrategy;
import '../utilities/wrapped_service.dart';
VMRef toVMRef(VM vm) => VMRef()..name = vm.name;
@@ -58,32 +57,3 @@
return expression +=
"let libs = $loadModule('dart_sdk').dart.getLibraries();\n";
}
-
-/// Creates a snippet of JS code that initializes a `library` variable that has
-/// the actual library object in DDC for [libraryUri].
-///
-/// In DDC we have module libraries indexed by names of the form
-/// 'packages/package/mainFile' with no .dart suffix on the file, or
-/// 'directory/packageName/mainFile', also with no .dart suffix, and relative to
-/// the serving root, normally /web within the package. These modules have a map
-/// from the URI with a Dart-specific scheme (package: or org-dartlang-app:) to
-/// the library objects. The [libraryUri] parameter should be one of these
-/// Dart-specific scheme URIs, and we set `library` the corresponding library.
-String getLibrarySnippet(String libraryUri) => '''
- var sdkUtils = $loadModule('dart_sdk').dart;
- var library = sdkUtils.getLibrary('$libraryUri');
- if (!library) throw 'cannot find library for $libraryUri';
- ''';
-
-/// Throws an [ExceptionDetails] object if `exceptionDetails` is present on the
-/// result.
-void handleErrorIfPresent(WipResponse response,
- {String evalContents, Object additionalDetails}) {
- if (response == null) return;
- if (response.result.containsKey('exceptionDetails')) {
- throw ChromeDebugException(
- response.result['exceptionDetails'] as Map<String, dynamic>,
- evalContents: evalContents,
- additionalDetails: additionalDetails);
- }
-}
diff --git a/dwds/pubspec.yaml b/dwds/pubspec.yaml
index 6b50bb0..9e2c904 100644
--- a/dwds/pubspec.yaml
+++ b/dwds/pubspec.yaml
@@ -1,5 +1,5 @@
name: dwds
-version: 0.7.6
+version: 0.7.5
author: Dart Team <misc@dartlang.org>
homepage: https://github.com/dart-lang/webdev/tree/master/dwds
description: >-
diff --git a/fixnum/.travis.yml b/fixnum/.travis.yml
index 88939f9..7a04dbd 100644
--- a/fixnum/.travis.yml
+++ b/fixnum/.travis.yml
@@ -1,7 +1,7 @@
language: dart
dart:
- - 2.1.1
+ - stable
- dev
dart_task:
@@ -9,12 +9,7 @@
xvfb: false
- test: --platform chrome
- dartanalyzer: --fatal-warnings --fatal-infos .
-
-matrix:
- include:
- # Only validate formatting using the dev release
- - dart: dev
- dart_task: dartfmt
+ - dartfmt
# Only building master means that we don't run two builds for each pull request.
branches:
diff --git a/fixnum/BUILD.gn b/fixnum/BUILD.gn
index 080c0af..58f48b9 100644
--- a/fixnum/BUILD.gn
+++ b/fixnum/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for fixnum-0.10.11
+# This file is generated by importer.py for fixnum-0.10.9
import("//build/dart/dart_library.gni")
diff --git a/fixnum/CHANGELOG.md b/fixnum/CHANGELOG.md
index 3359d0a..9cfc509 100644
--- a/fixnum/CHANGELOG.md
+++ b/fixnum/CHANGELOG.md
@@ -1,13 +1,3 @@
-## 0.10.11
-
-* Update minimum SDK constraint to version 2.1.1.
-
-## 0.10.10
-
-* Fix `Int64` parsing to throw `FormatException` on an empty string or single
- minus sign. Previous incorrect behaviour was to throw a `RangeError` or
- silently return zero.
-
## 0.10.9
* Add `Int64.toStringUnsigned()` and `Int64.toRadixStringUnsigned()` functions.
diff --git a/fixnum/README.md b/fixnum/README.md
index cfb3164..3e6af18 100644
--- a/fixnum/README.md
+++ b/fixnum/README.md
@@ -1,3 +1,6 @@
+Fixnum
+======
+
A fixed-width 32- and 64- bit integer library for Dart.
[![Build Status](https://travis-ci.org/dart-lang/fixnum.svg?branch=master)](https://travis-ci.org/dart-lang/fixnum)
@@ -10,5 +13,5 @@
whether executed on the Dart VM or compiled to JavaScript.
For more information, see the
-[fixnum package](https://pub.dev/packages/fixnum) on
-[pub.dev](https://pub.dev/).
+[fixnum package](http://pub.dartlang.org/packages/fixnum) on
+[pub.dartlang.org](http://pub.dartlang.org).
diff --git a/fixnum/analysis_options.yaml b/fixnum/analysis_options.yaml
index 6ddb107..8ef67de 100644
--- a/fixnum/analysis_options.yaml
+++ b/fixnum/analysis_options.yaml
@@ -1,7 +1,4 @@
include: package:pedantic/analysis_options.yaml
-analyzer:
- strong-mode:
- implicit-casts: false
linter:
rules:
#- annotate_overrides
@@ -41,13 +38,14 @@
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_final_fields
- - prefer_generic_function_type_aliases
- prefer_initializing_formals
- prefer_interpolation_to_compose_strings
#- prefer_single_quotes
- prefer_typing_uninitialized_variables
- slash_for_doc_comments
- test_types_in_equals
+ - super_goes_last
+ - test_types_in_equals
- throw_in_finally
- type_init_formals
- unnecessary_brace_in_string_interps
diff --git a/fixnum/codereview.settings b/fixnum/codereview.settings
new file mode 100644
index 0000000..25faff7
--- /dev/null
+++ b/fixnum/codereview.settings
@@ -0,0 +1,3 @@
+CODE_REVIEW_SERVER: http://codereview.chromium.org/
+VIEW_VC: https://github.com/dart-lang/fixnum/commit/
+CC_LIST: reviews@dartlang.org
diff --git a/fixnum/lib/fixnum.dart b/fixnum/lib/fixnum.dart
index 72f9742..6d08ba8 100644
--- a/fixnum/lib/fixnum.dart
+++ b/fixnum/lib/fixnum.dart
@@ -6,6 +6,10 @@
///
/// The integer implementations in this library are designed to work
/// identically whether executed on the Dart VM or compiled to JavaScript.
+///
+/// For information on installing and importing this library, see the
+/// [fixnum package on pub.dartlang.org]
+/// (http://pub.dartlang.org/packages/fixnum).
library fixnum;
part 'src/intx.dart';
diff --git a/fixnum/lib/src/int32.dart b/fixnum/lib/src/int32.dart
index 3a9d017..f3cc72c 100644
--- a/fixnum/lib/src/int32.dart
+++ b/fixnum/lib/src/int32.dart
@@ -61,7 +61,7 @@
if (digit < 0 || digit >= radix) {
throw FormatException("Non-radix code unit: $c");
}
- x = ((x * radix) + digit) as Int32;
+ x = (x * radix) + digit;
}
return x;
}
@@ -189,7 +189,7 @@
Int64 t = this.toInt64();
return (t - (t ~/ other) * other).toInt32();
}
- return (this - (this ~/ other) * other) as Int32;
+ return this - (this ~/ other) * other;
}
Int32 operator &(other) {
diff --git a/fixnum/lib/src/int64.dart b/fixnum/lib/src/int64.dart
index 3453a09..a1109c0 100644
--- a/fixnum/lib/src/int64.dart
+++ b/fixnum/lib/src/int64.dart
@@ -59,17 +59,10 @@
static Int64 _parseRadix(String s, int radix) {
int i = 0;
bool negative = false;
- if (i < s.length && s[0] == '-') {
+ if (s[0] == '-') {
negative = true;
i++;
}
-
- // TODO(https://github.com/dart-lang/sdk/issues/38728). Replace with "if (i
- // >= s.length)".
- if (!(i < s.length)) {
- throw FormatException("No digits in '$s'");
- }
-
int d0 = 0, d1 = 0, d2 = 0; // low, middle, high components.
for (; i < s.length; i++) {
int c = s.codeUnitAt(i);
diff --git a/fixnum/pubspec.yaml b/fixnum/pubspec.yaml
index a08ee33..db003b8 100644
--- a/fixnum/pubspec.yaml
+++ b/fixnum/pubspec.yaml
@@ -1,13 +1,13 @@
name: fixnum
-version: 0.10.11
+version: 0.10.9
description: Library for 32- and 64-bit signed fixed-width integers.
author: Dart Team <misc@dartlang.org>
homepage: https://github.com/dart-lang/fixnum
environment:
- sdk: '>=2.1.1 <3.0.0'
+ sdk: '>=2.0.0 <3.0.0'
dev_dependencies:
- pedantic: ^1.8.0
+ pedantic: ^1.3.0
test: ^1.2.0
diff --git a/source_gen/BUILD.gn b/source_gen/BUILD.gn
deleted file mode 100644
index 6f0367f..0000000
--- a/source_gen/BUILD.gn
+++ /dev/null
@@ -1,25 +0,0 @@
-# This file is generated by importer.py for source_gen-0.9.4+4
-
-import("//build/dart/dart_library.gni")
-
-dart_library("source_gen") {
- package_name = "source_gen"
-
- # This parameter is left empty as we don't care about analysis or exporting
- # these sources outside of the tree.
- sources = []
-
- disable_analysis = true
-
- deps = [
- "//third_party/dart-pkg/pub/pedantic",
- "//third_party/dart-pkg/pub/async",
- "//third_party/dart-pkg/pub/glob",
- "//third_party/dart-pkg/pub/analyzer",
- "//third_party/dart-pkg/pub/meta",
- "//third_party/dart-pkg/pub/build",
- "//third_party/dart-pkg/pub/path",
- "//third_party/dart-pkg/pub/source_span",
- "//third_party/dart-pkg/pub/dart_style",
- ]
-}
diff --git a/source_gen/CHANGELOG.md b/source_gen/CHANGELOG.md
deleted file mode 100644
index fb1b9da..0000000
--- a/source_gen/CHANGELOG.md
+++ /dev/null
@@ -1,654 +0,0 @@
-## 0.9.4+4
-
-* Allow `pkg:analyzer` version `0.38.x`.
-
-## 0.9.4+3
-
-* Allow `pkg:analyzer` version `0.37.x`.
-
-## 0.9.4+2
-
-* Allow `pkg:analyzer` version `0.36.x`.
-
-## 0.9.4+1
-
-* Support the latest `pkg:analyzer`.
-
-## 0.9.4
-
-* Use `ParsedLibraryResult` to find source spans for unresolvable annotations.
-
-## 0.9.3
-
-* Rename `LibraryReader.classElements` to `LibraryReader.classes` to better
- reflect the behavior. Deprecate the old name.
-* Add `LibraryReader.enums`.
-
-## 0.9.2
-
-* Avoid using the AST analyzer model from `LibraryReader`.
-* Don't create part files with no corresponding library.
-* Update analyzer constraint to allow 0.34.x.
-
-## 0.9.1+3
-
-* Support the latest `pkg:analyzer`.
-
-## 0.9.1+2
-
-* Correctly handle properties in `spanForElement`.
-
-## 0.9.1+1
-
-* Allow `package:build` version 1.0.0.
-
-## 0.9.1
-
-* The result of `ConstantReader.revive()` now returns a `Revivable` that assumes
- access to a private class, constructor, or function _instead_ of `null` where
- possible. This allows generators that use `part` files to still use this
- functionality _and_ allows generators that use separate libraries to emit more
- actionable error messages (i.e. `"cannot use private class _X"`).
-
-* `Revivable.isPrivate` now returns `true` when the underyling class was public
- but the constructor was private, or the `Revivable` was pointing to a
- top-level or static private field or method. Previously it was only `true`
- when referencing a private class.
-
-## 0.9.0+1
-
-* Fix `LibraryReader.classElements` to return classes from parts, if they exist,
- as well as from the defining library file.
-
-## 0.9.0
-
-* Introduce `SharedPartBuilder` for creating part files that can be merged
- with a new `CombiningBuilder`. Note that `CombiningBuilder` only outputs
- `.g.dart` files.
-* **Breaking** `PartBuilder` now requires a `generatedExtensions` argument. The
- value should not be `.g.dart`. To produce `.g.dart` files please use the
- `SharedPartBuilder`.
-
-## 0.8.3+1
-
-* Allow using non-dev Dart 2 SDK.
-
-## 0.8.3
-
-* `GeneratorForAnnotation`
- * `generateForAnnotatedElement` now allow multiple return values when
- implementations return an `Iterable` or `Stream`.
- * Values from `generateForAnnotatedElement` have whitespace trimmed. `null`
- and empty values are ignored.
- * Duplicate values are collapsed into a single values. This allows emitting
- shared, top-level members without naming collisions.
-
-## 0.8.2
-
-* Simplification to the output of generator names in header sections.
-
-* Update handling of whitespace in generator outputs.
- * If the output from a generator has wrapping whitespace, it is trimmed.
- * If the output from a generator is empty or whitespace-only, it is ignored.
- * These changes will likely have no effect on output, unless you customize
- the code formatter.
-
-## 0.8.1+3
-
-* More redundant new lines elimination.
-
-## 0.8.1+2
-
-* Eliminate redundant new lines in the core builder. These were almost removed
- by running the default formatter. Now the unformatted code more closely
- matches the default output.
-
-## 0.8.1+1
-
-* Support `package:analyzer` `0.32.0`.
-
-## 0.8.1
-
-* Cleanup logging output that duplicates headers provided by
- `package:build_runner`.
-
-* `InvalidGenerationSourceError` added an optional `element`
- parameter to support more helpful error messages.
-
-## 0.8.0
-
-* **BREAKING** removed the deprecated `requireLibraryDirective` parameter in
- `PartBuilder`.
-
-* `Revivable` no longer throws a type error when attempting to revive a
- reference to a top-level function or static-class method. Now is returns a
- reference to that function or method, as expected.
-
-## 0.7.6
-
-* `TypeChecker` now throws an `UnresolvedAnnotationException` with a more
- detailed exception body (and properties useful for further debugging) instead
- of `Could not resolve @null`.
-
-## 0.7.5+1
-
-* `LibraryBuilder` and `PartBuilder` now have a more readable `toString()`,
- which is useful when emitting a warning or error in a build system. For
- example you may see `Generating .g.dart: MyBuilder` instead of
- `Instance of LibraryBuilder` in your build logs.
-
-## 0.7.5
-
-* The `PartBuilder` constructor parameter `requireLibraryDirective` now defaults
- to `false`. It will be removed in `0.8.0`.
-
-* Require at least Dart `2.0.0-dev.19.0`.
-
-## 0.7.4+3
-
-* Support the latest `analyzer` package.
-
-## 0.7.4+2
-
-* **BUG FIX**: `ConstantReader.revive()` now properly returns no URL fragment
- when the constant expression is resolved from a top-level or static-field.
- The documentation had said otherwise, and it was impossible to tell the
- difference between a constructor and a field. _Now_, fields are always in
- the form of accessor = `{clazz}.{field}` or `{topLevelField}`.
-
-* Fix file URIs on windows.
-
-## 0.7.4+1
-
-* Removed a `log.finest` with the output source of each generator. This allows
- a verbose option (`-v`) for tools like bazel or build_runner to be much more
- readable and debuggable. Files are emitted to disk for inspection in any
- case.
-
-## 0.7.4
-
-* Added `typeNameOf`, which is a safe way to get the name of a `DartType`,
- even when the type is a `FunctionType`, which has a `null` name in newer
- versions of the Dart analyzer.
-
-* Added `LibraryReader.pathToUrl(Uri|String)`, which computes the `import` or
- `export` path necessary to reach the provided URL from the current library.
- Also added `pathToAsset` and `pathToElement` as convenience functions.
-
-* Expanded `package:build` support to allow version `0.12.0`.
-
-## 0.7.3
-
-* Allow null and empty outputs form `GeneratorForAnnotation`.
-
-## 0.7.2+1
-
-* Allow `package:build` version 0.11.0
-
-## 0.7.2
-
-* Support an optional `header` argument to `PartBuilder` and `LibraryBuilder`.
-
-## 0.7.1
-
-### `Generator{ForAnnotation}`
-
-* Return type of `generate{ForAnnotatedElement}` is now `FutureOr<String>`.
-
-### `LibraryReader`
-
-* Added `annotatedElements` to return all elements annotated with something.
-* Added `classElements` getter for returning all `class`-es in a library.
-
-### `TypeChecker`
-
-* Added `hasAnnotationOf` and `hasAnnotationOfExact`.
-
-### `ConstantReader`
-
-* Added `isAny` (for consistency, but _deprecated_) and `isLiteral`.
-* Added `literalValue` as an alias for the now deprecated `anyValue`.
-* Allow `literalValue` to return `null` if the value is actually `null`.
-* Fixed a bug where a `Symbol` would return as a `String` for `anyValue`.
-* Fixed a bug where a `List` and `Map` were not considered literals.
-
-## 0.7.0
-
-* **Breaking changes**: See [the wiki](https://github.com/dart-lang/source_gen/wiki/Migrating-to-0.7.x)
- for help upgrading.
- * `Generator.generate` now operates on a `LibraryReader` rather than being
- called for every `Element` within a library. Generators can iterate over
- elements using `LibraryReader.allElements`. `GeneratorForAnnotation` will
- continue to call `generateForAnnotatedElement` repeatedly for each element.
- * `GeneratorForAnnotation` passes in a `ConstantReader` for the annotation
- instance rather than re-creating it using mirrors.
- * `GeneratorBuilder` is replaced with `PartBuilder` and `LibraryBuilder`
- depending on whether the output is meant to be included in a `part` file.
- * Removed `JsonSerializable` and related classes. These are moved to
- `package:json_serializable`.
- * Removed `lib/builder.dart`. Import through `source_gen.dart` instead.
- * Removed `OutputFormatter` typedef.
-
-* Add `LibraryReader.allElements` - a utility to iterate across all `Element`
- instances contained in Dart library.
-* Add `LibraryReader.element` to get back to the `LibraryElement` instance.
-* Add `ConstantReader.objectValue` to get back to the `DartObject` instance.
-* Add `ConstantReader.peek` to read a value that returns `null` if not found:
-
-```dart
-// Tries to read the field "token" first, then "_token".
-findTokenField(DartObject o) {
- final reader = new ConstantReader(o);
- final token = o.peek('token') ?? o.read('_token');
-}
-```
-
-* Add `throwOnUnresolved` optional parameter to `TypeChecker.annotationsOf`,
- `TypeChecker.annotationsOfExact`, `TypeChecker.firstAnnotationOf`, and
- `TypeChecker.firstAnnotationOfExact`. Setting this to `false` will enable you
- to check for matching annotations with incomplete type information (at your
- own risk).
-* Builder logs now log the primary inputs `AssetId` instead of the `library`,
- which is more useful for tracking down the actual files.
-
-## 0.6.1+1
-
-* Tighten constraint on `source_span`.
-
-## 0.6.1
-
-* Added `spanForElement`; returns a `SourceSpan` for an analyzer `Element`.
-* Logs a _warning_ to the console when a `GeneratorBuilder` outputs a part file
- for a given input, but that input does not define `part 'name.g.dart';`.
-
-## 0.6.0
-
-* **Breaking change**: `TypeChecker#annotationsOf|firstAnnotationOf` now
- returns annotations that are _assignable_ to the `TypeChecker`'s type. As a
- result we've added `#annotationsOfExact|firstAnnotationOfExact` which has the
- old behavior for precise checks.
-* `TypeChecker#annotations...`-methods now throw a `StateError` if one or more
- annotations on an element are not resolvable. This is usually a sign of a
- misspelling, missing import, or missing dependency.
-* Added `TypeChecker.any`, which delegates to multiple other `TypeChecker`
- implementations when making a type check.
-
-## 0.5.10+1
-
-* Update minimum `analyzer` package to `0.29.10`.
-
-## 0.5.10
-
-* Bug fixes:
- * Do not fail when "library" is omitted but nothing would be output.
- * Do not fail on extensions that don't end in ".dart" (valid use case).
-
-## 0.5.9
-
-* Update the minimum Dart SDK to `1.22.1`.
-* Deprecated `builder.dart`: import `source_gen.dart` instead.
-* Added `TypeChecker`, a high-level API for performing static type checks:
-
- ```dart
- import 'package:analyzer/dart/element/type.dart';
- import 'package:source_gen/source_gen.dart';
-
- void checkType(DartType dartType) {
- // Checks compared to runtime type `SomeClass`.
- print(const TypeChecker.forRuntime(SomeClass).isExactlyType(dartType));
-
- // Checks compared to a known Url/Symbol:
- const TypeChecker.forUrl('package:foo/foo.dart#SomeClass');
-
- // Checks compared to another resolved `DartType`:
- const TypeChecker.forStatic(anotherDartType);
- }
- ```
-
-* Failing to add a `library` directive to a library that is being used as a
- generator target that generates partial files (`part of`) is now an explicit
- error that gives a hint on how to name and fix your library:
-
- ```bash
- > Could not find library identifier so a "part of" cannot be built.
- >
- > Consider adding the following to your source file:
- >
- > "library foo.bar;"
- ```
-
- In Dart SDK `>=1.25.0` this can be relaxed as `part of` can refer to a path.
- To opt-in, `GeneratorBuilder` now has a new flag, `requireLibraryDirective`.
- Set it to `false`, and also set your `sdk` constraint appropriately:
-
- ```yaml
- sdk: '>=1.25.0 <2.0.0'
- ```
-
-* Added `LibraryReader`, a utility class for `LibraryElement` that exposes
- high-level APIs, including `findType`, which traverses `export` directives
- for publicly exported types. For example, to find `Generator` from
- `package:source_gen/source_gen.dart`:
-
- ```dart
- void example(LibraryElement pkgSourceGen) {
- var library = new LibraryReader(pkgSourceGen);
-
- // Instead of pkgSourceGen.getType('Generator'), which is null.
- library.findType('Generator');
- }
- ```
-
-* Added `ConstantReader`, a high-level API for reading from constant (static)
- values from Dart source code (usually represented by `DartObject` from the
- `analyzer` package):
-
- ```dart
- abstract class ConstantReader {
- factory ConstantReader(DartObject object) => ...
-
- // Other methods and properties also exist.
-
- /// Reads[ field] from the constant as another constant value.
- ConstantReader read(String field);
-
- /// Reads [field] from the constant as a boolean.
- ///
- /// If the resulting value is `null`, uses [defaultTo] if defined.
- bool readBool(String field, {bool defaultTo()});
-
- /// Reads [field] from the constant as an int.
- ///
- /// If the resulting value is `null`, uses [defaultTo] if defined.
- int readInt(String field, {int defaultTo()});
-
- /// Reads [field] from the constant as a string.
- ///
- /// If the resulting value is `null`, uses [defaultTo] if defined.
- String readString(String field, {String defaultTo()});
- }
- ```
-
-## 0.5.8
-
-* Add `formatOutput` optional parameter to the `GeneratorBuilder` constructor.
- This is a lambda of the form `String formatOutput(String originalCode)` which
- allows you do do custom formatting.
-
-## 0.5.7
-
-* Support for package:analyzer 0.30.0
-
-## 0.5.6
-
-* Support for package:build 0.9.0
-
-## 0.5.5
-
-* Support package:build 0.8.x
-* Less verbose errors when analyzer fails to resolve the input.
-
-## 0.5.4+3
-
-* Support the latest release of `pkg/dart_style`.
-
-## 0.5.4+2
-
-* Use the new `log` field instead of the deprecated `buildStep.logger`
-
-## 0.5.4+1
-
-* Give more information when `dartfmt` fails.
-
-## 0.5.4
-
-* Update to latest `build`, `build_runner`, and `build_test` releases.
-
-## 0.5.3+2
-
-* BugFix: Always release the Resolver instance, even when generation does not
- run
-
-## 0.5.3+1
-
-* Don't throw when running against a non-library asset and getting no
- LibraryElement
-
-## 0.5.3
-
-* Add matchTypes method. As with anything imported from /src/ this is
- use-at-your-own-risk since it is not guaranteed to be stable
-* Internal cleanup
- * Drop some unused utility methods
- * Move cli_util to dev_dependencies
- * Avoid some deprecated analyzer apis
- * Syntax tweaks
- * Drop results.dart which had no usages
-
-## 0.5.2
-
-* Use library URIs (not names) to look up annotations in the mirror system.
-* Loosen version constraint to allow package:build version 0.6
-* Fix a bug against the latest SDK checking whether List implements Iterable
-
-## 0.5.1+7
-
-* Generate valid strong-mode code for typed lists.
-
-## 0.5.1+6
-
-* Support the latest version of `pkg/build`.
-
-## 0.5.1+5
-
-* Remove "experimental" comment in `README.md`.
-
-## 0.5.1+4
-
-* Support `package:analyzer` 0.29.0
-
-## 0.5.1+3
-
-* Upgrade to be compatible with the breaking changes in analyzer 0.28.0
-
-## 0.5.1+2
-
-* Avoid calling `computeNode()` while instantiating annotation values
-
-## 0.5.1+1
-
-* Support the latest version of `build` package.
-
-## 0.5.1
-
-* Added GeneratorBuilder option isStandalone to generate files that aren't
- part of source file.
-
-## 0.5.0+3
-
-* Fixed multi-line error output.
-
-## 0.5.0+2
-
-* Remove an outdated work-around.
-
-* Make strong-mode clean.
-
-## 0.5.0+1
-
-* Support the latest version of `pkg/build`.
-
-## 0.5.0
-
-* **Breaking**: Switch to the `build` package for running `Generator`s. This
- means that the top level `build` and `generate` functions are no longer
- available, and have been replaced by the top level `build`, `watch`, and
- `serve` functions from the `build` package, and the `GeneratorBuilder` class.
- See `tool/build.dart`, `tool/watch.dart`, and `tool/phases.dart` for usage.
-
- * Note that the `build` package is experimental, and likely to change.
-
-* **Breaking**: The build package provides an abstraction for reading/writing
- files via the `BuildStep` class, and that is now also provided to
- `Generator#generate` and `GeneratorForAnnotation#generateForAnnotatedElement`
- as a second argument.
-
-* Timestamps are no longer included in generated code.
-
-* There is no longer a need to specify the files related to an individual
- generator via `AssociatedFileSet`. Simply use the `BuildStep` instance to read
- and write files and the `build` package will track any files you read in and
- run incremental rebuilds as necessary.
-
-## 0.4.8
-
-* Added support for `Symbol` and `Type` in annotations.
-
-* Improved error output when unable to create an instance from an annotation.
-
-## 0.4.7+2
-
-* Upgrade to `analyzer '^0.27.1'` and removed a work-around for a fixed
- `analyzer` issue.
-
-## 0.4.7+1
-
-* Upgrade to `analyzer '^0.27.0'`.
-
-## 0.4.7
-
-* `JsonSerializableGenerator` now supports classes with read-only properties.
-
-## 0.4.6
-
-* `JsonSerializable`: Added `JsonKey` annotation.
-
-* Improved output of generation errors and stack traces.
-
-* Require `analyzer '^0.26.2'`.
-
-## 0.4.5+1
-
-* Handle `null` values for `List` properties.
-
-## 0.4.5
-
-* `JsonSerializable`: add support for `List` values.
-
-## 0.4.4+1
-
-* Updated `README.md` to highlight the `build_system` package and de-emphasize
- Dart Editor.
-
-## 0.4.4
-
-* Added `omitGenerateTimestamp` and `followLinks` named args to `build`.
-
-* Added `followLinks` to `generate`.
-
-## 0.4.3+1
-
-* Update tests to use a more reliable method to find the current package root.
-
-## 0.4.3
-
-* Require Dart `1.12`.
-
-* Add implicit support for `.packages`. If the file exists, it is used.
- If not, we fall back to using the `packages` directory.
-
-* Support the latest releases of `analyzer` and `dart_style` packages.
-
-## 0.4.2
-
-* Use `fromJson` if it's defined in a child field.
-
-## 0.4.1
-
-* Match annotations defined in parts. *Thanks, [Greg](https://github.com/greglittlefield-wf)!*
-
-## 0.4.0+1
-
-* Support the latest release of `analyzer` and `args`.
-
-## 0.4.0
-
-* Analysis no longer parses function bodies. This greatly speeds up generation,
- but it could break any usage that needs function bodies.
-
-## 0.3.0+2
-
-* Fixed `README.md`.
-
-## 0.3.0+1
-
-* Updates for move to `dart-lang` org on GitHub.
-
-## 0.3.0
-
-* **BREAKING** Returning a descriptive value from `generate`.
-
-* **BREAKING** Fixed incorrectly named argument `omitGenerateTimestamp`.
-
-* `JsonSerializable`: Handle `dynamic` and `var` as field types.
-
-## 0.2.4
-
-* Added `associatedFileSet` to `Generator`. Allows a generator to specify
- that changes to any file in a directory next to a Dart source file can
- initiate a generation run.
-
-## 0.2.3
-
-* Use `async *`. Requires SDK >= `1.9.0-dev.10`
-
-* Protect against crash during code format.
-
-## 0.2.2
-
-* Added `omitGenerateTimestamp` (incorrectly spelled) named argument to
- `generate` method.
-
-* `Generator.generate` is now called with the `LibraryElement`, too.
-
-## 0.2.1
-
-* Fixed critical bug affecting annotation matching.
- [#35](https://github.com/dart-lang/source_gen/issues/35)
-
-* Started using published `dart_style` package.
-
-## 0.2.0+2
-
-* Tweaks to `JsonGenerator` to address
- [#31](https://github.com/dart-lang/source_gen/issues/31) and
- [#32](https://github.com/dart-lang/source_gen/issues/32)
-
-## 0.2.0+1
-* Updated `README.md` with new examples.
-* Fixed sub-bullet indenting in `CHANGELOG.md`.
-
-## 0.2.0
-* **BREAKING** Moved and renamed JSON serialization classes.
-* Added a `JsonLiteral` generator.
-* Improved handling and reporting of Generator errors.
-* `JsonGenerator`
- * Learned how to use constructor arguments.
- * Learned how to properly handle `DateTime`.
-
-## 0.1.1
-* Support for parametrized annotations.
-* Add named arguments to `JsonGenerator`.
-
-## 0.1.0+1
-* `README.md` updates.
-
-## 0.1.0
-* **BREAKING** `Generator.generate` is now async – returns `Future<String>`
-* Big update to `README.md`.
-
-## 0.0.1
-* Ready for experimentation.
-
-## 0.0.0+1
-* First play release.
diff --git a/source_gen/LICENSE b/source_gen/LICENSE
deleted file mode 100644
index de31e1a..0000000
--- a/source_gen/LICENSE
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright 2015, the Dart project authors. All rights reserved.
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
- * Neither the name of Google Inc. nor the names of its
- contributors may be used to endorse or promote products derived
- from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/source_gen/README.md b/source_gen/README.md
deleted file mode 100644
index 9a35691..0000000
--- a/source_gen/README.md
+++ /dev/null
@@ -1,126 +0,0 @@
-<p align="center">
- <a href="https://travis-ci.org/dart-lang/source_gen">
- <img src="https://travis-ci.org/dart-lang/source_gen.svg?branch=master" alt="Build Status" />
- </a>
- <a href="https://pub.dev/packages/source_gen">
- <img src="https://img.shields.io/pub/v/source_gen.svg" alt="Pub Package Version" />
- </a>
- <a href="https://gitter.im/dart-lang/build">
- <img src="https://badges.gitter.im/dart-lang/build.svg" alt="Join the chat on Gitter" />
- </a>
-</p>
-
-## Overview
-
-`source_gen` provides utilities for automated source code generation for Dart:
-
-* A **framework** for writing Builders that consume and produce Dart code.
-* A **convention** for human and tool generated Dart code to coexist with clean
- separation, and for multiple code generators to integrate in the same project.
-
-It's main purpose is to expose a developer-friendly API on top of lower-level
-packages like the [analyzer][] or [build][]. You don't _have_ to use
-`source_gen` in order to generate source code; we also expose a set of library
-APIs that might be useful in your generators.
-
-## Quick Start Guide for writing a Generator
-
-Add a dependency on `source_gen` in your pubspec.
-
-```yaml
-dependencies:
- source_gen:
-```
-
-If you're only using `source_gen` in your own project to generate code and you
-won't publish your Generator for others to use, it can be a `dev_dependency`:
-
-```yaml
-dev_dependencies:
- source_gen:
-```
-
-Once you have `source_gen` setup, you should reference the examples below.
-
-### Writing a generator to output Dart source code
-
-Extend the `Generator` or `GeneratorForAnnotation` class and `source_gen` will
-call your generator for a Dart library or for each element within a library
-tagged with the annotation you are interested in.
-
-* [Trivial example][]
-* [Full example package][] with [example usage][].
-
-### Configuring and Running generators
-
-`source_gen` is based on the [build][] package and exposes options for using
-your `Generator` in a `Builder`. Choose a Builder based on where you want the
-generated code to end up:
-
-- If you want to write to `.g.dart` files which are referenced as a `part` in
- the original source file, use `SharedPartBuilder`. This is the convention for
- generated code in part files, and this file may also contain code from
- `Generator`s provided by other packages.
-- If you want to write to `.some_name.dart` files which are referenced as a
- `part` in the original source file, use `PartBuilder`. You should choose an
- extension unique to your package. Multiple `Generator`s may output to this
- file, but they will all come from your package and you will set up the entire
- list when constructing the builder.
-- If you want to write standalone Dart library which can be `import`ed use
- `LibraryBuilder`. Only a single `Generator` may be used as a `LibraryBuilder`.
-
-In order to get the `Builder` used with [build_runner][] it must be configured
-in a `build.yaml` file. See [build_config][] for more details. Whenever you are
-publishing a package that includes a `build.yaml` file you should include a
-dependency on `build_config` in your pubspec.
-
-When using `SharedPartBuilder` it should always be configured to `build_to:
-cache` (hidden files) and apply the `combining_builder` from this package. The
-combining builder reads in all the pieces written by different shared part
-builders and writes them to the final `.g.dart` output in the user's source
-directory. You should never use the `.g.dart` extension for any other Builder.
-
-```yaml
-builders:
- some_cool_builder:
- import: "package:this_package/builder.dart"
- builder_factories: ["someCoolBuilder"]
- # The `partId` argument to `SharedPartBuilder` is "some_cool_builder"
- build_extensions: {".dart": [".some_cool_builder.g.part"]}
- auto_apply: dependents
- build_to: cache
- # To copy the `.g.part` content into `.g.dart` in the source tree
- applies_builders: ["source_gen|combining_builder"]
-```
-
-## FAQ
-
-### What is the difference between `source_gen` and [build][]?
-
-Build is a platform-agnostic framework for Dart asset or code generation that
-is pluggable into build systems including [bazel][bazel_codegen], and
-standalone tools like [build_runner][]. You could also build your own.
-
-Meanwhile, `source_gen` provides an API and tooling that is easily usable on
-top of `build` to make common tasks easier and more developer friendly. For
-example the [`PartBuilder`][api:PartBuilder] class wraps one or more
-[`Generator`][api:Generator] instances to make a [`Builder`][api:Builder] which
-creates `part of` files, while the [`LibraryBuilder`][api:LibraryBuilder] class
-wraps a single Generator to make a `Builder` which creates Dart library files.
-
-<!-- Packages -->
-[analyzer]: https://pub.dev/packages/analyzer
-[bazel_codegen]: https://pub.dev/packages/_bazel_codegen
-[build]: https://pub.dev/packages/build
-[build_config]: https://pub.dev/packages/build_config
-[build_runner]: https://pub.dev/packages/build_runner
-
-<!-- Dartdoc -->
-[api:Builder]: https://pub.dev/documentation/build/latest/build/Builder-class.html
-[api:Generator]: https://pub.dev/documentation/source_gen/latest/source_gen/Generator-class.html
-[api:PartBuilder]: https://pub.dev/documentation/source_gen/latest/source_gen/PartBuilder-class.html
-[api:LibraryBuilder]: https://pub.dev/documentation/source_gen/latest/source_gen/LibraryBuilder-class.html
-
-[Trivial example]: https://github.com/dart-lang/source_gen/blob/master/source_gen/test/src/comment_generator.dart
-[Full example package]: https://github.com/dart-lang/source_gen/tree/master/example
-[example usage]: https://github.com/dart-lang/source_gen/tree/master/example_usage
diff --git a/source_gen/build.yaml b/source_gen/build.yaml
deleted file mode 100644
index d7903e8..0000000
--- a/source_gen/build.yaml
+++ /dev/null
@@ -1,14 +0,0 @@
-# Read about `build.yaml` at https://pub.dev/packages/build_config
-builders:
- combining_builder:
- import: "package:source_gen/builder.dart"
- builder_factories: ["combiningBuilder"]
- build_extensions: {".dart": [".g.dart"]}
- auto_apply: none
- build_to: source
- required_inputs: [".g.part"]
- applies_builders: ["source_gen|part_cleanup"]
-post_process_builders:
- part_cleanup:
- import: "package:source_gen/builder.dart"
- builder_factory: "partCleanup"
diff --git a/source_gen/lib/builder.dart b/source_gen/lib/builder.dart
deleted file mode 100644
index 5d7feda..0000000
--- a/source_gen/lib/builder.dart
+++ /dev/null
@@ -1,112 +0,0 @@
-// 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.
-
-/// Configuration for using `package:build`-compatible build systems.
-///
-/// See:
-/// * [build_runner](https://pub.dev/packages/build_runner)
-///
-/// This library is **not** intended to be imported by typical end-users unless
-/// you are creating a custom compilation pipeline. See documentation for
-/// details, and `build.yaml` for how these builders are configured by default.
-library source_gen.builder;
-
-import 'dart:async';
-
-import 'package:build/build.dart';
-import 'package:glob/glob.dart';
-import 'package:path/path.dart' as p;
-import 'package:source_gen/src/utils.dart';
-import 'src/builder.dart';
-
-const _outputExtensions = '.g.dart';
-const _partFiles = '.g.part';
-
-Builder combiningBuilder([BuilderOptions options]) {
- final optionsMap = Map<String, dynamic>.from(options?.config ?? {});
-
- final builder = CombiningBuilder(
- includePartName: optionsMap.remove('include_part_name') as bool);
-
- if (optionsMap.isNotEmpty) {
- if (log == null) {
- throw StateError('Upgrade `build_runner` to at least 0.8.2.');
- } else {
- log.warning('These options were ignored: `$optionsMap`.');
- }
- }
- return builder;
-}
-
-PostProcessBuilder partCleanup(BuilderOptions options) =>
- const FileDeletingBuilder(['.g.part']);
-
-/// A [Builder] which combines part files generated from [SharedPartBuilder].
-///
-/// This will glob all files of the form `.*.g.part`.
-class CombiningBuilder implements Builder {
- final bool _includePartName;
-
- @override
- Map<String, List<String>> get buildExtensions => const {
- '.dart': [_outputExtensions]
- };
-
- /// Returns a new [CombiningBuilder].
- ///
- /// If [includePartName] is `true`, the name of each source part file
- /// is output as a comment before its content. This can be useful when
- /// debugging build issues.
- const CombiningBuilder({bool includePartName = false})
- : _includePartName = includePartName ?? false;
-
- @override
- Future build(BuildStep buildStep) async {
- // Pattern used for `findAssets`, which must be glob-compatible
- final pattern = buildStep.inputId.changeExtension('.*$_partFiles').path;
-
- final inputBaseName =
- p.basenameWithoutExtension(buildStep.inputId.pathSegments.last);
-
- // Pattern used to ensure items are only considered if they match
- // [file name without extension].[valid part id].[part file extension]
- final restrictedPattern = RegExp([
- '^', // start of string
- RegExp.escape(inputBaseName), // file name, without extension
- '\.', // `.` character
- partIdRegExpLiteral, // A valid part ID
- RegExp.escape(_partFiles), // the ending part extension
- '\$', // end of string
- ].join(''));
-
- final assetIds = await buildStep
- .findAssets(Glob(pattern))
- .where((id) => restrictedPattern.hasMatch(id.pathSegments.last))
- .toList()
- ..sort();
-
- final assets = await Stream.fromIterable(assetIds)
- .asyncMap((id) async {
- var content = (await buildStep.readAsString(id)).trim();
- if (_includePartName) {
- content = '// Part: ${id.pathSegments.last}\n$content';
- }
- return content;
- })
- .where((s) => s.isNotEmpty)
- .join('\n\n');
- if (assets.isEmpty) return;
- final partOf =
- nameOfPartial(await buildStep.inputLibrary, buildStep.inputId);
- final output = '''
-$defaultFileHeader
-
-part of $partOf;
-
-$assets
-''';
- await buildStep.writeAsString(
- buildStep.inputId.changeExtension(_outputExtensions), output);
- }
-}
diff --git a/source_gen/lib/source_gen.dart b/source_gen/lib/source_gen.dart
deleted file mode 100644
index 0cb8dda..0000000
--- a/source_gen/lib/source_gen.dart
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-export 'src/builder.dart'
- show defaultFileHeader, LibraryBuilder, PartBuilder, SharedPartBuilder;
-export 'src/constants/reader.dart' show ConstantReader;
-export 'src/constants/revive.dart' show Revivable;
-export 'src/generator.dart' show Generator, InvalidGenerationSourceError;
-export 'src/generator_for_annotation.dart' show GeneratorForAnnotation;
-export 'src/library.dart' show AnnotatedElement, LibraryReader;
-export 'src/span_for_element.dart' show spanForElement;
-export 'src/type_checker.dart' show TypeChecker, UnresolvedAnnotationException;
-export 'src/utils.dart' show typeNameOf;
diff --git a/source_gen/lib/src/builder.dart b/source_gen/lib/src/builder.dart
deleted file mode 100644
index 85f6233..0000000
--- a/source_gen/lib/src/builder.dart
+++ /dev/null
@@ -1,307 +0,0 @@
-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-import 'dart:convert';
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:build/build.dart';
-import 'package:dart_style/dart_style.dart';
-import 'package:pedantic/pedantic.dart';
-
-import 'generated_output.dart';
-import 'generator.dart';
-import 'library.dart';
-import 'utils.dart';
-
-/// A [Builder] wrapping on one or more [Generator]s.
-class _Builder extends Builder {
- /// Function that determines how the generated code is formatted.
- final String Function(String) formatOutput;
-
- /// The generators run for each targeted library.
- final List<Generator> _generators;
-
- /// The [buildExtensions] configuration for `.dart`
- final String _generatedExtension;
-
- /// Whether to emit a standalone (non-`part`) file in this builder.
- bool get _isLibraryBuilder => this is LibraryBuilder;
-
- final String _header;
-
- @override
- final Map<String, List<String>> buildExtensions;
-
- /// Wrap [_generators] to form a [Builder]-compatible API.
- _Builder(this._generators,
- {String Function(String code) formatOutput,
- String generatedExtension = '.g.dart',
- List<String> additionalOutputExtensions = const [],
- String header})
- : _generatedExtension = generatedExtension,
- buildExtensions = {
- '.dart': [generatedExtension]..addAll(additionalOutputExtensions)
- },
- formatOutput = formatOutput ?? _formatter.format,
- _header = (header ?? defaultFileHeader).trim() {
- if (_generatedExtension == null) {
- throw ArgumentError.notNull('generatedExtension');
- }
- if (_generatedExtension.isEmpty || !_generatedExtension.startsWith('.')) {
- throw ArgumentError.value(_generatedExtension, 'generatedExtension',
- 'Extension must be in the format of .*');
- }
- if (_isLibraryBuilder && _generators.length > 1) {
- throw ArgumentError(
- 'A standalone file can only be generated from a single Generator.');
- }
- }
-
- @override
- Future build(BuildStep buildStep) async {
- final resolver = buildStep.resolver;
- if (!await resolver.isLibrary(buildStep.inputId)) return;
- final lib = await buildStep.inputLibrary;
- await _generateForLibrary(lib, buildStep);
- }
-
- Future _generateForLibrary(
- LibraryElement library, BuildStep buildStep) async {
- final generatedOutputs =
- await _generate(library, _generators, buildStep).toList();
-
- // Don't output useless files.
- //
- // NOTE: It is important to do this check _before_ checking for valid
- // library/part definitions because users expect some files to be skipped
- // therefore they do not have "library".
- if (generatedOutputs.isEmpty) return;
- final outputId = buildStep.inputId.changeExtension(_generatedExtension);
-
- final contentBuffer = StringBuffer();
-
- if (_header.isNotEmpty) {
- contentBuffer.writeln(_header);
- }
-
- if (!_isLibraryBuilder) {
- final asset = buildStep.inputId;
- final name = nameOfPartial(library, asset);
- if (name == null) {
- final suggest = suggestLibraryName(asset);
- throw InvalidGenerationSourceError(
- 'Could not find library identifier so a "part of" cannot be built.',
- todo: ''
- 'Consider adding the following to your source file:\n\n'
- 'library $suggest;');
- }
- contentBuffer.writeln();
-
- String part;
- if (this is PartBuilder) {
- contentBuffer.writeln('part of $name;');
- part = computePartUrl(buildStep.inputId, outputId);
- } else {
- assert(this is SharedPartBuilder);
- final finalPartId = buildStep.inputId.changeExtension('.g.dart');
- part = computePartUrl(buildStep.inputId, finalPartId);
- }
- if (!library.parts.map((c) => c.uri).contains(part)) {
- // TODO: Upgrade to error in a future breaking change?
- log.warning('Missing "part \'$part\';".');
- return;
- }
- }
-
- for (var item in generatedOutputs) {
- contentBuffer
- ..writeln()
- ..writeln(_headerLine)
- ..writeAll(
- LineSplitter.split(item.toString()).map((line) => '// $line\n'))
- ..writeln(_headerLine)
- ..writeln()
- ..writeln(item.output);
- }
-
- var genPartContent = contentBuffer.toString();
-
- try {
- genPartContent = formatOutput(genPartContent);
- } catch (e, stack) {
- log.severe(
- 'Error formatting generated source code for ${library.identifier}'
- 'which was output to ${outputId.path}.\n'
- 'This may indicate an issue in the generated code or in the '
- 'formatter.\n'
- 'Please check the generated code and file an issue on source_gen if '
- 'appropriate.',
- e,
- stack);
- }
-
- unawaited(buildStep.writeAsString(outputId, genPartContent));
- }
-
- @override
- String toString() {
- return 'Generating $_generatedExtension: ${_generators.join(', ')}';
- }
-}
-
-/// A [Builder] which generates content intended for `part of` files.
-///
-/// Generated files will be prefixed with a `partId` to ensure multiple
-/// [SharedPartBuilder]s can produce non conflicting `part of` files. When the
-/// `source_gen|combining_builder` is applied to the primary input these
-/// snippets will be conacatenated into the final `.g.dart` output.
-///
-/// This builder can be used when multiple generators may need to output to the
-/// same part file but [PartBuilder] can't be used because the generators are
-/// not all defined in the same location. As a convention most codegen which
-/// generates code should use this approach to get content into a `.g.dart` file
-/// instead of having individual outputs for each building package.
-class SharedPartBuilder extends _Builder {
- /// Wrap [generators] as a [Builder] that generates `part of` files.
- ///
- /// [partId] indicates what files will be created for each `.dart`
- /// input. This extension should be unique as to not conflict with other
- /// [SharedPartBuilder]s. The resulting file will be of the form
- /// `<generatedExtension>.g.part`. If any generator in [generators] will
- /// create additional outputs through the [BuildStep] they should be indicated
- /// in [additionalOutputExtensions].
- ///
- /// [formatOutput] is called to format the generated code. Defaults to
- /// [DartFormatter.format].
- SharedPartBuilder(List<Generator> generators, String partId,
- {String Function(String code) formatOutput,
- List<String> additionalOutputExtensions = const []})
- : super(generators,
- formatOutput: formatOutput,
- generatedExtension: '.$partId.g.part',
- additionalOutputExtensions: additionalOutputExtensions,
- header: '') {
- if (!_partIdRegExp.hasMatch(partId)) {
- throw ArgumentError.value(
- partId,
- 'partId',
- '`partId` can only contain letters, numbers, `_` and `.`. '
- 'It cannot start or end with `.`.');
- }
- }
-}
-
-/// A [Builder] which generates `part of` files.
-///
-/// This builder should be avoided - prefer using [SharedPartBuilder] and
-/// generating content that can be merged with output from other builders into a
-/// common `.g.dart` part file.
-///
-/// Each output should correspond to a `part` directive in the primary input,
-/// this will be validated.
-///
-/// Content output by each generator is concatenated and written to the output.
-/// A `part of` directive will automatically be included in the output and
-/// should not need be written by any of the generators.
-class PartBuilder extends _Builder {
- /// Wrap [generators] as a [Builder] that generates `part of` files.
- ///
- /// [generatedExtension] indicates what files will be created for each
- /// `.dart` input. The [generatedExtension] should *not* be `.g.dart`. If you
- /// wish to produce `.g.dart` files please use [SharedPartBuilder].
- ///
- /// If any generator in [generators] will create additional outputs through
- /// the [BuildStep] they should be indicated in [additionalOutputExtensions].
- ///
- /// [formatOutput] is called to format the generated code. Defaults to
- /// [DartFormatter.format].
- ///
- /// [header] is used to specify the content at the top of each generated file.
- /// If `null`, the content of [defaultFileHeader] is used.
- /// If [header] is an empty `String` no header is added.
- PartBuilder(List<Generator> generators, String generatedExtension,
- {String Function(String code) formatOutput,
- List<String> additionalOutputExtensions = const [],
- String header})
- : super(generators,
- formatOutput: formatOutput,
- generatedExtension: generatedExtension,
- additionalOutputExtensions: additionalOutputExtensions,
- header: header);
-}
-
-/// A [Builder] which generates standalone Dart library files.
-///
-/// A single [Generator] is responsible for generating the entirety of the
-/// output since it must also output any relevant import directives at the
-/// beginning of it's output.
-class LibraryBuilder extends _Builder {
- /// Wrap [generator] as a [Builder] that generates Dart library files.
- ///
- /// [generatedExtension] indicates what files will be created for each `.dart`
- /// input.
- /// Defaults to `.g.dart`, however this should usually be changed to
- /// avoid conflicts with outputs from a [SharedPartBuilder].
- /// If [generator] will create additional outputs through the [BuildStep] they
- /// should be indicated in [additionalOutputExtensions].
- ///
- /// [formatOutput] is called to format the generated code. Defaults to
- /// [DartFormatter.format].
- ///
- /// [header] is used to specify the content at the top of each generated file.
- /// If `null`, the content of [defaultFileHeader] is used.
- /// If [header] is an empty `String` no header is added.
- LibraryBuilder(
- Generator generator, {
- String Function(String code) formatOutput,
- String generatedExtension = '.g.dart',
- List<String> additionalOutputExtensions = const [],
- String header,
- }) : super([generator],
- formatOutput: formatOutput,
- generatedExtension: generatedExtension,
- additionalOutputExtensions: additionalOutputExtensions,
- header: header);
-}
-
-Stream<GeneratedOutput> _generate(LibraryElement library,
- List<Generator> generators, BuildStep buildStep) async* {
- final libraryReader = LibraryReader(library);
- for (var i = 0; i < generators.length; i++) {
- final gen = generators[i];
- try {
- var msg = 'Running $gen';
- if (generators.length > 1) {
- msg = '$msg - ${i + 1} of ${generators.length}';
- }
- log.fine(msg);
- var createdUnit = await gen.generate(libraryReader, buildStep);
-
- if (createdUnit == null) {
- continue;
- }
-
- createdUnit = createdUnit.trim();
- if (createdUnit.isEmpty) {
- continue;
- }
-
- yield GeneratedOutput(gen, createdUnit);
- } catch (e, stack) {
- log.severe('Error running $gen', e, stack);
- yield GeneratedOutput.fromError(gen, e, stack);
- }
- }
-}
-
-final _formatter = DartFormatter();
-
-const defaultFileHeader = '// GENERATED CODE - DO NOT MODIFY BY HAND';
-
-final _headerLine = '// '.padRight(77, '*');
-
-const partIdRegExpLiteral = r'[A-Za-z_\d-]+';
-
-final _partIdRegExp = RegExp('^$partIdRegExpLiteral\$');
diff --git a/source_gen/lib/src/constants/reader.dart b/source_gen/lib/src/constants/reader.dart
deleted file mode 100644
index 494ae57..0000000
--- a/source_gen/lib/src/constants/reader.dart
+++ /dev/null
@@ -1,277 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/constant/value.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:meta/meta.dart';
-
-import '../type_checker.dart';
-import 'revive.dart';
-import 'utils.dart';
-
-/// A wrapper for analyzer's [DartObject] with a predictable high-level API.
-///
-/// Unlike [DartObject.getField], the [read] method attempts to access super
-/// classes for the field value if not found.
-abstract class ConstantReader {
- factory ConstantReader(DartObject object) =>
- isNullLike(object) ? const _NullConstant() : _DartObjectConstant(object);
-
- const ConstantReader._();
-
- /// Whether this constant is a literal value.
- @Deprecated('Use `isLiteral`, will be removed in 0.8.0')
- bool get isAny => isLiteral;
-
- /// Constant as a literal value.
- ///
- /// Throws [FormatException] if a valid literal value cannot be returned. This
- /// is the case if the constant is not a literal or if the literal value
- /// is represented at least partially with [DartObject] instances.
- @Deprecated('Use `literalValue`, will be removed in 0.8.0')
- Object get anyValue => literalValue;
-
- /// Whether this constant is a literal value.
- bool get isLiteral => true;
-
- /// Constant as a literal value.
- ///
- /// Throws [FormatException] if a valid literal value cannot be returned. This
- /// is the case if the constant is not a literal or if the literal value
- /// is represented at least partially with [DartObject] instances.
- Object get literalValue => null;
-
- /// Underlying object this instance is reading from.
- DartObject get objectValue;
-
- /// Whether the value this constant represents matches [checker].
- bool instanceOf(TypeChecker checker) => false;
-
- /// Reads [field] from the constant as another constant value.
- ///
- /// If the field is not present in the [DartObject] crawl up the chain of
- /// super classes until it is found. If the field is not present throw a
- /// [FormatException].
- ConstantReader read(String field);
-
- /// Reads [field] from the constant as another constant value.
- ///
- /// Unlike [read], returns `null` if the field is not found.
- ConstantReader peek(String field);
-
- /// Whether this constant is a `null` value.
- bool get isNull => true;
-
- /// Whether this constant represents a `bool` value.
- bool get isBool => false;
-
- /// Constant as a `bool` value.
- bool get boolValue;
-
- /// Whether this constant represents an `int` value.
- bool get isInt => false;
-
- /// Constant as a `int` value.
- int get intValue;
-
- /// Whether this constant represents a `double` value.
- bool get isDouble => false;
-
- /// Constant as a `double` value.
- double get doubleValue;
-
- /// Whether this constant represents a `String` value.
- bool get isString => false;
-
- /// Constant as a `String` value.
- String get stringValue;
-
- /// Whether this constant represents a `Symbol` value.
- bool get isSymbol => false;
-
- /// Constant as a `Symbol` value.
- Symbol get symbolValue;
-
- /// Whether this constant represents a `Type` value.
- bool get isType => false;
-
- /// Constant as a [DartType] representing a `Type` value.
- DartType get typeValue;
-
- /// Whether this constant represents a `Map` value.
- bool get isMap => false;
-
- /// Constant as a `Map` value.
- Map<DartObject, DartObject> get mapValue;
-
- /// Whether this constant represents a `List` value.
- bool get isList => false;
-
- /// Constant as a `List` value.
- List<DartObject> get listValue;
-
- /// Returns as a revived meta class.
- ///
- /// This is appropriate for cases where the underlying object is not a literal
- /// and code generators will want to figure out how to "recreate" a constant
- /// at runtime.
- Revivable revive();
-}
-
-class _NullConstant extends ConstantReader {
- @alwaysThrows
- static T _throw<T>(String expected) {
- throw FormatException('Not an instance of $expected.');
- }
-
- const _NullConstant() : super._();
-
- @override
- DartObject get objectValue => throw UnsupportedError('Null');
-
- @override
- bool get boolValue => _throw('bool');
-
- @override
- double get doubleValue => _throw('double');
-
- @override
- int get intValue => _throw('int');
-
- @override
- List<DartObject> get listValue => _throw('List');
-
- @override
- Map<DartObject, DartObject> get mapValue => _throw('Map');
-
- @override
- ConstantReader peek(_) => null;
-
- @override
- ConstantReader read(_) => throw UnsupportedError('Null');
-
- @override
- String get stringValue => _throw('String');
-
- @override
- Symbol get symbolValue => _throw('Symbol');
-
- @override
- DartType get typeValue => _throw('Type');
-
- @override
- Revivable revive() => throw UnsupportedError('Null');
-}
-
-class _DartObjectConstant extends ConstantReader {
- @override
- final DartObject objectValue;
-
- const _DartObjectConstant(this.objectValue) : super._();
-
- T _check<T>(T value, String expected) {
- if (value == null) {
- throw FormatException('Not an instance of $expected.', objectValue);
- }
- return value;
- }
-
- @override
- Object get literalValue =>
- objectValue.toBoolValue() ??
- objectValue.toStringValue() ??
- objectValue.toIntValue() ??
- objectValue.toDoubleValue() ??
- objectValue.toListValue() ??
- objectValue.toMapValue() ??
- Symbol(_check(objectValue.toSymbolValue(), 'literal'));
-
- @override
- bool get isLiteral =>
- isBool ||
- isString ||
- isInt ||
- isDouble ||
- isList ||
- isMap ||
- isSymbol ||
- isNull;
-
- @override
- bool instanceOf(TypeChecker checker) =>
- checker.isAssignableFromType(objectValue.type);
-
- @override
- bool get isNull => isNullLike(objectValue);
-
- @override
- bool get isBool => objectValue.toBoolValue() != null;
-
- @override
- bool get boolValue => _check(objectValue.toBoolValue(), 'bool');
-
- @override
- bool get isDouble => objectValue.toDoubleValue() != null;
-
- @override
- double get doubleValue => _check(objectValue.toDoubleValue(), 'double');
-
- @override
- bool get isInt => objectValue.toIntValue() != null;
-
- @override
- int get intValue => _check(objectValue.toIntValue(), 'int');
-
- @override
- bool get isList => objectValue.toListValue() != null;
-
- @override
- List<DartObject> get listValue => _check(objectValue.toListValue(), 'List');
-
- @override
- bool get isMap => objectValue.toMapValue() != null;
-
- @override
- Map<DartObject, DartObject> get mapValue =>
- _check(objectValue.toMapValue(), 'Map');
-
- @override
- bool get isString => objectValue.toStringValue() != null;
-
- @override
- String get stringValue => _check(objectValue.toStringValue(), 'String');
-
- @override
- bool get isSymbol => objectValue.toSymbolValue() != null;
-
- @override
- Symbol get symbolValue =>
- Symbol(_check(objectValue.toSymbolValue(), 'Symbol'));
-
- @override
- bool get isType => objectValue.toTypeValue() != null;
-
- @override
- DartType get typeValue => _check(objectValue.toTypeValue(), 'Type');
-
- @override
- ConstantReader peek(String field) {
- final constant = ConstantReader(getFieldRecursive(objectValue, field));
- return constant.isNull ? null : constant;
- }
-
- @override
- ConstantReader read(String field) {
- final reader = peek(field);
- if (reader == null) {
- assertHasField(objectValue?.type?.element as ClassElement, field);
- return const _NullConstant();
- }
- return reader;
- }
-
- @override
- Revivable revive() => reviveInstance(objectValue);
-}
diff --git a/source_gen/lib/src/constants/revive.dart b/source_gen/lib/src/constants/revive.dart
deleted file mode 100644
index 0994608..0000000
--- a/source_gen/lib/src/constants/revive.dart
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/constant/value.dart';
-import 'package:analyzer/dart/element/element.dart';
-// ignore: implementation_imports
-import 'package:analyzer/src/dart/constant/value.dart';
-
-import '../utils.dart';
-
-/// Attempts to extract what source code could be used to represent [object].
-///
-/// Returns `null` if it wasn't possible to parse [object], or [object] is a
-/// primitive value (such as a number, string, boolean) that does not need to be
-/// revived in order to represent it.
-///
-/// **NOTE**: Some returned [Revivable] instances are not representable as valid
-/// Dart source code (such as referencing private constructors). It is up to the
-/// build tool(s) using this library to surface error messages to the user.
-Revivable reviveInstance(DartObject object, [LibraryElement origin]) {
- origin ??= object.type.element.library;
- final element = object.type.element;
- var url = Uri.parse(urlOfElement(element));
- if (element is FunctionElement) {
- return Revivable._(
- source: url.removeFragment(),
- accessor: element.name,
- );
- }
- if (element is MethodElement && element.isStatic) {
- return Revivable._(
- source: url.removeFragment(),
- accessor: '${element.enclosingElement.name}.${element.name}',
- );
- }
- // Enums are not included in .definingCompilationUnit.types.
- final clazz = element as ClassElement;
- if (clazz.isEnum) {
- for (final e in clazz.fields.where(
- (f) => f.isPublic && f.isConst && f.computeConstantValue() == object)) {
- return Revivable._(
- source: url.removeFragment(),
- accessor: '${clazz.name}.${e.name}',
- );
- }
- }
-
- // We try and return a public accessor/constructor if available.
- final allResults = <Revivable>[];
-
- /// Returns whether [result] is an acceptable result to immediately return.
- bool tryResult(Revivable result) {
- allResults.add(result);
- return !result.isPrivate;
- }
-
- for (final e in origin.definingCompilationUnit.types
- .expand((t) => t.fields)
- .where((f) => f.isConst && f.computeConstantValue() == object)) {
- final result = Revivable._(
- source: url.removeFragment(),
- accessor: '${clazz.name}.${e.name}',
- );
- if (tryResult(result)) {
- return result;
- }
- }
- final i = (object as DartObjectImpl).getInvocation();
- if (i != null) {
- url = Uri.parse(urlOfElement(i.constructor.enclosingElement));
- final result = Revivable._(
- source: url,
- accessor: i.constructor.name,
- namedArguments: i.namedArguments,
- positionalArguments: i.positionalArguments,
- );
- if (tryResult(result)) {
- return result;
- }
- }
- if (origin != null) {
- for (final e in origin.definingCompilationUnit.topLevelVariables.where(
- (f) => f.isConst && f.computeConstantValue() == object,
- )) {
- final result = Revivable._(
- source: Uri.parse(urlOfElement(origin)).replace(fragment: ''),
- accessor: e.name,
- );
- if (tryResult(result)) {
- return result;
- }
- }
- }
- // We could try and return the "best" result more intelligently.
- return allResults.first;
-}
-
-/// Decoded "instructions" for re-creating a const [DartObject] at runtime.
-class Revivable {
- /// A URL pointing to the location and class name.
- ///
- /// For example, `LinkedHashMap` looks like: `dart:collection#LinkedHashMap`.
- ///
- /// An accessor to a top-level field or method does not have a fragment and
- /// is instead represented as just something like `dart:collection`, with the
- /// [accessor] field as the name of the symbol.
- final Uri source;
-
- /// Constructor or getter name used to invoke `const Class(...)`.
- ///
- /// Optional - if empty string (`''`) then this means the default constructor.
- final String accessor;
-
- /// Positional arguments used to invoke the constructor.
- final List<DartObject> positionalArguments;
-
- /// Named arguments used to invoke the constructor.
- final Map<String, DartObject> namedArguments;
-
- const Revivable._({
- this.source,
- this.accessor = '',
- this.positionalArguments = const [],
- this.namedArguments = const {},
- });
-
- /// Whether this instance is visible outside the same library.
- ///
- /// Builds tools may use this to fail when the symbol is expected to be
- /// importable (i.e. isn't used with `part of`).
- bool get isPrivate {
- return source.fragment.startsWith('_') || accessor.startsWith('_');
- }
-
- @override
- String toString() {
- if (source.fragment.isNotEmpty) {
- if (accessor.isEmpty) {
- return 'const $source';
- }
- return 'const $source.$accessor';
- }
- return '$source::$accessor';
- }
-}
diff --git a/source_gen/lib/src/constants/utils.dart b/source_gen/lib/src/constants/utils.dart
deleted file mode 100644
index 989ae0c..0000000
--- a/source_gen/lib/src/constants/utils.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/constant/value.dart';
-import 'package:analyzer/dart/element/element.dart';
-
-/// Throws a [FormatException] if [root] does not have a given field [name].
-///
-/// Super types [ClassElement.supertype] are also checked before throwing.
-void assertHasField(ClassElement root, String name) {
- var element = root;
- while (element != null) {
- final field = element.getField(name);
- if (field != null) {
- return;
- }
- element = element.supertype?.element;
- }
- final allFields = root.fields.toSet()
- ..addAll(root.allSupertypes.expand((t) => t.element.fields));
- throw FormatException(
- 'Class ${root.name} does not have field "$name".',
- 'Fields: \n - ${allFields.map((e) => e.name).join('\n - ')}',
- );
-}
-
-/// Returns whether or not [object] is or represents a `null` value.
-bool isNullLike(DartObject object) => object?.isNull != false;
-
-/// Similar to [DartObject.getField], but traverses super classes.
-///
-/// Returns `null` if ultimately [field] is never found.
-DartObject getFieldRecursive(DartObject object, String field) {
- if (isNullLike(object)) {
- return null;
- }
- final result = object.getField(field);
- if (isNullLike(result)) {
- return getFieldRecursive(object.getField('(super)'), field);
- }
- return result;
-}
diff --git a/source_gen/lib/src/generated_output.dart b/source_gen/lib/src/generated_output.dart
deleted file mode 100644
index d6a82a3..0000000
--- a/source_gen/lib/src/generated_output.dart
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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 'generator.dart';
-
-class GeneratedOutput {
- final String output;
- final Generator generator;
- final dynamic error;
- final StackTrace stackTrace;
-
- bool get isError => error != null;
-
- GeneratedOutput(this.generator, this.output)
- : error = null,
- stackTrace = null,
- assert(output != null),
- assert(output.isNotEmpty),
- // assuming length check is cheaper than simple string equality
- assert(output.length == output.trim().length);
-
- GeneratedOutput.fromError(this.generator, this.error, this.stackTrace)
- : output = _outputFromError(error);
-
- @override
- String toString() {
- final output = generator.toString();
- if (output.endsWith('Generator')) {
- return output;
- }
- return 'Generator: $output';
- }
-}
-
-String _outputFromError(Object error) {
- final buffer = StringBuffer();
-
- _commentWithHeader(_errorHeader, error.toString(), buffer);
-
- if (error is InvalidGenerationSourceError && error.todo.isNotEmpty) {
- _commentWithHeader(_todoHeader, error.todo, buffer);
- }
-
- return buffer.toString();
-}
-
-void _commentWithHeader(String header, String content, StringSink buffer) {
- final lines = const LineSplitter().convert(content);
-
- buffer
- ..writeAll([_commentPrefix, header, lines.first])
- ..writeln();
-
- final blankPrefix = ''.padLeft(header.length, ' ');
- for (var i = 1; i < lines.length; i++) {
- buffer
- ..writeAll([_commentPrefix, blankPrefix, lines[i]])
- ..writeln();
- }
-}
-
-const _commentPrefix = '// ';
-const _errorHeader = 'Error: ';
-const _todoHeader = 'TODO: ';
diff --git a/source_gen/lib/src/generator.dart b/source_gen/lib/src/generator.dart
deleted file mode 100644
index d8dece9..0000000
--- a/source_gen/lib/src/generator.dart
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:build/build.dart';
-
-import 'library.dart';
-import 'span_for_element.dart';
-
-/// A tool to generate Dart code based on a Dart library source.
-///
-/// During a build [generate] is called once per input library.
-abstract class Generator {
- const Generator();
-
- /// Generates Dart code for an input Dart library.
- ///
- /// May create additional outputs through the `buildStep`, but the 'primary'
- /// output is Dart code returned through the Future. If there is nothing to
- /// generate for this library may return null, or a Future that resolves to
- /// null or the empty string.
- FutureOr<String> generate(LibraryReader library, BuildStep buildStep) => null;
-
- @override
- String toString() => runtimeType.toString();
-}
-
-/// May be thrown by generators during [Generator.generate].
-class InvalidGenerationSourceError extends Error {
- /// What failure occurred.
- final String message;
-
- /// What could have been changed in the source code to resolve this error.
- ///
- /// May be an empty string if unknown.
- final String todo;
-
- /// The code element associated with this error.
- ///
- /// May be `null` if the error had no associated element.
- final Element element;
-
- InvalidGenerationSourceError(this.message, {String todo, this.element})
- : todo = todo ?? '';
-
- @override
- String toString() {
- final buffer = StringBuffer(message);
-
- if (element != null) {
- final span = spanForElement(element);
- buffer
- ..writeln()
- ..writeln(span.start.toolString)
- ..write(span.highlight());
- }
-
- return buffer.toString();
- }
-}
diff --git a/source_gen/lib/src/generator_for_annotation.dart b/source_gen/lib/src/generator_for_annotation.dart
deleted file mode 100644
index 5f4f76f..0000000
--- a/source_gen/lib/src/generator_for_annotation.dart
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:build/build.dart';
-
-import 'constants/reader.dart';
-import 'generator.dart';
-import 'library.dart';
-import 'output_helpers.dart';
-import 'type_checker.dart';
-
-/// Extend this type to create a [Generator] that invokes
-/// [generateForAnnotatedElement] for every element in the source file annotated
-/// with [T].
-///
-/// When all annotated elements have been processed, the results will be
-/// combined into a single output with duplicate items collapsed.
-///
-/// For example, this will allow code generated for all elements which are
-/// annotated with `@Deprecated`:
-///
-/// ```dart
-/// class DeprecatedGenerator extends GeneratorForAnnotation<Deprecated> {
-/// @override
-/// Future<String> generateForAnnotatedElement(
-/// Element element,
-/// ConstantReader annotation,
-/// BuildStep buildStep) async {
-/// // Return a string representing the code to emit.
-/// }
-/// }
-/// ```
-abstract class GeneratorForAnnotation<T> extends Generator {
- const GeneratorForAnnotation();
-
- TypeChecker get typeChecker => TypeChecker.fromRuntime(T);
-
- @override
- FutureOr<String> generate(LibraryReader library, BuildStep buildStep) async {
- final values = Set<String>();
-
- for (var annotatedElement in library.annotatedWith(typeChecker)) {
- final generatedValue = generateForAnnotatedElement(
- annotatedElement.element, annotatedElement.annotation, buildStep);
- await for (var value in normalizeGeneratorOutput(generatedValue)) {
- assert(value == null || (value.length == value.trim().length));
- values.add(value);
- }
- }
-
- return values.join('\n\n');
- }
-
- /// Implement to return source code to generate for [element].
- ///
- /// This method is invoked based on finding elements annotated with an
- /// instance of [T]. The [annotation] is provided as a [ConstantReader].
- ///
- /// Supported return values include a single [String] or multiple [String]
- /// instances within an [Iterable] or [Stream]. It is also valid to return a
- /// [Future] of [String], [Iterable], or [Stream].
- ///
- /// Implementations should return `null` when no content is generated. Empty
- /// or whitespace-only [String] instances are also ignored.
- dynamic generateForAnnotatedElement(
- Element element, ConstantReader annotation, BuildStep buildStep);
-}
diff --git a/source_gen/lib/src/library.dart b/source_gen/lib/src/library.dart
deleted file mode 100644
index 87696bf..0000000
--- a/source_gen/lib/src/library.dart
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:build/build.dart';
-import 'package:path/path.dart' as p;
-
-import 'constants/reader.dart';
-import 'type_checker.dart';
-import 'utils.dart';
-
-/// Result of finding an [annotation] on [element] through [LibraryReader].
-class AnnotatedElement {
- final ConstantReader annotation;
- final Element element;
-
- const AnnotatedElement(this.annotation, this.element);
-}
-
-/// A high-level wrapper API with common functionality for [LibraryElement].
-class LibraryReader {
- final LibraryElement element;
-
- LibraryReader(this.element);
-
- /// Returns a top-level [ClassElement] publicly visible in by [name].
- ///
- /// Unlike [LibraryElement.getType], this also correctly traverses identifiers
- /// that are accessible via one or more `export` directives.
- ClassElement findType(String name) {
- final type = element.exportNamespace.get(name);
- return type is ClassElement ? type : null;
- }
-
- /// All of the declarations in this library.
- Iterable<Element> get allElements sync* {
- for (var cu in element.units) {
- yield* cu.accessors;
- yield* cu.enums;
- yield* cu.functionTypeAliases;
- yield* cu.functions;
- yield* cu.mixins;
- yield* cu.topLevelVariables;
- yield* cu.types;
- }
- }
-
- /// All of the declarations in this library annotated with [checker].
- Iterable<AnnotatedElement> annotatedWith(TypeChecker checker,
- {bool throwOnUnresolved}) sync* {
- for (final element in allElements) {
- final annotation = checker.firstAnnotationOf(element,
- throwOnUnresolved: throwOnUnresolved);
- if (annotation != null) {
- yield AnnotatedElement(ConstantReader(annotation), element);
- }
- }
- }
-
- /// All of the declarations in this library annotated with exactly [checker].
- Iterable<AnnotatedElement> annotatedWithExact(TypeChecker checker,
- {bool throwOnUnresolved}) sync* {
- for (final element in allElements) {
- final annotation = checker.firstAnnotationOfExact(element,
- throwOnUnresolved: throwOnUnresolved);
- if (annotation != null) {
- yield AnnotatedElement(ConstantReader(annotation), element);
- }
- }
- }
-
- /// Returns a [Uri] from the current library to the target [asset].
- ///
- /// This is a typed convenience function for using [pathToUrl], and the same
- /// API restrictions hold around supported schemes and relative paths.
- Uri pathToAsset(AssetId asset) => pathToUrl(asset.uri);
-
- /// Returns a [Uri] from the current library to the target [element].
- ///
- /// This is a typed convenience function for using [pathToUrl], and the same
- /// API restrictions hold around supported schemes and relative paths.
- Uri pathToElement(Element element) => pathToUrl(element.source.uri);
-
- /// Returns a [Uri] from the current library to the one provided.
- ///
- /// If possible, a `package:` or `dart:` URL scheme will be used to reference
- /// the library, falling back to relative paths if required (such as in the
- /// `test` directory).
- ///
- /// The support [Uri.scheme]s are (others throw [ArgumentError]):
- /// * `dart`
- /// * `package`
- /// * `asset`
- ///
- /// May throw [ArgumentError] if it is not possible to resolve a path.
- Uri pathToUrl(dynamic toUrlOrString) {
- if (toUrlOrString == null) {
- throw ArgumentError.notNull('toUrlOrString');
- }
- final to = toUrlOrString is Uri
- ? toUrlOrString
- : Uri.parse(toUrlOrString as String);
- if (to.scheme == 'dart') {
- // Convert dart:core/map.dart to dart:core.
- return normalizeDartUrl(to);
- }
- if (to.scheme == 'package') {
- // Identity (no-op).
- return to;
- }
- if (to.scheme == 'asset') {
- // This is the same thing as a package: URL.
- //
- // i.e.
- // asset:foo/lib/foo.dart ===
- // package:foo/foo.dart
- if (to.pathSegments.length > 1 && to.pathSegments[1] == 'lib') {
- return assetToPackageUrl(to);
- }
- var from = element.source.uri;
- if (from == null) {
- throw StateError('Current library has no source URL');
- }
- // Normalize (convert to an asset: URL).
- from = normalizeUrl(from);
- if (_isRelative(from, to)) {
- if (from == to) {
- // Edge-case: p.relative('a.dart', 'a.dart') == '.', but that is not
- // a valid import URL in Dart source code.
- return Uri(path: to.pathSegments.last);
- }
- final relative = p.toUri(p.relative(
- to.toString(),
- from: from.toString(),
- ));
- // We now have a URL like "../b.dart", but we just want "b.dart".
- return relative.replace(
- pathSegments: relative.pathSegments.skip(1),
- );
- }
- throw ArgumentError.value(to, 'to', 'Not relative to $from');
- }
- throw ArgumentError.value(to, 'to', 'Cannot use scheme "${to.scheme}"');
- }
-
- /// Returns whether both [from] and [to] are in the same package and folder.
- ///
- /// For example these are considered relative:
- /// * `asset:foo/test/foo.dart` and `asset:foo/test/bar.dart`.
- ///
- /// But these are not:
- /// * `asset:foo/test/foo.dart` and `asset:foo/bin/bar.dart`.
- /// * `asset:foo/test/foo.dart` and `asset:bar/test/foo.dart`.
- static bool _isRelative(Uri from, Uri to) {
- final fromSegments = from.pathSegments;
- final toSegments = to.pathSegments;
- return fromSegments.length >= 2 &&
- toSegments.length >= 2 &&
- fromSegments[0] == toSegments[0] &&
- fromSegments[1] == toSegments[1];
- }
-
- /// All of the elements reperesenting classes in this library.
- Iterable<ClassElement> get classes => element.units.expand((cu) => cu.types);
-
- @Deprecated('Use classes instead')
- Iterable<ClassElement> get classElements => classes;
-
- /// All of the elements representing enums in this library.
- Iterable<ClassElement> get enums => element.units.expand((cu) => cu.enums);
-}
diff --git a/source_gen/lib/src/output_helpers.dart b/source_gen/lib/src/output_helpers.dart
deleted file mode 100644
index 877a144..0000000
--- a/source_gen/lib/src/output_helpers.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:async/async.dart';
-
-/// Converts [Future], [Iterable], and [Stream] implementations
-/// containing [String] to a single [Stream] while ensuring all thrown
-/// exceptions are forwarded through the return value.
-Stream<String> normalizeGeneratorOutput(Object value) {
- if (value == null) {
- return const Stream.empty();
- } else if (value is Future) {
- return StreamCompleter.fromFuture(value.then(normalizeGeneratorOutput));
- } else if (value is String) {
- value = [value];
- }
-
- if (value is Iterable) {
- value = Stream.fromIterable(value as Iterable);
- }
-
- if (value is Stream) {
- return value.where((e) => e != null).map((e) {
- if (e is String) {
- return e.trim();
- }
-
- throw _argError(e);
- }).where((e) => e.isNotEmpty);
- }
- throw _argError(value);
-}
-
-ArgumentError _argError(Object value) => ArgumentError(
- 'Must be a String or be an Iterable/Stream containing String values. '
- 'Found `${Error.safeToString(value)}` (${value.runtimeType}).');
diff --git a/source_gen/lib/src/span_for_element.dart b/source_gen/lib/src/span_for_element.dart
deleted file mode 100644
index 14398b1..0000000
--- a/source_gen/lib/src/span_for_element.dart
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:source_span/source_span.dart';
-
-import 'utils.dart';
-
-/// Returns a source span that spans the location where [element] is defined.
-///
-/// May be used to emit user-friendly warning and error messages:
-/// ```dart
-/// void invalidClass(ClassElement class) {
-/// log.warning(spanForElement.message('Cannot implement "Secret"'));
-/// }
-/// ```
-///
-/// Not all results from the analyzer API may return source information as part
-/// of the element, so [file] may need to be manually provided in those cases.
-SourceSpan spanForElement(Element element, [SourceFile file]) {
- final url = assetToPackageUrl(element.source.uri);
- if (file == null) {
- final contents = element?.source?.contents;
- if (contents == null) {
- return SourceSpan(
- SourceLocation(
- element.nameOffset,
- sourceUrl: url,
- ),
- SourceLocation(
- element.nameOffset + element.nameLength,
- sourceUrl: url,
- ),
- element.name,
- );
- }
- file = SourceFile.fromString(contents.data, url: url);
- }
- if (element.nameOffset < 0) {
- if (element is PropertyInducingElement) {
- if (element.getter != null) {
- return spanForElement(element.getter);
- }
-
- if (element.setter != null) {
- return spanForElement(element.setter);
- }
- }
- }
-
- return file.span(element.nameOffset, element.nameOffset + element.nameLength);
-}
diff --git a/source_gen/lib/src/type_checker.dart b/source_gen/lib/src/type_checker.dart
deleted file mode 100644
index cc597ab..0000000
--- a/source_gen/lib/src/type_checker.dart
+++ /dev/null
@@ -1,333 +0,0 @@
-// 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:mirrors' hide SourceLocation;
-
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/constant/value.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:source_span/source_span.dart';
-
-import 'utils.dart';
-
-/// An abstraction around doing static type checking at compile/build time.
-abstract class TypeChecker {
- const TypeChecker._();
-
- /// Creates a new [TypeChecker] that delegates to other [checkers].
- ///
- /// This implementation will return `true` for type checks if _any_ of the
- /// provided type checkers return true, which is useful for deprecating an
- /// API:
- /// ```dart
- /// const $Foo = const TypeChecker.fromRuntime(Foo);
- /// const $Bar = const TypeChecker.fromRuntime(Bar);
- ///
- /// // Used until $Foo is deleted.
- /// const $FooOrBar = const TypeChecker.forAny(const [$Foo, $Bar]);
- /// ```
- const factory TypeChecker.any(Iterable<TypeChecker> checkers) = _AnyChecker;
-
- /// Create a new [TypeChecker] backed by a runtime [type].
- ///
- /// This implementation uses `dart:mirrors` (runtime reflection).
- const factory TypeChecker.fromRuntime(Type type) = _MirrorTypeChecker;
-
- /// Create a new [TypeChecker] backed by a static [type].
- const factory TypeChecker.fromStatic(DartType type) = _LibraryTypeChecker;
-
- /// Create a new [TypeChecker] backed by a library [url].
- ///
- /// Example of referring to a `LinkedHashMap` from `dart:collection`:
- /// ```dart
- /// const linkedHashMap = const TypeChecker.fromUrl(
- /// 'dart:collection#LinkedHashMap',
- /// );
- /// ```
- ///
- /// **NOTE**: This is considered a more _brittle_ way of determining the type
- /// because it relies on knowing the _absolute_ path (i.e. after resolved
- /// `export` directives). You should ideally only use `fromUrl` when you know
- /// the full path (likely you own/control the package) or it is in a stable
- /// package like in the `dart:` SDK.
- const factory TypeChecker.fromUrl(dynamic url) = _UriTypeChecker;
-
- /// Returns the first constant annotating [element] assignable to this type.
- ///
- /// Otherwise returns `null`.
- ///
- /// Throws on unresolved annotations unless [throwOnUnresolved] is `false`.
- DartObject firstAnnotationOf(Element element, {bool throwOnUnresolved}) {
- if (element.metadata.isEmpty) {
- return null;
- }
- final results =
- annotationsOf(element, throwOnUnresolved: throwOnUnresolved);
- return results.isEmpty ? null : results.first;
- }
-
- /// Returns if a constant annotating [element] is assignable to this type.
- ///
- /// Throws on unresolved annotations unless [throwOnUnresolved] is `false`.
- bool hasAnnotationOf(Element element, {bool throwOnUnresolved}) =>
- firstAnnotationOf(element, throwOnUnresolved: throwOnUnresolved) != null;
-
- /// Returns the first constant annotating [element] that is exactly this type.
- ///
- /// Throws [UnresolvedAnnotationException] on unresolved annotations unless
- /// [throwOnUnresolved] is explicitly set to `false` (default is `true`).
- DartObject firstAnnotationOfExact(Element element, {bool throwOnUnresolved}) {
- if (element.metadata.isEmpty) {
- return null;
- }
- final results =
- annotationsOfExact(element, throwOnUnresolved: throwOnUnresolved);
- return results.isEmpty ? null : results.first;
- }
-
- /// Returns if a constant annotating [element] is exactly this type.
- ///
- /// Throws [UnresolvedAnnotationException] on unresolved annotations unless
- /// [throwOnUnresolved] is explicitly set to `false` (default is `true`).
- bool hasAnnotationOfExact(Element element, {bool throwOnUnresolved}) =>
- firstAnnotationOfExact(element, throwOnUnresolved: throwOnUnresolved) !=
- null;
-
- DartObject _computeConstantValue(
- Element element,
- int annotationIndex, {
- bool throwOnUnresolved,
- }) {
- throwOnUnresolved ??= true;
- final annotation = element.metadata[annotationIndex];
- final result = annotation.computeConstantValue();
- if (result == null && throwOnUnresolved) {
- throw UnresolvedAnnotationException._from(element, annotationIndex);
- }
- return result;
- }
-
- /// Returns annotating constants on [element] assignable to this type.
- ///
- /// Throws [UnresolvedAnnotationException] on unresolved annotations unless
- /// [throwOnUnresolved] is explicitly set to `false` (default is `true`).
- Iterable<DartObject> annotationsOf(
- Element element, {
- bool throwOnUnresolved,
- }) =>
- _annotationsWhere(
- element,
- isAssignableFromType,
- throwOnUnresolved: throwOnUnresolved,
- );
-
- Iterable<DartObject> _annotationsWhere(
- Element element,
- bool Function(DartType) predicate, {
- bool throwOnUnresolved,
- }) sync* {
- for (var i = 0; i < element.metadata.length; i++) {
- final value = _computeConstantValue(
- element,
- i,
- throwOnUnresolved: throwOnUnresolved,
- );
- if (value?.type != null && predicate(value.type)) {
- yield value;
- }
- }
- }
-
- /// Returns annotating constants on [element] of exactly this type.
- ///
- /// Throws [UnresolvedAnnotationException] on unresolved annotations unless
- /// [throwOnUnresolved] is explicitly set to `false` (default is `true`).
- Iterable<DartObject> annotationsOfExact(
- Element element, {
- bool throwOnUnresolved,
- }) =>
- _annotationsWhere(
- element,
- isExactlyType,
- throwOnUnresolved: throwOnUnresolved,
- );
-
- /// Returns `true` if the type of [element] can be assigned to this type.
- bool isAssignableFrom(Element element) =>
- isExactly(element) ||
- (element is ClassElement && element.allSupertypes.any(isExactlyType));
-
- /// Returns `true` if [staticType] can be assigned to this type.
- bool isAssignableFromType(DartType staticType) =>
- isAssignableFrom(staticType.element);
-
- /// Returns `true` if representing the exact same class as [element].
- bool isExactly(Element element);
-
- /// Returns `true` if representing the exact same type as [staticType].
- bool isExactlyType(DartType staticType) => isExactly(staticType.element);
-
- /// Returns `true` if representing a super class of [element].
- ///
- /// This check only takes into account the *extends* hierarchy. If you wish
- /// to check mixins and interfaces, use [isAssignableFrom].
- bool isSuperOf(Element element) {
- if (element is ClassElement) {
- var theSuper = element.supertype;
-
- do {
- if (isExactlyType(theSuper)) {
- return true;
- }
-
- theSuper = theSuper.superclass;
- } while (theSuper != null);
- }
-
- return false;
- }
-
- /// Returns `true` if representing a super type of [staticType].
- ///
- /// This only takes into account the *extends* hierarchy. If you wish
- /// to check mixins and interfaces, use [isAssignableFromType].
- bool isSuperTypeOf(DartType staticType) => isSuperOf(staticType.element);
-}
-
-// Checks a static type against another static type;
-class _LibraryTypeChecker extends TypeChecker {
- final DartType _type;
-
- const _LibraryTypeChecker(this._type) : super._();
-
- @override
- bool isExactly(Element element) =>
- element is ClassElement && element == _type.element;
-
- @override
- String toString() => '${urlOfElement(_type.element)}';
-}
-
-// Checks a runtime type against a static type.
-class _MirrorTypeChecker extends TypeChecker {
- static Uri _uriOf(ClassMirror mirror) =>
- normalizeUrl((mirror.owner as LibraryMirror).uri)
- .replace(fragment: MirrorSystem.getName(mirror.simpleName));
-
- // Precomputed type checker for types that already have been used.
- static final _cache = Expando<TypeChecker>();
-
- final Type _type;
-
- const _MirrorTypeChecker(this._type) : super._();
-
- TypeChecker get _computed =>
- _cache[this] ??= TypeChecker.fromUrl(_uriOf(reflectClass(_type)));
-
- @override
- bool isExactly(Element element) => _computed.isExactly(element);
-
- @override
- String toString() => _computed.toString();
-}
-
-// Checks a runtime type against an Uri and Symbol.
-class _UriTypeChecker extends TypeChecker {
- final String _url;
-
- // Precomputed cache of String --> Uri.
- static final _cache = Expando<Uri>();
-
- const _UriTypeChecker(dynamic url)
- : _url = '$url',
- super._();
-
- @override
- bool operator ==(Object o) => o is _UriTypeChecker && o._url == _url;
-
- @override
- int get hashCode => _url.hashCode;
-
- /// Url as a [Uri] object, lazily constructed.
- Uri get uri => _cache[this] ??= normalizeUrl(Uri.parse(_url));
-
- /// Returns whether this type represents the same as [url].
- bool hasSameUrl(dynamic url) =>
- uri.toString() ==
- (url is String ? url : normalizeUrl(url as Uri).toString());
-
- @override
- bool isExactly(Element element) => hasSameUrl(urlOfElement(element));
-
- @override
- String toString() => '$uri';
-}
-
-class _AnyChecker extends TypeChecker {
- final Iterable<TypeChecker> _checkers;
-
- const _AnyChecker(this._checkers) : super._();
-
- @override
- bool isExactly(Element element) => _checkers.any((c) => c.isExactly(element));
-}
-
-/// Exception thrown when [TypeChecker] fails to resolve a metadata annotation.
-///
-/// Methods such as [TypeChecker.firstAnnotationOf] may throw this exception
-/// when one or more annotations are not resolvable. This is usually a sign that
-/// something was misspelled, an import is missing, or a dependency was not
-/// defined (for build systems such as Bazel).
-class UnresolvedAnnotationException implements Exception {
- /// Element that was annotated with something we could not resolve.
- final Element annotatedElement;
-
- /// Source span of the annotation that was not resolved.
- ///
- /// May be `null` if the import library was not found.
- final SourceSpan annotationSource;
-
- static SourceSpan _findSpan(
- Element annotatedElement,
- int annotationIndex,
- ) {
- final parsedLibrary = annotatedElement.session
- .getParsedLibraryByElement(annotatedElement.library);
- final declaration = parsedLibrary.getElementDeclaration(annotatedElement);
- final annotatedNode = declaration.node as AnnotatedNode;
- final annotation = annotatedNode.metadata[annotationIndex];
- final start = annotation.offset;
- final end = start + annotation.length;
- return SourceSpan(
- SourceLocation(start, sourceUrl: declaration.parsedUnit.uri),
- SourceLocation(end, sourceUrl: declaration.parsedUnit.uri),
- declaration.parsedUnit.content.substring(start, end),
- );
- }
-
- /// Creates an exception from an annotation ([annotationIndex]) that was not
- /// resolvable while traversing [Element.metadata] on [annotatedElement].
- factory UnresolvedAnnotationException._from(
- Element annotatedElement,
- int annotationIndex,
- ) {
- final sourceSpan = _findSpan(annotatedElement, annotationIndex);
- return UnresolvedAnnotationException._(annotatedElement, sourceSpan);
- }
-
- const UnresolvedAnnotationException._(
- this.annotatedElement,
- this.annotationSource,
- );
-
- @override
- String toString() {
- final message = 'Could not resolve annotation for $annotatedElement';
- if (annotationSource != null) {
- return annotationSource.message(message);
- }
- return message;
- }
-}
diff --git a/source_gen/lib/src/utils.dart b/source_gen/lib/src/utils.dart
deleted file mode 100644
index aac7aa7..0000000
--- a/source_gen/lib/src/utils.dart
+++ /dev/null
@@ -1,123 +0,0 @@
-// 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/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:build/build.dart';
-import 'package:path/path.dart' as p;
-
-/// Returns a non-null name for the provided [type].
-///
-/// In newer versions of the Dart analyzer, a `typedef` does not keep the
-/// existing `name`, because it is used an alias:
-/// ```
-/// // Used to return `VoidFunc` for name, is now `null`.
-/// typedef VoidFunc = void Function();
-/// ```
-///
-/// This function will return `'VoidFunc'`, unlike [DartType.name].
-String typeNameOf(DartType type) {
- if (type is FunctionType) {
- final element = type.element;
- if (element is GenericFunctionTypeElement) {
- return element.enclosingElement.name;
- }
- }
- return type.name;
-}
-
-/// Returns a name suitable for `part of "..."` when pointing to [element].
-///
-/// Returns `null` if [element] is missing identifier.
-String nameOfPartial(LibraryElement element, AssetId source) {
- if (element.name != null && element.name.isNotEmpty) {
- return element.name;
- }
-
- final sourceUrl = p.basename(source.uri.toString());
- return '\'$sourceUrl\'';
-}
-
-/// Returns a suggested library identifier based on [source] path and package.
-String suggestLibraryName(AssetId source) {
- // lib/test.dart --> [lib/test.dart]
- final parts = source.path.split('/');
- // [lib/test.dart] --> [lib/test]
- parts[parts.length - 1] = parts.last.split('.').first;
- // [lib/test] --> [test]
- if (parts.first == 'lib') {
- parts.removeAt(0);
- }
- return '${source.package}.${parts.join('.')}';
-}
-
-/// Returns what 'part "..."' URL is needed to import [output] from [input].
-///
-/// For example, will return `test_lib.g.dart` for `test_lib.dart`.
-String computePartUrl(AssetId input, AssetId output) =>
- p.joinAll(p.split(p.relative(output.path, from: input.path)).skip(1));
-
-/// Returns a URL representing [element].
-String urlOfElement(Element element) => element.kind == ElementKind.DYNAMIC
- ? 'dart:core#dynmaic'
- // using librarySource.uri – in case the element is in a part
- : normalizeUrl(element.librarySource.uri)
- .replace(fragment: element.name)
- .toString();
-
-Uri normalizeUrl(Uri url) {
- switch (url.scheme) {
- case 'dart':
- return normalizeDartUrl(url);
- case 'package':
- return packageToAssetUrl(url);
- default:
- return url;
- }
-}
-
-/// Make `dart:`-type URLs look like a user-knowable path.
-///
-/// Some internal dart: URLs are something like `dart:core/map.dart`.
-///
-/// This isn't a user-knowable path, so we strip out extra path segments
-/// and only expose `dart:core`.
-Uri normalizeDartUrl(Uri url) => url.pathSegments.isNotEmpty
- ? url.replace(pathSegments: url.pathSegments.take(1))
- : url;
-
-/// Returns a `package:` URL converted to a `asset:` URL.
-///
-/// This makes internal comparison logic much easier, but still allows users
-/// to define assets in terms of `package:`, which is something that makes more
-/// sense to most.
-///
-/// For example, this transforms `package:source_gen/source_gen.dart` into:
-/// `asset:source_gen/lib/source_gen.dart`.
-Uri packageToAssetUrl(Uri url) => url.scheme == 'package'
- ? url.replace(
- scheme: 'asset',
- pathSegments: <String>[]
- ..add(url.pathSegments.first)
- ..add('lib')
- ..addAll(url.pathSegments.skip(1)))
- : url;
-
-/// Returns a `asset:` URL converted to a `package:` URL.
-///
-/// For example, this transformers `asset:source_gen/lib/source_gen.dart' into:
-/// `package:source_gen/source_gen.dart`. Asset URLs that aren't pointing to a
-/// file in the 'lib' folder are not modified.
-///
-/// Asset URLs come from `package:build`, as they are able to describe URLs that
-/// are not describable using `package:...`, such as files in the `bin`, `tool`,
-/// `web`, or even root directory of a package - `asset:some_lib/web/main.dart`.
-Uri assetToPackageUrl(Uri url) => url.scheme == 'asset' &&
- url.pathSegments.isNotEmpty &&
- url.pathSegments[1] == 'lib'
- ? url.replace(
- scheme: 'package',
- pathSegments: [url.pathSegments.first]
- ..addAll(url.pathSegments.skip(2)))
- : url;
diff --git a/source_gen/mono_pkg.yaml b/source_gen/mono_pkg.yaml
deleted file mode 100644
index 5976359..0000000
--- a/source_gen/mono_pkg.yaml
+++ /dev/null
@@ -1,20 +0,0 @@
-# See https://github.com/dart-lang/mono_repo for details
-dart:
-- 2.1.0
-- dev
-
-stages:
-- analyze_format:
- - group:
- - dartfmt
- - dartanalyzer: --fatal-infos --fatal-warnings .
- dart: dev
- - group:
- - dartanalyzer: --fatal-warnings .
- dart: 2.1.0
-- unit_test:
- - command: pub run build_runner test -- -j 1
-
-cache:
- directories:
- - .dart_tool/build
diff --git a/source_gen/pubspec.yaml b/source_gen/pubspec.yaml
deleted file mode 100644
index e0ca4c1..0000000
--- a/source_gen/pubspec.yaml
+++ /dev/null
@@ -1,27 +0,0 @@
-name: source_gen
-version: 0.9.4+4
-author: Dart Team <misc@dartlang.org>
-description: Automated source code generation for Dart.
-homepage: https://github.com/dart-lang/source_gen
-
-environment:
- sdk: ">=2.1.0 <3.0.0"
-
-dependencies:
- analyzer: '>=0.35.0 <0.39.0'
- async: ^2.0.7
- build: ^1.0.0
- dart_style: ^1.0.0
- glob: ^1.1.0
- meta: ^1.1.0
- path: ^1.3.2
- pedantic: ^1.0.0
- source_span: ^1.4.0
-
-dev_dependencies:
- build_runner: ^1.0.0
- build_test: ^0.10.0
- build_vm_compilers: '>=0.1.1 <2.0.0'
- test: ^1.0.0
- _test_annotations:
- path: ../_test_annotations
diff --git a/url_launcher/BUILD.gn b/url_launcher/BUILD.gn
index b832cd7..2e4f6bd 100644
--- a/url_launcher/BUILD.gn
+++ b/url_launcher/BUILD.gn
@@ -1,4 +1,4 @@
-# This file is generated by importer.py for url_launcher-5.2.5
+# This file is generated by importer.py for url_launcher-5.2.3
import("//build/dart/dart_library.gni")
@@ -12,7 +12,6 @@
disable_analysis = true
deps = [
- "//third_party/dart-pkg/pub/url_launcher_platform_interface",
"//third_party/dart-pkg/git/flutter/packages/flutter",
]
}
diff --git a/url_launcher/CHANGELOG.md b/url_launcher/CHANGELOG.md
index 1ae93df..3b83231 100644
--- a/url_launcher/CHANGELOG.md
+++ b/url_launcher/CHANGELOG.md
@@ -1,12 +1,3 @@
-## 5.2.5
-
-* Include lifecycle dependency as a compileOnly one on Android to resolve
- potential version conflicts with other transitive libraries.
-
-## 5.2.4
-
-* Use `package:url_launcher_platform_interface` to get the platform-specific implementation.
-
## 5.2.3
Android: Use android.arch.lifecycle instead of androidx.lifecycle:lifecycle in `build.gradle` to support apps that has not been migrated to AndroidX.
diff --git a/url_launcher/android/build.gradle b/url_launcher/android/build.gradle
index 46d0bf4..75643ad 100644
--- a/url_launcher/android/build.gradle
+++ b/url_launcher/android/build.gradle
@@ -75,9 +75,9 @@
android {
dependencies {
def lifecycle_version = "1.1.1"
- compileOnly "android.arch.lifecycle:runtime:$lifecycle_version"
- compileOnly "android.arch.lifecycle:common:$lifecycle_version"
- compileOnly "android.arch.lifecycle:common-java8:$lifecycle_version"
+ api "android.arch.lifecycle:runtime:$lifecycle_version"
+ api "android.arch.lifecycle:common:$lifecycle_version"
+ api "android.arch.lifecycle:common-java8:$lifecycle_version"
}
}
}
diff --git a/url_launcher/example/android/app/gradle.properties b/url_launcher/example/android/app/gradle.properties
new file mode 100644
index 0000000..5465fec
--- /dev/null
+++ b/url_launcher/example/android/app/gradle.properties
@@ -0,0 +1,2 @@
+android.enableJetifier=true
+android.useAndroidX=true
\ No newline at end of file
diff --git a/url_launcher/lib/url_launcher.dart b/url_launcher/lib/url_launcher.dart
index 97af771..045448f 100644
--- a/url_launcher/lib/url_launcher.dart
+++ b/url_launcher/lib/url_launcher.dart
@@ -7,7 +7,8 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
-import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
+
+const MethodChannel _channel = MethodChannel('plugins.flutter.io/url_launcher');
/// Parses the specified URL string and delegates handling of it to the
/// underlying platform.
@@ -83,14 +84,17 @@
? SystemUiOverlayStyle.dark
: SystemUiOverlayStyle.light);
}
- final bool result = await UrlLauncherPlatform.instance.launch(
- urlString,
- useSafariVC: forceSafariVC ?? isWebURL,
- useWebView: forceWebView ?? false,
- enableJavaScript: enableJavaScript ?? false,
- enableDomStorage: enableDomStorage ?? false,
- universalLinksOnly: universalLinksOnly ?? false,
- headers: headers ?? <String, String>{},
+ final bool result = await _channel.invokeMethod<bool>(
+ 'launch',
+ <String, Object>{
+ 'url': urlString,
+ 'useSafariVC': forceSafariVC ?? isWebURL,
+ 'useWebView': forceWebView ?? false,
+ 'enableJavaScript': enableJavaScript ?? false,
+ 'enableDomStorage': enableDomStorage ?? false,
+ 'universalLinksOnly': universalLinksOnly ?? false,
+ 'headers': headers ?? <String, String>{},
+ },
);
if (statusBarBrightness != null) {
WidgetsBinding.instance.renderView.automaticSystemUiAdjustment =
@@ -105,7 +109,10 @@
if (urlString == null) {
return false;
}
- return await UrlLauncherPlatform.instance.canLaunch(urlString);
+ return await _channel.invokeMethod<bool>(
+ 'canLaunch',
+ <String, Object>{'url': urlString},
+ );
}
/// Closes the current WebView, if one was previously opened via a call to [launch].
@@ -120,5 +127,5 @@
/// SafariViewController is only available on IOS version >= 9.0, this method does not do anything
/// on IOS version below 9.0
Future<void> closeWebView() async {
- return await UrlLauncherPlatform.instance.closeWebView();
+ return await _channel.invokeMethod<void>('closeWebView');
}
diff --git a/url_launcher/pubspec.yaml b/url_launcher/pubspec.yaml
index 78d6a74..4763469 100644
--- a/url_launcher/pubspec.yaml
+++ b/url_launcher/pubspec.yaml
@@ -3,7 +3,7 @@
web, phone, SMS, and email schemes.
author: Flutter Team <flutter-dev@googlegroups.com>
homepage: https://github.com/flutter/plugins/tree/master/packages/url_launcher/url_launcher
-version: 5.2.5
+version: 5.2.3
flutter:
plugin:
@@ -14,13 +14,10 @@
dependencies:
flutter:
sdk: flutter
- url_launcher_platform_interface: ^1.0.1
dev_dependencies:
flutter_test:
sdk: flutter
- test: ^1.3.0
- mockito: ^4.1.1
environment:
sdk: ">=2.0.0-dev.28.0 <3.0.0"
diff --git a/url_launcher_platform_interface/BUILD.gn b/url_launcher_platform_interface/BUILD.gn
deleted file mode 100644
index df84ee0..0000000
--- a/url_launcher_platform_interface/BUILD.gn
+++ /dev/null
@@ -1,18 +0,0 @@
-# This file is generated by importer.py for url_launcher_platform_interface-1.0.1
-
-import("//build/dart/dart_library.gni")
-
-dart_library("url_launcher_platform_interface") {
- package_name = "url_launcher_platform_interface"
-
- # This parameter is left empty as we don't care about analysis or exporting
- # these sources outside of the tree.
- sources = []
-
- disable_analysis = true
-
- deps = [
- "//third_party/dart-pkg/pub/meta",
- "//third_party/dart-pkg/git/flutter/packages/flutter",
- ]
-}
diff --git a/url_launcher_platform_interface/CHANGELOG.md b/url_launcher_platform_interface/CHANGELOG.md
deleted file mode 100644
index a849e40..0000000
--- a/url_launcher_platform_interface/CHANGELOG.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## 1.0.1
-
-* Enforce that UrlLauncherPlatform isn't implemented with `implements`.
-
-## 1.0.0
-
-* Initial release.
diff --git a/url_launcher_platform_interface/LICENSE b/url_launcher_platform_interface/LICENSE
deleted file mode 100644
index c892933..0000000
--- a/url_launcher_platform_interface/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/url_launcher_platform_interface/README.md b/url_launcher_platform_interface/README.md
deleted file mode 100644
index 3fd6b02..0000000
--- a/url_launcher_platform_interface/README.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# url_launcher_platform_interface
-
-A common platform interface for the [`url_launcher`][1] plugin.
-
-This interface allows platform-specific implementations of the `url_launcher`
-plugin, as well as the plugin itself, to ensure they are supporting the
-same interface.
-
-# Usage
-
-To implement a new platform-specific implementation of `url_launcher`, extend
-[`UrlLauncherPlatform`][2] with an implementation that performs the
-platform-specific behavior, and when you register your plugin, set the default
-`UrlLauncherPlatform` by calling
-`UrlLauncherPlatform.instance = MyPlatformUrlLauncher()`.
-
-# Note on breaking changes
-
-Strongly prefer non-breaking changes (such as adding a method to the interface)
-over breaking changes for this package.
-
-See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
-on why a less-clean interface is preferable to a breaking change.
-
-[1]: ../url_launcher
-[2]: lib/url_launcher_platform_interface.dart
diff --git a/url_launcher_platform_interface/lib/method_channel_url_launcher.dart b/url_launcher_platform_interface/lib/method_channel_url_launcher.dart
deleted file mode 100644
index 3fbd2ee..0000000
--- a/url_launcher_platform_interface/lib/method_channel_url_launcher.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:flutter/services.dart';
-import 'package:meta/meta.dart' show required;
-
-import 'url_launcher_platform_interface.dart';
-
-const MethodChannel _channel = MethodChannel('plugins.flutter.io/url_launcher');
-
-/// An implementation of [UrlLauncherPlatform] that uses method channels.
-class MethodChannelUrlLauncher extends UrlLauncherPlatform {
- @override
- Future<bool> canLaunch(String url) {
- return _channel.invokeMethod<bool>(
- 'canLaunch',
- <String, Object>{'url': url},
- );
- }
-
- @override
- Future<void> closeWebView() {
- return _channel.invokeMethod<void>('closeWebView');
- }
-
- @override
- Future<bool> launch(
- String url, {
- @required bool useSafariVC,
- @required bool useWebView,
- @required bool enableJavaScript,
- @required bool enableDomStorage,
- @required bool universalLinksOnly,
- @required Map<String, String> headers,
- }) {
- return _channel.invokeMethod<bool>(
- 'launch',
- <String, Object>{
- 'url': url,
- 'useSafariVC': useSafariVC,
- 'useWebView': useWebView,
- 'enableJavaScript': enableJavaScript,
- 'enableDomStorage': enableDomStorage,
- 'universalLinksOnly': universalLinksOnly,
- 'headers': headers,
- },
- );
- }
-}
diff --git a/url_launcher_platform_interface/lib/url_launcher_platform_interface.dart b/url_launcher_platform_interface/lib/url_launcher_platform_interface.dart
deleted file mode 100644
index a17aa06..0000000
--- a/url_launcher_platform_interface/lib/url_launcher_platform_interface.dart
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-import 'dart:async';
-
-import 'package:meta/meta.dart' show required, visibleForTesting;
-
-import 'method_channel_url_launcher.dart';
-
-/// The interface that implementations of url_launcher must implement.
-///
-/// Platform implementations should extend this class rather than implement it as `url_launcher`
-/// does not consider newly added methods to be breaking changes. Extending this class
-/// (using `extends`) ensures that the subclass will get the default implementation, while
-/// platform implementations that `implements` this interface will be broken by newly added
-/// [UrlLauncherPlatform] methods.
-abstract class UrlLauncherPlatform {
- /// Only mock implementations should set this to true.
- ///
- /// Mockito mocks are implementing this class with `implements` which is forbidden for anything
- /// other than mocks (see class docs). This property provides a backdoor for mockito mocks to
- /// skip the verification that the class isn't implemented with `implements`.
- @visibleForTesting
- bool get isMock => false;
-
- /// The default instance of [UrlLauncherPlatform] to use.
- ///
- /// Platform-specific plugins should override this with their own
- /// platform-specific class that extends [UrlLauncherPlatform] when they
- /// register themselves.
- ///
- /// Defaults to [MethodChannelUrlLauncher].
- static UrlLauncherPlatform _instance = MethodChannelUrlLauncher();
-
- static UrlLauncherPlatform get instance => _instance;
-
- // TODO(amirh): Extract common platform interface logic.
- // https://github.com/flutter/flutter/issues/43368
- static set instance(UrlLauncherPlatform instance) {
- if (!instance.isMock) {
- try {
- instance._verifyProvidesDefaultImplementations();
- } on NoSuchMethodError catch (_) {
- throw AssertionError(
- 'Platform interfaces must not be implemented with `implements`');
- }
- }
- _instance = instance;
- }
-
- /// Returns `true` if this platform is able to launch [url].
- Future<bool> canLaunch(String url) {
- throw UnimplementedError('canLaunch() has not been implemented.');
- }
-
- /// Returns `true` if the given [url] was successfully launched.
- ///
- /// For documentation on the other arguments, see the `launch` documentation
- /// in `package:url_launcher/url_launcher.dart`.
- Future<bool> launch(
- String url, {
- @required bool useSafariVC,
- @required bool useWebView,
- @required bool enableJavaScript,
- @required bool enableDomStorage,
- @required bool universalLinksOnly,
- @required Map<String, String> headers,
- }) {
- throw UnimplementedError('launch() has not been implemented.');
- }
-
- /// Closes the WebView, if one was opened earlier by [launch].
- Future<void> closeWebView() {
- throw UnimplementedError('closeWebView() has not been implemented.');
- }
-
- // This method makes sure that UrlLauncher isn't implemented with `implements`.
- //
- // See class doc for more details on why implementing this class is forbidden.
- //
- // This private method is called by the instance setter, which fails if the class is
- // implemented with `implements`.
- void _verifyProvidesDefaultImplementations() {}
-}
diff --git a/url_launcher_platform_interface/pubspec.yaml b/url_launcher_platform_interface/pubspec.yaml
deleted file mode 100644
index cbdfed1..0000000
--- a/url_launcher_platform_interface/pubspec.yaml
+++ /dev/null
@@ -1,21 +0,0 @@
-name: url_launcher_platform_interface
-description: A common platform interface for the url_launcher plugin.
-author: Flutter Team <flutter-dev@googlegroups.com>
-homepage: https://github.com/flutter/plugins/tree/master/packages/url_launcher/url_launcher_platform_interface
-# NOTE: We strongly prefer non-breaking changes, even at the expense of a
-# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
-version: 1.0.1
-
-dependencies:
- flutter:
- sdk: flutter
- meta: ^1.0.5
-
-dev_dependencies:
- flutter_test:
- sdk: flutter
- mockito: ^4.1.1
-
-environment:
- sdk: ">=2.0.0-dev.28.0 <3.0.0"
- flutter: ">=1.9.1+hotfix.4 <2.0.0"