TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Decorators

Open rbuckton opened this issue 11 years ago • 139 comments

ES7 proposal

The ES7 proposal for decorators can be found here: https://github.com/wycats/javascript-decorators The ES7 proposal serves as the base of this proposal. Below are notes about how the type system

Decorator targets:

Class constructor

@F("color")
@G
class Foo {
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo = __decorate([F("color"), G], Foo);
    return Foo;
})();

Methods

class Foo {
  @F(color)
  @G
  bar() { }
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.bar = function () {
    };
    Object.defineProperty(Foo.prototype, "bar", __decorate([F(color), G], Foo.prototype, "bar", Object.getOwnPropertyDescriptor(Foo.prototype, "bar")));
    return Foo;
})();

Static method

class Foo {
    @F("color")
    @G
    static sMethod() {}
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo.sMethod = function () {
    };
    Object.defineProperty(Foo, "sMethod", __decorate([F("color"), G], Foo, "sMethod", Object.getOwnPropertyDescriptor(Foo, "sMethod")));
    return Foo;
})();

Properties

class Foo {
    @F("color")
    @G
    prop: number;
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    __decorate([F("color"), G], Foo.prototype, "prop");
    return Foo;
})();

Method/Accessor formal parameter

class Foo {
    method(@G a, @F("color") b) {}
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.method = function (a, b) {
    };
    __decorate([G], Foo.prototype, "method", 0);
    __decorate([F("color")], Foo.prototype, "method", 1);
    return Foo;
})();

Where the __decorate is defined as:

var __decorate = this.__decorate || function (decorators, target, key, value) {
    var kind = typeof (arguments.length == 2 ? value = target : value);
    for (var i = decorators.length - 1; i >= 0; --i) {
        var decorator = decorators[i];
        switch (kind) {
            case "function": value = decorator(value) || value; break;
            case "number": decorator(target, key, value); break;
            case "undefined": decorator(target, key); break;
            case "object": value = decorator(target, key, value) || value; break;
        }
    }
    return value;
};

Decorator signatures:

A valid decorator should be:

  1. Assignable to one of the Decorator types (ClassDecorator | PropertyDecorator | MethodDecorator | ParameterDecorator) as described below.
  2. Return a value (in the case of class decorators and method decorator) that is assignable to the decorated value.
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;

Notes:

  • Decorating a function declaration is not allowed as it will block hoisting the function to the top of the scope, which is a significant change in semantics.
  • Decorating function expressions and arrow functions are not supported. The same effect can be achived by applying the decorator function as var x = dec(function () { });
  • Decorating function formal parameters is currently not part of the ES7 proposal.
  • Decorators are not allowed when targeting ES3

rbuckton avatar Mar 07 '15 03:03 rbuckton

I also have to ask that question - does it make sense to maintain syntactic parity with with functions if (and only if) there is no real reason to do so other than "because it's defined using functions". I see Decorators as an entirely unrelated feature to functions which just happen to be defined using them.

Right now the fact that @F and @F() are not identical causes the following issues:

  • Developers needing to understand the difference between @F and @F() and why sometimes this may work and why sometimes this may not work (and the need to use @F vs. @F() could be entirely framework/code/usage specific - therefore inconsistent from a consumption standpoint: Imagine declare function A(params?: any): ParameterDecorator vs declare function B(target, name), @A won't work, but @A() will, @B will work but @B() won't, yet cognitively they're the same thing, an application of a decorator with no arguments).
  • Solving the issue from a code level requires a cludgy workaround that removes ones ability to adequately document the Decorator's invocation syntax.
  • Refactoring is a bit more work if you've created a 'raw decorator' (@F) and now you want to add some parameters (but make them optional for backwards compatibility). Under the current method, all those @F applies will now need to be refactored to @F() - some within code you may not have access to - while implicit invocation would allow you keep things working and restrict the change to your code.

Tharaxis avatar May 22 '15 06:05 Tharaxis

@Tharaxis I understand that the distinction between @F and @F() can be a high cognitive burden on consumers. However, it sounds like you are asking for the emitted code, and therefore the behavior, to change, so that the two behave equivalently. This would likely conflict with the ES7 proposal for decorators, since the two forms are very unlikely to be treated the same. It will not be good if this leads to a divergence.

Another point is that the confusion here is akin to the confusion between passing a function as a callback, and calling the function. If you had this

function callbackFactory() {
     return function(...args: any[]) { // do stuff };
}
function takesCallback(cb: (...args: any[]) => void) { }
takesCallback(callbackFactory());

A user may get confused and call takesCallback(callbackFactory) without invoking callbackFactory. This is really just like the confusion you pointed out with decorators, but if the language normalized these two forms to do the same thing, there would be a loss in expressivity. Sometimes the distinction is important, and needs to be maintained. Not sure if this commonly applies for decorators as well, but in theory it certainly could.

JsonFreeman avatar May 23 '15 05:05 JsonFreeman

@JsonFreeman I don't really get your argument though. You're saying that you can't make decorators make sense as their own entity because an ES7 proposal exists for decorators, but that's the thing, ES7 decorators are just that, a proposal, and as far as I'm aware, they're partly based on a combination of the decorator work described by both Google and yourselves, correct? Nothing has been decided on yet as to how they are to work, and it is likely that the proposal will go through many iterations prior to approval, so why not have them working in a consistent manner in TS and then (at least try) get the various parties involved in the proposal behind the idea, using experience gained in TS as a basis? This would not be the first time TS has implemented a feature only to have to refactor later because the ES6 spec called for slightly different behaviour. You'll always have that problem as long as you're tracking against a spec that does not yet exist and has not yet been agreed upon.

As for your example regarding functions, it appears yet again we're is conflating functions with decorators when they are in reality (and should be) completely different constructs. When I'm working with a function in JavaScript, I understand how functions are used and I understand the difference between a function reference and a function call (and when I might want to use one vs. the other) - and when I describe something as a function, there is no confusion as to what usages it has. Decorators are not functions and should not inherit behaviour of functions. Functions are merely the method upon which decorators are constructed. That's like saying classes are functions, which is not the case, functions are merely the way though which we describe classes prior to ES6 because there was no more obvious method available. Classes don't take on the properties of functions, you cannot call classes like functions, but you do declare them using functions prior to ES6.

Regardless, I feel that I've exhausted my points of argument on the issue. I'll just have to work around the choice. In my own code I'll always make use of factories for the sake of my own consistency. I still believe treating decorators literally as functions is likely to cause plenty frustration in the future, but that's just me.

Tharaxis avatar May 23 '15 11:05 Tharaxis

@mhegazy This is the same issue I brought up on the @jonathandturner decorator repo here: https://github.com/jonathandturner/decorators/issues/16 I do think this is something that should be thought about. As it stands, I expect this design choice to be the subject of many blog posts titled something similar too "ES7 Decorator Pitfalls".

EisenbergEffect avatar May 23 '15 14:05 EisenbergEffect

@Tharaxis, I agree with your first point. I don't think an ES7 proposal should prevent us from designing something well, and our design is indeed one of the precursors to ES7 anyway.

As for the "decorators are not functions argument", if I'm not mistaken, we are not discussing decorators themselves, we are discussing decorator factories. And regardless of any distinction between decorators and functions, I think decorator factories are actually just functions. And it sounds like you are asking for the compiler to automatically generate a call to a decorator factory, which is an ordinary function. If that happened, there would be no way for the programmer to distinguish between the decorator factory and the decorator.

Also, the nice thing about treating decorators as functions is that a consumer can apply it as a decorator or by simply calling it as they see fit.

JsonFreeman avatar May 23 '15 23:05 JsonFreeman

@JsonFreeman the argument revolves around the current situation where there are two ways to both describe and invoke a decorator, one through a factory function, and then one as a "raw" function (which in the factory case is the result of a factory call), and the question was more about "shouldn't there just be one way, and have factories be that way".

What I am asking is yes, could we not just have the compiler turn @F into the equivalent of @F() call and have type checking require an argument list of 0...n parameters when using the unbracketed syntax. Perhaps you could elaborate on what is meant by "...there would be no way for the programmer to distinguish between the decorator factory and the decorator...", since I would think it's very easy to distinguish. The decorator is always the response from the factory, and the name of the factory is the decorator's name... not that difficult, or am I misunderstanding?

As for your last point about allowing the consumer to just apply the decorator, if it's well described that all decorators use factories, it's pretty easy to then invoke a decorator yourself, you just do <decorator name>(<argument list>)(target, name) compared to <decorator name>(target, name) as an example. Keep in mind that mandating the use of factories would mean the former example will always work, while not mandating it will result in the latter example sometimes not working, and is entirely dependent on how the decorator is implemented - a headache just waiting to happen.

I feel it necessary to point out, I have no problem with decorators using functions, my issue is however that having two ways to describe the same thing leads to consistency issues. Especially when it those two ways also mean your method of invocation has to differ. This is a disparity that hinders everything from refactoring to language consistency.

The refactoring problem I described a few posts back should already be more than enough of a reason why the current method needs to be inspected.

Tharaxis avatar May 24 '15 00:05 Tharaxis

Hi all, just a final 1.5 cents worth from a regular user along the lines of what @Tharaxis has said.

I'd be more than happy with current proposal if: a) the universe mandates it. b) decorators will loose important capabilities if things were different.

The later is of course a value judgment, to which the answer will depend to some degree on the type of developer you are (i.e. general user / expert user etc). I'm in the former category and am generally spread thinly across multiple languages and frameworks. So for me 'important capabilities' aren't going to include flexibility to write decorators 2 different ways. Examples of all the tradeoffs would be great if they exist.

Ideally it'd be great if @F and @F() could be consistent regardless of how decorators are implemented, but if not I'd vastly prefer to be constrained to using factories when writing decorators rather than having to avoid rakes in the grass whenever I'm using them.

Thanks & cheers

pietschy avatar May 24 '15 03:05 pietschy

It seems like this request hinges on the idea that decorator factories are the canonical way to use decorators, but I don't see how this allows the user to define and use raw decorators. If I define a decorator F, and the application @F gets treated as @F(), then the result of calling F is used as the decorator, instead of F itself. Are you suggesting we give an error somewhere if someone tries to apply a raw decorator instead of a decorator factory?

This idea feels like it would reverse the natural compositionality of decorators and decorator factories. Decorators definitely feel like the primitive construct here, with decorator factories being a layer of abstraction built on top of decorators. They are just a pattern, nothing more. If instead the decorator factory became the canonical thing, the primitive, then people would define a bunch of decorator factories, that take no arguments and return a flat decorator. This would start to feel very silly, and it would reverse the natural intuition of what is considered basic and what is considered more complex.

One thing I am very wary of with decorators is an excess of magic. I personally get nervous when I don't understand what the code is doing, and if the compiler is secretly adding extra invocations that the programmer did not write, that feels to me like too much voodoo.

JsonFreeman avatar May 24 '15 04:05 JsonFreeman

Hi @JsonFreeman,

As I mentioned my preference would always be for the ugliness to be with the author of the decorator rather than the user. However, I agree that lots of no arg factories is a whole lot of ugly. Could a decorator be used to fix this? E.g.

// wraps rawDecoratorMethod in a no-arg factory method.
@Decorator
function rawDecoroatorMethod(target, name, descriptor) {...}
// looks like this one would be a no-op... so that feels not quite right unless there's other advantages.
@DecoratorFactory
function decoroatorFactoryMethod(someArg) {...}

Anyway, if such an approach could be found to make sense it has the advantage that the annotation documents the purpose of the function. i.e. it decorates.

Cheers

pietschy avatar May 24 '15 06:05 pietschy

Good gravy, decorators to help define decorators, a serious case of Typeception.

@JsonFreeman I'm not sure having zero-param functions are necessarily any more ugly than having a multitude of (target, name) functions in their stead. If anything at least the zero-param functions provide a level of specificity/explicitness that the other method lacks (since the parameters don't ever match the invocation in the latter case), and on top of that provides a single target to document instead of an unnecessary level of inconsistency. I also see a reluctance to go any one route due to a perceived "possible" complexity, but I would say in the light of the very real "obvious" complexity the current implementation imposes on the consumption side, one should err more on the side of the obvious than the possible.

The other option is to mandate that decorators which are called as @F are able to match either the pattern for ClassDecorator, MethodDecorator, PropertyDecorator or ParameterDecorator, OR a 0..n arg factory function that returns ClassDecorator, MethodDecorator, PropertyDecorator or ParameterDecorator. However I would feel that that implementation would cause other errors (what if you have two conflicting functions, which one would be considered best possible match?) and would just add undue complexity within the compiler. Simply converting @F calls to @F() would be the simpler solution and would solve the various problems stated.

Tharaxis avatar May 25 '15 00:05 Tharaxis

Sorry, to clarify, I wasn't claiming that your solution is complex. I meant that automatically invoking the decorator before applying it is opaque. The inserted invocation is invisible to the user, and I feel like many users will not expect it.

I think the way it currently stands is not complex either. As you point out, it allows library authors to be vague or wishy-washy about whether their function is meant to be applied as a decorator. That I will grant you. But a good library will make it clear.

In the scheme you suggest, where you do the invocation automatically, what happens when you use an arbitrary decorator expression instead of just an identifier? Does that get invoked too?

JsonFreeman avatar May 25 '15 03:05 JsonFreeman

I'll agree, that unless documented otherwise the implicit invocation is likely to be surprising, but only to those that haven't used concepts such as C# attributes and the like.

Could you elaborate on what you mean by an arbitrary decorator expression?

Tharaxis avatar May 25 '15 12:05 Tharaxis

Good gravy, decorators to help define decorators, a serious case of Typeception.

Fair call. Serves me right for a poorly thought-out comment late on a weekend afternoon. Lesson learnt. Internet.undo().

My point being that if it turns out that consistent call site syntax mandates the use of factories then I'm more than happy with that. I'll no doubt write a decorator to remove the boiler plate. Again I'd prefer a little pain when writing the decorator over repeated pain using them (albeit potential pain at this point). Others will disagree.

Isn't there also the issue with API enhancement? A decorator created without a factory can't have optional parameters added at a later time, hence I predict @F and @F2() in my future.

I also don't see that you'd get this scenario when using f and f(), they're different use cases on the consumption side. In the decorator case I'm always applying/invoking the decorator on the target right then and there, and there's always a method invocation going on behind the scenes.

But the crux of this for me is the usability issue, when I'm applying a decorator I don't want to have to google to find out how the author implemented it - I'm interested in the behaviour, not the packaging.

Cheers

pietschy avatar May 25 '15 23:05 pietschy

Just a final note to summarise and then I'll keep quiet. In short, this is really just an interaction design issue for me. I'm really keen to see decorators designed from the outside in and not the other way around.

As a UI/UX guy I see this fairly often. I've worked with talented developers who have suggested UI solutions that would hurt users (one example was two save buttons in one case to solve a transaction complexity - again a smart guy and good human). I just think when you're knee deep in complex implementation details logic it can be hard to forget what you know and see it through the eyes of average user.

Now if as the average I'm just plain wrong, or if the complexity mandates the current design then all good, I'll just have to get my brain on and learn.

Cheers

pietschy avatar May 25 '15 23:05 pietschy

If your decorator is not an identifier, but some other expression, would you automatically invoke it?For example, let's say it was a decorator. OR-ed with a fallback function expression. Something like:

@(F || function (target) { // default decorator behavior })
class C { }

Do you then automatically invoke this? That would give you the wrong result because you end up invoking the default decorator before it's applied:

(F || function (target) { // default decorator behavior })()

This does not seem right.

JsonFreeman avatar May 26 '15 04:05 JsonFreeman

@JsonFreeman, does the decorator syntax allow for arbitrary expressions like that? I'm not 100% certain allowing developers that much rope with which to hang themselves with is necessarily a good idea, but that's just me (purely because I don't see arbitrary expressions like that solving the reuse/boilerplate issue decorators aim to solve and instead just serve to make the code look ugly and even more difficult to follow).

That said, I suppose the only way it would work then would be if the arbitrary expression itself evaluates to the same factory syntax, so:

@(F || () => function(target) { /* default decorator behaviour */ })
class C { }

I agree it does result in you having to put a few more fiddly bits around your arbitrary decorator, but I think one has greater issues than the addition of () => if you're using arbitrary expressions as decorators.

NOTE: I obviously did not mean that lambda syntax would be the only way to declare it, but () => is slightly nicer than function() { return function(target) { /*...*/ } }.

Tharaxis avatar May 26 '15 09:05 Tharaxis

Really sorry to interrupt this decorator calling syntax debate, but could anyone officially clarify the order the decorator expressions are called? Especially, along the lines of decorator target type, the position of the target member in the original source and the order of the decorators on a single target.

qc00 avatar May 27 '15 16:05 qc00

@billccn The decorators are applied from bottom to top. So in the original source code if you had

class C {
    @F
    @G
    method() { }
}

This would first apply G to method, and then apply F to the result. Is this what you are asking?

JsonFreeman avatar May 27 '15 17:05 JsonFreeman

How about for this:

@A
class Clazz {
    @B
    prop = 1;

    @C
    method() {}

    @D
    get prop() {return 1;}

    @E
    method2() {}

    @F
    prop2 = 1;
}

qc00 avatar May 27 '15 17:05 qc00

they follow scope order, so all properties/methods first, in order of declaration, then the class one. i.e. B, C, D, E, F, A.

you can see the generated code here.

mhegazy avatar May 27 '15 17:05 mhegazy