Skip to content

Instantly share code, notes, and snippets.

@fmamud
Created August 4, 2016 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmamud/23845248def4d15fc38dbd4d2608d6d8 to your computer and use it in GitHub Desktop.
Save fmamud/23845248def4d15fc38dbd4d2608d6d8 to your computer and use it in GitHub Desktop.
Groovy compiler customization with type checking and static compilation
beforeVisitMethod { methodNode ->
println "calling ${methodNode.name}(${methodNode.parameters.join(',')})"
}
afterMethodCall { call ->
if (getTargetMethod(call).name=='plus') {
addStaticTypeError('plus() not allowed',call)
handled = true
}
if (getTargetMethod(call).name=='somar') {
if (getTargetMethod(call).returnType.typeClass != int) {
addStaticTypeError('somar() must returns int', call)
handled = true
}
if (getTargetMethod(call).parameters*.type*.typeClass != [int, int]) {
addStaticTypeError('somar() must be int, int parameters', call)
handled = true
}
}
}
int somar(int a, int b) {
a + b
}
println "Resultado: ${somar(2, 2)}"
import groovy.transform.CompileStatic
withConfig(configuration) {
ast(extensions: ['MyExtension.groovy'], CompileStatic)
inline(phase:'CONVERSION') { source, context, classNode ->
println ">> CONVERSION $classNode"
}
imports {
star 'java.time'
normal 'java.util.function.Function', 'java.util.function.Supplier'
}
secureAst {
closuresAllowed = false
methodDefinitionAllowed = true
}
}
groovy --configscript rules.groovy MyTypedScript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment