JS++ 0.8.1: auto, catch-all, and Time

JS++ 0.8.1 fixes two major bug fixes that appeared when we introduced generics (0.8.0) and introduces some very useful new features. If you come from a C++ background, you might appreciate some of the new syntax :-).

‘auto’ Keyword

With the introduction of generic programming in 0.8.0, we need a more concise syntax to instantiate generic classes. The auto keyword solves this problem.

Now, instead of the following:

VeryLongClassName<string> foo = new VeryLongClassName<string>();

You can instead instantiate classes using auto:

auto foo = new VeryLongClassName<string>();

auto can be used for more than just generic classes though:

class Foo {}

auto foo = new Foo();

The auto keyword can only be used for variable declarations, and it reduces the redundancy of having to specify the type on the left-hand side only to repeat yourself on the right-hand side. This is known as local-variable type inference (to use the Java 10 terminology). For fans of C++, you may recognize this syntax.

Catch-all Clauses

This is another syntax that comes from C++.

Sometimes, you’ll want to catch an exception, but you don’t care to do anything with the exception object. In other cases, you may want to catch a specific type of exception but ignore all other exceptions. The “catch-all” clause can help you:

import System;

try {
    throw new System.Exception();
}
catch(System.Exception e) {
    Console.log(e.getMessage());
}
catch(...) {
    Console.log("The catch-all clause provides no exception object but will catch all exceptions - whether the type of the exception is internal or external.");
}
import Externals.JS;

try {
    throw new ReferenceError();
}
catch(...) {
    Console.log("Do nothing");
}

System.Time.TimeUnits

JS++ has an emphasis on readability. Have you ever seen code that looks like this?

setInterval(function() { /* ... */ }, 3600000);

The System.Time module has been introduced for dealing with time. Specifically, we’ve introduced a TimeUnits module to directly deal with the above case:

import System.Time;
external setInterval;

setInterval(void() { /* ... */ }, TimeUnits.hours(1));

Or, more succinctly:

import System.Time.TimeUnits;
external setInterval;

setInterval(void() { /* ... */ }, hours(1));

As always, we’ve had a focus on readable code. Here’s a preview of how well this composes:

import System;
import System.Time.TimeUnits;

Console.log(hours(1) + minutes(5));

Externals.Time

In JavaScript, functions such as setTimeout and setInterval are not part of the ECMAScript standard; they are provided by the host environment. Web browsers and Node.js ship with these functions, but it would not have been correct to add this to the Externals.JS module. Therefore, we’ve introduced the Externals.Time external module so you can more clearly work with timers.

Bug Fixes

  • Fixed methods with variadic parameters passing by reference
  • Fixed implementing of generic interfaces from generic classes
  • MAJOR BUG FIX: Fixed double calls being generated for getters
  • MAJOR BUG FIX: Fix this binding in code generation

JS++ 0.8.0: Altitude MVC, Generics, System.Dictionary, and More

This is a major update that has been in the works for a while.

Altitude MVC

Altitude MVC

Altitude is an MVC/MVP framework for JS++. It follows a “pure MVC” approach. In other words, the user uses the controller to manipulate the model, the model updates the view, and the view is fed back to the user as explained in this diagram from Wikipedia.

The “pure MVC” approach has historically proven to scale. Internally, we have tested Altitude for an application consisting of 3,000+ lines of JS++ code, and it has served us well.

Lastly, Altitude contains fewer than 100 lines of code (if you remove comments and whitespace). In an age when load times influence search rankings and you can get downgraded to a 2G/3G connection at any time, it’s important for libraries to be as lightweight as possible. However, there is one external JavaScript dependency (Handlebars.js), and, optionally, jQuery.

Despite the small size of the library, we’ve managed to scale it for a relatively large and complex internal email application. Examples are included to get you started. As usual, we also spoil you with documentation.

Download it here.

Generics

The major new language feature is generics (parametric polymorphism). You can now define generic classes in JS++:

