add type info for compiled functions

This commit is contained in:
markfisher
2017-05-25 12:38:54 -04:00
parent 098c77279b
commit 5a7c95bd97
11 changed files with 150 additions and 34 deletions

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -58,6 +58,12 @@ public abstract class AbstractFunctionCompiler<F> {
+ " public %s<%s> getResult() {\n" + " public %s<%s> getResult() {\n"
+ " %s\n" + " %s\n"
+ " }\n" + " }\n"
+ " public String getInputType() {\n"
+ " return \"%s\";\n"
+ " }\n"
+ " public String getOutputType() {\n"
+ " return \"%s\";\n"
+ " }\n"
+ "}\n"; + "}\n";
// @formatter:on // @formatter:on
@@ -91,23 +97,22 @@ public abstract class AbstractFunctionCompiler<F> {
* *
* @return a factory instance * @return a factory instance
*/ */
public CompiledFunctionFactory<F> compile(String name, String code, public final CompiledFunctionFactory<F> compile(String name, String code,
String... resultTypeParameterizations) { String... resultTypeParameterizations) {
if (name == null || name.length() == 0) { if (name == null || name.length() == 0) {
throw new IllegalArgumentException("name must not be empty"); throw new IllegalArgumentException("name must not be empty");
} }
logger.info("Initial code property value :'{}'", code); logger.info("Initial code property value :'{}'", code);
String parameterizations = StringUtils.arrayToCommaDelimitedString( String[] parameterizedTypes = (!ObjectUtils.isEmpty(resultTypeParameterizations))
(!ObjectUtils.isEmpty(resultTypeParameterizations)) ? resultTypeParameterizations
? resultTypeParameterizations : this.defaultResultTypeParameterizations;
: this.defaultResultTypeParameterizations);
code = decode(code); code = decode(code);
if (code.startsWith("\"") && code.endsWith("\"")) { if (code.startsWith("\"") && code.endsWith("\"")) {
code = code.substring(1, code.length() - 1); code = code.substring(1, code.length() - 1);
} }
if (!code.startsWith("return ") && !code.endsWith(";")) { if (!code.startsWith("return ") && !code.endsWith(";")) {
code = String.format("return (%s<%s> & java.io.Serializable) %s;", resultType, code = String.format("return (%s<%s> & java.io.Serializable) %s;", resultType,
parameterizations, code); StringUtils.arrayToCommaDelimitedString(parameterizedTypes), code);
} }
logger.info("Processed code property value :\n{}\n", code); logger.info("Processed code property value :\n{}\n", code);
String firstLetter = name.substring(0, 1).toUpperCase(); String firstLetter = name.substring(0, 1).toUpperCase();
@@ -115,15 +120,26 @@ public abstract class AbstractFunctionCompiler<F> {
String className = String.format("%s.%s%sFactory", String className = String.format("%s.%s%sFactory",
this.getClass().getPackage().getName(), name, resultType); this.getClass().getPackage().getName(), name, resultType);
CompilationResult compilationResult = buildAndCompileSourceCode(className, code, CompilationResult compilationResult = buildAndCompileSourceCode(className, code,
parameterizations); parameterizedTypes);
if (compilationResult.wasSuccessful()) { if (compilationResult.wasSuccessful()) {
return new CompiledFunctionFactory<F>(className, compilationResult); CompiledFunctionFactory<F> factory = new CompiledFunctionFactory<>(className, compilationResult);
return this.postProcessCompiledFunctionFactory(factory);
} }
List<CompilationMessage> compilationMessages = compilationResult List<CompilationMessage> compilationMessages = compilationResult
.getCompilationMessages(); .getCompilationMessages();
throw new CompilationFailedException(compilationMessages); throw new CompilationFailedException(compilationMessages);
} }
/**
* Implementing subclasses may override this, e.g. to set the input and/or output types.
*
* @param factory the {@link CompiledFunctionFactory} produced by {@link #compile(String, String, String...)}
* @return the post-processed {@link CompiledFunctionFactory}
*/
protected CompiledFunctionFactory<F> postProcessCompiledFunctionFactory(CompiledFunctionFactory<F> factory) {
return factory;
}
/** /**
* Create the source for and then compile and load a class that embodies the supplied * Create the source for and then compile and load a class that embodies the supplied
* methodBody. The methodBody is inserted into a class template that returns the * methodBody. The methodBody is inserted into a class template that returns the
@@ -133,15 +149,15 @@ public abstract class AbstractFunctionCompiler<F> {
* *
* @param className the name of the class * @param className the name of the class
* @param methodBody the source code for a method * @param methodBody the source code for a method
* @param parameterTypeString the String representation for the parameterized return * @param parameterizedTypes the array of String representations for the parameterized
* type, e.g.: <tt>&lt;Flux&lt;Object&gt;,Flux&lt;Object&gt;</tt> * input and/or output types, e.g.: <tt>&lt;Flux&lt;Object&gt;&gt;</tt>
* @return the list of Classes produced by compiling and then loading the snippet of * @return the list of Classes produced by compiling and then loading the snippet of
* code * code
*/ */
private CompilationResult buildAndCompileSourceCode(String className, private CompilationResult buildAndCompileSourceCode(String className,
String methodBody, String parameterTypeString) { String methodBody, String[] parameterizedTypes) {
String sourceCode = makeSourceClassDefinition(className, methodBody, String sourceCode = makeSourceClassDefinition(className, methodBody,
parameterTypeString); parameterizedTypes);
return compiler.compile(className, sourceCode); return compiler.compile(className, sourceCode);
} }
@@ -156,15 +172,31 @@ public abstract class AbstractFunctionCompiler<F> {
* *
* @param className the name of the class * @param className the name of the class
* @param methodBody the code to insert into the Reactive source class template * @param methodBody the code to insert into the Reactive source class template
* @param types the parameterized input and/or output types as Strings
* @return a complete Java Class definition * @return a complete Java Class definition
*/ */
private String makeSourceClassDefinition(String className, String methodBody, private String makeSourceClassDefinition(String className, String methodBody,
String types) { String[] types) {
String inputType = null;
String outputType = null;
if (ResultType.Supplier.equals(this.resultType)) {
outputType = types[0];
}
else if (ResultType.Consumer.equals(this.resultType)) {
inputType = types[0];
}
else if (ResultType.Function.equals(this.resultType)) {
inputType = types[0];
outputType = types[1];
}
else {
throw new IllegalStateException("no FunctionType available");
}
String shortClassName = className.substring(className.lastIndexOf('.') + 1); String shortClassName = className.substring(className.lastIndexOf('.') + 1);
String s = String.format(SOURCE_CODE_TEMPLATE, shortClassName, resultType, String s = String.format(SOURCE_CODE_TEMPLATE, shortClassName, resultType,
resultType, types, methodBody); resultType, StringUtils.arrayToCommaDelimitedString(types),
methodBody, inputType, outputType);
System.out.println(s); System.out.println(s);
return s; return s;
} }
} }

View File

@@ -1,11 +1,11 @@
/* /*
* Copyright 2016 the original author or authors. * Copyright 2016-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -23,4 +23,7 @@ public interface CompilationResultFactory<T> {
T getResult(); T getResult();
String getInputType();
String getOutputType();
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2016 the original author or authors. * Copyright 2016-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -29,6 +29,10 @@ public class CompiledFunctionFactory<T> implements CompilationResultFactory<T> {
private final byte[] generatedClassBytes; private final byte[] generatedClassBytes;
private String inputType;
private String outputType;
public CompiledFunctionFactory(String className, CompilationResult compilationResult) { public CompiledFunctionFactory(String className, CompilationResult compilationResult) {
List<Class<?>> clazzes = compilationResult.getCompiledClasses(); List<Class<?>> clazzes = compilationResult.getCompiledClasses();
T result = null; T result = null;
@@ -55,6 +59,22 @@ public class CompiledFunctionFactory<T> implements CompilationResultFactory<T> {
return result; return result;
} }
public String getInputType() {
return inputType;
}
public void setInputType(String inputType) {
this.inputType = inputType;
}
public String getOutputType() {
return outputType;
}
public void setOutputType(String outputType) {
this.outputType = outputType;
}
public byte[] getGeneratedClassBytes() { public byte[] getGeneratedClassBytes() {
return generatedClassBytes; return generatedClassBytes;
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2016 the original author or authors. * Copyright 2016-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,7 +23,20 @@ import java.util.function.Consumer;
*/ */
public class ConsumerCompiler<T> extends AbstractFunctionCompiler<Consumer<T>> { public class ConsumerCompiler<T> extends AbstractFunctionCompiler<Consumer<T>> {
private final String inputType;
public ConsumerCompiler() { public ConsumerCompiler() {
super(ResultType.Consumer, "Object"); this("Object");
}
public ConsumerCompiler(String inputType) {
super(ResultType.Consumer, inputType);
this.inputType = inputType;
}
@Override
protected CompiledFunctionFactory<Consumer<T>> postProcessCompiledFunctionFactory(CompiledFunctionFactory<Consumer<T>> factory) {
factory.setInputType(this.inputType);
return factory;
} }
} }

View File

@@ -23,6 +23,10 @@ import java.util.function.Function;
*/ */
public class FunctionCompiler<T, R> extends AbstractFunctionCompiler<Function<T, R>> { public class FunctionCompiler<T, R> extends AbstractFunctionCompiler<Function<T, R>> {
private final String inputType;
private final String outputType;
public FunctionCompiler() { public FunctionCompiler() {
this("Flux<Object>"); this("Flux<Object>");
} }
@@ -32,6 +36,15 @@ public class FunctionCompiler<T, R> extends AbstractFunctionCompiler<Function<T,
} }
public FunctionCompiler(String inputType, String outputType) { public FunctionCompiler(String inputType, String outputType) {
super(ResultType.Function, String.format("%s, %s", inputType, outputType)); super(ResultType.Function, inputType, outputType);
this.inputType = inputType;
this.outputType = outputType;
}
@Override
protected CompiledFunctionFactory<Function<T, R>> postProcessCompiledFunctionFactory(CompiledFunctionFactory<Function<T, R>> factory) {
factory.setInputType(this.inputType);
factory.setOutputType(this.outputType);
return factory;
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2016 the original author or authors. * Copyright 2016-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,7 +23,20 @@ import java.util.function.Supplier;
*/ */
public class SupplierCompiler<T> extends AbstractFunctionCompiler<Supplier<T>> { public class SupplierCompiler<T> extends AbstractFunctionCompiler<Supplier<T>> {
private final String outputType;
public SupplierCompiler() { public SupplierCompiler() {
super(ResultType.Supplier, "Flux<Object>"); this("Flux<Object>");
}
public SupplierCompiler(String outputType) {
super(ResultType.Supplier, outputType);
this.outputType = outputType;
}
@Override
protected CompiledFunctionFactory<Supplier<T>> postProcessCompiledFunctionFactory(CompiledFunctionFactory<Supplier<T>> factory) {
factory.setOutputType(this.outputType);
return factory;
} }
} }

View File

@@ -32,7 +32,7 @@ public abstract class AbstractByteCodeLoadingProxy<T> implements InitializingBea
private final Class<?> type; private final Class<?> type;
private T target; private CompilationResultFactory<T> factory;
private final SimpleClassLoader classLoader = new SimpleClassLoader(AbstractByteCodeLoadingProxy.class.getClassLoader()); private final SimpleClassLoader classLoader = new SimpleClassLoader(AbstractByteCodeLoadingProxy.class.getClassLoader());
@@ -42,6 +42,7 @@ public abstract class AbstractByteCodeLoadingProxy<T> implements InitializingBea
} }
@Override @Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
byte[] bytes = FileCopyUtils.copyToByteArray(this.resource.getInputStream()); byte[] bytes = FileCopyUtils.copyToByteArray(this.resource.getInputStream());
String functionName = this.resource.getFilename().replaceAll(".fun$", ""); String functionName = this.resource.getFilename().replaceAll(".fun$", "");
@@ -50,9 +51,7 @@ public abstract class AbstractByteCodeLoadingProxy<T> implements InitializingBea
String className = String.format("%s.%s%sFactory", FunctionCompiler.class.getPackage().getName(), upperCasedName, this.type.getSimpleName()); String className = String.format("%s.%s%sFactory", FunctionCompiler.class.getPackage().getName(), upperCasedName, this.type.getSimpleName());
Class<?> factoryClass = this.classLoader.defineClass(className, bytes); Class<?> factoryClass = this.classLoader.defineClass(className, bytes);
try { try {
@SuppressWarnings("unchecked") this.factory = (CompilationResultFactory<T>) factoryClass.newInstance();
CompilationResultFactory<T> factory = (CompilationResultFactory<T>) factoryClass.newInstance();
this.target = factory.getResult();
} }
catch (InstantiationException | IllegalAccessException e) { catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException("failed to load Function byte code", e); throw new IllegalArgumentException("failed to load Function byte code", e);
@@ -60,6 +59,14 @@ public abstract class AbstractByteCodeLoadingProxy<T> implements InitializingBea
} }
public final T getTarget() { public final T getTarget() {
return this.target; return this.factory.getResult();
}
public String getInputType() {
return this.factory.getInputType();
}
public String getOutputType() {
return this.factory.getOutputType();
} }
} }

View File

@@ -37,7 +37,7 @@ public class AbstractLambdaCompilingProxy<T> implements InitializingBean, BeanNa
private String beanName; private String beanName;
private T target; private CompiledFunctionFactory<T> factory;
private String[] typeParameterizations; private String[] typeParameterizations;
@@ -60,11 +60,18 @@ public class AbstractLambdaCompilingProxy<T> implements InitializingBean, BeanNa
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
String lambda = FileCopyUtils.copyToString(new InputStreamReader(this.resource.getInputStream())); String lambda = FileCopyUtils.copyToString(new InputStreamReader(this.resource.getInputStream()));
CompiledFunctionFactory<T> factory = this.compiler.compile(this.beanName, lambda, this.typeParameterizations); this.factory = this.compiler.compile(this.beanName, lambda, this.typeParameterizations);
this.target = factory.getResult();
} }
public final T getTarget() { public final T getTarget() {
return this.target; return this.factory.getResult();
}
public final String getInputType() {
return this.factory.getInputType();
}
public final String getOutputType() {
return this.factory.getOutputType();
} }
} }

View File

@@ -30,4 +30,6 @@ public interface ConsumerProxy<T> extends Consumer<T> {
} }
Consumer<T> getTarget(); Consumer<T> getTarget();
String getInputType();
} }

View File

@@ -31,4 +31,8 @@ public interface FunctionProxy<T, R> extends Function<T, R> {
} }
Function<T, R> getTarget(); Function<T, R> getTarget();
String getInputType();
String getOutputType();
} }

View File

@@ -30,4 +30,6 @@ public interface SupplierProxy<T> extends Supplier<T> {
} }
Supplier<T> getTarget(); Supplier<T> getTarget();
String getOutputType();
} }