Search in sources :

Example 41 with CannotCompileException

use of javassist.CannotCompileException in project incubator-systemml by apache.

the class GenerateClassesForMLContext method createFunctionOutputClass.

/**
 * Create a class that encapsulates the outputs of a function.
 *
 * @param scriptFilePath
 *            the path to a script file
 * @param fs
 *            a SystemML function statement
 */
public static void createFunctionOutputClass(String scriptFilePath, FunctionStatement fs) {
    try {
        ArrayList<DataIdentifier> oparams = fs.getOutputParams();
        // than encapsulating it in a function output class
        if ((oparams.size() == 0) || (oparams.size() == 1)) {
            return;
        }
        String fullFunctionOutputClassName = getFullFunctionOutputClassName(scriptFilePath, fs);
        System.out.println("Generating Class: " + fullFunctionOutputClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctFuncOut = pool.makeClass(fullFunctionOutputClassName);
        // add fields
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String type = getParamTypeAsString(oparam);
            String name = oparam.getName();
            String fstring = "public " + type + " " + name + ";";
            CtField field = CtField.make(fstring, ctFuncOut);
            ctFuncOut.addField(field);
        }
        // add constructor
        String simpleFuncOutClassName = fullFunctionOutputClassName.substring(fullFunctionOutputClassName.lastIndexOf(".") + 1);
        StringBuilder con = new StringBuilder();
        con.append("public " + simpleFuncOutClassName + "(");
        for (int i = 0; i < oparams.size(); i++) {
            if (i > 0) {
                con.append(", ");
            }
            DataIdentifier oparam = oparams.get(i);
            String type = getParamTypeAsString(oparam);
            String name = oparam.getName();
            con.append(type + " " + name);
        }
        con.append(") {\n");
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String name = oparam.getName();
            con.append("this." + name + "=" + name + ";\n");
        }
        con.append("}\n");
        String cstring = con.toString();
        CtConstructor ctCon = CtNewConstructor.make(cstring, ctFuncOut);
        ctFuncOut.addConstructor(ctCon);
        // add toString
        StringBuilder s = new StringBuilder();
        s.append("public String toString(){\n");
        s.append("StringBuilder sb = new StringBuilder();\n");
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String name = oparam.getName();
            s.append("sb.append(\"" + name + " (" + getSimpleParamTypeAsString(oparam) + "): \" + " + name + " + \"\\n\");\n");
        }
        s.append("String str = sb.toString();\nreturn str;\n");
        s.append("}\n");
        String toStr = s.toString();
        CtMethod toStrMethod = CtNewMethod.make(toStr, ctFuncOut);
        ctFuncOut.addMethod(toStrMethod);
        ctFuncOut.writeFile(destination);
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : DataIdentifier(org.apache.sysml.parser.DataIdentifier) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtField(javassist.CtField) CtMethod(javassist.CtMethod)

Example 42 with CannotCompileException

use of javassist.CannotCompileException in project incubator-systemml by apache.

the class GenerateClassesForMLContext method addDescriptionFunctionCallMethod.

/**
 * Create a method that returns either: (1) the full function body, or (2)
 * the function body up to the end of the documentation comment for the
 * function. If (1) is generated, the method name will be followed
 * "__source". If (2) is generated, the method name will be followed by
 * "__docs". If (2) is generated but no end of documentation comment is
 * detected, the full function body will be displayed.
 *
 * @param fs
 *            a SystemML function statement
 * @param scriptFilePath
 *            the path to a script file
 * @param ctNewScript
 *            the javassist compile-time class representation of a script
 * @param full
 *            if {@code true}, create method to return full function body;
 *            if {@code false}, create method to return the function body up
 *            to the end of the documentation comment
 */
public static void addDescriptionFunctionCallMethod(FunctionStatement fs, String scriptFilePath, CtClass ctNewScript, boolean full) {
    try {
        int bl = fs.getBeginLine();
        int el = fs.getEndLine();
        File f = new File(scriptFilePath);
        List<String> lines = FileUtils.readLines(f);
        int end = el;
        if (!full) {
            for (int i = bl - 1; i < el; i++) {
                String line = lines.get(i);
                if (line.contains("*/")) {
                    end = i + 1;
                    break;
                }
            }
        }
        List<String> sub = lines.subList(bl - 1, end);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < sub.size(); i++) {
            String line = sub.get(i);
            String escapeLine = StringEscapeUtils.escapeJava(line);
            sb.append(escapeLine);
            sb.append("\\n");
        }
        String functionString = sb.toString();
        String docFunctionCallMethod = generateDescriptionFunctionCallMethod(fs, functionString, full);
        CtMethod m = CtNewMethod.make(docFunctionCallMethod, ctNewScript);
        ctNewScript.addMethod(m);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }
}
Also used : IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException) File(java.io.File) CtMethod(javassist.CtMethod)

