This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

Bug 258989 - An public Object function(List args).... 330 lines, 3 catches and finally. They thinks the catches need ';'. The finally thinks "illegal start of type"
Summary: An public Object function(List args).... 330 lines, 3 catches and finally. Th...
Status: NEW
Alias: None
Product: java
Classification: Unclassified
Component: Editor (show other bugs)
Version: 8.2
Hardware: PC Mac OS X
: P3 normal (vote)
Assignee: Dusan Balek
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-04-23 17:38 UTC by jerryb
Modified: 2016-04-23 17:38 UTC (History)
0 users

See Also:
Issue Type: DEFECT
Exception Reporter:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description jerryb 2016-04-23 17:38:01 UTC
@SuppressWarnings("unchecked")
    public Object function(List args) { //, Environment env) {        
        Object input = args.getCar();
        Object output = args.rest().getCar();
        Object verbose = args.rest().rest().getCar();
        long duration = System.currentTimeMillis();

        java.lang.String inputAsString = input.toString();
        boolean correctInputType = inputAsString.endsWith(".lsp") || inputAsString.endsWith(".lisp");

        Object sa = SemanticAnalyzer(args, env);
        Object icg = IntermediateCodeGenerator(sa);

        if (args == Null.NIL) {
            throw new WrongNumberOfArgsException("too few arguments given to COMPILE-FILE:");
        } else if (!correctInputType) {
            throw new FunctionException("file to compile must be of type .lsp or .lisp");
        }

        List formList = Null.NIL;
        java.lang.String outputFile = null;

        try {
            // bind *package* to itself
            ((lisp.system.SymbolImpl)Variable.Package).bind(Variable.Package.getValue());
            ((lisp.system.SymbolImpl)Variable.FileCompiling).bind(lisp.common.type.Boolean.T);
            File f = new File(input.toString());

            if (output != Null.NIL) {
                //Need to associate this value with the correct keyword
                outputFile = output.toString();
            } else {
                java.lang.String temp = f.getAbsolutePath();
                if (inputAsString.endsWith(".lsp")) {
                    temp = temp.substring(0, temp.length() - 4);
                } else {
                    temp = temp.substring(0, temp.length() - 5);
                }
                outputFile = temp.concat(".jar");
            }

            // get the name and javafy it
            java.lang.String name = f.getName();
            java.lang.String nameRegex = "(\\p{Punct}|\\p{Space})+";
            java.util.regex.Pattern namePattern = java.util.regex.Pattern.compile(nameRegex);
            java.util.Scanner scanner = new java.util.Scanner(name).useDelimiter(namePattern);
            StringBuilder sb = new StringBuilder();
            while (scanner.hasNext()) {
                java.lang.String str = scanner.next();
                sb.append("").append(java.lang.Character.toUpperCase(str.charAt(0))).append(str.
                        substring(1));
            }
            Symbol newJavaClassName = Symbol.Factory.newInstance(sb.toString());

            lisp.common.function.Open open = lisp.common.function.Open.FUNCTION;
            Pathname.Factory fact = Pathname.Factory.getFactory(f.getPath());
            CharacterInputFileStream stream = (CharacterInputFileStream)open.apply(List.Factory.
                    newInstance(new Object[] {f.toString(), Boolean.NIL, Boolean.NIL,
                                              Keyword.NewVersion}));
            Vector formsInfo = readForms(stream);
            Vector formsToCompile = (Vector)formsInfo.get(0);
            Vector<Integer> formLneNumbers = (Vector<Integer>)formsInfo.get(1);

            // Create the wrap-around lambda expression that encloses all of the forms in the file.
            // We have to give it a specific name so it can be loaded by name
            formList = List.Factory.newInstance(formsToCompile.toArray());

            List nameDeclSpec = List.Factory.newInstance(new Object[] {Declaration.JAVA_CLASS_NAME,
                                                                       newJavaClassName});
            List fileDeclSpec = List.Factory.newInstance(new Object[] {Declaration.SOURCE_FILE, f.
                                                                       getAbsoluteFile().getName()});
            List nameDecl = List.Factory.newInstance(
                        new Object[] {Declaration.DECLARE, nameDeclSpec, fileDeclSpec});

            formList = Cons.Factory.newInstance(nameDecl, formList);
            formList = Cons.Factory.newInstance(Null.NIL, formList);
            formList = Cons.Factory.newInstance(lisp.common.type.SpecialOperator.LAMBDA, formList);

            Symbol newSA = Package.Compiler.findSymbol("SEMANTIC-ANALYZER")[0];
        } catch (Exception e) {
            System.out.flush();
            System.out.println("Exception in Compile Caught!!");
            System.out.println(e.toString());
            e.printStackTrace();
        }

        // set up the timers...
        long baseTime;
        long saTime = 0;
        long icgTime;
        long jarTime;

//        baseTime = System.currentTimeMillis();
//        formList = (List)sa.funcall(formList);
//        saTime = System.currentTimeMillis() - baseTime;
        baseTime = System.currentTimeMillis();

        java.util.Vector<Emitter.ClassDef> v = (java.util.Vector<Emitter.ClassDef>)icg; //.funcall(formList);
        java.util.Vector<java.lang.String> oc = new java.util.Vector<java.lang.String>(v.size());
        java.util.Vector classBytes = new java.util.Vector(v.size());

        DocumentFactory docFactory = new DocumentFactory();
        Document xmlDoc = docFactory.newInstance();

        Element root = xmlDoc.createElement("documentation");
        xmlDoc.appendChild(root);

        // change all of the ClassWriters into byte arrays
        for (lisp.system.compiler.Emitter.ClassDef classDef : v) {
            byte[] byteArray = classDef.getClassBytes();
//                ClassReader cr = new ClassReader(byteArray);
//                ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);

            java.lang.String key = "";
            java.lang.String value = "";
            AnnotationCollector annCollect = new AnnotationCollector();
//            AnnotationVistor annVistor = new AnnotationVistor(root, xmlDoc);
//                cr.accept(annVistor, 0); //ClassReader.EXPAND_FRAMES);
            Hashtable docInfo = annCollect.getTable();

            Set keys = docInfo.keySet();
            Iterator iterator = keys.iterator();

            if (iterator.hasNext()) {
                Element newDocNode = xmlDoc.createElement("docInstance");
                xmlDoc.getDocumentElement().appendChild(newDocNode);

                while (iterator.hasNext()) {
                    key = (java.lang.String)iterator.next();
                    value = docInfo.get(key).toString();

                    if (!"docUID".equals(key)) {
                        Element nodeName = xmlDoc.createElement(key);
                        newDocNode.appendChild(nodeName);
                        Node nodeValue = xmlDoc.createTextNode(value);
                        nodeName.appendChild(nodeValue);
                    } else {
                        newDocNode.setAttribute(key, value);
                    }
                }
            }

            if (bDebug) {
                System.out.println("Printing the class " + classDef.getName() + '\n');
                CheckClassAdapter.verify(new ClassReader(byteArray), true,
                        new java.io.PrintWriter(System.out));
//                    TraceClassVisitor tcv = new TraceClassVisitor(new java.io.PrintWriter(System.out));
//                    cr.accept(tcv, false);
                System.out.println("Done  with class " + classDef.getName() + '\n');
            } else {
                ClassReader cr = new ClassReader(byteArray);
                ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
                ClassVisitor cv = new CheckClassAdapter(new CheckClassAdapter(cw));
                cr.accept(cv, 0); //ClassReader.EXPAND_FRAMES);
//                    ClassVisitor cv = new CheckClassAdapter(cw);
//                    cv.accept(cr, 0);        //ClassReader.EXPAND_FRAMES);
            }
            classBytes.add(byteArray);
            oc.add(classDef.getName());
        }
        // now load them
        java.util.Vector classesLoaded = new java.util.Vector(v.size());

        Transformer transformer = null;
        
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
        }

        transformer.setOutputProperty("indent", "yes");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(xmlDoc);

        try {
            transformer.transform(source, result);
        } catch (TransformerException ex) {
            Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
        }

        java.lang.String xmlString = result.getWriter().toString();
        java.lang.String xmlFileName = oc.get(0) + ".xml";

        icgTime = System.currentTimeMillis() - baseTime;

        baseTime = System.currentTimeMillis();

        Enumeration classes = classBytes.elements();
        int nameCounter = 0;
        int xmlCounter = 0;

        Object classFile;
        java.lang.String file;
        JarEntry entry = null;
        java.io.ByteArrayOutputStream baos = null;

        byte[] buf = new byte[1024];
        FileOutputStream fileStream = null;
        JarOutputStream jar = null;
        File outputFileFile = new File(outputFile);

        // now we make a temp file to hold the results. Then we rename the temp to
        // the desired file name. This avoids problems when the system has loaded
        // a jar file, compiles the source again, and reloads with the new data.
        File tmpFile = null;
        
        try {
            tmpFile = File.createTempFile("TMP_JAR_" + System.currentTimeMillis(), ".jar");
        } catch (IOException ex) {
            Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //Get first class to make Main-Class Attribute
        if (classes.hasMoreElements()) {
            try {
                Manifest mani = new Manifest();
                mani.getMainAttributes().put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.0");
                mani.getMainAttributes().put(java.util.jar.Attributes.Name.MAIN_CLASS, oc.get(0));
                mani.getMainAttributes().putValue("XmlDocumentation", xmlFileName);

                fileStream = new FileOutputStream(tmpFile, false);
                jar = new JarOutputStream(fileStream, mani);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        java.lang.String name = "";
        while (classes.hasMoreElements()) {
            try {
                name = oc.get(nameCounter) + ".class";
                entry = new JarEntry(name);
                jar.putNextEntry(entry);
                jar.write((byte[])classes.nextElement());
                jar.closeEntry();
                nameCounter++;
            } catch (IOException ex) {
                Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        try {
            entry = new JarEntry(xmlFileName);
            jar.putNextEntry(entry);
            jar.write(xmlString.getBytes());
            jar.closeEntry();
            jar.close();
        } catch (IOException ex) {
            Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (outputFileFile.exists()) {
            System.out.println("Closing and deleting " + outputFileFile);
            try {
                new java.util.jar.JarFile(outputFileFile).close();
            } catch (IOException ex) {
                Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
            }
            outputFileFile.delete();
        }

        if (!tmpFile.renameTo(outputFileFile)) {

            System.out.println("Warning: Unable to rename temp file: " + tmpFile + ". JAR file not created.");
            System.out.println("\t Attempting to copy then delete temp file instead...");

            try {
                // copying file to destination
                FileInputStream srcFile = new FileInputStream(tmpFile);
                FileOutputStream dstFile = new FileOutputStream(outputFileFile);

                byte[] buffer = new byte[1024];
                for (int x = 0; (x = srcFile.read(buffer)) != -1;) {
                    dstFile.write(buffer, 0, x);
                }

                srcFile.close();
                dstFile.close();
            } catch (IOException ex) {
                Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex);
            }

            // deleting temp jar file
            if (!tmpFile.delete()) {
                System.out.println("WARNING: Failed to delete temp jar file.");
            }
        }

        jarTime = System.currentTimeMillis() - baseTime;
        System.out.println("; Total compilation time: "
                + (System.currentTimeMillis() - duration) + " ms\n");
        System.out.println("; Details:\n"
                + ";  SA: " + saTime + " ms\n"
                + ";  ICG: " + icgTime + " ms\n"
                + ";  Jar: " + jarTime + " ms\n");

        // returns 3 values
        Object[] ret = new Object[3];
        ret[0] = lisp.common.type.Pathname.Factory.getFactory(outputFile).newInstance(outputFile);
        ret[1] = lisp.common.type.Null.NIL;
        ret[2] = lisp.common.type.Null.NIL;
        return ret;
        
    } catch (FileNotFoundException ex) {
        System.err.println(ex.getCause());
        ex.printStackTrace();
        throw new FunctionException("File " + input.toString() + " does not exist.");
    } catch (IOException ex) {
        System.err.println(ex.getCause());
        ex.printStackTrace();
        throw new FunctionException("Unable to view contents of File " + input.toString());
    } catch (Exception ex) {
        System.err.println(ex.getCause());
        ex.printStackTrace();
        throw new FunctionException("Exception caught in COMPILE-FILE:");
    } finally  {
        ((lisp.system.SymbolImpl)Variable.Package).unbind();
        ((lisp.system.SymbolImpl)Variable.FileCompiling).unbind();
    }
}