mirror of
https://github.com/cincheo/jsweet.git
synced 2025-12-15 07:19:22 +00:00
827 lines
35 KiB
TeX
827 lines
35 KiB
TeX
\documentclass[a4paper]{report}
|
|
|
|
\usepackage[a4paper, margin=3cm]{geometry}
|
|
\usepackage{times}
|
|
\usepackage{graphicx}
|
|
%\usepackage{color}
|
|
%\usepackage{multirow}
|
|
\usepackage{url}
|
|
\usepackage{verbatim}
|
|
\usepackage{hyperref}
|
|
\usepackage{wrapfig}
|
|
\usepackage{titling}
|
|
|
|
\usepackage{listings}
|
|
\usepackage{color}
|
|
\usepackage{titlesec}
|
|
\usepackage[htt]{hyphenat}
|
|
|
|
\definecolor{dkgreen}{rgb}{0,0.6,0}
|
|
\definecolor{gray}{rgb}{0.5,0.5,0.5}
|
|
\definecolor{lightgray}{rgb}{0.95,0.95,0.95}
|
|
\definecolor{mauve}{rgb}{0.58,0,0.82}
|
|
|
|
\definecolor{dkgreen}{rgb}{0,0.6,0}
|
|
\definecolor{gray}{rgb}{0.5,0.5,0.5}
|
|
\definecolor{lightgray}{rgb}{0.7,0.7,0.7}
|
|
\definecolor{lightlightgray}{rgb}{0.98,0.98,0.98}
|
|
\definecolor{mauve}{rgb}{0.58,0,0.82}
|
|
|
|
\lstset{
|
|
language=Java,
|
|
aboveskip=3mm,
|
|
belowskip=3mm,
|
|
showstringspaces=false,
|
|
columns=flexible,
|
|
basicstyle={\small\ttfamily},
|
|
numbers=none,
|
|
numberstyle=\tiny\color{gray},
|
|
keywordstyle=\color{blue},
|
|
commentstyle=\color{dkgreen},
|
|
stringstyle=\color{mauve},
|
|
breaklines=true,
|
|
breakatwhitespace=true,
|
|
tabsize=2,
|
|
backgroundcolor=\color{lightlightgray},
|
|
frame=single,
|
|
rulecolor=\color{lightgray},
|
|
morekeywords={assert}
|
|
}
|
|
|
|
\titleformat{\chapter}{\bfseries\LARGE}{\thechapter.}{1ex}{}[]
|
|
\titlespacing{\chapter}{0pt}{20pt}{16pt}
|
|
|
|
\pretitle{%
|
|
\begin{center}
|
|
\LARGE
|
|
\includegraphics[width=6cm,height=6cm]{logo}\\[\bigskipamount]
|
|
}
|
|
\posttitle{\end{center}}
|
|
|
|
\newcommand{\code}[1]{\texttt{\small #1}}
|
|
\newcommand{\api}[1]{\subsection*{\normalsize\texttt{#1}}}
|
|
|
|
\begin{document}
|
|
|
|
\title{JSweet Language Specifications\\{\large Version 1.0.0 BETA\\\colorbox{red}{IN PROGRESS DRAFT}}}
|
|
\author{%
|
|
Renaud Pawlak\\
|
|
{\normalsize renaud.pawlak@jsweet.org}\\
|
|
{\normalsize http://www.jsweet.org}\\
|
|
}% author
|
|
\date{}
|
|
\maketitle
|
|
|
|
\tableofcontents
|
|
|
|
\chapter{Basic concepts}
|
|
|
|
This section presents the JSweet language basic concepts. One must keep in mind that JSweet, as a Java-to-JavaScript transpiler, is an extension of Java at compile-time, and executes as JavaScript at runtime. Thus, most Java typing and syntactic constraints will apply at compile time, but some JavaScript semantics may apply at runtime. This document will mention when Java syntactic constructs and semantics are not legal (or differ) in JSweet.
|
|
|
|
\section{Core types and objects}
|
|
|
|
JSweet allows the use of primitive Java types, core Java objects (with some restrictions) and of core JavaScript objects, which are defined in the \texttt{jsweet.lang} package. Next, we describe the use of such core types and objects.
|
|
|
|
\subsection{Primitive Java types}
|
|
|
|
JSweet allows the use of Java primitive types (and associated literals).
|
|
|
|
\begin{itemize}
|
|
\item \texttt{int}, \texttt{byte}, \texttt{short}, \texttt{double}, \texttt{float} are all converted to JavaScript numbers (precision does not matter in JSweet).
|
|
\item \texttt{char} follows the Java typing rules but is converted to a JavaScript string by the transpiler.
|
|
\item \texttt{boolean} corresponds to the JavaScript boolean.
|
|
\item \texttt{java.lang.String} corresponds to the JavaScript \texttt{string}. (not per say a primitive type, but is immutable and used as the class of string literals in Java)
|
|
\end{itemize}
|
|
|
|
\noindent
|
|
Examples of valid statements:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
// warning '==' behaves like the JavaScript one at runtime
|
|
int i = 2;
|
|
assert i == 2;
|
|
double d = i + 4;
|
|
assert d == 6;
|
|
String s = "string" + '0' + i;
|
|
assert s == "string02"; // JavaScript '=='
|
|
boolean b = false;
|
|
assert !b;
|
|
\end{lstlisting}
|
|
|
|
\subsection{Allowed Java objects}
|
|
|
|
Here follows the list of allowed Java classes in JSweet:
|
|
|
|
\begin{itemize}
|
|
\item \texttt{java.lang.Object}
|
|
\begin{itemize}
|
|
\item allowed methods: \texttt{toString()}
|
|
\end{itemize}
|
|
\item \texttt{java.lang.String}
|
|
\begin{itemize}
|
|
\item allowed methods:
|
|
\begin{itemize}
|
|
\item \texttt{charAt(int)}
|
|
\item \texttt{concat(java.lang.String)}
|
|
\item \texttt{indexOf(java.lang.String)}
|
|
\item \texttt{lastIndexOf(java.lang.String)}
|
|
\item \texttt{lastIndexOf(java.lang.String,int)}
|
|
\item \texttt{substring(int)}
|
|
\item \texttt{substring(int,int)} (with the JavaScript behavior)
|
|
\item \texttt{replace(java.lang.String,java.lang.String)}
|
|
\item \texttt{split(java.lang.String)}
|
|
\item \texttt{trim()}
|
|
\item \texttt{toLowerCase()}
|
|
\item \texttt{toUpperCase()}
|
|
\end{itemize}
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Class}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Boolean}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Void}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Integer}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Double}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Number}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Float}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Byte}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Short}
|
|
\begin{itemize}
|
|
\item allowed methods: none
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Iterable}
|
|
\begin{itemize}
|
|
\item allowed methods: none (for using the \emph{foreach} loop on indexed objects)
|
|
\end{itemize}
|
|
\item \texttt{java.lang.Runnable}
|
|
\begin{itemize}
|
|
\item allowed methods: none (for declaring lambdas)
|
|
\end{itemize}
|
|
\item \texttt{java.util.function.*} (for declaring lambdas)
|
|
\begin{itemize}
|
|
\item prohibited method names:
|
|
\begin{itemize}
|
|
\item \texttt{and}
|
|
\item \texttt{negate}
|
|
\item \texttt{or}
|
|
\item \texttt{andThen}
|
|
\end{itemize}
|
|
\end{itemize}
|
|
\end{itemize}
|
|
|
|
\noindent
|
|
Examples of valid statements:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
// warning '==' behaves like the JavaScript one at runtime
|
|
Integer i = 2;
|
|
assert i == 2; // JavaScript '=='
|
|
Double d = i + 4;
|
|
assert d.toString() == "6"; // JavaScript '=='
|
|
assert d == "6"; // JavaScript '=='
|
|
BiFunction<String, Integer, String> f = (s, i) -> { return s.substring(i); };
|
|
assert "bc" == f.apply("abc", 1); // JavaScript '=='
|
|
\end{lstlisting}
|
|
|
|
\subsection{Java arrays}
|
|
|
|
Arrays can be used in JSweet and are transpiled to JavaScript arrays. Array initialization, accesses and and iteration are all valid statements.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
int[] arrayOfInts = { 1, 2, 3, 4};
|
|
assert arrayOfInts.length == 4;
|
|
assert arrayOfInts[0] == 1;
|
|
for(int i : arrayOfInts) {
|
|
arrayOfInts[i] = arrayOfInts[i] - 1;
|
|
assert arrayOfInts[i] == i;
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\subsection{Core JavaScript API}
|
|
|
|
The core JavaScript API is defined in \texttt{jsweet.lang} (the full documentation can be found at \url{http://www.jsweet.org/core-api-javadoc/}). Main JavaScript classes are:
|
|
|
|
\begin{itemize}
|
|
\item \texttt{jsweet.lang.Object}: common ancestor for JavaScript objects functions and properties.
|
|
\item \texttt{jsweet.lang.Boolean}: a wrapper for boolean values.
|
|
\item \texttt{jsweet.lang.Number}: a wrapper for numerical values.
|
|
\item \texttt{jsweet.lang.String}: a wrapper and constructor for strings.
|
|
\item \texttt{jsweet.lang.Function}: a constructor for functions.
|
|
\item \texttt{jsweet.lang.Date}: enables basic storage and retrieval of dates and times.
|
|
\item \texttt{jsweet.lang.Array<T>}: used in the construction of arrays, which are high-level, list-like objects.
|
|
\item \texttt{jsweet.lang.Error}: this class implements \texttt{java.lang.RuntimeException} and can be thrown and caught with \texttt{try} ... \texttt{catch} statements.
|
|
\end{itemize}
|
|
|
|
Programmers should use this API most of the time. However, for objects that need to be used with Java literals (numbers, booleans, and strings), the use of the \texttt{java.lang} package classes is recommended. For instance, the jQuery API declares \texttt{\$(java.lang.String)} instead of \texttt{\$(jsweet.\-lang.\-String)}. This allows the programmer to write expressions using literals, such as \texttt{\$("a")} (for selecting all links in a document).
|
|
|
|
As a consequence, programmers need to be able to switch to the JavaScript API when coming from a Java object. The \texttt{jsweet.util.Globals} class defines convenient static methods to cast back and forth core Java objects to their corresponding JSweet objects. For instance the \texttt{string(...)} method will allow the programmer to switch from the Java to the JSweet strings and conversely.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
import jsweet.util.Globals.string;
|
|
String str = "This is a test string";
|
|
str.toLowerCase(); // valid: toLowerCase it defined both in Java and JavaScript
|
|
str.substr(1); // compile error: substr is not a Java method
|
|
string(str).substr(1); // valid: string(str) is a jsweet.lang.String.
|
|
\end{lstlisting}
|
|
|
|
\noindent
|
|
Here is another example that shows the use of the \texttt{array} method to access the \texttt{push} method available on JavaScript arrays.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
import jsweet.util.Globals.array;
|
|
String[] strings = { "a", "b", "c" };
|
|
array(strings).push("d");
|
|
assert strings[3] == "d";
|
|
\end{lstlisting}
|
|
|
|
\section{Classes}
|
|
|
|
Classes in JSweet are very similar to Java classes. For example:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public class BankAccount {
|
|
public double balance = 0;
|
|
public double deposit(double credit) {
|
|
balance += credit;
|
|
return this.balance;
|
|
}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\noindent
|
|
Which is transpiled to the following JavaScript code:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
var BankAccount = (function () {
|
|
function BankAccount() {
|
|
this.balance = 0;
|
|
}
|
|
BankAccount.prototype.deposit = function(credit) {
|
|
this.balance += credit;
|
|
return this.balance;
|
|
};
|
|
return BankAccount;
|
|
})();
|
|
\end{lstlisting}
|
|
|
|
Classes can define constructors, have super classes and be instantiated exactly like in Java. The only restriction compared to Java is that inner classes or anonymous classes are not allowed in JSweet. For instance, the following code will raise an error.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public class ContainerClass {
|
|
// error: inner classes are not allowed
|
|
public class InnerClass {
|
|
}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\section{Interfaces}
|
|
|
|
In JSweet, an interface (a.k.a. object type) can be seen as object signature, that is to say the accessible functions and properties of an object (without specifying any implementation). An interface is defined for typing only and has no runtime representation (no instances), however, they can be used to type objects.
|
|
|
|
JSweet interfaces can be defined as regular Java interfaces, but also as Java classes annotated with \texttt{@jsweet.lang.Interface}, so that is is possible to define properties as fields. Such classes impose many constraints, as shown in the following code.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
@Interface
|
|
public class WrongConstructsInInterfaces {
|
|
native public void m1(); // OK
|
|
// error: field initializers are not allowed
|
|
public long l = 4;
|
|
// error: statics are not allowed
|
|
static String s1;
|
|
// error: private are not allowed
|
|
private String s2;
|
|
// error: constructors are not allowed
|
|
public WrongConstructsInInterfaces() {
|
|
l = 4;
|
|
}
|
|
// error: bodies are not allowed
|
|
public void m2() {
|
|
l = 4;
|
|
}
|
|
// error: statics are not allowed
|
|
native static void m3();
|
|
// error: initializers are not allowed
|
|
{
|
|
l = 4;
|
|
}
|
|
// error: static initializers are not allowed
|
|
static {
|
|
s1 = "";
|
|
}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\subsection{Object typing}
|
|
|
|
In JSweet, typed object can be constructed out of interfaces. If we take the following interface:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
@Interface
|
|
public class Point {
|
|
public double x;
|
|
public double y;
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\noindent
|
|
We can create an object typed after the interface. Note that the following code is not actually creating an instance of the \texttt{Point} interface, it is creating an object that conforms to the interface.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
Point p1 = new Point() {{ x=1; y=1; }};
|
|
\end{lstlisting}
|
|
|
|
\noindent
|
|
As a direct consequence, in JSweet it is not allowed to check an instance against an interface type.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
if (p1 instanceof Point) { ... } // compile error
|
|
\end{lstlisting}
|
|
|
|
\noindent
|
|
This may seems quite confusing for Java programmers, but you have to remember that, on contrary to Java where interfaces are available as special classes at runtime, in JSweet, interfaces have no reality at runtime. Think of generics, which are of the same kind in Java. As a consequence, the \texttt{instanceof} operator is not applicable on interfaces at runtime (like it is not applicable on generics).
|
|
|
|
\subsection{Optional fields}
|
|
|
|
Interfaces can define \emph{optional fields}, which are used to report errors when the programmer forgets to initialize a mandatory field in an object. Supporting optional fields in JSweet is done through the use of \texttt{@jsweet.lang.Optional} annotations. For instance:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
@Interface
|
|
public class Point {
|
|
public double x;
|
|
public double y;
|
|
@Optional
|
|
public double z = 0;
|
|
}
|
|
\end{lstlisting}
|
|
|
|
It is the JSweet compiler that will check that the fields are correctly initialized, when constructing an object.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
// no errors (z is optional)
|
|
Point p1 = new Point() {{ x=1; y=1; }};
|
|
// JSweet reports a compile error since y is not optional
|
|
Point p2 = new Point() {{ x=1; z=1; }};
|
|
\end{lstlisting}
|
|
|
|
\subsection{Special functions in interfaces}
|
|
|
|
In JavaScript, objects can have properties and functions, but can also (not exclusively), be used as constructors and functions themselves. This is not possible in Java, so JSweet defines special functions for handling these cases.
|
|
|
|
\begin{itemize}
|
|
\item \texttt{\$apply} is used to state that the object can be used as a function.
|
|
\item \texttt{\$new} is used to state that the object can be used as a constructor.
|
|
\end{itemize}
|
|
|
|
\section{Enums}
|
|
|
|
JSweet allows the definition of enums similarly to Java, but with some restrictions. The following code declares an enum with tree possible values (\texttt{A}, \texttt{B}, and \texttt{C}).
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
enum MyEnum {
|
|
A, B, C
|
|
}
|
|
\end{lstlisting}
|
|
|
|
The following statements are valid statements in JSweet.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
MyEnum e = MyEnum.A;
|
|
assert MyEnum.A == e;
|
|
assert e.name().equals("A");
|
|
assert e.ordinal() == 0;
|
|
assert MyEnum.valueOf("A") == e;
|
|
assert array(MyEnum.values()).indexOf(MyEnum.valueOf("C")) == 2;
|
|
\end{lstlisting}
|
|
|
|
On the other hand, unlike Java enums, other members than constants are not allowed, raising JSweet transpilation errors, as shown in the following code.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public enum WrongConstructsInEnums {
|
|
|
|
A, B, C;
|
|
|
|
// error: fields are not allowed
|
|
public long l = 4;
|
|
// error: fields are not allowed
|
|
static String s1;
|
|
// error: fields are not allowed
|
|
private String s2;
|
|
// error: constructors are not allowed
|
|
private WrongConstructsInEnums() {
|
|
l = 4;
|
|
}
|
|
// error: methods are not allowed
|
|
native public void m1();
|
|
// error: methods are not allowed
|
|
public void m2() {
|
|
l = 4;
|
|
}
|
|
// error: methods are not allowed
|
|
native static void m3();
|
|
// error: initializers are not allowed
|
|
{
|
|
l = 4;
|
|
}
|
|
// error: initializers are not allowed
|
|
static {
|
|
s1 = "";
|
|
}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\section{Indexed objects}
|
|
|
|
In JavaScript, object can be seen as maps containing key-value pairs (key is often called \emph{index}, especially when it is a number). So, in JSweet, all objects define the special functions (defined on \texttt{jsweet.lang.Object}):
|
|
|
|
\begin{itemize}
|
|
\item \texttt{\$get(key)} accesses a value with the given key.
|
|
\item \texttt{\$set(key,value)} sets or replace a value for the given key.
|
|
\item \texttt{\$delete(key)} deletes the value for the given key.
|
|
\end{itemize}
|
|
|
|
The type of keys and values can be overloaded for every object. For example, the \texttt{Array<T>} class, will define keys as numbers and values as objects conforming to type \texttt{T}.
|
|
|
|
In the case of objects indexed with number keys, it is allowed to implement the \texttt{java.lang.Iterable} interface so that it is possible to use they in \emph{foreach} loops. For instance, the \texttt{NodeList} type (from the DOM) defines an indexed function:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
@Interface
|
|
class NodeList implements java.lang.Iterable {
|
|
public double length;
|
|
public Node item(double index);
|
|
public Node $get(double index);
|
|
}
|
|
\end{lstlisting}
|
|
|
|
In JSweet, you can access the node list elements with the \texttt{\$get} function, and your can also iterate with the \emph{foreach} syntax. The following code generates fully valid JavaScript code.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
NodeList nodes = ...
|
|
for (int i = 0; i < nodes.length; i++) {
|
|
HTMLElement element = (HTMLElement) nodes.$get(i);
|
|
[...]
|
|
}
|
|
// same as:
|
|
NodeList nodes = ...
|
|
for (Node node : nodes) {
|
|
HTMLElement element = (HTMLElement) node;
|
|
[...]
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\section{Globals}
|
|
|
|
In Java, on contrary to JavaScript, there is no such thing as global variables or functions (there are only static members, but even those must belong to a class). Thus, JSweet introduces reserved \texttt{Globals} classes and \texttt{globals} packages. These have two purposes:
|
|
|
|
\begin{itemize}
|
|
\item Generate code that has global variables and functions (this is discouraged in Java)
|
|
\item Bind to existing JavaScript code that defines global variables and functions (as many JavaScript frameworks do)
|
|
\end{itemize}
|
|
|
|
In Globals classes, only static fields (global variables) and static methods (global functions) are allowed. Here are the main constraints applying to Globals classes:
|
|
|
|
\begin{itemize}
|
|
\item no non-static members
|
|
\item no super class
|
|
\item cannot be extended
|
|
\item cannot be used as types like regular classes
|
|
\item no public constructor (empty private constructor is OK)
|
|
\item cannot use \$get, \$set and \$delete within the methods
|
|
\end{itemize}
|
|
|
|
For instance, the following code snippets will raise transpilation errors.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
class Globals {
|
|
public int a;
|
|
// error: public constructors are not allowed
|
|
public Globals() {
|
|
this.a = 3;
|
|
}
|
|
public static void test() {
|
|
// error: no instance is available
|
|
$delete("key");
|
|
}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
// error: Globals classes cannot be used as types
|
|
Globals myVariable = null;
|
|
\end{lstlisting}
|
|
|
|
One must remember that \texttt{Globals} classes and \texttt{global} packages are erased at runtime so that their members will be directly accessible. For instance \texttt{mypackage.Globals.m()} in a JSweet program corresponds to the \texttt{mypackage.m()} function in the generated code and in the JavaScript VM at runtime. Also, \texttt{mypackage.globals.Globals.m()} corresponds to \emph{m()}.
|
|
|
|
In order to erase packages in the generated code, programmers can also use the \texttt{@Root} annotation, which will be explained in Section~\ref{packaging}.
|
|
|
|
\section{Optional parameters}
|
|
\label{optional-parameters}
|
|
|
|
In JavaScript, parameters can be optional, in the sense that a parameter value does not need to be provided when calling a function. Except for varargs, which are fully supported in JSweet, the general concept of an optional parameter does not exits in Java. To simulate optional parameters, JSweet supports overloading as long as it is for implementing optional parameters -- a very commonly used idiom. Here are some example of valid and invalid overloading in JSweet:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
String m(String s, double n) { return s + n; }
|
|
// valid overloading (JSweet transpiles to optional parameter)
|
|
String m(String s) { return m(s, 0); }
|
|
// invalid overloading (JSweet error)
|
|
String m(String s) { return s; }
|
|
\end{lstlisting}
|
|
|
|
\section{Ambient declarations}
|
|
|
|
It can be the case that programmers need to use existing libraries from JSweet. In most cases, one should look up in the available candies (\url{http://www.jsweet.org/candies-releases/}, which are automatically generated from TypeScript's DefinitelyTyped. When the candy does not exist, or does not entirely cover what is needed, one can use the \texttt{@jsweet.lang.Ambient} annotation, which will make available to the programmers a class definition or an interface. The following example, shows the backbone store classes made accessible to the JSweet programmer with a simple ambiant declaration. This class will be erased during the JavaScript generation.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
@Ambient
|
|
class Store {
|
|
public Store(String dbName) {}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\chapter{Auxiliary types}
|
|
|
|
JSweet uses most Java typing features (including functional types) but also extends the Java type system with so-called \emph{auxiliary types}. The idea behind auxiliary types is to create classes or interfaces that can hold the typing information through the use of type parameters (a.k.a \emph{generics}), so that the JSweet transpiler can cover more typing scenarios. These types have been mapped from TypeScript type system, which is much richer than the Java one (mostly because JavaScript is a dynamic language and request more typing scenarios than Java).
|
|
|
|
\section{Functional types}
|
|
|
|
For functional types, JSweet reuses the \texttt{java.\-Runnable} and \texttt{java.\-util.\-function} functional interfaces of Java 8. These interfaces only support up to 2-parameter functions. Thus, JSweet adds some support for more parameters in \texttt{jsweet.\-util.\-function}, since it is a common case in JavaScript APIs.
|
|
|
|
// To be completed
|
|
|
|
\section{Object types}
|
|
|
|
// Todo
|
|
|
|
\section{String types}
|
|
|
|
For string types, the use of specific types and final instances of these types is the way to simulate string types in Java. For instance, if a \texttt{"span"} string type needs to be defined, a Java interface called \texttt{span} and a static final field called \texttt{span} in a \texttt{StringTypes} class will do the job.
|
|
|
|
// To be completed
|
|
|
|
\section{Tuple types}
|
|
|
|
Tuple types represent JavaScript arrays with individually tracked element types. For tuple types, JSweet defines parameterized auxiliary classes \texttt{TupleN<T0, ... TN-1>}, which define \texttt{\$0}, \texttt{\$1}, ... \texttt{\$N-1} public fields to simulate typed array accessed (field \texttt{\$i} is typed with \texttt{Ti}).
|
|
|
|
// To be completed
|
|
|
|
\section{Union types}
|
|
|
|
Union types represent values that may have one of several distinct representations. For union types, JSweet takes advantage of the \texttt{method overloading} mechanism available in Java~\cite{gil2010use}. For more general cases, it defines an auxiliary interface \texttt{Union<T1, T2>} (and \texttt{UnionN<T1, ... TN>}) in the \texttt{jsweet.\-util.\-union} package. By using this auxiliary type and a \texttt{union} utility method, programmer can cast back and forth between union types and union-ed type, so that JSweet can ensure similar properties as TypeScript union types.
|
|
|
|
The following code shows a typical use of union types in JSweet. It simply declares a variable as a union between a string and a number, which means that the variable can actually be of one of that types (but of no other types). The switch from a union type to a regular type is done through the \texttt{jsweet\-.util\-.Globals\-.union} helper method. This helper method is completely untyped, allowing from a Java perspective any union to be transformed to another type. It is actually the JSweet transpiler that checks that the union type is consistently used.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
import static jsweet.util.Globals.union;
|
|
import jsweet.util.union.Union;
|
|
[...]
|
|
Union<String, Number> u = ...;
|
|
// u can be used as a String
|
|
String s = union(u);
|
|
// or a number
|
|
Number n = union(u);
|
|
// but nothing else
|
|
Date d = union(u); // JSweet error
|
|
\end{lstlisting}
|
|
|
|
The \texttt{union} helper can also be used the other way, to switch from a regular type back to a union type, when expected.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
import static jsweet.util.Globals.union;
|
|
import jsweet.util.union.Union3;
|
|
[...]
|
|
public void m(Union3<String, Number, Date>> u) { ... }
|
|
[...]
|
|
// u can be a String, a Number or a Date
|
|
m(union("a string"));
|
|
// but nothing else
|
|
m(union(new RegExp(".*"))); // compile error
|
|
\end{lstlisting}
|
|
|
|
Note: the use of Java function overloading is preferred over union types when typing function parameters. For example:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
// with union types (discouraged)
|
|
native public void m(Union3<String, Number, Date>> u);
|
|
// with overloading (preferred way)
|
|
native public void m(String s);
|
|
native public void m(Number n);
|
|
native public void m(Date d);
|
|
\end{lstlisting}
|
|
|
|
\chapter{Semantics}
|
|
\label{semantics}
|
|
|
|
Semantics designate how a given program behaves when executed. Although JSweet relies on the Java syntax, programs are transpiled to JavaScript and do not run in a JRE. As a consequence, the JavaScript semantics will impact the final semantics of a JSweet program compared to a Java program. In this section, we discuss the semantics by focusing on differences or commonalities between Java/JavaSript and JSweet.
|
|
|
|
\section{Main methods}
|
|
|
|
Main methods are the program execution entry points and will be invoked globally when a class containing a \texttt{main} method is evaluated. For instance:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public class C {
|
|
private int n;
|
|
public static C instance;
|
|
public static main(String[] args) {
|
|
instance = new C();
|
|
instance.n = 4;
|
|
}
|
|
public int getN() {
|
|
return n;
|
|
}
|
|
}
|
|
// when the source file containing C has been evaluated:
|
|
assert C.instance != null;
|
|
assert C.instance.getN() == 4;
|
|
\end{lstlisting}
|
|
|
|
Main methods do not behave exactly like in Java and depend on the way the program is packaged and deployed.
|
|
|
|
\begin{itemize}
|
|
\item \textbf{Regular packaging (no modules)}. With regular packaging, one Java source file corresponds to one generated JavaScript file. In that case, when loading a file in the browser, all the main methods will be invoked, right after the file is evaluated.
|
|
\item \textbf{Module packaging}. With module packaging (module option), one Java package corresponds to one module. With modules, it is mandatory to have only one main method in the program, which will be the global entry point from which the module dependency graph will be calculated. The main module will use directly or transitively all the other modules.
|
|
\end{itemize}
|
|
|
|
Because of modules, it is good practice to have only one main method in an application.
|
|
|
|
\section{Initializers}
|
|
|
|
Initializers behave like in Java.
|
|
|
|
\noindent
|
|
For example:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public class C1 {
|
|
int n;
|
|
{
|
|
n = 4;
|
|
}
|
|
}
|
|
assert new C1().n == 4;
|
|
\end{lstlisting}
|
|
|
|
\noindent
|
|
And similarly with static initializers:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public class C2 {
|
|
static int n;
|
|
static {
|
|
n = 4;
|
|
}
|
|
}
|
|
assert new C2.n == 4;
|
|
\end{lstlisting}
|
|
|
|
|
|
\section{Name clashes}
|
|
|
|
On contrary to Java, methods and fields of the same name are not allowed within the same class or within classes having a subclassing link. The reason behind this behavior is that in JavaScript, object variables and functions are stored within the same object map, which basically means that you cannot have the same key for several object members (this also explains that method overloading in the Java sense is not possible in JavaScript).
|
|
|
|
In order to avoid programming mistakes due to this JavaScript behavior, which is not necessarily known by Java programmers, JSweet adds a semantics check to avoid duplicate names in classes (this also takes into account members defined in parent classes). As an example:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
public class NameClashes {
|
|
|
|
// error: field name clashes with existing method name
|
|
public String a;
|
|
|
|
// error: method name clashes with existing field name
|
|
public void a() {
|
|
return a;
|
|
}
|
|
|
|
}
|
|
\end{lstlisting}
|
|
|
|
In general, it also not possible to have two methods with the same name but with different parameters (so-called overloads). An exception to this behavior is the use of method overloading for defining optional parameters. JSweet allows this idiom under the condition that it corresponds to the following template:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
String m(String s, double n) { return s + n; }
|
|
// valid overloading (JSweet transpiles to optional parameter)
|
|
String m(String s) { return m(s, 0); }
|
|
\end{lstlisting}
|
|
|
|
In that case, JSweet will generate JavaScript code with only one method having default values for the optional parameters, so that the behavior of the generated program corresponds to the original one. In this case:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
function m(s, n = 0) { return s + n; }
|
|
\end{lstlisting}
|
|
|
|
|
|
If the programmer tries to use overloading differently, for example by defining two different implementations for the same method name, JSweet will raise a compile error.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
String m(String s, double n) { return s + n; }
|
|
// invalid overloading (JSweet error)
|
|
String m(String s) { return s; }
|
|
\end{lstlisting}
|
|
|
|
|
|
\section{Variable scoping in lambda expressions}
|
|
|
|
JavaScript variable scope is known to pose some problems to the programmers, because it is possible to change the reference to a variable from outside of a lambda that would use this variable. As a consequence, a JavaScript programmer cannot rely on a variable declared outside of a lambda scope, because when the lambda is executed, the variable may have been modified somewhere else in the program. For instance, the following program shows a typical case:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
NodeList nodes = document.querySelectorAll(".control");
|
|
for (int i = 0; i < nodes.length; i++) {
|
|
HTMLElement element = (HTMLElement) nodes.$get(i); // final
|
|
element.addEventListener("keyup", (evt) -> {
|
|
// this element variable will not change here
|
|
element.classList.add("hit");
|
|
});
|
|
}
|
|
\end{lstlisting}
|
|
|
|
In JavaScript (note that EcmaScript 6 fixes this issue), such a program would fail its purpose because the \texttt{element} variable used in the event listener is modified by the for loop and does not hold the expected value. In JSweet, such problems are dealt with similarly to final Java variables. In our example, the \texttt{element} variable is re-scoped in the lambda expression so that the enclosing loop does not change its value and so that the program behaves like in Java (as expected by most programmers).
|
|
|
|
\section{Scope of \emph{this}}
|
|
|
|
On contrary to JavaScript and similarly to Java, using a method as a lambda will prevent loosing the reference to \texttt{this}. For instance, in the \texttt{action} method of the following program, \texttt{this} holds the right value, even when \texttt{action} was called as a lambda in the \texttt{main} method. Although this seem logical to Java programmers, it is not a given that the JavaScript semantics ensures this behavior.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
package example;
|
|
import static jsweet.dom.Globals.console;
|
|
|
|
public class Example {
|
|
private int i = 8;
|
|
public Runnable getAction() {
|
|
return this::action;
|
|
}
|
|
public void action() {
|
|
console.log(this.i); // this.i is 8
|
|
}
|
|
public static void main(String[] args) {
|
|
Example instance = new Example();
|
|
instance.getAction().run();
|
|
}
|
|
}
|
|
\end{lstlisting}
|
|
|
|
\chapter{Packaging}
|
|
\label{packaging}
|
|
|
|
Packaging is one of the complex point of JavaScript, especially when coming from Java. Complexity with JavaScript packaging boils down to the fact that JavaScript did not define any packaging natively. As a consequence, many \emph{de facto} solutions and quidelines came up along the years, making the understanding of packaging uneasy for regular Java programmers. In spite EcmaScript UMS is supposed to bring a standard for modules in Java, other \emph{de facto} standards remain and the notion of a namespace/package is still not handled by JavaScript, making the notion of a module and a namespace confusing for JavaScript and TypeScript developers themselves.
|
|
|
|
\section{Packages and modules}
|
|
|
|
Packages and modules are two similar concepts but for different contexts.
|
|
|
|
Java packages must be understood as compile-time \emph{namespaces}. They allow a compile-time structuration of the programs through name paths, with implicit or explicit visibility rules. Packages have usually not much impact on how the program is actually bundled and deployed.
|
|
|
|
Modules must be understood as deployment and runtime \emph{bundles}. The closest concept to a module in the Java world would probably be an OSGi bundle. A module defines imported and exported elements so that they create a strong runtime structure that can be used for deploying software components independently and thus avoiding name clashes. For instance, with modules, two different libraries may define a \texttt{util.List} class and be actually running and used on the same VM with no naming issues (as long as the libraries are bundled in different modules).
|
|
|
|
JSweet uses the Java package concept for namespaces. Modules are a deployment concept and should be created with some deployment scripts involving third party tools. However, for easy deployment, JSweet defines a \texttt{module} option that automatically creates a default module organization following the simple rule: one package = one module. With this rule, it is actually possible to run a JSweet program on Node.js without requiring extra work from the programmer. Also, using both the \texttt{bundle} and \texttt{module} options of JSweet creates a bundle file containing the application modules, and which can be deployed on a browser with no extra packaging.
|
|
|
|
\section{Root packages}
|
|
|
|
Root packages are a way to tune the generated code so that JSweet packages are erased in the generated code and thus at runtime. To set a root package, just define a package-info.java file and use the @Root annotation on the package, as follows:
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
@Root
|
|
package a.b.c;
|
|
\end{lstlisting}
|
|
|
|
The above declaration means that the \texttt{c} package is a root package, i.e. it will be erased in the generated code, as well as all its parent packages. Thus, if \texttt{c} contains a package \texttt{d}, and a class \texttt{C}, these will be top-level objects at runtime. In other words, \texttt{a.b.c.d} becomes \texttt{d}, and \texttt{a.b.c.C} becomes \texttt{C}.
|
|
|
|
\section{External modules}
|
|
|
|
When compiling JSweet programs with the \texttt{module} options, all external libraries and components must be required as external modules. JSweet can automatically require modules, simply by using the \texttt{@Module(name)} annotation. In JSweet, importing or using a class or a member annotated with \texttt{@Module(name)} will automatically require the corresponding module at runtime. Please not that it is true only when the code is generated with the \texttt{module} option. If the \texttt{module} option is off, the \texttt{@Module} annotations are ignored.
|
|
|
|
\begin{lstlisting}[language=Java]
|
|
package def.jquery;
|
|
public final class Globals extends jsweet.lang.Object {
|
|
...
|
|
@jsweet.lang.Module("jquery")
|
|
native public static def.jquery.JQuery $(java.lang.String selector);
|
|
...
|
|
}
|
|
\end{lstlisting}
|
|
|
|
The above code shows an excerpt of the JSweet jQuery API. As we can notice, the \$ function is annotated with \texttt{@Module("jquery")}. As a consequence, any call to this function will trigger the require of the \texttt{jquery} module.
|
|
|
|
Note: the notion of manual require of a module may be available in future releases. However, automatic require is sufficient for most programmers and hides the complexity of having to require modules explicitly. It also brings the advantage of having the same code whether modules are used or not.
|
|
|
|
\end{document}
|