Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typesafe-core #319

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 45 additions & 6 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
apply from: file('gradle/convention.gradle')
apply from: file('gradle/maven.gradle')
//apply from: file('gradle/check.gradle')
apply from: file('gradle/license.gradle')
apply from: file('gradle/release.gradle')

ext.githubProjectName = rootProject.name

buildscript {
Expand All @@ -9,20 +15,53 @@ allprojects {
repositories { mavenCentral() }
}

apply from: file('gradle/convention.gradle')
apply from: file('gradle/maven.gradle')
//apply from: file('gradle/check.gradle')
apply from: file('gradle/license.gradle')
apply from: file('gradle/release.gradle')

subprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

group = "com.netflix.${githubProjectName}"

ext.codeGenOutputDir = file("build/rewritten_classes")

// make 'examples' use the same classpath
configurations {
core
examplesCompile.extendsFrom compile
examplesRuntime.extendsFrom runtime
}

sourceSets.test.java.srcDir 'src/main/java'

tasks.withType(Javadoc).each {
it.classpath = sourceSets.main.compileClasspath
}

sourceSets {
//include /src/examples folder
examples
}

// include 'examples' in build task
tasks.build {
dependsOn(examplesClasses)
}

eclipse {
classpath {
// include 'provided' dependencies on the classpath
plusConfigurations += configurations.provided

downloadSources = true
downloadJavadoc = true
}
}

idea {
module {
// include 'provided' dependencies on the classpath
scopes.PROVIDED.plus += configurations.provided
}
}
}

2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.3-bin.zip
distributionUrl=http\://services.gradle.org/distributions/gradle-1.6-bin.zip
22 changes: 22 additions & 0 deletions language-adaptors/codegen/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'osgi'

dependencies {
compile project(':rxjava-core')
compile 'org.javassist:javassist:3.17.1-GA'

provided 'junit:junit:4.10'
}

jar {
manifest {
name = 'rxjava-codegen'
instruction 'Bundle-Vendor', 'Netflix'
instruction 'Bundle-DocURL', 'https://github.com/Netflix/RxJava'
instruction 'Import-Package', '!org.junit,!junit.framework,!org.mockito.*,*'
instruction 'Fragment-Host', 'com.netflix.rxjava.core'
}
}
47 changes: 47 additions & 0 deletions language-adaptors/codegen/examples.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Here's the example source of Observable (heavily elided):

public class rx.Observable {
public static <T> Observable<T> create(Func1<Observer<T>, Subscription> func) {
return new Observable<T>(func);
}

public static <T> Observable<T> create(Object func) {
...
}

public static <T> Observable<T> take(final Observable<T> items, final int num) {
return create(OperationTake.take(items, num));
}

public static <T> Observable<T> takeWhile(final Observable<T> items, Func1<T, Boolean> predicate) {
return create(OperationTakeWhile.takeWhile(items, predicate));
}

public Observable<T> filter(Func1<T, Boolean> predicate) {
return filter(this, predicate);
}

public static <T> Observable<T> filter(Observable<T> that, Func1<T, Boolean> predicate) {
return create(OperationFilter.filter(that, predicate));
}
}

Groovy-friendly version adds:

