[swift-evolution] Adding custom attributes

Dmitri Gribenko gribozavr at gmail.com
Sat Dec 26 09:20:09 CST 2015


On Sat, Dec 26, 2015 at 3:59 PM, Radosław Smogura <rsmogura at icloud.com> wrote:
> So,
>
> What do you think about syntax like this:
>
> // Declaration
> @AttributeUsage(RUNTIME) //Can be SOURCE - attribute not emitted into binary
> @AttributeTarget(PROPERTY) //Other CLASS, ENUM, METHOD, INIT
> @attribute JSONProperty {
> var name:String!;
> var serializable:Bool? = true;
> var deserializable:Bool? = true;
> }

Is this a new declaration kind?  Do you think we could make it work
with existing language constructs instead, like structs?  Any
downsides to that?

> // Usage
> @JSONProperty(name=“id”)
> var id:Int;
>
>
> Attributes should be module aware (actual attributes should be redefined as Swift attribute, for beginning still can be hardcoded).

Sorry, I'm not sure what this means.

> The attribute’s name have to be unique in module. It’s compile time error if attribute, class, enum, struct, etc has same name.
>
> Attribute’s properties are read only and can’t be assigned - so during reflection no-one would change ‘shared’ values.

I think using structs and requiring that attributes are value types
would solve both issues.

> Attribute’s properties can only support basic types: primitives, strings, types, and other attributes (optional).

Well, there is no such thing as "basic types" in Swift.  Strings,
integers etc. are defined in the standard library and the compiler
does not know anything special about them.

> When declaring attributes, properties can be set to constant values (static let) or enum values, however the final value is stored in binary, not a reference to it.

Again, given that strings are defined in the standard library, and
that the language does not have a notion of a constant expression, I'm
not sure how this would work.  I'm not saying it can't, I'm just
saying you need to introduce a lot of new language concepts and
compiler machinery.

> The compiler has build in support for core attributes, which can affect code generation. Compiler may perform additional checks on core attributes.

OK.

Another question is, how would you inspect attributes at runtime?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-evolution mailing list