Bug 20595 – there should be a way to suggest that `auto` return will only be of certain types

Status
NEW
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2020-02-22T17:57:16Z
Last change time
2024-12-13T19:07:11Z
Assigned to
No Owner
Creator
basile-z
See also
https://issues.dlang.org/show_bug.cgi?id=24197
Moved to GitHub: dmd#19667 →

Comments

Comment #0 by b2.temp — 2020-02-22T17:57:16Z
`auto` as a function return type is sometimes avoided by people who like to have a clean API. Unfortunately this is not always possible. This has a negative effect on completion, code navigation, and documentation. There should exist a syntax to indicate that `auto` will be among certain types or instance of a certain template declaration, similarly to constraint on template parameters. examples: // before... for now you have to navigate into two nested templates to find // the hint we will attach to auto. auto matchAll(R, RegEx)(R input, RegEx re); // after, type returned must be a template instance of RegexMatch auto(RegexMatch) matchAll(R, RegEx)(R input, RegEx re) // before... for now you're not sure because depending on the langs you already know // you'll think that either trunc() will return an integer or a floating type auto trunc(T)(T t) if (isIntegral!T); // after, type return is aliased as RT and RT must verify the template isFloating. auto(RT, isFloating!RT) trunc(T)(T t) if (isIntegral!T); so for the syntax maybe 'auto' ('(' AutoHint ')')? AutoHint < BasicType / AutoHintExpression AutoHintExpression < Identifier ',' RelExpression AutoHint as BasicType semantics: The BasicType must either represent a type or a template declaration. The infered type must be of the type or an instance of the tempalte declaration, according to what represented BasicType AutoHint as AutoHintExpression semantics: The identifier represents the type that's inferred The relational expression uses the identifier to performs checks. The type inferred must verify the RelExpression The would also works for declaring variables (AutoDeclarationX), with const(...) immutable(...) too, although essentially useful for functions.
Comment #1 by nick — 2023-03-31T12:17:58Z
You can already do this with an OutStatement with a static assert: auto f() out (r) { static assert(is(typeof(r) : int)); } do { return ""; } Compiling this you get an error, and the out contract should/could be shown in the docs (haven't checked).
Comment #2 by robert.schadek — 2024-12-13T19:07:11Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/19667 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB