自定义静态分析

Static analysis allows you to find problems beforeexecuting a single line of code. It’s a powerful toolused to prevent bugs and ensure that code conforms to styleguidelines.

With the help of the analyzer, you can findsimple typos. For example, perhaps an accidental semicolonmade its way into an if statement:

  1. void increment() { if (count < 10) ; count++;}
  1. lint Avoid empty statements example.dart:11 empty_statements

The analyzer can also help you find more subtle problems.For example, perhaps you’ve forgotten to close a sink method:

  1. var _controller = StreamController<String>();
  1. lint Close instances of dart.core.Sink example.dart:11 close_sinks

In the Dart ecosystem,the Dart Analysis Server and other tools use theanalyzer packageto perform static analysis.

You can customize static analysis to look for a variety of potentialproblems, including errors and warnings specified in theDart language spec.You can also configure the linter, one of the analyzer’s plugins,to ensure that your code complies with theDart Style Guideand other suggested guidelines inEffective Dart. Dart tools such as theDart dev compiler (dartdevc),dartanalyzer,flutter analyze,and JetBrains IDEsuse the analyzer package to evaluate your code.

This document explains how to customize the behavior of the analyzerusing either an analysis options file or comments in Dart source code. If you want toadd static analysis to your tool, see theanalyzer package docs and theAnalysis Server API Specification.

备忘: The analyzer error codes are listed in the Dart SDK repo.

The analysis options file

Place the analysis options file, analysis_options.yaml,at the root of the package, in the same directory as the pubspec file.

Breaking change: The conventional name for the analysis options file used to be .analysis_options (note the leading dot and missing .yaml suffix). We expect support for the .analysis_options name to go away in a future release, so we recommend that you rename your .analysis_options files to analysis_options.yaml.