Example 43 with CannotCompileException

use of javassist.CannotCompileException in project incubator-systemml by apache.

the class GenerateClassesForMLContext method addFunctionMethods.

/**
 * Add methods to a derived script class to allow invocation of script
 * functions.
 *
 * @param scriptFilePath
 *            the path to a script file
 * @param ctNewScript
 *            the javassist compile-time class representation of a script
 */
public static void addFunctionMethods(String scriptFilePath, CtClass ctNewScript) {
    try {
        DMLProgram dmlProgram = dmlProgramFromScriptFilePath(scriptFilePath);
        if (dmlProgram == null) {
            System.out.println("Could not generate DML Program for: " + scriptFilePath);
            return;
        }
        Map<String, FunctionStatementBlock> defaultNsFsbsMap = dmlProgram.getFunctionStatementBlocks(DMLProgram.DEFAULT_NAMESPACE);
        List<FunctionStatementBlock> fsbs = new ArrayList<>();
        fsbs.addAll(defaultNsFsbsMap.values());
        for (FunctionStatementBlock fsb : fsbs) {
            ArrayList<Statement> sts = fsb.getStatements();
            for (Statement st : sts) {
                if (!(st instanceof FunctionStatement)) {
                    continue;
                }
                FunctionStatement fs = (FunctionStatement) st;
                String dmlFunctionCall = generateDmlFunctionCall(scriptFilePath, fs);
                String functionCallMethod = generateFunctionCallMethod(scriptFilePath, fs, dmlFunctionCall);
                CtMethod m = CtNewMethod.make(functionCallMethod, ctNewScript);
                ctNewScript.addMethod(m);
                addDescriptionFunctionCallMethod(fs, scriptFilePath, ctNewScript, false);
                addDescriptionFunctionCallMethod(fs, scriptFilePath, ctNewScript, true);
            }
        }
    } catch (LanguageException e) {
        System.out.println("Could not add function methods for " + ctNewScript.getName());
    } catch (CannotCompileException e) {
        System.out.println("Could not add function methods for " + ctNewScript.getName());
    } catch (RuntimeException e) {
        System.out.println("Could not add function methods for " + ctNewScript.getName());
    }
}
Also used : FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) FunctionStatement(org.apache.sysml.parser.FunctionStatement) Statement(org.apache.sysml.parser.Statement) ArrayList(java.util.ArrayList) CannotCompileException(javassist.CannotCompileException) LanguageException(org.apache.sysml.parser.LanguageException) FunctionStatement(org.apache.sysml.parser.FunctionStatement) DMLProgram(org.apache.sysml.parser.DMLProgram) CtMethod(javassist.CtMethod)

Example 44 with CannotCompileException

use of javassist.CannotCompileException in project incubator-systemml by apache.

the class GenerateClassesForMLContext method recurseDirectoriesForConvenienceClassGeneration.

/**
 * Generate convenience classes recursively. This allows for code such as
 * {@code ml.scripts.algorithms...}.
 *
 * @param dirPath
 *            path to directory
 * @return the full name of the class representing the dirPath directory
 */
