From 4689dfb0977c3908a2cc9cf66a43c09d1a04c56b Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 7 Feb 2026 10:08:55 +0200 Subject: [PATCH] Fixed DM_CONVERT_CASE and IntelliJ suggestions --- .../src/com/codename1/contacts/Contact.java | 2 +- .../impl/android/AndroidImplementation.java | 35 ++-- .../impl/android/CodenameOneView.java | 3 - .../impl/android/InPlaceEditView.java | 25 --- .../codename1/impl/ios/IOSImplementation.java | 54 +----- .../builders/AndroidGradleBuilder.java | 1 - .../GenerateArchetypeFromTemplateMojo.java | 3 - .../com/codename1/maven/SimulatorMojo.java | 10 - .../tools/translator/ByteCodeTranslator.java | 181 ++++++------------ .../codename1/tools/translator/Parser.java | 118 +++++------- .../translator/bytecodes/CustomInvoke.java | 56 ++---- .../tools/translator/bytecodes/Invoke.java | 46 ++--- .../BytecodeInstructionIntegrationTest.java | 20 +- 13 files changed, 157 insertions(+), 397 deletions(-) diff --git a/CodenameOne/src/com/codename1/contacts/Contact.java b/CodenameOne/src/com/codename1/contacts/Contact.java index 034dd1b1c5..b309197f94 100644 --- a/CodenameOne/src/com/codename1/contacts/Contact.java +++ b/CodenameOne/src/com/codename1/contacts/Contact.java @@ -111,7 +111,7 @@ public Hashtable getAddresses() { /// #### Parameters /// /// - `addresses`: @param addresses the Hashtable contains key/value pairs where - /// the key is a String which represents the type of the Address, types can + /// the key is a String that represents the type of the Address, types can /// be: "home", "work", "other" the value is an Address Object. public void setAddresses(Hashtable addresses) { this.addresses = addresses; diff --git a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java index 27c49bef7b..8fdad9c2c8 100644 --- a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java +++ b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java @@ -522,7 +522,7 @@ public static void appendNotification(String type, String body, String image, St msg += "&category="+java.net.URLEncoder.encode(category, "UTF-8"); } if (image != null) { - image += "&image="+java.net.URLEncoder.encode(image, "UTF-8"); + msg += "&image="+java.net.URLEncoder.encode(image, "UTF-8"); } os.writeUTF(msg); @@ -1591,9 +1591,6 @@ public boolean isNativeInputImmediate() { } public void editString(final Component cmp, int maxSize, final int constraint, String text, int keyCode) { - if (keyCode > 0 && getKeyboardType() == Display.KEYBOARD_TYPE_QWERTY) { - text += (char) keyCode; - } InPlaceEditView.edit(this, cmp, constraint); } @@ -3933,7 +3930,6 @@ public void run() { ); final com.codename1.media.AudioBuffer audioBuffer = com.codename1.media.MediaManager.getAudioBuffer(path, true, 64); - final boolean[] stop = new boolean[1]; record[0] = new AbstractMedia() { private int lastTime; @@ -8122,11 +8118,7 @@ private void removeCompletionHandler(Runnable onCompletion) { private String getImageFilePath(Uri uri) { - - File file = new File(uri.getPath()); String scheme = uri.getScheme(); - //String[] filePaths = file.getPath().split(":"); - //String image_id = filePath[filePath.length - 1]; String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContext().getContentResolver().query( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, @@ -8151,8 +8143,10 @@ private String getImageFilePath(Uri uri) { if (filePath == null || "content".equals(scheme)) { //if the file is not on the filesystem download it and save it //locally + InputStream inputStream = null; + OutputStream tmp = null; try { - InputStream inputStream = getContext().getContentResolver().openInputStream(uri); + inputStream = getContext().getContentResolver().openInputStream(uri); if (inputStream != null) { String name = new File(uri.toString()).getName();//getContentName(getContext().getContentResolver(), uri); if (name != null) { @@ -8163,27 +8157,20 @@ private String getImageFilePath(Uri uri) { filePath = homePath + getFileSystemSeparator() + name; File f = new File(removeFilePrefix(filePath)); - OutputStream tmp = createFileOuputStream(f); - byte[] buffer = new byte[1024]; - int read = -1; - while ((read = inputStream.read(buffer)) > -1) { - tmp.write(buffer, 0, read); - } - tmp.close(); - inputStream.close(); + tmp = createFileOuputStream(f); + Util.copy(inputStream, tmp); } } } catch (Exception e) { - e.printStackTrace(); + com.codename1.io.Log.e(e); + } finally { + Util.cleanup(tmp); + Util.cleanup(inputStream); } } - //long len = new com.codename1.io.File(filePath).length(); return filePath; } - - - - + @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { diff --git a/Ports/Android/src/com/codename1/impl/android/CodenameOneView.java b/Ports/Android/src/com/codename1/impl/android/CodenameOneView.java index 0c2cf4974b..83180c26a0 100644 --- a/Ports/Android/src/com/codename1/impl/android/CodenameOneView.java +++ b/Ports/Android/src/com/codename1/impl/android/CodenameOneView.java @@ -303,7 +303,6 @@ public void handleSizeChange(int w, int h) { if (InPlaceEditView.isEditing()) { final Form f = this.implementation.getCurrentForm(); ActionListener sizeChanged = new ActionListener() { - @Override public void actionPerformed(ActionEvent evt) { CodenameOneView.this.implementation.getActivity().runOnUiThread(new Runnable() { @@ -311,8 +310,6 @@ public void actionPerformed(ActionEvent evt) { @Override public void run() { InPlaceEditView.reLayoutEdit(); - InPlaceEditView.scrollActiveTextfieldToVisible(); - } }); f.removeSizeChangedListener(this); diff --git a/Ports/Android/src/com/codename1/impl/android/InPlaceEditView.java b/Ports/Android/src/com/codename1/impl/android/InPlaceEditView.java index 24f8152082..eab3a68c84 100644 --- a/Ports/Android/src/com/codename1/impl/android/InPlaceEditView.java +++ b/Ports/Android/src/com/codename1/impl/android/InPlaceEditView.java @@ -104,31 +104,6 @@ public class InPlaceEditView extends FrameLayout{ public static final int REASON_TOUCH_OUTSIDE = 2; public static final int REASON_SYSTEM_KEY = 3; - static void scrollActiveTextfieldToVisible() { - if (isEditing() && sInstance != null) { - Runnable r = new Runnable() { - - @Override - public void run() { - if (sInstance != null && sInstance.mEditText != null && sInstance.mEditText.mTextArea != null) { - TextArea ta = sInstance.mEditText.mTextArea; - if (isScrollableParent(ta)) { - ta.scrollRectToVisible(0, 0, ta.getWidth(), ta.getHeight(), ta); - ta.getComponentForm().getAnimationManager().flushAnimation(new Runnable() { - - @Override - public void run() { - reLayoutEdit(); - } - - }); - } - } - } - - }; - } - } // The native Android edit-box to place over Codename One's edit-component private EditView mEditText = null; private EditView mLastEditText = null; diff --git a/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java b/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java index 17a6f26e10..aa29b3195c 100644 --- a/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java +++ b/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java @@ -6655,7 +6655,15 @@ public Contact getContactById(String id, boolean includesFullName, boolean inclu if (includeAddress) { // This is a hack to make sure that // Address and its methods aren't stripped out by the BytecodeCompiler - Address tmp = new Address(); + if (System.currentTimeMillis() == 0) { + Address tmp = new Address(); + tmp.setCountry(""); + tmp.setLocality(""); + tmp.setRegion(""); + tmp.setPostalCode(""); + tmp.setStreetAddress(""); + c.getAddresses().put("", tmp); + } } c.setEmails(new Hashtable()); @@ -6670,50 +6678,6 @@ public Contact getContactById(String id) { throw new RuntimeException("Please add the ios.NSContactsUsageDescription build hint"); } return getContactById(id, true, true, true, true, true); - - /*c.setId("" + id); - long person = nativeInstance.getPersonWithRecordID(recId); - String fname = nativeInstance.getPersonFirstName(person); - c.setFirstName(fname); - String sname = nativeInstance.getPersonSurnameName(person); - c.setFamilyName(sname); - if(c.getFirstName() != null) { - StringBuilder s = new StringBuilder(); - if(fname != null && fname.length() > 0) { - if(sname != null && sname.length() > 0) { - c.setDisplayName(fname + " " + sname); - } else { - c.setDisplayName(fname); - } - } else { - if(sname != null && sname.length() > 0) { - c.setDisplayName(sname); - } - } - } - c.setPrimaryEmail(nativeInstance.getPersonEmail(person)); - - int phones = nativeInstance.getPersonPhoneCount(person); - Hashtable h = new Hashtable(); - for(int iter = 0 ; iter < phones ; iter++) { - String t = nativeInstance.getPersonPhoneType(person, iter); - if(t == null) { - t = "work"; - } - String phone = nativeInstance.getPersonPhone(person, iter); - if(phone != null) { - h.put(t, phone); - } - } - c.setPhoneNumbers(h); - - c.setPrimaryPhoneNumber(nativeInstance.getPersonPrimaryPhone(person)); - - //h = new Hashtable(); - //h.put("Work", h); - c.setAddresses(h); - nativeInstance.releasePeer(person); - return c;*/ } @Override diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/builders/AndroidGradleBuilder.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/builders/AndroidGradleBuilder.java index f2f1931ff2..7cea0473d6 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/builders/AndroidGradleBuilder.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/builders/AndroidGradleBuilder.java @@ -904,7 +904,6 @@ public boolean build(File sourceZip, final BuildRequest request) throws BuildExc } File androidToolsDir = new File(androidSDKDir, "tools"); - File androidCommand = new File(androidToolsDir, "android" + bat); File projectDir = new File(tmpFile, request.getMainClass()); gradleProjectDirectory = projectDir; diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateArchetypeFromTemplateMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateArchetypeFromTemplateMojo.java index 9351a23123..adcab82b64 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateArchetypeFromTemplateMojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/GenerateArchetypeFromTemplateMojo.java @@ -328,11 +328,9 @@ private void processString(String contents, File projectDir) throws MojoExecutio } private File generateBaseArchetype(String string, File templateFile) throws TemplateParseException, IOException { - Dependency out = new Dependency(); String archetype = extractSectionFrom(string, "archetype"); Properties props = new Properties(); - props.load(new StringReader(archetype)); String[] requiredProperties = new String[]{ "artifactId", "groupId", "version" @@ -343,7 +341,6 @@ private File generateBaseArchetype(String string, File templateFile) throws Temp } } - File dest = new File(outputDir, props.getProperty("artifactId")); if (dest.exists()) { if (overwrite) { diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/SimulatorMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/SimulatorMojo.java index 7bded01810..6c7bf29e7a 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/SimulatorMojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/SimulatorMojo.java @@ -200,8 +200,6 @@ protected void processBuffer(ByteArrayOutputStream buffer) { private Path prepareClasspath(Java java) { Log log = getLog(); log.debug("Preparing classpath for Simulator"); - List paths = new ArrayList<>(); - //StringBuilder classpath = new StringBuilder(); Path classpath = java.createClasspath(); if (System.getProperty("cef.dir") != null) { Variable v = new Variable(); @@ -242,15 +240,7 @@ private Path prepareClasspath(Java java) { if (getProjectInternalTmpJar() != null && getProjectInternalTmpJar().exists()) { classpath.add(new Path(antProject, getProjectInternalTmpJar().getAbsolutePath())); } - - //classpath.append(file.getPath()); - //paths.add(file.getAbsolutePath()); } - //if (classpath.length() > 0) { - // classpath.append(':'); - //} - //classpath.append(classFiles.getPath()); - //paths.add(classFiles.getAbsolutePath()); classpath.add(new Path(antProject, project.getBuild().getOutputDirectory())); log.debug("Using the following classpath for Stubber: " + classpath); return classpath; diff --git a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeTranslator.java b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeTranslator.java index 4fda07baa9..cf283d2e95 100644 --- a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeTranslator.java +++ b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/ByteCodeTranslator.java @@ -25,14 +25,12 @@ import java.io.DataInputStream; import java.io.File; -import java.io.FileFilter; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.FileWriter; -import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -44,7 +42,7 @@ * @author Shai Almog */ public class ByteCodeTranslator { - public static enum OutputType { + public enum OutputType { OUTPUT_TYPE_IOS { @Override @@ -68,7 +66,7 @@ public String extension() { }; public abstract String extension(); - }; + } public static OutputType output = OutputType.OUTPUT_TYPE_IOS; public static boolean verbose = true; @@ -85,22 +83,14 @@ void execute(File[] sourceDirs, File outputDir) throws Exception { } void execute(File sourceDir, File outputDir) throws Exception { - File[] directoryList = sourceDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return !pathname.isHidden() && !pathname.getName().startsWith(".") && pathname.isDirectory(); - } - }); - File[] fileList = sourceDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return !pathname.isHidden() && !pathname.getName().startsWith(".") && !pathname.isDirectory(); - } - }); + File[] directoryList = sourceDir.listFiles(pathname -> + !pathname.isHidden() && !pathname.getName().startsWith(".") && pathname.isDirectory()); + File[] fileList = sourceDir.listFiles(pathname -> + !pathname.isHidden() && !pathname.getName().startsWith(".") && !pathname.isDirectory()); if(fileList != null) { for(File f : fileList) { if (f.getName().equals("module-info.class")) { - // Remove module-info.class that might have been added by jdk9 compile + // Remove module-info.class that might have been added by jdk9 compiler System.out.println("WARNING: Found module-info.class file at "+f+". One or more of your jars must have been built for JDK9 or higher. -target 8 or lower is required."); System.out.println(" Will ignore this warning and attempt build anyways."); continue; @@ -110,7 +100,7 @@ public boolean accept(File pathname) { } else { if(!f.isDirectory()) { // copy the file to the dest dir - copy(new FileInputStream(f), new FileOutputStream(new File(outputDir, f.getName()))); + copy(Files.newInputStream(f.toPath()), Files.newOutputStream(new File(outputDir, f.getName()).toPath())); } } } @@ -130,36 +120,18 @@ private void copyDir(File source, File destDir) throws IOException { File destFile = new File(destDir, source.getName()); destFile.mkdirs(); File[] files = source.listFiles(); + if (files == null) { + return; + } for(File f : files) { if(f.isDirectory()) { copyDir(f, destFile); } else { - copy(new FileInputStream(f), new FileOutputStream(new File(destFile, f.getName()))); + copy(Files.newInputStream(f.toPath()), Files.newOutputStream(new File(destFile, f.getName()).toPath())); } } } - // - // make sure a directory is clean. This is applied - // to output directories, and should normally be a no-op - // .. except if some accident occurred or this is a reliberate - // re-run of a failed build. - // the underlying purpose is to make repeated builds produce the same result. - // - /*private static void cleanDir(File dir) - { // - // this recursively deletes everything, so be cautious about this! - // this is called only on directories we supposedly have just created. - // - File [] current = dir.listFiles(); - if(current.length>0) { // unusual and worth a mention - System.out.println("cleanup before build, removing "+current.length+" files in "+dir); - for(File cf : current) - { if(cf.isDirectory()) { cleanDir(cf); } - cf.delete(); - } - } - }*/ - + /** * @param args the command line arguments */ @@ -181,7 +153,7 @@ public static void main(String[] args) throws Exception { final String appVersion = args[6]; final String appType = args[7]; final String addFrameworks = args[8]; - // we accept 3 arguments output type, input directory & output directory + // we accept 3 argument output types, input directory and output directory if (System.getProperty("saveUnitTests", "false").equals("true")) { System.out.println("Generating Unit Tests"); ByteCodeClass.setSaveUnitTests(true); @@ -236,38 +208,40 @@ private static void handleCleanOutput(ByteCodeTranslator b, File[] sources, File b.execute(sources, srcRoot); File cn1Globals = new File(srcRoot, "cn1_globals.h"); - copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.h"), new FileOutputStream(cn1Globals)); + copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.h"), Files.newOutputStream(cn1Globals.toPath())); if (System.getProperty("INCLUDE_NPE_CHECKS", "false").equals("true")) { replaceInFile(cn1Globals, "//#define CN1_INCLUDE_NPE_CHECKS", "#define CN1_INCLUDE_NPE_CHECKS"); } File cn1GlobalsC = new File(srcRoot, "cn1_globals.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.m"), new FileOutputStream(cn1GlobalsC)); + copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.m"), Files.newOutputStream(cn1GlobalsC.toPath())); File nativeMethodsC = new File(srcRoot, "nativeMethods.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/nativeMethods.m"), new FileOutputStream(nativeMethodsC)); + copy(ByteCodeTranslator.class.getResourceAsStream("/nativeMethods.m"), Files.newOutputStream(nativeMethodsC.toPath())); if (System.getProperty("USE_RPMALLOC", "false").equals("true")) { File malloc = new File(srcRoot, "malloc.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/malloc.c"), new FileOutputStream(malloc)); + copy(ByteCodeTranslator.class.getResourceAsStream("/malloc.c"), Files.newOutputStream(malloc.toPath())); File rpmalloc = new File(srcRoot, "rpmalloc.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.c"), new FileOutputStream(rpmalloc)); + copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.c"), Files.newOutputStream(rpmalloc.toPath())); File rpmalloch = new File(srcRoot, "rpmalloc.h"); - copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.h"), new FileOutputStream(rpmalloch)); + copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.h"), Files.newOutputStream(rpmalloch.toPath())); } File xmlvm = new File(srcRoot, "xmlvm.h"); - copy(ByteCodeTranslator.class.getResourceAsStream("/xmlvm.h"), new FileOutputStream(xmlvm)); + copy(ByteCodeTranslator.class.getResourceAsStream("/xmlvm.h"), Files.newOutputStream(xmlvm.toPath())); Parser.writeOutput(srcRoot); File javaIoFileHeader = new File(srcRoot, "java_io_File.h"); if (javaIoFileHeader.exists()) { File javaIoFileC = new File(srcRoot, "java_io_File_runtime.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/java_io_File.m"), new FileOutputStream(javaIoFileC)); + copy(ByteCodeTranslator.class.getResourceAsStream("/java_io_File.m"), Files.newOutputStream(javaIoFileC.toPath())); } File classMethodIndexM = new File(srcRoot, "cn1_class_method_index.m"); if (classMethodIndexM.exists()) { File classMethodIndexC = new File(srcRoot, "cn1_class_method_index.c"); - copy(new FileInputStream(classMethodIndexM), new FileOutputStream(classMethodIndexC)); - classMethodIndexM.delete(); + copy(Files.newInputStream(classMethodIndexM.toPath()), Files.newOutputStream(classMethodIndexC.toPath())); + if(!classMethodIndexM.delete()) { + System.err.println("Deletion of " + classMethodIndexM.getAbsolutePath() + " failed"); + } } writeCmakeProject(root, srcRoot, appName); @@ -291,13 +265,13 @@ private static void handleIosOutput(ByteCodeTranslator b, File[] sources, File d launchImageLaunchimage.mkdirs(); //cleanDir(launchImageLaunchimage); - copy(ByteCodeTranslator.class.getResourceAsStream("/LaunchImages.json"), new FileOutputStream(new File(launchImageLaunchimage, "Contents.json"))); + copy(ByteCodeTranslator.class.getResourceAsStream("/LaunchImages.json"), Files.newOutputStream(new File(launchImageLaunchimage, "Contents.json").toPath())); File appIconAppiconset = new File(imagesXcassets, "AppIcon.appiconset"); appIconAppiconset.mkdirs(); //cleanDir(appIconAppiconset); - copy(ByteCodeTranslator.class.getResourceAsStream("/Icons.json"), new FileOutputStream(new File(appIconAppiconset, "Contents.json"))); + copy(ByteCodeTranslator.class.getResourceAsStream("/Icons.json"), Files.newOutputStream(new File(appIconAppiconset, "Contents.json").toPath())); File xcproj = new File(root, appName + ".xcodeproj"); @@ -306,59 +280,51 @@ private static void handleIosOutput(ByteCodeTranslator b, File[] sources, File d File projectXCworkspace = new File(xcproj, "project.xcworkspace"); projectXCworkspace.mkdirs(); - //cleanDir(projectXCworkspace); - - /*File xcsharedData = new File(projectXCworkspace, "xcshareddata"); - xcsharedData.mkdirs();*/ b.execute(sources, srcRoot); File cn1Globals = new File(srcRoot, "cn1_globals.h"); - copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.h"), new FileOutputStream(cn1Globals)); + copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.h"), Files.newOutputStream(cn1Globals.toPath())); if (System.getProperty("INCLUDE_NPE_CHECKS", "false").equals("true")) { replaceInFile(cn1Globals, "//#define CN1_INCLUDE_NPE_CHECKS", "#define CN1_INCLUDE_NPE_CHECKS"); } File cn1GlobalsM = new File(srcRoot, "cn1_globals.m"); - copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.m"), new FileOutputStream(cn1GlobalsM)); + copy(ByteCodeTranslator.class.getResourceAsStream("/cn1_globals.m"), Files.newOutputStream(cn1GlobalsM.toPath())); File nativeMethods = new File(srcRoot, "nativeMethods.m"); - copy(ByteCodeTranslator.class.getResourceAsStream("/nativeMethods.m"), new FileOutputStream(nativeMethods)); + copy(ByteCodeTranslator.class.getResourceAsStream("/nativeMethods.m"), Files.newOutputStream(nativeMethods.toPath())); File javaIoFileM = new File(srcRoot, "java_io_File.m"); - copy(ByteCodeTranslator.class.getResourceAsStream("/java_io_File.m"), new FileOutputStream(javaIoFileM)); + copy(ByteCodeTranslator.class.getResourceAsStream("/java_io_File.m"), Files.newOutputStream(javaIoFileM.toPath())); if (System.getProperty("USE_RPMALLOC", "false").equals("true")) { File malloc = new File(srcRoot, "malloc.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/malloc.c"), new FileOutputStream(malloc)); + copy(ByteCodeTranslator.class.getResourceAsStream("/malloc.c"), Files.newOutputStream(malloc.toPath())); File rpmalloc = new File(srcRoot, "rpmalloc.c"); - copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.c"), new FileOutputStream(rpmalloc)); + copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.c"), Files.newOutputStream(rpmalloc.toPath())); File rpmalloch = new File(srcRoot, "rpmalloc.h"); - copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.h"), new FileOutputStream(rpmalloch)); + copy(ByteCodeTranslator.class.getResourceAsStream("/rpmalloc.h"), Files.newOutputStream(rpmalloch.toPath())); } Parser.writeOutput(srcRoot); File templateInfoPlist = new File(srcRoot, appName + "-Info.plist"); - copy(ByteCodeTranslator.class.getResourceAsStream("/template/template/template-Info.plist"), new FileOutputStream(templateInfoPlist)); + copy(ByteCodeTranslator.class.getResourceAsStream("/template/template/template-Info.plist"), Files.newOutputStream(templateInfoPlist.toPath())); File templatePch = new File(srcRoot, appName + "-Prefix.pch"); - copy(ByteCodeTranslator.class.getResourceAsStream("/template/template/template-Prefix.pch"), new FileOutputStream(templatePch)); + copy(ByteCodeTranslator.class.getResourceAsStream("/template/template/template-Prefix.pch"), Files.newOutputStream(templatePch.toPath())); File xmlvm = new File(srcRoot, "xmlvm.h"); - copy(ByteCodeTranslator.class.getResourceAsStream("/xmlvm.h"), new FileOutputStream(xmlvm)); + copy(ByteCodeTranslator.class.getResourceAsStream("/xmlvm.h"), Files.newOutputStream(xmlvm.toPath())); File projectWorkspaceData = new File(projectXCworkspace, "contents.xcworkspacedata"); - copy(ByteCodeTranslator.class.getResourceAsStream("/template/template.xcodeproj/project.xcworkspace/contents.xcworkspacedata"), new FileOutputStream(projectWorkspaceData)); + copy(ByteCodeTranslator.class.getResourceAsStream("/template/template.xcodeproj/project.xcworkspace/contents.xcworkspacedata"), Files.newOutputStream(projectWorkspaceData.toPath())); replaceInFile(projectWorkspaceData, "KitchenSink", appName); File projectPbx = new File(xcproj, "project.pbxproj"); - copy(ByteCodeTranslator.class.getResourceAsStream("/template/template.xcodeproj/project.pbxproj"), new FileOutputStream(projectPbx)); + copy(ByteCodeTranslator.class.getResourceAsStream("/template/template.xcodeproj/project.pbxproj"), Files.newOutputStream(projectPbx.toPath())); - String[] sourceFiles = srcRoot.list(new FilenameFilter() { - @Override - public boolean accept(File pathname, String string) { - return string.endsWith(".bundle") || string.endsWith(".xcdatamodeld") || !pathname.isHidden() && !string.startsWith(".") && !"Images.xcassets".equals(string); - } - }); + String[] sourceFiles = srcRoot.list((pathname, string) -> + string.endsWith(".bundle") || string.endsWith(".xcdatamodeld") || !pathname.isHidden() && !string.startsWith(".") && !"Images.xcassets".equals(string)); StringBuilder fileOneEntry = new StringBuilder(); StringBuilder fileTwoEntry = new StringBuilder(); @@ -368,12 +334,12 @@ public boolean accept(File pathname, String string) { StringBuilder frameworks2 = new StringBuilder(); StringBuilder resources = new StringBuilder(); - List noArcFiles = new ArrayList(); + List noArcFiles = new ArrayList<>(); noArcFiles.add("CVZBarReaderViewController.m"); noArcFiles.add("OpenUDID.m"); - List includeFrameworks = new ArrayList(); - Set optionalFrameworks = new HashSet(); + List includeFrameworks = new ArrayList<>(); + Set optionalFrameworks = new HashSet<>(); for (String optionalFramework : System.getProperty("optional.frameworks", "").split(";")) { optionalFramework = optionalFramework.trim(); if (!optionalFramework.isEmpty()) { @@ -413,9 +379,9 @@ public boolean accept(File pathname, String string) { int currentValue = 0xF63EAAA; - ArrayList arr = new ArrayList(); + ArrayList arr = new ArrayList<>(); arr.addAll(includeFrameworks); - arr.addAll(Arrays.asList(sourceFiles)); + arr.addAll(sourceFiles != null ? Arrays.asList(sourceFiles) : new ArrayList<>()); for(String file : arr) { fileListEntry.append(" 0"); @@ -474,9 +440,13 @@ public boolean accept(File pathname, String string) { } String fileSettingsDefault = "settings = {"+injectFileSettings.trim()+" }; "; if(noArcFiles.contains(file)) { - fileOneEntry.append(" */; settings = {COMPILER_FLAGS = \"-fno-objc-arc\";"+injectFileSettings+" }; };\n"); + fileOneEntry.append(" */; settings = {COMPILER_FLAGS = \"-fno-objc-arc\";") + .append(injectFileSettings) + .append(" }; };\n"); } else { - fileOneEntry.append(" */;"+fileSettingsDefault+" };\n"); + fileOneEntry.append(" */;") + .append(fileSettingsDefault) + .append(" };\n"); } if(file.endsWith(".m") || file.endsWith(".c") || file.endsWith(".cpp") || file.endsWith(".hh") || file.endsWith(".hpp") || @@ -517,30 +487,6 @@ public boolean accept(File pathname, String string) { frameworks2.append("18E9ABBC002F3D1D /* "); frameworks2.append(file); frameworks2.append(" */,\n"); - - - - /* - - // Removing this because it causes crashes in cocoapods. - // Why was it necessary to add .a files to the same group - // as the sources, if we've already added it to frameworks. - // Related to https://stackoverflow.com/questions/47210585/codename-one-issue-devilering-binary-for-ios - if(file.endsWith(".a")) { - fileTwoEntry.append(" 0"); - fileTwoEntry.append(fileOneValue); - fileTwoEntry.append("18E9ABBC002F3D1D /* "); - fileTwoEntry.append(file); - fileTwoEntry.append(" *").append("/,\n"); - - if(!file.endsWith(".h") && !file.endsWith(".bundle") && !file.endsWith(".xcdatamodeld")) { - fileThreeEntry.append(" 0"); - fileThreeEntry.append(referenceValue); - fileThreeEntry.append("18E9ABBC002F3D1D /* "); - fileThreeEntry.append(file); - fileThreeEntry.append(" *").append("/,\n"); - } - }*/ } else { // standard resource file resources.append("\n 0"); @@ -576,8 +522,7 @@ public boolean accept(File pathname, String string) { private static void writeCmakeProject(File projectRoot, File srcRoot, String appName) throws IOException { File cmakeLists = new File(projectRoot, "CMakeLists.txt"); String srcRootPath = srcRoot.getAbsolutePath(); - FileWriter writer = new FileWriter(cmakeLists); - try { + try (FileWriter writer = new FileWriter(cmakeLists)) { writer.append("cmake_minimum_required(VERSION 3.10)\n"); writer.append("project(").append(appName).append(" LANGUAGES C)\n"); writer.append("set(CMAKE_C_STANDARD 99)\n"); @@ -589,8 +534,6 @@ private static void writeCmakeProject(File projectRoot, File srcRoot, String app writer.append("file(GLOB TRANSLATOR_HEADERS \"${CN1_APP_SOURCE_ROOT}/*.h\")\n"); writer.append("add_library(${PROJECT_NAME} ${TRANSLATOR_SOURCES} ${TRANSLATOR_HEADERS})\n"); writer.append("target_include_directories(${PROJECT_NAME} PUBLIC ${CN1_APP_SOURCE_ROOT})\n"); - } finally { - writer.close(); } } @@ -653,12 +596,11 @@ private static String getFileType(String s) { // private static StringBuilder readFileAsStringBuilder(File sourceFile) throws IOException { - DataInputStream dis = new DataInputStream(new FileInputStream(sourceFile)); + DataInputStream dis = new DataInputStream(Files.newInputStream(sourceFile.toPath())); byte[] data = new byte[(int)sourceFile.length()]; dis.readFully(data); dis.close(); - StringBuilder b = new StringBuilder(new String(data)); - return b; + return new StringBuilder(new String(data)); } // // rewrite 4/2017 by ddyer to use more appropriate data @@ -697,7 +639,7 @@ private static void replaceInFile(File sourceFile, String... values) throws IOEx /** * Copy the input stream into the output stream, closes both streams when finishing or in - * a case of an exception + * the case of an exception * * @param i source * @param o destination @@ -708,7 +650,7 @@ public static void copy(InputStream i, OutputStream o) throws IOException { /** * Copy the input stream into the output stream, closes both streams when finishing or in - * a case of an exception + * the case of an exception * * @param i source * @param o destination @@ -729,10 +671,10 @@ public static void copy(InputStream i, OutputStream o, int bufferSize) throws IO } /** - * Closes the object (connection, stream etc.) without throwing any exception, even if the + * Closes the object (connection, stream, etc.) without throwing any exception, even if the * object is null * - * @param o Connection, Stream or other closeable object + * @param o Connection, Stream or another closeable object */ public static void cleanup(Object o) { try { @@ -742,7 +684,6 @@ public static void cleanup(Object o) { } if(o instanceof InputStream) { ((InputStream)o).close(); - return; } } catch(IOException err) { err.printStackTrace(); diff --git a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/Parser.java b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/Parser.java index c5c5603190..b91079bb8e 100644 --- a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/Parser.java +++ b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/Parser.java @@ -24,6 +24,8 @@ package com.codename1.tools.translator; import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.*; import org.objectweb.asm.AnnotationVisitor; @@ -49,8 +51,8 @@ public class Parser extends ClassVisitor { private ByteCodeClass cls; private String clsName; private static String[] nativeSources; - private static List classes = new ArrayList(); - private static MethodDependencyGraph dependencyGraph = new MethodDependencyGraph(); + private static List classes = new ArrayList<>(); + private static final MethodDependencyGraph dependencyGraph = new MethodDependencyGraph(); private int lambdaCounter; public static void cleanup() { nativeSources = null; @@ -64,10 +66,7 @@ public static void parse(File sourceFile) throws Exception { System.out.println("Parsing: " + sourceFile.getAbsolutePath()); } BytecodeMethod.setDependencyGraph(dependencyGraph); - ClassReader r = new ClassReader(new FileInputStream(sourceFile)); - /*if(ByteCodeTranslator.verbose) { - System.out.println("Class: " + r.getClassName() + " derives from: " + r.getSuperName() + " interfaces: " + Arrays.asList(r.getInterfaces())); - }*/ + ClassReader r = new ClassReader(Files.newInputStream(sourceFile.toPath())); Parser p = new Parser(); p.clsName = r.getClassName().replace('/', '_').replace('$', '_'); @@ -106,7 +105,7 @@ private static void appendClassOffset(ByteCodeClass bc, List clsIds) { } } - private static ArrayList constantPool = new ArrayList(); + private static final ArrayList constantPool = new ArrayList<>(); public static ByteCodeClass getClassObject(String name) { for(ByteCodeClass cls : classes) { @@ -134,7 +133,7 @@ public static int addToConstantPool(String s) { private static void generateClassAndMethodIndexHeader(File outputDirectory) throws Exception { int classOffset = 0; int methodOffset = 0; - ArrayList methods = new ArrayList(); + ArrayList methods = new ArrayList<>(); for(ByteCodeClass bc : classes) { bc.setClassOffset(classOffset); classOffset++; @@ -161,7 +160,6 @@ private static void generateClassAndMethodIndexHeader(File outputDirectory) thro } first = false; bldM.append(addToConstantPool(bc.getClsName().replace('_', '.'))); - bldM.append(""); } bldM.append("};\n\n"); @@ -203,13 +201,6 @@ private static void generateClassAndMethodIndexHeader(File outputDirectory) thro bld.append(arrayId); bld.append("\n"); arrayId++; - - /*bld.append("#define cn1_array_4_id_"); - bld.append(bc.getClsName()); - bld.append(" "); - bld.append(arrayId); - bld.append("\n"); - arrayId++;*/ } bld.append("\n\n"); @@ -225,16 +216,12 @@ private static void generateClassAndMethodIndexHeader(File outputDirectory) thro } first = false; bldM.append(addToConstantPool(m.getMethodName())); - bldM.append(""); } bldM.append("};\n\n"); - ArrayList instances = new ArrayList(); + ArrayList instances = new ArrayList<>(); int counter = 0; for(ByteCodeClass bc : classes) { - /*bld.append("extern int classInstanceOfArr"); - bld.append(counter); - bld.append("[];\n");*/ bldM.append("int classInstanceOfArr"); bldM.append(counter); bldM.append("[] = {"); @@ -253,8 +240,8 @@ private static void generateClassAndMethodIndexHeader(File outputDirectory) thro bldM.append(classes.size()); bldM.append("] = {"); first = true; - counter = 0; - for(ByteCodeClass bc : classes) { + int classCount = classes.size(); + for(counter = 0 ; counter < classCount ; counter++) { if(first) { bldM.append("\n "); } else { @@ -263,7 +250,6 @@ private static void generateClassAndMethodIndexHeader(File outputDirectory) thro first = false; bldM.append("classInstanceOfArr"); bldM.append(counter); - counter++; } bldM.append("};\n\n"); @@ -330,10 +316,10 @@ private static void generateClassAndMethodIndexHeader(File outputDirectory) thro bld.append("\n\n#endif // __CN1_CLASS_METHOD_INDEX_H__\n"); FileOutputStream fos = new FileOutputStream(new File(outputDirectory, "cn1_class_method_index.h")); - fos.write(bld.toString().getBytes("UTF-8")); + fos.write(bld.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); fos = new FileOutputStream(new File(outputDirectory, "cn1_class_method_index.m")); - fos.write(bldM.toString().getBytes("UTF-8")); + fos.write(bldM.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); } @@ -386,16 +372,16 @@ public static void writeOutput(File outputDirectory) throws Exception { String file = "Unknown File"; try { for(ByteCodeClass bc : classes) { - // special case for object + // special case for an object if(bc.getClsName().equals("java_lang_Object")) { continue; } file = bc.getClsName(); bc.setBaseClassObject(getClassByName(bc.getBaseClass())); - List lst = new ArrayList(); + List lst = new ArrayList<>(); for(String s : bc.getBaseInterfaces()) { - ByteCodeClass bcode=getClassByName(s); - if(bcode==null){ + ByteCodeClass byteCode = getClassByName(s); + if(byteCode == null){ System.out.println("Error while working with the class: " + s+" file:"+file+" no class definition"); } else { lst.add(getClassByName(s)); @@ -416,7 +402,7 @@ public static void writeOutput(File outputDirectory) throws Exception { // load the native sources (including user native code) // We need to load native sources before we clear any unmarked classes - // because native source may be the only thing referencing a class, + // because a native source may be the only thing referencing a class, // and the class may be purged before it even has a shot. readNativeFiles(outputDirectory); @@ -425,9 +411,9 @@ public static void writeOutput(File outputDirectory) throws Exception { bc.updateAllDependencies(); } ByteCodeClass.markDependencies(classes, nativeSources); - Set unmarked = new HashSet(classes); + Set unmarked = new HashSet<>(classes); classes = ByteCodeClass.clearUnmarked(classes); - unmarked.removeAll(classes); + classes.forEach(unmarked::remove); int neliminated = 0; for (ByteCodeClass removedClass : unmarked) { removedClass.setEliminated(true); @@ -441,7 +427,7 @@ public static void writeOutput(File outputDirectory) throws Exception { neliminated += eliminateUnusedMethods(); Date later = new Date(); long dif = later.getTime()-now.getTime(); - System.out.println("unusued Method cull removed "+neliminated+" methods in "+(dif/1000)+" seconds"); + System.out.println("unused Method cull removed "+neliminated+" methods in "+(dif/1000)+" seconds"); } generateClassAndMethodIndexHeader(outputDirectory); @@ -454,30 +440,25 @@ public static void writeOutput(File outputDirectory) throws Exception { writeFile(bc, outputDirectory, cos); } if (cos != null) cos.realClose(); - } catch(Throwable t) { System.out.println("Error while working with the class: " + file); t.printStackTrace(); if(t instanceof Exception) { throw (Exception)t; } - if(t instanceof RuntimeException) { - throw (RuntimeException)t; - } } finally { cleanup(); } } private static void readNativeFiles(File outputDirectory) throws IOException { - File[] mFiles = outputDirectory.listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - return file.getName().endsWith(".m") || file.getName().endsWith("." + ByteCodeTranslator.output.extension()); - } - }); + File[] mFiles = outputDirectory.listFiles(file -> + file.getName().endsWith(".m") || file.getName().endsWith("." + ByteCodeTranslator.output.extension())); + if(mFiles == null) { + return; + } nativeSources = new String[mFiles.length]; int size = 0; - System.out.println(""+mFiles.length +" native files"); + System.out.println(mFiles.length + " native files"); for(int iter = 0 ; iter < mFiles.length ; iter++) { FileInputStream fi = new FileInputStream(mFiles[iter]); DataInputStream di = new DataInputStream(fi); @@ -486,10 +467,9 @@ public boolean accept(File file) { byte[] dat = new byte[len]; di.readFully(dat); fi.close(); - nativeSources[iter] = new String(dat, "UTF-8"); + nativeSources[iter] = new String(dat, StandardCharsets.UTF_8); } System.out.println("Native files total "+(size/1024)+"K"); - } private static int eliminateUnusedMethods() { @@ -584,20 +564,12 @@ private static int cullClasses(boolean found, int depth) { ByteCodeClass.markDependencies(classes, nativeSources); List tmp = ByteCodeClass.clearUnmarked(classes); - /*if(ByteCodeTranslator.verbose) { - System.out.println("Classes removed from: " + classCount + " to " + classes.size()); - for(ByteCodeClass bc : classes) { - if(!tmp.contains(bc)) { - System.out.println("Removed class: " + bc.getClsName()); - } - } - }*/ // 2nd pass to mark classes as eliminated so that we can propagate down to each // method of the class to mark it eliminated so that virtual methods // aren't included later on when writing virtual methods - Set removedClasses = new HashSet(classes); - removedClasses.removeAll(tmp); + Set removedClasses = new HashSet<>(classes); + tmp.forEach(removedClasses::remove); int nfound = 0; for (ByteCodeClass cls : removedClasses) { nfound += cls.setEliminated(true); @@ -635,7 +607,7 @@ private static void writeFile(ByteCodeClass cls, File outputDir, ConcatenatingFi OutputStream outMain = writeBufferInstead != null && ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS ? writeBufferInstead : - new FileOutputStream(new File(outputDir, cls.getClsName() + "." + ByteCodeTranslator.output.extension())); + Files.newOutputStream(new File(outputDir, cls.getClsName() + "." + ByteCodeTranslator.output.extension()).toPath()); if (outMain instanceof ConcatenatingFileOutputStream) { ((ConcatenatingFileOutputStream)outMain).beginNextFile(cls.getClsName()); @@ -668,8 +640,7 @@ public void visitEnd() { public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { BytecodeMethod mtd = new BytecodeMethod(clsName, access, name, desc, signature, exceptions); cls.addMethod(mtd); - JSRInlinerAdapter a = new JSRInlinerAdapter(new MethodVisitorWrapper(super.visitMethod(access, name, desc, signature, exceptions), mtd), access, name, desc, signature, exceptions); - return a; + return new JSRInlinerAdapter(new MethodVisitorWrapper(super.visitMethod(access, name, desc, signature, exceptions), mtd), access, name, desc, signature, exceptions); } @Override @@ -743,7 +714,7 @@ public void visit(int version, int access, String name, String signature, String } class MethodVisitorWrapper extends MethodVisitor { - private BytecodeMethod mtd; + private final BytecodeMethod mtd; public MethodVisitorWrapper(MethodVisitor mv, BytecodeMethod mtd) { super(Opcodes.ASM9, mv); this.mtd = mtd; @@ -907,12 +878,11 @@ public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object. // 5. Implement the interface method Type samMethodType = (Type) bsmArgs[0]; Handle implMethod = (Handle) bsmArgs[1]; - Type instantiatedMethodType = (Type) bsmArgs[2]; - String samMethodName = name; // Name from invokedynamic + // Name from invokedynamic String samMethodDesc = samMethodType.getDescriptor(); // Signature from BSM arg 0 - BytecodeMethod interfaceMethod = new BytecodeMethod(lambdaClassName, Opcodes.ACC_PUBLIC, samMethodName, samMethodDesc, null, null); + BytecodeMethod interfaceMethod = new BytecodeMethod(lambdaClassName, Opcodes.ACC_PUBLIC, name, samMethodDesc, null, null); lambdaClass.addMethod(interfaceMethod); // Method Body: @@ -950,9 +920,12 @@ public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object. case Opcodes.H_INVOKESTATIC: invokeOpcode = Opcodes.INVOKESTATIC; break; case Opcodes.H_INVOKEVIRTUAL: invokeOpcode = Opcodes.INVOKEVIRTUAL; break; case Opcodes.H_INVOKEINTERFACE: invokeOpcode = Opcodes.INVOKEINTERFACE; break; - case Opcodes.H_INVOKESPECIAL: invokeOpcode = Opcodes.INVOKESPECIAL; break; - case Opcodes.H_NEWINVOKESPECIAL: invokeOpcode = Opcodes.INVOKESPECIAL; break; - default: invokeOpcode = Opcodes.INVOKESTATIC; // Fallback + case Opcodes.H_INVOKESPECIAL: + case Opcodes.H_NEWINVOKESPECIAL: + invokeOpcode = Opcodes.INVOKESPECIAL; break; + default: + invokeOpcode = Opcodes.INVOKESTATIC; + break;// Fallback } if (isCtorRef) { @@ -969,7 +942,7 @@ public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object. // 6. Add static factory method String factoryMethodName = "lambda$factory"; - String factoryDesc = desc; // The desc of invokedynamic is (CapturedArgs)Interface. + // The desc of invokedynamic is (CapturedArgs)Interface. // We want factory to be (CapturedArgs)LambdaClass (to match NEW output but wrapped) // Actually, replacing invokedynamic with INVOKESTATIC means the return type on stack should match @@ -1016,11 +989,6 @@ public void visitMethodInsn(int opcode, String owner, String name, String desc, super.visitMethodInsn(opcode, owner, name, desc, itf); } - @Override - public void visitMethodInsn(int opcode, String owner, String name, String desc) { - super.visitMethodInsn(opcode, owner, name, desc); - } - @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { mtd.addField(cls, opcode, owner, name, desc); @@ -1098,7 +1066,7 @@ public void visitParameter(String name, int access) { } - class FieldVisitorWrapper extends FieldVisitor { + static class FieldVisitorWrapper extends FieldVisitor { public FieldVisitorWrapper(FieldVisitor fv) { super(Opcodes.ASM9, fv); @@ -1126,7 +1094,7 @@ public AnnotationVisitor visitAnnotation(String desc, boolean visible) { } - class AnnotationVisitorWrapper extends AnnotationVisitor { + static class AnnotationVisitorWrapper extends AnnotationVisitor { public AnnotationVisitorWrapper(AnnotationVisitor av) { super(Opcodes.ASM9, av); diff --git a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/CustomInvoke.java b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/CustomInvoke.java index 626a118ccc..7abd68daee 100644 --- a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/CustomInvoke.java +++ b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/CustomInvoke.java @@ -38,11 +38,11 @@ */ public class CustomInvoke extends Instruction { private String owner; - private String name; - private String desc; - private boolean itf; + private final String name; + private final String desc; + private final boolean itf; private String[] literalArgs; - private int origOpcode; + private final int origOpcode; private String targetObjectLiteral; private boolean noReturn; @@ -86,7 +86,7 @@ public boolean isMethodUsed(String desc, String name) { public String getMethodUsed() { return desc + "." + name; } - public String getMethodUsedName() { return(name); } + public String getSignature() { return(desc); } @Override @@ -113,8 +113,8 @@ public void addDependencies(List dependencyList) { } } bld.append("__"); - ArrayList args = new ArrayList(); - String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); + ArrayList args = new ArrayList<>(); + BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); String str = bld.toString(); BytecodeMethod.addVirtualMethodsInvoked(str); } @@ -136,14 +136,13 @@ private String findActualOwner(ByteCodeClass bc) { } public boolean methodHasReturnValue() { - return BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, new StringBuilder(), new ArrayList()) != null; + return BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, new StringBuilder(), new ArrayList<>()) != null; } public String getReturnValue() { - ArrayList args = new ArrayList(); + ArrayList args = new ArrayList<>(); StringBuilder sb = new StringBuilder(); - String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, sb, args); - return returnVal; + return BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, sb, args); } @@ -190,7 +189,7 @@ public boolean appendExpression(StringBuilder b) { } if(origOpcode == Opcodes.INVOKESTATIC) { - // find the actual class of the static method to workaround javac not defining it correctly + // find the actual class of the static method to work around javac not defining it correctly ByteCodeClass bc = Parser.getClassObject(owner.replace('/', '_').replace('$', '_')); owner = findActualOwner(bc); } @@ -210,7 +209,7 @@ public boolean appendExpression(StringBuilder b) { } } bld.append("__"); - ArrayList args = new ArrayList(); + ArrayList args = new ArrayList<>(); String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); if (isVirtualCall) { BytecodeMethod.addVirtualMethodsInvoked(bld.substring("virtual_".length())); @@ -219,39 +218,24 @@ public boolean appendExpression(StringBuilder b) { if (numLiteralArgs > 0) { b.append("/* CustomInvoke */"); } - boolean noPop = false; b.append(bld); b.append("(threadStateData"); - - - + if(origOpcode != Opcodes.INVOKESTATIC) { if (targetObjectLiteral == null) { - //b.append(", SP[-"); - //b.append(args.size() + 1 - numLiteralArgs); - //b.append("].data.o"); return false; } else { b.append(", ").append(targetObjectLiteral); - numLiteralArgs++; } } - //int offset = args.size(); - //int numArgs = offset; int argIndex=0; - for(String a : args) { - + for(String ignored : args) { b.append(", "); if (literalArgs != null && literalArgs[argIndex] != null) { b.append(literalArgs[argIndex]); } else { return false; - //b.append("SP[-"); - //b.append(offset); - //b.append("].data."); - //b.append(a); - //offset--; } argIndex++; } @@ -262,7 +246,6 @@ public boolean appendExpression(StringBuilder b) { b.append(")"); return true; - } @@ -308,13 +291,10 @@ public void appendInstruction(StringBuilder b) { } if(origOpcode == Opcodes.INVOKESTATIC) { - // find the actual class of the static method to workaround javac not defining it correctly + // find the actual class of the static method to work around javac not defining it correctly ByteCodeClass bc = Parser.getClassObject(owner.replace('/', '_').replace('$', '_')); owner = findActualOwner(bc); } - //if(owner.replace('/', '_').replace('$', '_').equals("java_lang_System_1") && name.equals("sleep")) { - // System.out.println("Break"); - //} if (owner.startsWith("[")) { bld.append("java_lang_Object"); } else{ @@ -331,7 +311,7 @@ public void appendInstruction(StringBuilder b) { } } bld.append("__"); - ArrayList args = new ArrayList(); + ArrayList args = new ArrayList<>(); String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); int numLiteralArgs = this.getNumLiteralArgs(); if (numLiteralArgs > 0) { @@ -368,8 +348,6 @@ public void appendInstruction(StringBuilder b) { noPop = true; b.append("("); } else { - //b.append("POP_MANY_AND_"); - //b.append(returnVal); b.append("{ "); b.append(returnVal); b.append(" tmpResult = "); @@ -386,7 +364,7 @@ public void appendInstruction(StringBuilder b) { b.append(args.size() + 1 - numLiteralArgs); b.append("].data.o"); } else { - b.append(", "+targetObjectLiteral); + b.append(", ").append(targetObjectLiteral); numLiteralArgs++; } } diff --git a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/Invoke.java b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/Invoke.java index 78c51ec900..51d64aeec5 100644 --- a/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/Invoke.java +++ b/vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/Invoke.java @@ -39,9 +39,9 @@ */ public class Invoke extends Instruction { private String owner; - private String name; - private String desc; - private boolean itf; + private final String name; + private final String desc; + private final boolean itf; private char[] stackInputTypes; private char[] stackOutputTypes; @@ -111,8 +111,8 @@ public void addDependencies(List dependencyList) { } } bld.append("__"); - ArrayList args = new ArrayList(); - String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); + ArrayList args = new ArrayList<>(); + BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); String str = bld.toString(); BytecodeMethod.addVirtualMethodsInvoked(str); } @@ -150,7 +150,7 @@ public void appendInstruction(StringBuilder b) { b.append(" "); // Well, it is actually legal to call private methods with invoke virtual, and kotlin - // generates such calls. But ParparVM strips out these virtual method definitions + // generates such calls. But ParparVM strips out these virtual method definitions, // so we need to check if the method is private, and remove the virtual invocation // if it is. boolean isVirtual = true; @@ -173,16 +173,13 @@ public void appendInstruction(StringBuilder b) { } if(opcode == Opcodes.INVOKESTATIC) { - // find the actual class of the static method to workaround javac not defining it correctly + // find the actual class of the static method to work around javac not defining it correctly ByteCodeClass bc = Parser.getClassObject(owner.replace('/', '_').replace('$', '_')); owner = findActualOwner(bc); } - //if(owner.replace('/', '_').replace('$', '_').equals("java_lang_System_1") && name.equals("sleep")) { - // System.out.println("Break"); - //} if (owner.startsWith("[")) { // Kotlin seems to generate calls to toString() on arrays using the array class - // as owner. We'll just change this to java_lang_Object instead. + // as an owner. We'll just change this to java_lang_Object instead. bld.append("java_lang_Object"); } else{ bld.append(owner.replace('/', '_').replace('$', '_')); @@ -198,7 +195,7 @@ public void appendInstruction(StringBuilder b) { } } bld.append("__"); - ArrayList args = new ArrayList(); + ArrayList args = new ArrayList<>(); String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, bld, args); if (isVirtualCall) { BytecodeMethod.addVirtualMethodsInvoked(bld.substring("virtual_".length())); @@ -207,7 +204,7 @@ public void appendInstruction(StringBuilder b) { if(returnVal == null) { b.append(bld); } else { - if(args.size() == 0 && opcode == Opcodes.INVOKESTATIC) { + if(args.isEmpty() && opcode == Opcodes.INVOKESTATIC) { // special case for static method if(returnVal.equals("JAVA_OBJECT")) { b.append("PUSH_OBJ"); @@ -234,8 +231,6 @@ public void appendInstruction(StringBuilder b) { noPop = true; b.append("("); } else { - //b.append("POP_MANY_AND_"); - //b.append(returnVal); b.append("{ "); b.append(returnVal); b.append(" tmpResult = "); @@ -253,18 +248,13 @@ public void appendInstruction(StringBuilder b) { } int offset = args.size(); //int numArgs = offset; - int argIndex=0; for(String a : args) { - b.append(", "); - b.append("SP[-"); b.append(offset); b.append("].data."); b.append(a); offset--; - - argIndex++; } if(noPop) { b.append("));\n"); @@ -273,7 +263,7 @@ public void appendInstruction(StringBuilder b) { if(returnVal != null) { b.append(");\n"); if(opcode != Opcodes.INVOKESTATIC) { - if(args.size() > 0) { + if(!args.isEmpty()) { b.append(" SP-="); b.append(args.size()); b.append(";\n"); @@ -306,14 +296,7 @@ public void appendInstruction(StringBuilder b) { } } } - - /*if(opcode != Opcodes.INVOKESTATIC) { - b.append(args.size() + 1); - } else { - b.append(args.size()); - } - b.append(");\n"); */ - + return; } b.append("); "); @@ -324,9 +307,6 @@ public void appendInstruction(StringBuilder b) { val = args.size(); } if(val > 0) { - /*b.append("popMany(threadStateData, "); - b.append(val); - b.append(", stack, &stackPointer); \n"); */ b.append(" SP-= "); b.append(val); b.append(";\n"); @@ -364,7 +344,7 @@ public char[] getStackInputTypes() { @Override public char[] getStackOutputTypes() { if (stackOutputTypes == null) { - String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, new StringBuilder(), new ArrayList()); + String returnVal = BytecodeMethod.appendMethodSignatureSuffixFromDesc(desc, new StringBuilder(), new ArrayList<>()); if (returnVal == null) { stackOutputTypes = new char[0]; } else { diff --git a/vm/tests/src/test/java/com/codename1/tools/translator/BytecodeInstructionIntegrationTest.java b/vm/tests/src/test/java/com/codename1/tools/translator/BytecodeInstructionIntegrationTest.java index 0cd74f0e45..a6a084dc94 100644 --- a/vm/tests/src/test/java/com/codename1/tools/translator/BytecodeInstructionIntegrationTest.java +++ b/vm/tests/src/test/java/com/codename1/tools/translator/BytecodeInstructionIntegrationTest.java @@ -341,7 +341,7 @@ public boolean assignTo(String varName, StringBuilder sb) { void annotationVisitorWrapperDelegatesAndHandlesNullVisitor() { Parser parser = new Parser(); - Parser.AnnotationVisitorWrapper wrapperWithNull = parser.new AnnotationVisitorWrapper(null); + Parser.AnnotationVisitorWrapper wrapperWithNull = new Parser.AnnotationVisitorWrapper(null); assertNull(wrapperWithNull.visitArray("values")); assertNull(wrapperWithNull.visitAnnotation("name", "LExample;")); assertDoesNotThrow(() -> wrapperWithNull.visit("flag", true)); @@ -356,28 +356,12 @@ public AnnotationVisitor visitArray(String name) { } }; - Parser.AnnotationVisitorWrapper wrapperWithDelegate = parser.new AnnotationVisitorWrapper(delegate); + Parser.AnnotationVisitorWrapper wrapperWithDelegate = new Parser.AnnotationVisitorWrapper(delegate); AnnotationVisitor result = wrapperWithDelegate.visitArray("values"); assertSame(delegate, result); assertTrue(delegated.get(), "AnnotationVisitorWrapper should forward to the underlying visitor"); } - @Test - void byteCodeTranslatorFilenameFilterMatchesExpectedFiles() throws Exception { - Class filterClass = Class.forName("com.codename1.tools.translator.ByteCodeTranslator$3"); - Constructor ctor = filterClass.getDeclaredConstructor(); - ctor.setAccessible(true); - - FilenameFilter filter = (FilenameFilter) ctor.newInstance(); - File directory = Files.createTempDirectory("bytecode-filter").toFile(); - - assertTrue(filter.accept(directory, "assets.bundle")); - assertTrue(filter.accept(directory, "model.xcdatamodeld")); - assertTrue(filter.accept(directory, "VisibleSource.m")); - assertFalse(filter.accept(directory, ".hidden")); - assertFalse(filter.accept(directory, "Images.xcassets")); - } - @Test void concatenatingFileOutputStreamWritesShardedOutputs() throws Exception { Path outputDir = Files.createTempDirectory("concatenating-output");