Here’s a sample analysis options file:

  1. include: package:pedantic/analysis_options.1.8.0.yaml
  2. analyzer:
  3. exclude: [build/**]
  4. strong-mode:
  5. implicit-casts: false
  6. linter:
  7. rules:
  8. - camel_case_types

The sample illustrates the most common top-level entries:

Another tag you might see is language:,which is used for experimental language features.

YAML is sensitive to whitespace. Don’t use tabs in a YAML file, and use 2 spaces to denote each level of indentation.

If the analyzer can’t find an analysis options file at the package root,it walks up the directory tree, looking for one.If no file is available, the analyzer defaults to standard checks.

Consider the following directory structure for a large project:

project root contains analysis_options.yaml (#1) and 3 packages, one of which (my_package) contains an analysis_options.yaml file (#2).

The analyzer uses file #1 to analyze the code in my_other_packageand my_other_other_package, and file #2 to analyze the code inmy_package.

Enabling stricter type checks

If you want stricter static checks thanthe Dart type system requires,consider using the implicit-casts and implicit-dynamic flags:

  1. analyzer:
  2. strong-mode:
  3. implicit-casts: false
  4. implicit-dynamic: false

You can use the flags together or separately; both default to true.

  • implicit-casts: <bool>
  • A value of false ensures that the type inference engine neverimplicitly casts to a more specific type.The following valid Dart codeincludes an implicit downcast that would be caught by this flag:
  1. Object o = ...
  2. String s = o; // Implicit downcast
  3. String s2 = s.substring(1);
  1. error A value of type 'Object' can't be assigned to a variable of type 'String' • invalid_assignment
  • implicit-dynamic: <bool>
  • A value of false ensures that the type inference engine never choosesthe dynamic type when it can’t determine a static type.

Enabling and disabling linter rules

The analyzer package also provides a code linter. A wide variety oflinter rules are available. Linters tend to benondenominational—rules don’t have to agree with each other.For example, some rules are more appropriate for library packagesand others are designed for Flutter apps.Note that linter rules can have false positives, unlike static analysis.

Enabling default Google rules: pedantic

To enable the list of linter rules that Google uses in its own Dart code,depend on the pedantic packageand include its analysis_options.yaml file.Unless you need to use the pedantic API, declare a dev dependency on pedanticin your pubspec.yaml file:

  1. dev_dependencies:
  2. pedantic: ^1.0.0

Run pub get, and thenadd the following line to your analysis_options.yaml file:

  1. include: package:pedantic/analysis_options.yaml

重要说明: When a new version of pedantic is published, code that previously passed analysis might start failing analysis. We recommend updating your code to work with the new rules. Other options are to include a specific version of the pedantic analysis options file (as described in the pedantic README), explicitly enable individual linter rules, or disable individual rules.

Enabling individual rules

To enable a single linter rule, add linter: to the analysis options file,followed by rules:.On subsequent lines, specify the rules that you want to apply,prefixed with dashes. For example:

  1. linter:
  2. rules:
  3. - annotate_overrides
  4. - await_only_futures
  5. - camel_case_types
  6. - cancel_subscriptions
  7. - close_sinks
  8. - comment_references
  9. - constant_identifier_names
  10. - control_flow_in_finally
  11. - empty_statements

Disabling individual rules

If you include an analysis options file such as the one in pedantic,you might want to disable some of the included rules.Disabling individual rules is similar to enabling them,but with two differences:

  • Omit the dash (-) before the rule name.
  • Add : false after the rule name.

Here’s an example of an analysis options filethat uses all pedantic rules except avoid_shadowing_type_parameters.It also enables the lint await_only_futures:

  1. include: package:pedantic/analysis_options.yaml
  2. linter:
  3. rules:
  4. avoid_shadowing_type_parameters: false
  5. await_only_futures: true

备忘: Due to YAML restrictions, you can’t mix list and key-value syntax in the same rules entry. You can, however, use the other syntax for rules in an included file.

Excluding code from analysis

Sometimes it’s OK for some code to fail analysis.For example, you might rely on code generated by a package thatyou don’t own—the generated code works,but produces errors during static analysis.Or a linter rule might cause a false positivethat you want to suppress.

You have several ways to exclude code from analysis:

  • Exclude entire files from analysis.
  • Stop specific rules from being applied to individual files.
  • Stop specific rules from being applied to individual lines of code.
  • Ignore specific rules or errors.

You can also change the severity of rules.

Excluding files

To exclude files from static analysis, use the exclude: analyzer option. Youcan list individual files, or use glob syntax:

  1. analyzer:
  2. exclude:
  3. - lib/client.dart
  4. - lib/server/*.g.dart
  5. - test/_data/**

Suppressing rules for a file

To ignore a specific rule for a specific file,add an ignore_for_file comment to the file:

  1. // ignore_for_file: unused_import

This acts for the whole file, before or after the comment, and isparticularly useful for generated code.

To suppress more than one rule, use a comma-separated list:

  1. // ignore_for_file: unused_import, unused_local_variable, omit_local_variable_types

Suppressing rules for a line of code

To suppress a specific rule on a specific line of code, put an ignore commentabove the line of code. Here’s an example of ignoring code that causes a runtimeerror, as you might do in a language test:

  1. // ignore: invalid_assignment
  2. int x = '';

To suppress more than one rule, supply a comma-separated list:

  1. // ignore: invalid_assignment, const_initialized_with_non_constant_value
  2. const x = y;

Alternatively, append the ignore rule to the line that it applies to:

  1. int x = ''; // ignore: invalid_assignment

Customizing analysis rules

Each analyzer error code andlinter rule has a default severity.You can use the analysis options file to changethe severity of individual rules, or to always ignore some rules.

The analyzer supports three severity levels:

  • info
  • An informational message that doesn’t cause analysis to fail.Example: todo
  • warning
  • A warning that doesn’t cause analysis to fail unlessthe analyzer is configured to treat warnings as errors.Example: analysis_option_deprecated
  • error
  • An error that causes analysis to fail.Example: invalid_assignment

Ignoring rules

You can ignore specific analyzer error codes and linter rulesby using the errors: field.List the rule, followed by : ignore. For example, the followinganalysis options file instructs the analysis tools to ignore the TODO rule:

  1. analyzer:
  2. errors:
  3. todo: ignore

Changing the severity of rules

You can globally change the severity of a particular rule.This technique works for regular analysis issues as well as for lints.For example, the following analysis options file instructs the analysis tools totreat invalid assignments as warnings and missing returns as errors,and to provide information (but not a warning or error) about dead code:

  1. analyzer:
  2. errors:
  3. invalid_assignment: warning
  4. missing_return: error
  5. dead_code: info

Resources

Use the following resources to learn more about static analysis in Dart: