Summary
Permit nested {} groups in imports.
Permit * in {} groups in imports.
use ;
use ; // * in braces
use ; // both * and nested braces
Motivation
The motivation is ergonomics. Prefixes are often shared among imports, especially if many imports import names from the same crate. With this nested grouping it's more often possible to merge common import prefixes and write them once instead of writing them multiple times.
Guide-level explanation
Several use items with common prefix can be merged into one use item,
in which the prefix is written once and all the suffixes are listed inside
curly braces {}.
All kinds of suffixes can be listed inside curly braces, including globs * and
"subtrees" with their own curly braces.
// BEFORE
use TokenTree;
use ;
use AstBuilder,
use Span,
use ast;
use *;
use *;
use ;
// AFTER
use ;
// `*` can be listed in braces too
use ;
// both `*` and nested braces
use ;
// the prefix can be empty
use ;
// `pub` imports can use this syntax as well
pub use ;
A use item with merged prefixes behaves identically to several use items
with all the prefixes "unmerged".
Reference-level explanation
Syntax:
IMPORT = ATTRS VISIBILITY `use` [`::`] IMPORT_TREE `;`
IMPORT_TREE = `*` |
REL_MOD_PATH `::` `*` |
`{` IMPORT_TREE_LIST `}` |
REL_MOD_PATH `::` `{` IMPORT_TREE_LIST `}` |
REL_MOD_PATH [`as` IDENT]
IMPORT_TREE_LIST = Ø | (IMPORT_TREE `,`)* IMPORT_TREE [`,`]
REL_MOD_PATH = (IDENT `::`)* IDENT
Resolution:
First the import tree is prefixed with ::, unless it already starts with
::, self or super.
Then resolution is performed as if the whole import tree were flattened, except
that {self}/{self as name} are processed specially because a::b::self
is illegal.
use ;
=>
use b as s;
use c;
use d as e;
use *;
use h as i;
use *;
Various corner cases are resolved naturally through desugaring
use ; // Use an owl!
=>
use *;
use *; // Legal, but reported as unused by `unused_imports` lint.
Relationships with other proposal
This RFC is an incremental improvement largely independent from other import-related proposals, but it can have effect on some other RFCs.
Some RFCs propose new syntaxes for absolute paths in the current crate and paths from other crates. Some arguments in those proposals are based on usage statistics - "imports from other crates are more common" or "imports from the current crate are more common". More common imports are supposed to get less verbose syntax.
This RFC removes the these statistics from the equation by reducing verbosity
for all imports with common prefix.
For example, the difference in verbosity between A, B and
C is minimal and doesn't depend on the number of imports.
// A
use extern::;
// B
use crate::;
// C
use ;
Drawbacks
The feature encourages (but not requires) multi-line formatting of a single import
use ;
With this formatting it becomes harder to grep for use.*MyName.
Rationale and Alternatives
Status quo is always an alternative.
Unresolved questions
None so far.