tc39 / proposal-decorators

Decorators for ES6 classes
https://arai-a.github.io/ecma262-compare/?pr=2417
2.76k stars 106 forks source link

Are class decorators always in strict mode? #545

Closed lpardosixtosMs closed 2 months ago

lpardosixtosMs commented 2 months ago

The decorators spec PR has the following note at the bottom of the Class Definition secition (15.8):

A class definition is always strict mode code.

The existing spec also specifies that "All parts of a ClassDeclaration or a ClassExpression are strict mode code." Given that DecoratorList is part of ClassDeclaration and ClassExpression, I understand that decorators are in strict mode too.

ClassDeclaration[Yield, Await, Default] :
  DecoratorList[?Yield, ?Await]opt class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await]

ClassExpression[Yield, Await] :
  DecoratorList[?Yield, ?Await]opt class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await]

As a consequence expressions like @yield class C{} or @yield() class C{} are not allowed because "yield" as an IdentifierReference is not allowed in strict mode. However, I saw this test262 test that explicitly tests that the latter is a valid expression.

I want to verify if decorators must be evaluated in strict mode.

ljharb commented 2 months ago

The decorator's definition (not its invocation) determines whether it's in strict mode, so they absolutely can be in sloppy mode.

lpardosixtosMs commented 2 months ago

I'm sorry, I think my concrete question was poorly worded. The decorator as a function can be in sloppy mode, but what about the decorator invocation?. Even if function yield() {} is a valid definition in sloppy mode, the following script causes a strict mode syntax error:

function yield() {}
class C {foo() {return yield()}}

And my understanding from the spec draft is that

function yield() {}
@yield() class C{}

causes a syntax error too.

ljharb commented 2 months ago

Modes apply to function definitions; the invocation has no effect on that. However, invoking a function named yield inside a class body will certainly error.

I agree that a class decorator is part of the class, and thus its local name must be valid in strict mode.

JLHwung commented 2 months ago

Duplicate of #204.

lpardosixtosMs commented 2 months ago

Thanks for the quick response!