I work with a language similar to JavaScript that is used for point-of-sale device programming. This language really s*cks and I'm trying to build some kind of framework in Java that "converts" Java code into this language.
I did this using some Regex and parsed the Java files directly. Now I found that this may be not the right/better way and I'm searching for alternatives. Are there any tools for helping me doing so?
I thought I should use some advanced reflection utilities like ASM (http://asm.ow2.org/index.html). Performance is not crucial, so that may be the way.
What do you think?
ANTLR is a terrific parser-generator. I'd look into it. It has a Java grammar already available; I'm not sure if it's Java 5, 6, or 7 (I'm guessing it's 5).
Once you have the AST, your problem will be walking the tree and generating the target code. Good luck.
I suggest to parse Java syntax with JavaCC or similar tool, Java grammar description written long time ago. It can be used to write compiler so probably can also be used to write a converter. Regular expressions are not very good at parsing programming languages.
I've never done anything with it myself, but you could take a look at one of the framework listed at altjs.org, specifically under the Java Ports section, and take a look at one of those frameworks and modify them to your specific needs.
There are at least three ways:
a) Interpret the bytecode. There are some existing interpreters in JS, e.g. DoppioVM. They can be very slow.
b) Compile bytecode to JS. I've seen at least one such attempt and the resulting JS was ugly and not very fast. But this approach can have a good performance (well, it may result in using HashMap instead of JS object and so on). The biggest issue is IMHO while/if reconstruction.
EDIT: OK, is possibly is not so slow, but it is ugly and contains garbage like j2js.invokeStatic("j2js.client.Engine", "getEngine()j2js.client.Engine", null);. The one compiler was https://github.com/decatur/j2js-compiler .
c) Compile Java to JS. You can try Google Web Toolkit or http://j2s.sourceforge.net/ .
Related
I need to develop a c parser in order to extract the function names, macros and its definitions. my approach was not to start from scratch, just access any c program editors like geany which already parses the functions and macros ,
may be a simple api to this editor will get all my requirements, I have googled it, but most of the solutions are to use javacc, so some other parser ...
As this job is already done by editors, so it would be easy , not taking pain to start with building grammar.
this approach would be simple, but unable to find any such editors which have any apis to access it through java.
What you are looking for is existing parser-generator
You could see,
ANTLR
Lex
Yacc
JavaCC
I've already used lex, flex, yacc, bison etc. But nothing can beat Perl for doing it. Moreover Perl regular expressions can be used in Java, PHP.
At least use Perl like regular expression to get it done rather than writing in yacc is very difficult to maintain and which can easily be done in a few lines in Perl or PHP.
Another possibility could be to develop a GCC plugin or a MELT extension to customize the GCC compiler for your needs. (MELT is a domain specific language that I developed to easily extend GCC).
The advantage of customizing GCC for your purposes is that you'll work on the exact internal representations of GCC. However, GCC being complex, extending it requires some work (in particular, partly understanding the complex GCC internal representations and passes).
(It is possible for functions, variables and classes, perhaps not for macros today with GCC 4.7, since GCC preprocessor don't have yet any plugin hooks)
And I am not sure you are right in believing that geany has a complete C parser. I believe it has some regexpr based thing, which e.g. ignores any preprocessor tricks. I don't think that geany is aware of e.g. functions or variables created by expanding complex macros (like some GTK implementation macros for instance).
There are several IDE's or programmers-editors with C parsers, written in Java. So getting at them shouldn't be too horrific (famous last words :-)
Eclipse CDT which has several books on how to write and use plugins/extensions
NetBeans
to mention just two. They both have active user communities who might be able to help too.
Their C editors, have a pretty good grasp of C syntax because they can fold functions. Eclipse's C editor keeps track of definitions, and I think NetBeans does too.
Personally, if I needed to parse C to get function bodies, and the code is syntactically correct, it wouldn't be too hard to use parser-development-tools. IIRC ANTLR might have a C grammar already.
I am asked to develop a software which should be able to create Flow chart/ Control Flow of the input Java source code. So I started researching on it and arrived at following solutions:
To create flow chart/control flow I have to recognize controlling statements and function calls made in the given source code Now I have two ways of recognizing:
Parse the Source code by writing my own grammars (A complex solution I think). I am thinking to use Antlr for this.
Read input source code files as text and search for the specific patterns (May become inefficient)
Am I right here? Or I am missing something very fundamental and simple? Which approach would take less time and do the work efficiently? Any other suggestions in this regard will be welcome too. Any other efficient approach would help because the input source code may span multiple files and can be fairly complex.
I am good in .NET languages but this is my first big project in Java. I have basic knowledge of Compiler Design so writing grammars should not be impossible for me.
Sorry If I am being unclear. Please ask for any clarifications.
I'd go with Antlr and use an existing Java grammar: https://github.com/antlr/grammars-v4
All tools handling Java code usually decide first whether they want to process the language Java or Java byte code files. That is a strategic decision and depends on your use case. I could image both for flow chart generation. When you have decided that question. There are already several frameworks or libraries, which could help you on that. For byte code engineering there are: ASM, JavaAssist, Soot, and BCEL, which seems to be dead. For Java language parsing and analyzing, there are: Polyglot, the eclipse compiler, and javac. All of these include a complete compiler frontend for Java and are open source.
I would try to avoid writing my own parser for Java. I did that once. Java has a rather complex grammar, but which can be found elsewhere. The real work begins with name and type resolution. And you would need both, if you want to generate graphs which cover more than one method body.
Eclipse has a library for parsing the source code and creating Abstract Syntax Tree from it which would let you extract what you want.
See here for a tutorial
http://www.vogella.de/articles/EclipseJDT/article.html
See here for api
http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/package-summary.html#package_description
Now I have two ways of recognizing:
You have many more ways than that. JavaCC ships with a Java 1.5 grammar already built. I'm sure other parser generators ditto. There is no reason for you to either have to write your own grammar or construct your own parser.
And specifically 'read[ing] input source code files as text and search for the specific patterns' isn't a viable choice at all, as it isn't parsing, and therefore cannot possibly recognize Java programs correctly.
Your input files are written in Java, and the software should be written in Java, but this is your first project in Java? First of all, I'd suggest learning the language with smaller projects. Also you need to learn how to use graphics in Java (there are various libraries). Then, you should focus on what you want to show on your graphs. Or is text sufficient?
The way I would do it is to analyse compiled code. This would allow you to read jars without source and avoid parsing the code yourself. I would use Objectwebs ASM to read the class files.
Smarter solution is to use Eclipse's java parser. Read more here: http://www.ibm.com/developerworks/opensource/library/os-ast/
Or even more easy: Use reflection. You should be able to compile the sources, load the classes with java classloader and analyse them from there. I think this is far more easy than any parsing.
Our DMS Software Reengineering Toolkit is general purpose program analysis and transformation machinery, with built in capability for parsing, building ASTs, constructing symbol tables, extracting control and data flow, transforming the ASTs, prettyprinting ASTs back to text, etc.
DMS is parameterized by an explicit language definition, and has a large set of preexisting definitions.
DMS's Java Front End already computes control and data flow graphs, so your problem would be reduced to exporting them.
EDIT 7/19/2014: Now handles Java 8.
I have an application written in C++ (makes heavy use of templates) that I need to take to the Java ME platform.
I have two questions:
Are there any good tools to convert C++ code to Java - do some basic stuff so I have a platform to start with. I found this - http://tangiblesoftwaresolutions.com/Product_Details/CPlusPlus_to_Java_Converter_Details.html. It would at least eliminate the need for simple but time-consuming stuff like moving classes to different files, namespaces to packages, etc. Has anyone tried it? Or knows of any better ones?
The bigger problem is how to deal with templates - the code makes very heavy use of them. Any suggestions on how to go about this? Are there any tools to expand templates for instance so I have a rudimentary base and then I could work on writing the modules in Java?
Any help would be appreciated.
For all of Sun's marketing, Java is not simply a better C++, and in fact does not support many of the idioms and paradigms C++ supports. This makes automated translation difficult. How should you automatically turn a multi-inheritance hierarchy into Java's single inheritance hierarchy? (Note, I am not saying that a multi-inheritance hierarchy is a good thing, only that it is explicitly allowed in C++). More fundamentally, how would you represent a pointer-to-member function in Java? Or handle the differences between Java and C++ overload resolution?
Java added generics a few years ago, but purposely made them less powerful than C++ templates. Regardless of whether that was a good idea, it limits what automated translation can do with heavily templatized code.
Aside from using some research compiler that can turn C++ into Java bytecode, I'm afraid you may be stuck doing the translation by hand.
Can you use JNI and call the old C++ code from the new Java code?
I think for your case a very simple tool would be possible and perhaps worthwhile. Might be a fun weekend-job, though! A friend of mine once did a port from C++ to Java and he just made a list of regular expression substitutions. Like, he had all occurrences of -> replaced by a dot. And so forth. This was some years ago, however, so I don't really feel like asking him.
So, you could do the same, collect some easy substitutions and perhaps publish them somewhere on github?
Generics is the Java feature that corresponds to C++ templates and they are not supported in J2ME. You can use them with the aid of a framework, which probably uses pre-processing to do the trick. (Actually Generics in Java is a compiler feature - the JVM knows nothing about them.)
Anyway, it will be difficult if not impossible to automatically port even a small portion of your code form C++ to Java Standard Edition - things are much worse with J2ME. There are many and important differences between Java Generics and C++ templates.
I don't think it's going to be possible, esp. if your original code is heavily templatized - J2ME doesn't support generics, AFAIK.
Unfortunately, it seems like this will require a lot of manual work to go through the original code and rewrite it (I'm assuming your target platform doesn't support JNI)
I have been tasked with converting several php classes into java classes, which is quickly becoming a nightmare for me. I understand the basic language structure, it being similar to C. It is all of the function calls and class calls that seem to go nowhere and the fact that a var can be declared in the !middle of an expression! that is spinning my head, oh and the fact that there is zero "0" documentation.
What is the best method (and/or) tool (and/or) reference material to convert the php into java code?
edit: There is 3 reasons that I am having to convert the php to java.
The usual reason, my boss told me too.
The php is too slow, it is taking minutes sometimes to run a request to the server.
php is a nightmare to scale and maintain.(at least for us strong typed language types)
You ask about best practices. I believe a good practice in your case is the approach pleasantly presented by theman: using an automated tool will probably give a bad result: garbage in, garbage out...
You have the code: analyze it, in its broad lines if necessary. And re-create it in Java. It might be time-consuming, but not necessarily worse than by doing blind conversion. And you can document on the way, and perhaps use this analysis to find the problematic parts.
A human is the best tool.
I would try to rewrite the php to remove most of the php features to something C like. Then you'll have an easy time rewriting in Java.
But I need to ask, why do you need to convert the php? Can you not wrap the php into something callable from Java? This way you won't add any errors while converting it.
throw code away
rewrite in java
????
profit!
I said this in the PHP Optimization Tips question and I'll say it again here: If you're running PHP from a static environment (web server module or FastCGI), use an opcode cache, such as APC. Otherwise, PHP is reinterpreting/recompiling your code on every request!
Check out http://www.numiton.com
Someone implied that Java is not as flexible as PHP : it is, by default, far more flexible actually (in that the core API contains thousands of classes and built-in functionality). You just have to learn the core concepts of both languages, such as autoboxing for Java, for example, to make room for dynamic types. Check out http://www.javaworld.com and I am currently working on porting a big API from PHP to Java, should take me a few days. Two classes, libcurl, json parsing, and maybe a hundred methods / functions.
Depending on the PHP code, this may be an almost impossible task. The other way around is much easier. PHP is a very dynamic language, and you can get away with things that are impossible in Java. One particularly disruptive thing is that a PHP variable may change type during execution. This is rarely used though, but it could happen. In addition, since PHP is loosely typed, there are a lot of implicit conversions. Some are coincidental, while others are important for the meaning of the program. And then there is the fact that PHP code isn't strictly object oriented, like Java is. Even in object oriented PHP programs, you will usually see some degree of procedural elements. These can not be mapped directly to Java code.
As Pyrolistical, I'm curious as to why you need to convert this code? If it's legacy code, wouldn't it be better to keep the PHP code running, and interface with it through some kind of service interface (SOAP, RPC, others)? You could then gradually replace parts over time.
For completeness, I should point out that there is a PHP runtime for the JVM. Check out Quercus.
You might consider leaving your current codebase in PHP and just getting it to run on the JVM. You can then rewrite code in Java as needed.
Caucho/Resin server converts PHP Code into Java servlets in run-time!
I would normally take the class generated by php5servlet, a jar thats available in tomcat & resin.
Then change the class file to Java.
cheers
I can not imagine that a tool for this is existing.
I did something similar with C++ und Java. It is a pain, but the best is to impement it by your self.
Or write it in C and create a dll with a jni warpper to call it from Java. This should be the fastet way.
You could probably write something with the Reflection API to do some of this, but you really couldn't do anything with function bodies - you'd end up with stub classes that have no implementation.
I've been looking into Groovy as a transition language from PHP to Java. They (the Groovy developers) claim that it compiles to java byte code the same as Java code would.
It's also less strict, they have several examples of translation on their website.
It sounds like you're trying to convert PHP code that is procedural into an OO code base.
This is not so much a question of PHP to Java, but rather a paradigm shift. There's no automated way to do it, it's going to be rough. Especially if one code base is badly written.
Btw, I would also why are you converting? Is it just performance? And if so, is there nothing you can do to fix the performance issues. I don't think just converting from one language to another will fix it, you'll still have to find the bottleneck.
I can only find two:
1) https://github.com/bafolts/java2php
2) http://www.runtimeconverter.com/
There is also Caucho Resin, but it is not exactly a converter. It is an implementation of php inside of Java.
There is a whole lot on the internet about numiton, but their website is down for several years now.
This question already has answers here:
Where can I find a Java to C# converter? [closed]
(9 answers)
Closed 7 years ago.
Is there an effective tool to convert C# code to Java code?
I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects always always always turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option.
We have an application that we need to maintain in both C# and Java. Since we actively maintain this product, a one-time port wasn't an option. We investigated Net2Java and the Mainsoft tools, but neither met our requirements (Net2Java for lack of robustness and Mainsoft for cost and lack of source code conversion). We created our own tool called CS2J that runs as part of our nightly build script and does a very effective port of our C# code to Java. Right now it is precisely good enough to translate our application, but would have a long way to go before being considered a comprehensive tool. We've licensed the technology to a few parties with similar needs and we're toying with the idea of releasing it publicly, but our core business just keeps us too busy these days.
This blog post suggests useful results from Tangible.
There is a tool from Microsoft to convert java to C#. For the opposite direction take a look here and here. If this doesn't work out, it should not take too long to convert the source manually because C# and java are very similar,
These guys seem to have a solution for this, but I haven't tried yet. They also have a demo version of the converter.
Although this is an old-ish question, take a look at xmlVM http://www.xmlvm.org/clr2jvm, I'm not sure if it's mature enough yet, although it has been around for several years now. XMLvm was made, I believe, primarily for translating Android Java apps to the iPhone, however, its XML-code-translation-based framework is flexible enough to do other combinations (see the diagrams on the site).
As for a reason to do this conversion, maybe there is a need to 'hijack' some of the highly abundant oss code out there and use it within his/their own [Java] project.
Cheers
Rich
Try to look at Net2Java It seems to me the best option for automatic (or semi-automatic at least) conversion from C# to Java
They don't convert directly, but it allows for interoperability between .NET and J2EE.
http://www.mainsoft.com/products/index.aspx
C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern.
Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java.
If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.
I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen:
http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen
(I've been registered with them for a while and they're good about not spamming)
I'm not sure what you are trying to do by wishing to convert C# to java, but if it is .net interoperability that you need, you might want to check out Mono
This is off the cuff, but isn't that what Grasshopper was for?
Well the syntax is almost the same but they rely on different frameworks so the only way to convert is by getting someone who knows both languages and convert the code :) the answer to your question is no there is no "effective" tool to convert c# to java
Possibly you could use jni4net - opensource bridge instead ?
Or list of other options I know.
Why not write it in Haxe (http://haxe.org/) and convert it to whatever you want it to be?