-
Notifications
You must be signed in to change notification settings - Fork 11
/
GroovyCompiler.groovy
245 lines (192 loc) · 6.38 KB
/
GroovyCompiler.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package play.groovysupport.compiler
import groovy.lang.GroovyClassLoader
import groovy.io.FileType
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.CompilationUnit
import org.codehaus.groovy.control.CompilationUnit.ClassgenCallback
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.control.CompilationFailedException
import org.codehaus.groovy.control.MultipleCompilationErrorsException
import org.codehaus.groovy.control.messages.SimpleMessage
import org.codehaus.groovy.control.messages.SyntaxErrorMessage
import static org.codehaus.groovy.control.CompilationUnit.SourceUnitOperation
import org.codehaus.groovy.ast.ClassHelper
import org.codehaus.groovy.ast.ClassNode
import play.Play
import play.vfs.VirtualFile
class GroovyCompiler {
def app
def output
def compilerConf
def prevClasses = [:]
def classesToSources = [:]
def GroovyCompiler(File app, File libs, List classpath, File output) {
this.app = app
this.output = output
// TODO: set source encoding to utf8
compilerConf = new CompilerConfiguration()
compilerConf.setTargetDirectory(new File(output, 'classes/'))
compilerConf.setClasspathList(classpath)
}
static def getSourceFiles = { path, regex = /^[^.].*[.](groovy|java)$/ ->
def list = []
if(path.exists()) {
path.eachFileRecurse(FileType.FILES, { f ->
if (f =~ regex) {
list << f
}
})
}
return list
}
File classNameToFile(className) {
def classFile = new File(output, 'classes/' + className.replace('.', '/') + '.class')
return classFile.exists() ? classFile : null
// TODO: instead of null, throw an exception? What to do if the class
// source can't be found?
}
def classNameToSource(name) {
if (name.contains('$')) {
// inner classes will be in the same file as
// their parent class, so look on that instead
name = name.substring(0, name.indexOf('$'))
}
return classesToSources[name]
}
CompilationResult update(List sources) {
// TODO: investigate if there's a better way than creating new
// CompilationUnit instances every time...
def classLoader = new ModClassLoader()
def cu = new CompilationUnit(classLoader)
cu.configure(compilerConf)
// reset classesToSources map
classesToSources = [:]
// fix static star imports, see comment on field
cu.addPhaseOperation(importFixer, org.codehaus.groovy.control.Phases.CONVERSION)
cu.addSources(sources as File[])
try {
def newClasses = [:]
cu.setClassgenCallback(new ClassgenCallback() {
void call(org.objectweb.asm.ClassVisitor writer, ClassNode node) {
//println 'classgen: ' + node
//println node.compileUnit.classesToCompile
}
})
cu.compile()
cu.getClasses().each {
newClasses[it.getName()] = [bytes: it.getBytes()]
}
// now that compilation is done we can create the classesToSources map
for (sourceUnit in cu) {
sourceUnit.getAST().classes.each { clazz ->
// ignore inner classes
if (!clazz.name.contains('$')) {
classesToSources[clazz.name] = new File(sourceUnit.name)
}
}
}
// NOTE: since the CompilationUnit will simply recompile everything
// it's given, we're not bothering with 'recompiled' classes
def updated = newClasses.keySet()
.collect { cn ->
new ClassDefinition(name: cn,
code: newClasses[cn].bytes, source: classNameToSource(cn))
}
def removed = prevClasses.keySet().findAll { !(it in newClasses.keySet()) }
.collect { cn ->
new ClassDefinition(name: cn, code: null, source: null)
}
prevClasses = newClasses
return new CompilationResult(updated, removed)
} catch (MultipleCompilationErrorsException e) {
if (e.getErrorCollector().getLastError() != null) {
def errorMessage = e.getErrorCollector().getLastError()// as SyntaxErrorMessage
if (errorMessage instanceof SimpleMessage) {
// TODO: this shouldn't happen but handle it somehow
// just in case
println 'This is really bad and should not have happened'
e.printStackTrace()
System.exit(1)
}
else {
errorMessage = errorMessage as SyntaxErrorMessage
def syntaxException = errorMessage.getCause()
def compilationError = new CompilationError(
message: syntaxException.getMessage(),
line: syntaxException.getLine(),
start: syntaxException.getStartColumn(),
end: syntaxException.getStartLine(),
source: new File(syntaxException.getSourceLocator())
)
throw new CompilationErrorException(compilationError)
}
}
throw new CompilationErrorException(
new CompilationError(message: 'Could not get compilation error')
)
}
}
/**
* the groovy compiler appears to ignore <import package.name.*> when
* trying to import nested static classes. Groovy considers these as
* 'static star imports', and needs the "import static package.org.*"
* syntax for them to work.
*
* Since Java files won't have this syntax,
* we need to do a little modification to the AST during compilation
* to ensure any of the compiled play-Java classes have their imports
* picked up. This seems like more of an interim solution though...
*/
def importFixer = new SourceUnitOperation() {
// TODO: add all the relative play static star imports
def playStaticStarImports = [
'play.mvc.Http'
]
void call(SourceUnit source) throws CompilationFailedException {
def ast = source.getAST()
def imports = ast.getStarImports()
.collect {
it.getPackageName()[0..it.getPackageName().length()-2]
}
.findAll {
it in playStaticStarImports
}
imports.each {
ast.addStaticStarImport('*', ClassHelper.make(it))
}
}
}
}
class ModClassLoader extends GroovyClassLoader {
def ModClassLoader() {
//super(Play.classloader)
}
}
class ClassDefinition {
String name
byte[] code
File source
@Override String toString() {
"ClassDefinition(name: ${name}, source: ${source})"
}
}
@Immutable class CompilationResult {
List<ClassDefinition> updatedClasses, removedClasses
}
class CompilationError {
String message
Integer line
Integer start
Integer end
File source
@Override String toString() {
"CompilationError(${message}, ${line}, ${start}, ${end}, ${source})"
}
}
class CompilationErrorException extends Exception {
CompilationError compilationError
def CompilationErrorException(compilationError) {
super()
this.compilationError = compilationError
}
}