public class rx.Observable {
public static <T> rx.Observable<T> create(groovy.lang.Closure func) {
return create(new GroovyFunctionAdaptor(func));
}

public static <T> rx.Observable<T> takeWhile(final Observable<T> items, groovy.lang.Closure predicate) {
return takeWhile(items, new GroovyFunctionAdaptor(predicate));
}

public rx.Observable<T> filter(groovy.lang.Closure predicate) {
return filter(new GroovyFunctionAdaptor(predicate));
}

public static <T> rxObservable<T> filter(Observable<T> that, groovy.lang.Closure predicate) {
return filter(that, new GroovyFunctionAdaptor(predicate));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.codegen;

import java.util.ArrayList;
import java.util.List;

import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;

import rx.util.functions.FunctionLanguageAdaptor;

/**
* An implementation of method rewriting that leaves the rx.Function variant alone and adds dynamic language
* support by adding a new method per native function class. The new methods do nothing more than convert the
* native function class into an rx.Function and forward to the core implementation.
*
* For example, if {@code Observable} has a method Integer foo(String s, Func1<A, B> f, Integer i), then the
* rewritten class will add more 'foo's with dynamic language support.
*
* For Groovy (as an example), the new class would contain:
* Integer foo(String s, Func1<A, B> f, Integer i);
* Integer foo(String s, Closure f, Integer i) {
* return foo(s, new GroovyFunctionWrapper(f), i);
* }
*/
public class AddSpecializedDynamicMethodRewriter extends MethodRewriter {

public AddSpecializedDynamicMethodRewriter(CtClass enclosingClass, CtMethod method, FunctionLanguageAdaptor adaptor) {
this.enclosingClass = enclosingClass;
this.initialMethod = method;
this.adaptor = adaptor;
}

@Override
public boolean needsRewrite() {
return true;
}

@Override
public boolean isReplacement() {
return false;
}

@Override
protected List<MethodRewriteRequest> getNewMethodsToRewrite(CtClass[] initialArgTypes) {
return duplicatedMethodsWithWrappedFunctionTypes();
}

@Override
protected String getRewrittenMethodBody(MethodRewriteRequest req) {
StringBuffer newBody = new StringBuffer();
List<String> argumentList = new ArrayList<String>();
newBody.append("{ return ");
if (Modifier.isStatic(initialMethod.getModifiers())) {
newBody.append(enclosingClass.getName() + ".");
} else {
newBody.append("this.");
}
newBody.append(initialMethod.getName());
newBody.append("(");
try {
for (int i = 0; i < initialMethod.getParameterTypes().length; i++) {
CtClass argType = initialMethod.getParameterTypes()[i];
if (isRxActionType(argType) && req.getActionAdaptorClass() != null) {
argumentList.add(getAdaptedArg(req.getActionAdaptorClass(), i + 1));
} else if (isRxFunctionType(argType) && req.getFunctionAdaptorClass() != null) {
argumentList.add(getAdaptedArg(req.getFunctionAdaptorClass(), i + 1));
} else {
argumentList.add(getUntouchedArg(i + 1));
}
}
} catch (Exception ex) {
System.out.println("Exception while creating body for dynamic version of : " + initialMethod.getName());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this wrap-and-throw rather than printing and ignoring the exception?

}
newBody.append(makeArgList(argumentList));
newBody.append(")");
newBody.append(";}");
return newBody.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.codegen;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javassist.ClassPool;
import javassist.CtClass;

import rx.util.functions.FunctionLanguageAdaptor;

/**
* Java Executable that performs bytecode rewriting at compile-time.
* It accepts 2 args: dynamic language and dir to store result output classfiles
*/
public class ClassPathBasedRunner {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage : Expects 2 args: (Language, File to place classfiles)");
System.out.println("Currently supported languages: Groovy/Clojure/JRuby");
System.exit(1);
}
String lang = args[0];
File dir = new File(args[1]);
System.out.println("Using dir : " + dir + " for outputting classfiles");
System.out.println("Looking for Adaptor for : " + lang);
String className = "rx.lang." + lang.toLowerCase() + "." + lang + "Adaptor";
try {
ClassPool pool = ClassPool.getDefault();

Class<?> adaptorClass = Class.forName(className);
System.out.println("Found Adaptor : " + adaptorClass);
FunctionLanguageAdaptor adaptor = (FunctionLanguageAdaptor) adaptorClass.newInstance();

Func1Generator func1Generator = new Func1Generator(pool, adaptor);
CtClass dynamicFunc1Class = func1Generator.createDynamicFunc1Class();
writeClassFile(dynamicFunc1Class, dir);
pool.appendPathList(dir.getCanonicalPath());

ObservableRewriter rewriter = new ObservableRewriter(pool, adaptor);
for (Class<?> observableClass: getObservableClasses()) {
CtClass rewrittenClass = rewriter.addMethods(observableClass);
writeClassFile(rewrittenClass, dir);
}
} catch (ClassNotFoundException ex) {
System.out.println("Did not find adaptor class : " + className);
System.exit(1);
} catch (InstantiationException ex) {
System.out.println("Reflective constuctor on : " + className + " failed");
System.exit(1);
} catch (IllegalAccessException ex) {
System.out.println("Access to constructor on : " + className + " failed");
System.exit(1);
} catch (Exception ex) {
System.out.println("Exception : " + ex.getMessage());
System.exit(1);
}
}

protected static void writeClassFile(CtClass clazz, File dir) {
try {
System.out.println("Using " + dir.getCanonicalPath() + " for dynamic class file");
clazz.writeFile(dir.getCanonicalPath());
} catch (java.io.IOException ioe) {
System.out.println("Could not write classfile to : " + dir.toString());
System.exit(1);
} catch (javassist.CannotCompileException cce) {
System.out.println("Could not create a valid classfile");
System.exit(2);
}
}

private static List<Class<?>> getObservableClasses() {
List<Class<?>> observableClasses = new ArrayList<Class<?>>();
observableClasses.add(rx.Observable.class);
observableClasses.add(rx.observables.BlockingObservable.class);
return observableClasses;
}
}
Loading