class Foo<T>
{
    /* ... */
}

Generic programming allows you to specify “type parameters” for a class. This allows you to create classes that can operate on any data type.

In version 0.8.0, JS++ supports the following generic programming features:

  • Multiple generic arguments
  • Multiple generic constraints
  • Inheritance (including generic from generic)

More advanced generic programming features (such as sound covariance/contravariance) are scheduled for upcoming releases.

System.Dictionary<T>

While generics are a major feature, on a day-to-day basis, the official introduction of System.Dictionary<T> may be more important. Dictionaries are documented here and here. Dictionaries are also known as associative arrays, maps, etc.

Dictionaries allow you to create key-value pairs. The keys must be strings, but the values can be any data type.

import System;

Dictionary<unsigned int> ages = {
    "Steve": 25,
    "David": 31
};

Arbitrary key types will be possible in the future as we continue to expand the Standard Library. It’s going to be so much easier than JavaScript objects with non-string keys.

Multi-line Strings

This feature was available from the last release (0.7.0), but it wasn’t properly announced.

You can create multi-line strings with a syntax similar to Python’s:

string html =
    """
    <!DOCTYPE html>
    <head></head>
    <body>
    <div id="notice the quotes are unescaped">some content goes here</div>
    </body>
    </html>
    """;

Multi-line strings are a useful way to create heredocs. One use case is pasting large blocks of HTML text that you don’t want to manually escape.

System.BoxedExternal

I consider this a critical class. If you understand the JS++ type system, you should understand the difference between “internal” types and “external” types. The BoxedExternal class basically allows you to construct an internal value (with an internal type) using any external value that has an external type.

When you box an external, it has an internal type. When you unbox the boxed external, you get a value with an external type. It’s extremely useful and is one way to achieve safe bi-directional communication between JavaScript and JS++.

Furthermore, if you’re using System.Object in your APIs, it becomes absolutely critical. Sometimes, you might want to define a function that can accept internal or external values.

System.Benchmark

This was a user request. The System.Benchmark class makes it easy for you to benchmark your code.

Here’s an example:

import System;
 
Benchmark bench = new Benchmark();
bench.start();

// ... do stuff
for (int i = 0; i < 500; ++i) {
    Math.sqrt(2);
}

bench.stop();
  
Console.log(bench.duration);

It wasn't that this wasn't possible prior to the Benchmark class being introduced. It was just painful and unreadable. Remember: JS++ has an emphasis on code readability.

Dead Code Elimination (DCE) Improvements

In previous versions of JS++, dead code elimination (DCE) would not eliminate inherited methods. Since 0.8.0, the JS++ compiler supports DCE even in inheritance settings. This reduces the code size and footprint of the final output.

.js++ File Extension

Previously, JS++ supported the .jspp and .jpp file extensions. As of version 0.8.0, the JS++ compiler now officially supports the .js++ file extension too. When you input a directory to the compiler, it will automatically recursively search for .jspp, .jpp, and .js++ files now.

In order to support the new .js++ file extension, you may need to update your editor support.

Warnings

This is probably the biggest release if you've been annoyed with the compiler warnings. We've completely suppressed the warnings for variable shadowing. JSPPW0015 and JSPPW0016 are gone. We're going to see how this goes or at least come up with saner rules before raising warnings. We've had applications internally that were raising hundreds of warnings on source code that otherwise compiled OK.

The #1 design principle here is that excessive warnings cause users to ignore warnings. Thus, we're being extra careful here.

Miscellaneous

  • System.Date copy constructor added
  • Binding on virtual methods
  • Removed System.Object.hashCode
  • Fixed segmentation fault for [].concat(1, 2, 3)
  • Fix segmentation fault for if(foo) where foo is an object
  • Fix closure capturing variable with name arguments
  • Don't cache .length of an array in for-in/each loops, to address potential array modification inside loops
  • Allow implicit conversion for double[] a = [1];
  • Forbid access modifier changes on override
  • Don't generate prototype chain for non-virtual methods
  • Lowest Common Ancestor (LCA) for expressions. This allows the type checker to deduce the type for arrays and dictionaries when polymorphism is present.