public static String recurseDirectoriesForConvenienceClassGeneration(String dirPath) {
    try {
        File dir = new File(dirPath);
        String fullDirClassName = dirPathToFullDirClassName(dirPath);
        System.out.println("Generating Class: " + fullDirClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctDir = pool.makeClass(fullDirClassName);
        File[] subdirs = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isDirectory();
            }
        });
        for (File subdir : subdirs) {
            String subDirPath = dirPath + File.separator + subdir.getName();
            if (skipDir(subdir, false)) {
                continue;
            }
            String fullSubDirClassName = recurseDirectoriesForConvenienceClassGeneration(subDirPath);
            CtClass subDirClass = pool.get(fullSubDirClassName);
            String subDirName = subdir.getName();
            subDirName = subDirName.replaceAll("-", "_");
            subDirName = subDirName.toLowerCase();
            System.out.println("Adding " + subDirName + "() to " + fullDirClassName);
            String methodBody = "{ " + fullSubDirClassName + " z = new " + fullSubDirClassName + "(); return z; }";
            CtMethod ctMethod = CtNewMethod.make(Modifier.PUBLIC, subDirClass, subDirName, null, null, methodBody, ctDir);
            ctDir.addMethod(ctMethod);
        }
        File[] scriptFiles = dir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return (name.toLowerCase().endsWith(".dml") || name.toLowerCase().endsWith(".pydml"));
            }
        });
        for (File scriptFile : scriptFiles) {
            String scriptFilePath = scriptFile.getPath();
            String fullScriptClassName = BASE_DEST_PACKAGE + "." + scriptFilePathToFullClassNameNoBase(scriptFilePath);
            CtClass scriptClass = pool.get(fullScriptClassName);
            String methodName = scriptFilePathToSimpleClassName(scriptFilePath);
            String methodBody = "{ " + fullScriptClassName + " z = new " + fullScriptClassName + "(); return z; }";
            CtMethod ctMethod = CtNewMethod.make(Modifier.PUBLIC, scriptClass, methodName, null, null, methodBody, ctDir);
            ctDir.addMethod(ctMethod);
        }
        ctDir.writeFile(destination);
        return fullDirClassName;
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) CtClass(javassist.CtClass) FilenameFilter(java.io.FilenameFilter) FileFilter(java.io.FileFilter) File(java.io.File) CtMethod(javassist.CtMethod)

Example 45 with CannotCompileException

use of javassist.CannotCompileException in project systemml by apache.

the class GenerateClassesForMLContext method addPackageConvenienceMethodsToMLContext.

/**
 * Add methods to MLContext to allow tab-completion to packages contained
 * within the source directory (such as {@code ml.nn()}).
 *
 * @param dirPath
 *            path to source directory (typically, the scripts directory)
 * @param ctMLContext
 *            javassist compile-time class representation of MLContext
 */
public static void addPackageConvenienceMethodsToMLContext(String dirPath, CtClass ctMLContext) {
    try {
        if (!SOURCE.equalsIgnoreCase(dirPath)) {
            return;
        }
        File dir = new File(dirPath);
        File[] subdirs = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isDirectory();
            }
        });
        for (File subdir : subdirs) {
            String subDirPath = dirPath + File.separator + subdir.getName();
            if (skipDir(subdir, false)) {
                continue;
            }
            String fullSubDirClassName = dirPathToFullDirClassName(subDirPath);
            ClassPool pool = ClassPool.getDefault();
            CtClass subDirClass = pool.get(fullSubDirClassName);
            String subDirName = subdir.getName();
            subDirName = subDirName.replaceAll("-", "_");
            subDirName = subDirName.toLowerCase();
            System.out.println("Adding " + subDirName + "() to " + ctMLContext.getName());
            String methodBody = "{ " + fullSubDirClassName + " z = new " + fullSubDirClassName + "(); return z; }";
            CtMethod ctMethod = CtNewMethod.make(Modifier.PUBLIC, subDirClass, subDirName, null, null, methodBody, ctMLContext);
            ctMLContext.addMethod(ctMethod);
        }
    } catch (NotFoundException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) CannotCompileException(javassist.CannotCompileException) FileFilter(java.io.FileFilter) File(java.io.File) CtMethod(javassist.CtMethod)

Aggregations

CannotCompileException (javassist.CannotCompileException)65 CtClass (javassist.CtClass)45 NotFoundException (javassist.NotFoundException)42 CtMethod (javassist.CtMethod)30 IOException (java.io.IOException)22 ClassPool (javassist.ClassPool)22 CtField (javassist.CtField)15 CtConstructor (javassist.CtConstructor)10 FileNotFoundException (java.io.FileNotFoundException)8 File (java.io.File)6 Method (java.lang.reflect.Method)5 ArrayList (java.util.ArrayList)5 EnhancementException (org.hibernate.bytecode.enhance.spi.EnhancementException)5 FileFilter (java.io.FileFilter)4 BadBytecode (javassist.bytecode.BadBytecode)3 Bytecode (javassist.bytecode.Bytecode)3 CodeAttribute (javassist.bytecode.CodeAttribute)3 CodeIterator (javassist.bytecode.CodeIterator)3 CompileError (javassist.compiler.CompileError)3 Javac (javassist.compiler.Javac)3