Paul King created GROOVY-12791:
----------------------------------

             Summary: @NoScript: compile a script file containing only methods 
and declarations as a plain class
                 Key: GROOVY-12791
                 URL: https://issues.apache.org/jira/browse/GROOVY-12791
             Project: Groovy
          Issue Type: New Feature
          Components: Compiler
            Reporter: Paul King


A script file containing only method definitions is compiled to a 
{{groovy.lang.Script}} subclass, with a {{Binding}} constructor, an empty 
{{run()}} and a {{main}}:

{code:groovy}
// Foo.groovy
def foo() { println new Date() }
{code}
{noformat}
public class Foo extends groovy.lang.Script {
  public Foo();
  public Foo(groovy.lang.Binding);
  public static void main(java.lang.String...);
  public java.lang.Object run();
  public java.lang.Object foo();
}
{noformat}

Writing a {{main}} method instead produces a plain class (GROOVY-11118), but it 
is package-private and adds a {{main}} method. That does not suit frameworks 
that expect a class with exactly one method, such as some dependency injection 
frameworks.

Proposal: a {{@groovy.transform.NoScript}} annotation (incubating, source 
retention) with the same targets as {{@BaseScript}}: package, import, top-level 
declaration and type. It compiles the file as if it were:

{code:groovy}
class Foo {
    def foo() { println new Date() }
}
{code}

* The class is public, extends {{Object}}, and has no {{run()}}, no generated 
{{main}} and no {{Binding}} constructor.
* Top-level declarations become fields.
* When every method is static and there are no declarations, the class gets a 
private no-arg constructor.
* Other annotations next to {{@NoScript}} on the package declaration or an 
import are moved to the class, so {{@CompileStatic}} and {{@POJO}} can apply to 
the whole class:

{code:groovy}
import groovy.transform.CompileStatic
import groovy.transform.stc.POJO

@NoScript @CompileStatic @POJO
import groovy.transform.NoScript

def foo() { println new Date() }
{code}

* A {{@NoScript}} file with statements other than declarations is a compile 
error. So is a {{@NoScript}} that has no effect, for example in a file 
containing only classes.

Since {{ModuleNode.createStatementsClass()}} runs before any transform, the 
annotation is recognised by name there, as {{@Override}} already is for 
{{main}}.

Open questions:
* Whether the type target should stay. It only matches {{@BaseScript}} and is 
reported as an error on a class.
* Annotations on a {{@NoScript}} top-level declaration are not copied to the 
field, the same as on the instance-main path.
* A {{@NoScript}} file without {{main}} cannot be run with {{groovy 
Foo.groovy}} or {{GroovyShell.evaluate}}.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to