Looking Ahead

Expect Standard Library expansion and modifications.

We made changes to the original JavaScript API in our original Standard Library implementation. (Because whose great idea was it to introduce a String.substring and a String.substr in JavaScript?) We're likely going to restore the JavaScript API, and we're going to add data structures such as sets, maps, and more. We're also thinking about popular cryptography algorithms such as MD5, SHA1, and AES.

Meanwhile, generics will continue to be expanded and improved in future short-term releases.

JS++ 0.5.2: BSD License, Interfaces, Abstract Classes, Virtual Methods, Non-generic Standard Library Classes

You’ve asked and we’ve listened. JS++ is now licensed under the 3-clause BSD License.

When we first announced 0.5.1 back in March, we introduced bare minimum classes. Specifically, I noted the following class features were unavailable:

  • Generic classes
  • Abstract classes
  • Inner classes
  • Interfaces
  • Virtual methods
  • Custom Conversion Rules as defined in my book, “The JS++ Type System”, Chapter 6.2

Every feature in the above list that isn’t crossed out is now available except the last feature (custom conversion rules) which will be arriving next. In addition, today’s release marks the introduction of the Standard Library. I’m going to briefly introduce the new features.

Update to Hello World

The JS++ Hello World program is now written as:

import System;

Console.log("Hello World");

Notice we no longer have to declare console as external. external is used for importing JavaScript libraries, and since we didn’t have a JS++ console implementation yet, we resorted to using the JavaScript console. However, now that we have a Console class in the Standard Library, it’s no longer a problem.

It is always recommended that you use the Standard Library’s Console class over the external JavaScript console. JS++ will detect if a console is available and will not crash if you try to log to an unavailable console. This can be a problem for web browsers like older versions of Internet Explorer, which are still used heavily in enterprise web applications.

Standard Library

The following Standard Library classes are now available:

  • System.Boolean
  • System.Character
  • System.Console
  • System.Date
  • System.Double
  • System.Exception
  • System.Exceptions
  • System.Integer8
  • System.UInteger8
  • System.Integer16
  • System.UInteger16
  • System.Integer32
  • System.UInteger32
  • System.Math
  • System.Object
  • System.RegExp
  • System.String

Many of the above classes, such as System.String and System.Integer32, are wrapper classes for auto-boxing. Currently, these wrapper classes simply provide a type-safe (and sometimes optimized) version of their JavaScript-equivalent methods. For example:

import System;

string s = "my string";
Console.log(s.replace(/^[a-z]/, string(string match){ return match.toUpperCase(); })); // Prints "My string"

The above example provides the exact same functionality as JavaScript’s String.prototype.replace. However, you get safety guarantees that you wouldn’t get with JavaScript. For example, if you try to call System.String.replace using the wrong arguments:

Console.log(s.replace(1));
[  ERROR  ] JSPPE5023: No overload for `System.String.replace' that takes `1' argument(s) at line 4 char 12 at replace.jspp

Optimizations

Always favor using the JS++ Standard Library over “rolling your own” functions. Consider the following code (which you can run yourself with the latest JS++):

import System;

double t = (new Date).getTime();
string z;
for (int i = 0; i < 5000000; ++i) {
	z += Double.POSITIVE_INFINITY.toString();
}
Console.log((new Date).getTime() - t);

And the nearly equivalent JavaScript code:

var t = (new Date).getTime();
var z = "";
for (var i = 0; i < 5000000; ++i) {
	z += Number.POSITIVE_INFINITY.toString();
}
console.log((new Date).getTime() - t);

JS++ average time: 124.4ms
JavaScript average time: 211ms

In this case, JS++ is roughly 70% faster... for nearly identical code.

You may think JS++ adds overhead (based on perceptions of what fast code may look like), but well-written JS++ will be faster than JavaScript. See my other article on optimization for more details.

Typed Exceptions and Multiple Catch Clauses

JS++ 0.5.2 introduces the System.Exception class and enables you to create your own custom exceptions.

Here's an example:

import System;

class CustomException : System.Exception
{
    CustomException() {
        super();
    }
    CustomException(string message) {
        super(message);
    }
}

try {
    throw new CustomException("This is a custom exception object.");
}
catch(CustomException e) {
    Console.log("Caught CustomException");
}
catch(System.Exception e) {
    Console.log("Caught System.Exception");
}

Variadic Parameters

The latest version of JS++ also introduces variadic parameters, which allow you to supply an arbitrary number of arguments to a function:

import System;

void log(Date date, ...string messages, bool silent) {
    if (silent) return;

    foreach(string message in messages) {
        Console.log(date.toString() + ": " + message);
    }
}

log(new Date(), "1", "2", "3", false);

Interfaces

An interface creates a contract. Methods defined in an interface must be implemented by all inheriting classes. Classes can inherit more than one interface.

According to JS++ naming conventions, interfaces should be prefixed with "I" and should be UpperCamelCase.

import System;

interface IWalkable {
	void walk();
}
interface ITalkable {
	void talk();
}

class Person : IWalkable, ITalkable
{
	void talk() {
		Console.log("Talking...");
	}
	void walk() {
		Console.log("Walking...");
	}
}

Person person = new Person();
person.talk();
person.walk();

Callback Type Parameter Names

Callback types can have parameters. Previously, you could only specify the parameter types for a callback/function type. However, you can now add names for these parameters. While these names cannot be used and have no meaningful effect on the executed code, they improve the readability of the code.

import System;

class Bird
{
	void fly() {
		Console.log("Flying...");
	}
}

void(Bird bird) fly = void(Bird bird) {
	bird.fly();
};
Bird bird = new Bird();
fly(bird);

Removal of 'Convert' Module

We have removed from the Convert module from the latest release. It was always used as a stopgap until we implemented the Standard Library wrapper classes, which provide toString() and other methods.

Bug fix: 'typeof' for internal types

For non-external types, typeof will always return the string "internal".

import System;

int x;
Console.log(typeof x); // "internal"

Virtual Methods

JS++ 0.5.2 introduces the virtual keyword and the override keyword to enable virtual methods on classes.

Virtual methods enable late binding and runtime polymorphism.

class Shape
{
    public virtual double area() {
        return 0;
    }
}
 
class Rectangle : Shape
{
    private int length, width;
 
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }
 
    public override double area() {
        return length * width;
    }
}
 
class Triangle : Shape
{
    private int base, height;
 
    public Triangle(int base, int height) {
        this.base = base;
        this.height = height;
    }
 
    public override double area() {
        return (base * height) / 2;
    }
}

Abstract Classes

Use the abstract modifier to create abstract classes and methods.

abstract class Shape
{
    public abstract int area();
}
class Rectangle : Shape
{
    private int length, width;
 
    public override int area() {
        return length * width;
    }
}

Enumerations

Enumerations (enums) can be used to restrict values and write type-safe code:

enum Importance { None, Regular, Critical }
 
Importance errorLevel = Importance.Critical;

The one missing feature...

Sadly, there is still one major missing feature from JS++. The Standard Library does not support System.Array yet because it is a generic class, and generics have not yet been implemented. In the meantime, you can resort to declaring your arrays as var:

var arr = [ 1, 2, 3 ];

BSD License

Last, but not least, JS++ 0.5.2 is the first version of JS++ licensed under the 3-clause BSD License.

The download for JS++ 0.5.2 is available from our home page.

Enjoy JS++!

JS++ 0.5.1: ‘foreach’

We just released JS++ 0.5.1, which features the foreach keyword.

Basic usage is as follows:

external console;

