Skip to content

Should we allow "?." as a null-aware element + dot shorthand? #4477

@munificent

Description

@munificent

The combination of null-aware elements and dot shorthands means this is now valid syntax:

list = [? .property];

However, if you remove the space between the ? and ., then it gets lexed as a single ?. token and you get a syntax error in:

list = [?.property];

I have a fix out to make sure the formatter doesn't output this syntax (dart-lang/dart_style#1642), but it's still a footgun if a user writes this.

Should we change the language so that it's allowed to not have a space there?

This is exactly analogous to how we handle the >> in List<List<int>> where we "un-lex" it from a right-shift >> to > > if we're in a context where right brackets are expected.

As far as I can tell, we should be able to do the same thing for a null-aware element followed by a dot shorthand. A null-aware element in that position will always be in a context where a null-aware access (i.e. ?.) can't appear.

I know it's hacky to have the parser and lexer interact in this way, but we already did for >> so maybe we should make the language accommodate ?.shorthand too? Otherwise, we are basically recapitulating C++'s mistake (which they finally fixed) and forcing users to remember to put a space in ? . or it won't do what they want.

cc @bwilkerson @jensjoha for thoughts on how this would interact with parsing and error handling.

Metadata

Metadata

Assignees

No one assigned

    Labels

    dot-shorthandsIssues related to the dot shorthands feature.null-aware-expressionsIssues proposing new expressions to manage null

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions