I inherited large monolithic body of OO Perl code that needs to be gradually converted to Java (per client request). I know both languages but am rusty on my Perl skills. Are there any tools (Eclipse plugins?) that you folks can recommend to ease the pain?
Does OO code use Moose? If yes, it is possible to convert class declarations automatically using introspection.
To gradually convert Perl to Java, you can include Java code into Perl program with Inline::Java.
There is Perl on JVM project, maybe it can be used to compile Perl to Java?
I'd say PLEAC is one of the greatest resources.
The inccode.com allows you to automatically convert the perl code to java code. Nevertheless the conversion of perl variables is slightly tricky due to dynamic typing in perl. The scalar variable in perl can contain the reference to any type and the real referenced type is known when the code is executed.
Translator uses VarBox class for encapsulating all predefined types: ref(HASH), ref(ARRAY) and BoxModule for encapsulating the reference to Perl Modules.
The example show perl script which call two modules to print “hello world”. The module LibConsole is instantiated in script and the module LibPrinter is accessed by calling the method in LibConsole.
#!/usr/bin/perl
use strict;
use test::LibPrinter;
use test::LibConsole;
hello_on_console( "hello world");
hello_on_printer( "hello world");
sub get_console
{
my $console = test::LibConsole->new();
return $console;
}
sub get_printer
{
##cast(module="test::LibPrinter")
my $printer = get_console()->get_printer();
return $printer;
}
sub hello_on_console
{
my ($hello) = #_;
my $console = get_console();
$console->output ($hello);
}
sub hello_on_printer
{
my ($hello) = #_;
my $printer= get_printer();
$printer->output ($hello);
}
Translator must now the types of both modules and while perl don’t define specific operators for declaring the object there’s an assumption that method named “new” return the reference to module. When the method which return reference to module is named otherwise the annotation cast(module=”{class}”) can be used to inform translator about the type of the module.
The identified type of the variable will be propagate because the translator control the conformity of types in assignments.
public class hello extends CRoutineProcess implements IInProcess
{
VarBox call ()
{
hello_on_console("hello world");
return hello_on_printer("hello world");
}
BoxModule<LibConsole> get_console ()
{
BoxModule<LibConsole> varConsole = new BoxModule<LibConsole>(LibConsole.apply());
return varConsole;
}
BoxModule<test.LibPrinter> get_printer ()
{
BoxModule<LibPrinter> varPrinter = new BoxModule<LibPrinter>(get_console().getModule().get_printer());
return varPrinter;
}
VarBox hello_on_console (VarBox varHello)
{
BoxModule<LibConsole> varConsole = new BoxModule<LibConsole>(get_console());
return varConsole.getModule().output(varHello);
}
VarBox hello_on_printer (VarBox varHello)
{
BoxModule<LibPrinter> varPrinter = new BoxModule<LibPrinter>(get_printer());
return varPrinter.getModule().output(varHello);
}
}
The translated code requires runtime library to be executed.
Related
Scala borrows Java String methods like toUpperCase/toLowerCase.
However, the way it does so is not very consistent:
Scala on JVM stick close to Java semantics, thus:
toUpperCase() is locale-sensitive and sticks to default locale (giving you infamous i → İ problem in Turkish locale)
to avoid that and keep locale-insensitive (en_US / C-like) process, you need to specifically do toUpperCase(Locale.ROOT)
Scala.JS does not implement a concept of Locale, thus:
toUpperCase() works in locale-insensitive manner
toUpperCase(Locale locale) method is effectively not available in ScalaJS
How do I implement locale-insensitive case conversion that will work in Scala on both JVM/JS?
I can think of several ways, all of them as ugly:
Method 1: My own implementation
Implement my own toUpperCase for specifically 26 ASCII characters of English alphabet.
Method 1.1: My own implementation using Scala chars
Basically the same, but at least reuse Scala toUpper to convert individual chars.
Method 2: Interface
Implement something like
trait CaseChangeOps {
def toUpperCase(s: String): String
}
object Main {
var caseChanger: CaseChanger
}
// whenever I want to use it, do it like that:
Main.caseChanger.toUpperCase("like this") // => "LIKE THIS"
in shared code, and then in JS have:
object CaseChangerJs {
def toUpperCase(s: String): String = s.toUpperCase
}
object MainJs {
Main.caseChanger = CaseChangerJs
}
... and in JVM:
object CaseChangerJvm {
def toUpperCase(s: String): String = s.toUpperCase(Locale.ROOT)
}
object MainJvm {
Main.caseChanger = CaseChangerJvm
}
Method 3: bring external scala-java-locales
There is a distinct 3rd party library scala-java-locales, which is listed as ScalaJS-compatible, and can be used to augument ScalaJS.
Looks like a massive overkill, though, as I literally only need locale-insensitive case conversions, not the whole thing for all possible locales.
Any better ideas?
The standard approach is close to your method 2, but much simpler. In shared code you just call
Platform.toUpperLocaleInsensitive(string)
which has different implementations on JVM and JS:
// JVM
object Platform {
def toUpperLocaleInsensitive(s: String) = s.toUpperCase(Locale.ROOT)
// other methods with different implementations
}
// JS
object Platform {
def toUpperLocaleInsensitive(s: String) = s.toUpperCase()
// other methods with different implementations
}
See the description of a similar case in Hands-on Scala.js.
This works because shared code doesn't need to compile by itself, only together with platform-specific code.
I am working on a Java project that has some Clojure involved. I know how to run compile and run clojure code:
public static void main(String[] args) throws Exception {
RT.init();
runCode();
}
public static Object runCode() {
String str = "(ns my-ns)" +
"(defn add [a b] (+ a b))" +
"(println (add 1 2))";
Compiler.load(new StringReader(str));
/* I know how to invoke it: */
Var foo = RT.var("my-ns", "add");
return foo.invoke(1,2);
}
What would be very useful at the point is to have a way to iterate over forms in Java, and in some sense "analyze" the compiler output. Basic things I want to know is:
What is the text source of a form?
What function is being called in a form.
What arguments are being passed to the function (forms are ok)
Be able to do this on top level forms, or drill in as needed.
Is there a way to do this using the clojure compiler, or runtime (or other Java classes in Clojure?) I see such compiler methods as analyze, for example:
Expr target = analyze(C.EXPRESSION, RT.second(form));
Though its not clear to me yet how form was constructed, and there are no Javadoc :-). Do I need to go The Compiler Source and figure out how it works?
To the downvoters - this is a legitimate question. Please take the time to examine it before assuming I'm mixing up my languages like some kind of programming newb!
I need to know if it's possible to import a Java object (specifically, an enum class) in a Typescript script.
I've googled but haven't found anything.
The ErrorCodeAuthority is for having custom, standardized errors thrown from our service for each known error with set messages (some parameterized, some not), http status codes, etc defined in one place.
In our javascript code we have
var JavaErrorCodeAuthority = Java.type("com.domain.ErrorCodeAuthority");
Is it possible to do the same in Typescript?
Edit based on answer below
I've declared the following:
declare module Java {
export enum ErrorCodeAuthority {
ENTITY_NOT_FOUND,
HTTP_VERB_NOT_SUPPORTED,
BAD_REQUEST,
//...
}
export function type(arg: "com.domain.ErrorCodeAuthority"): ErrorCodeAuthority;
export function type(arg: string): any;
}
var JavaErrorCodeAuthority = Java.type("com.domain.ErrorCodeAuthority");
and I'm attempting to use the new type as follows:
export class HttpFailResult extends HttpResult {
constructor(public errorCode : Java.ErrorCodeAuthority, public userParams? : UserParam[]) {
super(errorCode.httpStatus.value(), errorCode.toString());
}
}
I'm getting the following error when I try to use grunt to compile to js:
error TS2339: Property 'httpStatus' does not exist on type 'ErrorCodeAuthority'.
(For reference, the super HttpResult is an object that contains a number http code and astringbody. HttpStatus, in the Java enum, is of typeorg.springframework.http.HttpStatus`).
I tried removing the export function type(arg: "com.domain.ErrorCodeAuthority"): ErrorCodeAuthority; line but that didn't change the exception.
EDIT 2
We're running all of this inside a nashorn container if that makes a difference
Is it possible to do the same in Typescript?
Yes. With 1c, you can just write
let JavaErrorCodeAuthority = com.domain.ErrorCodeAuthority
And there will be auto-completion on each level of packages.
Yes, if you already did this in JavaScript you can use the code by creating a definition file for it and port it to TypeScript.
An example might be like this:
declare module Java {
export enum ErrorCodeAuthority {
item1,
item2
}
export function type(arg: "com.domain.ErrorCodeAuthority"): ErrorCodeAuthority;
export function type(arg: string): any;
}
var JavaErrorCodeAuthority = Java.type("com.domain.ErrorCodeAuthority");
The enum and the first type function with the "com.domain.ErrorCodeAuthority" is optional but it gives you better typeinfo when passed in that particular string. Note the declare module part doesn't generate any code and you can add it to a .ts or .d.ts file. More info about creating a definition file can be found here: https://github.com/Microsoft/TypeScript/wiki/Writing%20Definition%20Files
EDIT
after the info from the comments I hope this code below will better suite your need.
This has the downside that it isn't usable in a switch statement but in this case I think it is better to see the java enum as a module (or class was possible to). This might not be 100% correctly modelled but hopefully it gives you some extra idea's. Just a small side note, I find your case very interesting and challenging!
declare module Java {
interface ErrorCodeValue {
toString(): string;
value(): number;
}
module ErrorCodeAuthority {
var ENTITY_NOT_FOUND: IErrorCodeAuthority;
var HTTP_VERB_NOT_SUPPORTED: IErrorCodeAuthority;
var BAD_REQUEST: IErrorCodeAuthority;
}
interface IErrorCodeAuthority {
httpStatus: ErrorCodeValue;
}
export function type(arg: "com.domain.ErrorCodeAuthority"): typeof ErrorCodeAuthority;
export function type(arg: string): any;
}
export class HttpResult {
constructor(code: number, description: string) {
}
}
export class HttpFailResult extends HttpResult {
constructor(public errorCode: Java.IErrorCodeAuthority, public userParams? :any[]) {
super(errorCode.httpStatus.value(), errorCode.toString());
}
}
var JavaErrorCodeAuthority = Java.type("com.domain.ErrorCodeAuthority");
new HttpFailResult(JavaErrorCodeAuthority.BAD_REQUEST, null);
I have a code generator, which takes a syntax tree and converts it into a source file (text).
Basically, it traverses through all nodes of the tree, maps the node to text and appends the resulting texts to a StringBuilder.
Now I want the node to text mappers to be implemented using Xtend like this:
public class NodeXMapper
{
private XtendRunner xtendRunner = ...;
public String map(final NodeX aNode)
{
return xtendRunner.runScript("def String map(NodeX aNode) {
''' «aNode.fieldX» - «aNode.fieldY» '''
}", aNode);
}
}
xtendRunner.runScript(String aScript, final Object... aParams) is a method, which passes the parameters aParams to Xtend script aScript and returns the result.
How can I implement that method?
Update 1: Here I found this piece of code, which seems to run Xtend code in Java:
// setup
XtendFacade f = XtendFacade.create("my::path::MyExtensionFile");
// use
f.call("sayHello",new Object[]{"World"});
But I can't find XtendFacade class in the Type hiearchy view of Eclipse.
The interpreter you found was for the old Xtend1 language, which is not what you are looking for.
The new Xtend you are referring to is compiled, so there is no interpreter.
However, you could build an interpreted expression language using Xbase. See the documentation and Github for an example on how to do that. Then you could run the interpreter of your expression language from Java.
So far I only see closure in javascript:
var name=...;
$(..).onclick(function() {
//here I can reference to name
});
Does this feature exist in c/c++/java/PHP?
If exists,one hello world example available?
As for PHP, you can enable access to a specific variable inside a closure method like this:
$xVar = "var";
$closure = function() use ($xVar) {
echo $xVar;
}
$closure();
And it's also possible to alter this variable inside the closure:
$xVar = "var";
$closure = function($newVar) use (&$xVar) {
$xVar = $newVar;
}
$closure("new var content");
C no, as functions aren't first-class objects.
C++ not yet, but it does with the upcoming standard (commonly referred to as C++0x), with so called lambda expressions:
std::string name;
auto mylambda = [&](){ std::cout << name; };
// ^ automatically reference all objects in the enclosing scope.
C++11 has closures, as does PHP. Im not sure about Java.
At one point, closures (Project Lambda) were going to be part of Java 7, but they are currently listed as "Deferred to Java 8 or later".
http://en.wikipedia.org/wiki/Closure_%28computer_science%29#PHP
For PHP
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
PHP has those too, since 5.3. They're not as flexible (in that you can't use $this), but still very useful.
Lisp and its dialects also have closures.
For C, they are available as a non-standard extension called blocks.