int[] arr = [ 50, 40, 30 ];

foreach (int value in arr) {
    console.log(value);
}

// Output:
// 50
// 40
// 30

More complex usage, such as arrays of objects, are also possible:

external console;

class Foo
{
	string bar() {
		return "bar";
	}
}

Foo[] foo = [ new Foo(), new Foo(), new Foo() ];

foreach (Foo value in foo) {
    console.log(value.bar());
}

// Output:
// "bar"
// "bar"
// "bar"

Additionally, the for-in keyword has been implemented. It is a counterpart to the foreach keyword in the sense that it enumerates keys rather than values.

JS++ 0.5.0: Basic Classes

JS++ now supports the ‘class’ keyword. As promised, we would have classes available by Q1 2017. Notably, we are providing “basic” classes, so the following features are supported:

  • ‘class’ keyword
  • Inheritance
  • Constructors (including private/protected constructors that limit instantiation/inheritance)
  • Static Constructors
  • Instantiation
  • Fields
  • Methods
  • ‘this’ keyword
  • ‘super’ keyword
  • Method Overloading
  • Constructor Overloading
  • Getters and Setters (via ‘property’ keyword)
  • Type system support
  • Debugger support for classes (via source maps)

What did we consider to be outside the scope of basic classes? The following features are currently not available yet:

As an example of what you can do with JS++ classes, we included an example with the Tiled Map Editor:

Tiled Map Editor

The included sample for Tiled can be found in the ‘Samples/Classes/tiled-loader’ directory with JS++ 0.5.0. Currently, it will load all maps exported to JSON with orthogonal tiles. It’s just a small but powerful example of what you can start doing with JS++ for early adopters.

I am also happy to inform that the backend for the JS++ website is written completely in JS++, and it has now run stable for one week without a single crash or error (other than 404 errors).

Finally, we have made the decision to not include the Mac/Linux installer… yet.

Be sure to check out the documentation on the ‘class’ keyword to get up to speed on JS++ classes.

Download JS++ 0.5.0 from our home page.

Mac/Linux Installer Coming for JS++ 0.5

The next version of JS++ will feature the ‘class’ keyword and is expected for Q1 2017.

In addition, Mac and Linux users will benefit from a JS++ installer:


The installer is completely optional. However, it will be useful if you don’t want to manually install JS++ and various editor plugins. We auto-detect which editors are installed on your system, and, if a plugin is available, we will attempt to install it for you.

JS++ for Mac OS X Updated to Latest Version

During our Christmas release, we had to release one version down (0.4.2.3) for Mac OS X. I’m happy to announce that – now that our staff are back from their breaks – JS++ for Mac OS X has been updated to the latest version and is in sync with JS++ for Windows and Linux.

Please note that, as of 0.4.2.4 for Mac OS X, JS++ defaults to the 32-bit binary. The 64-bit binary is available as jspp-x64.

You can download JS++ for Mac OS X from our homepage.

A JS++ Christmas: AJAX, js++Unit, Mac compiler, Tutorials

Merry Christmas from JS++!

We have multiple “gifts” and announcements for you this Christmas. We have lots of new libraries written with JS++ and a new version.

Version 0.4.2.4 and Mac Support

We have released version 0.4.2.4 which supports callback conversions, array conversions, and C-style casts such as:

int x = (int) y;

For a long time now, we have not provided Mac support. That’s going to change beginning this Christmas. We’ve released 0.4.2.3 for Mac OS X. It is one version down from the latest release for PC, but this was due to the fact that I let our staff off on holiday, found a bug with auto-boxing, and patched it at the last minute.

If you want access to our new libraries, you will need to download the new versions.

Library: js++Unit

js++Unit is an xUnit testing framework for automated testing in JS++. js++Unit currently works best for Node.js and is inspired by the Mocha test framework. It doesn’t really support the browser yet, but we’ll get there. We’re taking open source contributions for js++Unit too!

