Are there any JavaScript (ECMAScript) implementations written in pure Python? It is okay even if its implementation is very slow.
Doesn't seem to be under active development anymore but you could check out pynarcissus, http://code.google.com/p/pynarcissus/source/browse/trunk/jsparser.py
Seems like a binding to V8 (JavaScript interpreter in Google Chromium) is available also, http://www.advogato.org/article/985.html
There is one, of an unknown level of completeness, written in RPython (a subset of Python, that is to say, it runs as normal Python): https://bitbucket.org/pypy/lang-js/overview
You may want to take a look at pydermonkey or python-spidermonkey, both of which, I believe, are python implementations of the Mozilla javascript interpreter.
I would recommend that you just stick to node.js on your local development box, translate your CoffeeScript files over to JavaScript, and deploy the translated scripts with your apps.
I get that you want to avoid having node.js on your servers, that's all fair and good. Jumping through hoops with Python invoking JavaScript to translate CoffeeScript seems more hassle to me than it's worth.
I created Jispy to embed JS in Python.
From the docs:
A JavaScript Interpreter In Python
Jispy is an interpreter for a strict subset of JavaScript, fondly called LittleJ (LJ). It employs recursive descent for parsing and is very easily extendable.
Built for embedding JavaScript
Jispy's original vision was to seamlessly allow embedding JavaScript programs in Python projects. By default, it doesn't expose the host's file system or any other sensitive element. Some checks on infinite looping and infinite recursion are provided to tackle possibly malicious code.
It comes with an interactive console, so you can get up and running in no time.
Hope this helps.
Have you heard of PyV8? It's a Python wrapper of Google's V8 JavaScript engine. It may be what you're looking for.
Related
Recently several tools have been released such as pyjamas and Scheme2js that allow one to take code in a language such as Python or Scheme and compile it to Javascript.
But how practical is such a tool?
I could see debugging being quite painful as you would have to debug the compiled javascript code itself, and correlate any bugs in that code with the corresponding lines in the original python/scheme/etc source code. Even with an intelligent stack trace such as the pyjamas -d option provides, this still seems tedious.
Also, libraries such as jQuery make writing Javascript much more fun and productive. But for many developers Javascript is still a new language to learn.
Has anyone worked with compiled Javascript in a production environment? Any recommendations or comments on the practicality of compiling to Javascript instead of writing your code directly in Javascript?
I believe GWT, based on Java, may be the most popular product of this kind, though I wouldn't describing it as "compiling Java to JS" but rather as "generating JS code". While I personally share some of your doubts, and would rather code JS directly, I have to admit that it is indeed an extremely practical as well as popular tool, entirely production-ready: I observe that, internally, many web apps that are rich and complex enough to warrant a front-end / back-end split are more and more often ending up as a Python back-end and a Java front-end -- the latter specifically to allow GWT (of course there are also plenty of Python front-ends, and plenty of Python back-ends, but I think this is a trend).
Google Wave uses GWT and is probably the most talked-about web app using it so far; together with the huge number of GWT-using web apps listed here, I think it establishes beyond any doubt that the approach is practical (as well as popular;-). Whether it's optimal (vs. writing actual javascript with a good framework in support) is a harder question to answer.
One of the more heavily used JavaScript compilers is GWT. This compiles Java to JavaScript, and is definitely used in production. The web interface to Google Wave is written in this system.
Also, Skydeck wrote Ocamljs, in order to make it easy for them to write FireFox extensions. That also worked quite well.
In summary, if you can write a good compiler, there is no showstoppers keeping you from writing a good JavaScript compiler.
Google Web Toolkit does it (Java to Javascript compiling), and GWT is used widely by Google (duh) and many others, so it definitely is practical.
Since the code is autogenerated, you debug problems in Java - assumption that the problem is in your code, and not in the compiler code, is true in 99% of all cases.
List of languages that compile to JS
As an another example Haxe could be mentioned. Haxe is a independent language and compiles to Flash 6-10, JavaScript, NekoVM and also to c++ - source code. Why is this practical?
you could use features the language itself could not offer
recompile code on multiple platforms (e.g.: form check in JavaScript and on server side)
there is a remoting package for communication between the platforms, and its genius.
autocompletion through the compiler
compile time type checks
If you are interested, you could start reading here.
I know that google's v8 compiles javascript into native machine (binary if I understand correctly) code.
Is there a way to take the output and turn it into a exe?
I don't think you can directly turn a piece of JavaScript into an executable using V8, but you can probably make an application that bundles the V8 engine with the JavaScript and runs it as a stand-alone.
You can find all information about V8 on its project page.
Also note that JavaScript can't be completely compiled as it's a dynamic language. With V8, it's JIT-compiled (like .NET, for example.) It's still possible to turn it into a stand-alone executable though (like .NET, for example.)
If you want to develop stand-alone applications that make use of HTML for rendering, you could have a look at Adobe Air as well.
Javascript cannot be compiled just once. The language has eval which is pretty widely used. (for JSON for instance) You need to carry around the JIT, and the whole runtime.
JIT here is only an optimization, not the way to get rid of the compiler/interpreter.
Node.js embeds V8. This might be a good example to learn from.
There have been a few tries at making js into native code, it's not something that can be used in production by any means, more of an academic interest.
The Rhino interpreter for java has an option to make js into (java) bytecode so one approach is to convert to bytecode and then from bytecode to native with GCJ. There is some discussion about Rhino and GCJ but I don't know if anyone ever tried exactly that. https://groups.google.com/forum/#!msg/netscape.public.mozilla.jseng/c3tqyLZ19fw/8V4HeuMtIXUJ
Another approach is using Python, specifically Py-Py which itself is written in a non-standard subset of Python called rPython. rPython is not meant for human consumption but it has the benefit of being something which can be compiled to native. One interesting (albeit wacky) experiment was to compile Javascript to Python and then in some cases that Python happens to be valid as rPython and can be compiled down to native with the rPython compiler.
http://mozakai.blogspot.com/2010/07/experiments-with-static-javascript-as.html
If a .exe file is really important, I would bundle V8 with your app since even if you can compile js to native, you still need a full interpreter if you use any eval() or similar. It would not be hard to write a tool for bundling everything into an .exe file as long as your users don't mind either an 8MB exe or 8MB V8.dll file.
As a last thought, Big G has started allowing "native" apps based on chrome (google: "chrome packaged apps"). They have low level system access and can use the WebKit renderer allowing you to create your GUI in CSS and HTML and they have their own windows and icons so it is not obvious that they are running inside of chrome. This is probably still premature but it's something to keep an eye on in the desktop applications field.
I'd like my rack application to be able to interface with a server-side javascript engine.
As of now the only way i know this could be possible, is by running JRuby and Rhino on the JVM, but I'm hoping for a leaner solution.
Has anyone heard of another, more rubyish perhaps, option ?
Edit : Reading the comments I'm starting to think I've been mistaken assumig that having both JRuby and Rhino run on the JVM would imply some interoperability between ruby and javascript...?
That's not a desirable solution for me anyhow, but still i'd like to clear that up.
The Ruby Racer is now out of pre-alpha and is hovering somewhere between alpha and beta. It now supports:
calling ruby code from javascript
calling javascript functions from ruby
embedding ruby objects into the javascript scope.
letting ruby objects be your javascript scope
Johnson is a RubyGem that turns the Mozilla SpiderMonkey JavaScript engine into an MRI C extension and allows very deep integration between Ruby and JavaScript,
there is a fork of Johnson which replaces the SpiderMonkey engine with the Mozilla TraceMonkey engine and
Lyndon is like Johnson but with JavaScriptCore instead of SpiderMonkey and MacRuby instead of MRI.
I think I also remember someone working on embedding V8 with MRI, but I can't find the reference right now.
The main problem with Johnson is that MRI is an incredibly crappy language implementation that leaks memory left and right, and the only language implementation in the world that could possibly be even more crappy is SpiderMonkey. Thus, the TODO list in the Johnson Git repository doesn't exactly inspire confidence; it only contains one item, and I quote literally:
Stop freaking segfaulting.
Lyndon is built on a much better foundation, but it obviously requires running OSX on the server. Plus, MacRuby hasn't been released yet.
I think JRuby+Rhino is probably the most stable option, although you will have to build the integration yourself: they are just two independent language implementations that happen to live on the same VM, but there is no integration between them.
A different take on the problem is RKelly which is a JavaScript parser and execution engine written in Ruby.
As an alternative you could try to approach the problem from a different direction: instead of keeping your application logic in JavaScript and running that both on the client and the server, you could keep your application logic in Ruby and run that on the server and the client: there are a couple of compilers out there that can compile (a subset of) Ruby to JavaScript. On of them is RubyJS. (There is also HotRuby, which is a YARV bytecode interpreter written in JavaScript, but that would very likely be tremendous overkill for what you are doing.)
And last but not least you could do what Rails originally did with their JavaScript helpers: you neither define your logic in Ruby nor JavaScript, instead you define it once in an internal Ruby DSL and generate both the Ruby and JavaScript logic from that.
Have a look at The Ruby Rhino. It uses jruby and rhino to embed javascript into your ruby environment. Among other things, it supports safe evaluation, calling ruby functions from javascript and vice-versa(javascript functions from ruby)
There is also "The Ruby Racer" which embeds v8 into MRI. This is still very much pre-alpha phase, but I hope to have a useable version sometime in march of next year
Another engine I know of is Snarl which also uses jruby and rhino to a similar effect.
Given a set of Java source code files, how can I compile them into one or more JavaScript files that can be used with hand-crafted JavaScript?
GWT is one option, but every example I've seen so far is aimed at building fancy websites. The simple use case of just converting Java source to Javascript that can be used together with handcrafted JavaScript hasn't been well-documented.
I started a thread on the GWT mailing list on this subject, but opinions seem to be mixed on whether this is even feasible.
One person gave a very useful tip, which was to check out GWT-Exporter. The problem is that neither source code nor documentation is readily available, although there's this and this.
edit: GWT-Exporter source code is here
I've also seen Java2Script. But again, I wasn't able to find examples of how to solve my simple use case.
What's the best approach to this problem? Is there something better I'm missing?
When you use GWT, you're basically converting the UI portion into Javascript (and it assumes that you use the UI widgets provided when you write your Java). Only some of the Java libraries are accessible within Javascript. Typically in a GWT application anything that makes heavy use of Java libraries would run on the server side and connect to the Javascript as AJAX (which GWT handles for you). So GWT isn't necessarily converting your full application into Javascript (though it can if you're willing to limit your use of Java libraries and some functionality).
At any rate, if this approach (calling out to Java running on a server from within Javascript) appeals to you, one nice option is DWR, which basically allows your Javascript to directly call methods in Java classes running on the server (without you having to build a web service or other frontend). Not what you asked, I know.
More relevantly, it looks like there's source code for a sample app demonstrating the use of gwt-exporter.
I am not sure if it fits your use case, but if you agree to drop Java APIs and use JavaScript APIs from Java, then you can use JSweet, a Java to JavaScript transpiler built on the top of TypeScript. It gives you access to hundreds of well-typed JavaScript APIs (DOM, jQuery, underscore, angularjs, etc). It generates JavaScript code and you can mix it with legacy JavaScript and TypeScript code.
Note: JSweet will not work for legacy Java code and legacy Java APIs, but your use case did not mention reusing legacy code.
[UPDATE] Since version 1.1, JSweet now also supports some Java APIs such as Collections (java.util). So, it is possible to reuse legacy Java code to a certain extent. It is also quite straightforward to add your own support for Java APIs.
While the question is about compiling Java sources to JavaScript I think it's worth mentioning that there is TeaVM which compiles Java bytecode to JavaScript. I have never tried it, but it seems very promising.
Given a set of Java source code files, how can I compile them into one or more JavaScript files that can be used with hand-crafted JavaScript?
Although there are many solutions to convert Java applications to Javascript, you are interested on a solution where new javascript code may interact with the resulting code. This is an update (as 2018) of the other answers.
There are different types of tools. For instance, you may find tools that allow you (1) convert java code to javascript; (2) convert bytecode to javascript, asm.js or webassembly; (3) execute java applications directly in the browser and (4) create solutions that combine java and javascript. You must select the solution to use depending on your requirements.
Converting Java source code to Javascript
Some solutions take java source code and produce a javascript equivalent version. Usually, these solutions transforms the Java to Javascript, but do not support all the behaviours and libraries of the Java runtime. The resulting code may not support some java standard libraries. Typically, they are used to create HTML application using Java but not for migrating the code. Pros: The resulting solution may include very small files. You can use it to reuse your own business logic classes without considering GUI or platform specific libraries. Cons: it is possible that you cannot use some functionalities of the Java platform. It requires access to the source code.
JSweet converts Java to javascript. It includes API bindings for 1000+ javascript libraries. You can write java code that use these libraries.
It converts java to typescript and later uses the typescript compiler to create the corresponding javascript.
It can produce multiple types of javascript modules and typescript definitions. You can use the resulting code in javascript very easily.
j2s, is the compiler used by the Eclipse RAP platform to translate java code to javascript. It is used there to convert the SWT (GUI) widgets to javascript and HTML. It does not support all the Java standard libraries
It may convert simple Java classes to be used in javascript. You must use the classes considering the OO Java-Javascript simulation performed by j2s.
Converting Javascript bytecode to javascript
These solutions take compiled java code (.class files) and produces equivalent code in javascript, asm.js or webassembly. Considering that the java code may depend on java standard libraries (i.e., the JRE), these solutions typically includes ported and pre-compiled libraries. Pros: you do not need to change anything in your code. You do not need the source code neither. Cons: the resulting solution may require the load of a lot of files.
Bck2Brwsr, a Java VM that may compile ahead-of-time the java bytecode to javascript. It produces a javascript file for each .jar file.
You may use the vm javascript object to load a class into javascript and execute static methods (using vm.loadClass(.., function(class){..}}). There is an example in the documentation for the gradle plugin and the maven task.
TeaVM, is another Java VM that may convert ahead-of-time the code to javascript. In contrast to Bck2Brwsr, it supports threads, produces a single file for all your classes and provide better debugging support.
You may call java from javascript using the javaMethods.get(..).invoke(...) method.
DukeScript, transpile java code and bytecode to javascript using Bck2Brwsr or TeaVM.
It provides maven tasks to compile the java code. The resulting code (and technique to call java from javascript) depends on the used transpiler.
Dragome, transpile java bytecode to javascript.
You can annotate static methods in Java and use it in Javascript: e.g. you can annotate a method with #MethodAlias(alias="windows.method1") and invoke it from javascript using window.method1()
CheerpJ (a commercial product) may run complete java applications using Swing and AWT. It provides a very complete javascript environment that support operating system, thread and network functionalities.
It provides a complete runtime API. You can run a main method using cheerpjRunMain( <class>, <jar> ). You can create objects using cjNew( <class>, <params>...) and invoke static methods using cjCall( <class>,<method>,<params>...). There are many other methods you may consider.
Running Java code in Javascript
DoppioJVM is a complete JVM written in Typescript. Pros: It emulates a lot of elements of the operating system, including filesystems, TTY consoles and threads. Cons: Considering that it is an interpeter, it may result slower than other solutions. (I have not tested it)
DoppioJVM is a JVM written in Typescript
The documentation includes snippets of code to load and run the classes. You can run a static method using jvm.runClass( <class>, [ <args>...], function(response){..}). You can run a Jar file and perform many other tasks.
Create applications combining Java and Javascript
Some other solutions provide, not only the tools for compiling the code, but also frameworks and solutions to create java and javascript solutions. For instance, CheerpJ has complete versions of the Swing and AWT libraries for graphical user interfaces, but they may result very slow. You may replace the user interface by using new HTML versions that run faster on the browser. Pros: You can reuse existing code without changes, mainly some libraries and business logic. You may remove from your solutions libraries that run not efficiently in the browser. Cons: If you wanna keep maintaining your java desktop version, you must deal with different code for the browser.
GWT converts Java code to javascript but uses a different set of libraries for the user interface and client-to-server communications.
The documentation maintains information of differences with the JRE
You may export Java classes to be used by Javascript code.
Dukescript uses the conversion tools mentioned before.
It provides a Knockout4j library that may interact easily with HTM, DOM and additional javascript code.
Dragome not only convert java code but also include means to interact with the HTML/DOM
You may use annotations to bind java objects to HTML elements and to handle the DOM
HTML/Java API is an Apache project that standardize the access to HTML/DOM/javascript from transpiled code
It was donated by Dukescript and other tool providers.
Recommendation
If you wanna reuse few classes created by your own, you may try JSweet. You may create javascript modules (libraries) that you can use easily with javascript and typescript.
If you wanna reuse a medium to large codebase that rely on multiple java libraries, you may try CheerpJ, Dukescript or Dragome. You may reuse large parts of your code and create (gradually) the user interface and client-to-server communications using technologies that are more browser-friendly.
If you wanna run complete java applications without change, you may try CheerpJ. It can run Swing and AWT user interfaces. It also provide an Applet runner.
Here's two other options, things to look into and a third option not converting, just living together.
Java2Javascript
I have been wanting to try this out -- Looks closer to what's been asked. Quoting the web page:
an Eclipse Java to JavaScript compiler plugin and an implementation of JavaScript version of Eclipse Standard Widget Toolkit (SWT) with other common utilities, such as java.lang.* and java.util.*. You can convert your SWT-base Rich Client Platform (RCP) into Rich Internet Application (RIA) by Java2Script Pacemaker.
A limited Java in Javascript experience - You'd need to port your necessary dependencies or find alternatives via tools like jQuery, etc.
DukeScript
As I view DukeScript, it compiles some front-end Javascript and calls Java behind, from the browser's Javascript. It seems more or less a hybrid approach so you can use the Java wealth of libraries from Javascript. I will fall foul of a browser security policy for Java.
A more full-Javascript on Java experience leveraging the Java-runtime. If I wanted that outside the browser environment I'd use Javascript on Java.
Nashhorn
Consider this as an example of using Java's resources as foundation for Javascript: Nashorn and JavaFX, as an example for a rich Javascript operated client. Anyway with a Javascript engine inside Java you're not needing to translate between a Javascript-VM to object-code to a Java-VM quite so much.
Not entirely on-topic, but Kotlin is a 100% Java-compatible language that can compile to JavaScript.
IntelliJ IDEA can automatically convert Java to Kotlin and compile it to run on Node or the browser.
Given a set of Java source code files, how can I compile them into one
or more JavaScript files that can be used with hand-crafted
JavaScript?
There is no direct correlation between both the built-in Java API and Java language features, and those of JavaScript. So any attempt at creating a "converter" is going to be incomplete. As a fundamental example, Java classes don't have a direct corresponding JavaScript idiom.
Whether or not an incomplete conversion tool will work for your use case is impossible to know without the source code.
That said, my suggestion to solving your problem would be to first attempt to use GWT: set up a demo project, drop in the source of your library and call it from the JavaScript side and see what GWT outputs in it's .js file. Some of the other tools suggested by other posters here are definitely worth checking out as well.
If that is fruitful and gets you part of the way, great.
From there, you'll need/want to do the remainder of the conversion by hand. After all, assuming you want the code to actually function correctly, a manual review would definitely be in order. Some unit tests being converted along with it would be ideal as well.
You don't state how large the source of your project is, but if it's small (let's say less than a thousand lines of code), even a complete conversion by hand shouldn't be extremely difficult. If it's much larger than that, I would suggest reviewing if you actually want that as JavaScript code anyway.
This question is from 13 years ago; yes, I know. But I'll put my addition here as this is an excellent repository of answers on the topic, and as it comes up first in a Google search it is likely to have the most eyeballs on it.
I'm a former GWT developer. And agree it is an excellent solution & technology. But also yes as mentioned, the cross compilation part mostly (arguably, completely) focuses on the W in its name (Google WEB Toolkit): the client-side JavaScript part of full stack SPA Web applications, its serialization & communication, it's client/server logic partitioning, et al.
I just stumbled onto something that is relatively new -- a 2014-2015 offshoot of GWT placed into the public domain in 2018 -- that I think is more generally focused and what was being requested in the original post (13 years ago, lol). I'm eager to try it.
J2CL: https://github.com/google/j2cl
I read about it here, which to me was a good & thorough intro of the technology (have a look and let me know if you agree or not):
https://www.infoq.com/news/2019/05/j2cl-java-javascript-transpiler/
Say you were mainly a C-syntax like programmer and Linux systems administrator, and you were tasked with creating some simple automation tasks on Windows (monitoring of back-up files, process monitoring, ...). Which language would you prefer to write your scripts in? There's a large collection of VBS-scripts out there (using VB syntax), but I'd prefer anything more C-related.
What are your best experiences in using scripts for Windows? Any obvious down- or upside to a certain language?
I would use Powershell.
It has a vaguely C-like syntaxt.
It has an integrated shell.
The newest version (currently in CTP) includes a builtin IDE (Although it is limited compared to other 3rd party ones).
It has easy access to something like 90% of the functionality in the .Net framework.
Going forward, MS products will explicitly provide Powershell integration.
It supports pipes.
Pretty much every script in VBS can be converted to an equivalent in JScript.
There are a few gotchas to watch out for. Read up on the enumerator and remember that in VBS is case insensitive so when translating a script, certain methods may have the wrong casing.
Try to do what you want to do in a CMD-file, it that doesn't cut it, use Windows Scripting Host to call a wsh-file with JScript and/or VBScript in it. If you prefer the JScript-look, use that as your primary language, and use VBScript for things you copy from the net or cannot find a JScript solution to. You can call VBScript from JScript and the other way around.
Check out the Microsoft Scriptomatic tool too.
It can generate lots of admin scripts in VBScript, Perl, JavaScript (JScript) and Python. Makes navigating WMI much easier too.