17

I'm trying to build a DSL and using a Global AST Transform to do it. The script is compiling with groovyc fine, but I'd like to be able to be able to have a user use Grab/Grape to pull the JAR and just have it execute right away as a groovy script.

I then found that I couldn't do it correctly because there's a parsing error in the script if there isn't a method declaration or import statement after the @Grab call.

Here's an example:

@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')

println "Hello World!"

It looks like it should work, but it complains (here's the output the GroovyConsole Script):

startup failed:
Script1.groovy: 4: unexpected token: println @ line 4, column 1.
   println "hello"
   ^

1 error

Trying different things makes it work, like an import statement:

@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
import groovy.lang.Object
println "Hello World!" ​

Or a method declation:

@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
def hello() {}
println "Hello World!"

Is this a bug in the parser? ​

Phuong LeCong
  • 1,834
  • 16
  • 19
  • at the current time (7 years later! v 2.4.13) `import groovy.lang.Object` gives an "unable to resolve class" error. I put `java.lang.Object` instead. – mike rodent Apr 21 '18 at 11:59

2 Answers2

16

Grab can only be applied as an annotation to certain targets

@Target(value={CONSTRUCTOR,FIELD,LOCAL_VARIABLE,METHOD,PARAMETER,TYPE})

So you need to annotate one of those things (like you are seeing)

There is unfortunately no way in Java (and hence Groovy) of annotations just appearing in the middle of code.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 2
    What you're saying makes sense, but I guess I think from a common sense point of view the example above should still work since there are so many implicit things being created including a type and method. It's not appearing in the middle of code, but I can understand how lexically there are some problems. – Phuong LeCong Jun 06 '11 at 19:22
0

test this

import static groovy.grape.Grape.grab
grab(group: "mysql", module: "mysql-connector-java", version: "5.1.6")
println "Hello World!"
Anders B
  • 3,343
  • 1
  • 26
  • 17
  • This is the recommended way of loading dependencies in groovy script files and not groovy class files per documentation, annotations are for groovy class files: http://docs.groovy-lang.org/latest/html/documentation/grape.html – Glushiator May 07 '21 at 15:48