js++Unit also comes with a full-featured assertion framework (Vendor.JSPPUnit.Assert) and will do neat things like working with cycles for deepEqual.

You can download js++Unit from GitHub.

Library: ConsoleStyle

If you have a terminal emulator that supports ANSI escape codes, we have a library for you to provide colors to your console output. Download the ConsoleStyle library from GitHub. js++Unit depends on it and you need to link ConsoleStyle to use js++Unit.

Library: AJAX

Are you tired of having to include the entire jQuery library just to send an AJAX request? In JS++, you no longer have to. Since JS++ features dead code elimination, if you import an AJAX library that defines functions for HTTP GET and POST requests and you only use GET requests, the logic for POST requests will not be compiled into your final application.

You can download the AJAX library here. (It also ships with the latest version of JS++.)

Tutorial: What Are “Type Guarantees?”

The Getting Started guide has been completely re-written. We now explain how to use JavaScript libraries from JS++. We go one step further and explain what “type guarantees” are and how you can take advantage of them from JS++ using a new “RGBtoHex” tutorial.

The RGBtoHex tutorial shows an “untyped” JavaScript library. We teach you how to use it from JS++ – without ever adding types to your code. We gradually begin to add types (without compromising the soundness of the type system). Finally, we end with fully typed code and a re-usable function.

RGBtoHex is an ideal tutorial. RGB values are limited to the values 0 to 255. This is the JS++ byte data type. In the RGBtoHex tutorial, we show you how JS++ will guarantee your values will remain within the 0 to 255 range.

Check out the Getting Started tutorial now.

Merry Christmas!

JS++ 0.4.2.2: Debugging with Source Maps

JS++ 0.4.2.2 is being released today with support for in-browser debugging via source maps. Source maps allow you to debug your JS++ programs from a web browser of your choice that supports source maps debugging: Google Chrome, Mozilla Firefox, Microsoft Edge (untested), etc. With source maps, you can set breakpoints, log messages, and more with all locations pointing back to the original source JS++ file—rather than the generated .jspp.js file.

At the time of this writing, the recommended web browser to use for source maps debugging is Google Chrome.

In order to leverage source maps, compile your JS++ files with the --debug (or -d) flag:

Compiling source maps with JS++

This will generate a .map file, which maps the generated code back to the original JS++ source code.

When you run the generated code in your web browser, you will notice that console.log statements point to the original source .jspp file’s location rather than the locations of the generated code:

Source Maps - console.log Original Location

In addition, you can set breakpoints, step into, step over, step out and use all the features you’d expect from your debugger:

Source Maps - Set Breakpoint

Finally, we have worked to improve Microsoft Windows integration even more. In JS++ 0.4.2, we gave you Windows context menu integration. However, due to restrictions in Windows, this only allowed compilation of one file. JS++ is a multi-file, modular programming language. Thus, we needed users to be able to select multiple files and compile them. You can now do this in the latest version of JS++:

jspp-windows-multifile

Another problem with Windows integration was that the JS++ CLI compiler would pop up and immediately exit. If you had an error, there was no way to know what to fix. With the latest version of JS++, you will now receive a popup dialog notifying you of the compilation results:

jspp-windows-multifile2

Get the latest download of JS++ by navigating to our home page.

JS++ 0.4.2.1 – Minor Bug Fix Release

JS++ 0.4.2.1 has been released. This is a minor bug fix release. The following issues have been fixed:

1. Checking for permissions. Compiler now checks if the user has permission to read input files and write to output directories.
2. Segmentation faults for built-in modules (e.g. `Externals.DOM`)
3. Dead Code Elimination (DCE) algorithm updates so parent modules do not get eliminated.
4. Error 0119 was incorrectly being raised on function parameters. This has been fixed so assignments to parameters can be done.
5. Parser bug for regular expression literals.

In the next release, 0.4.2.2, we will be including free, open-source libraries for AJAX and real-time streaming.

The latest version can be downloaded from the JS++ homepage.