JavaScript Code Model

Introduction

Please see this blog post.

JavaScript Code Model project (JSCM for short) provides a Java API for programmatic creation and manipulation of JavaScript source code.

JSCM models grammatical structure of JavaScript (accoring to the ECMAScript specification) in Java classes. This allows building JavaScript code from Java programmatically.

Once object model of the JavaScript program is built, it can be formatted and printed out into a writer. The result is well-formatted (with indentation, line breaks etc.) and is almost guaranteed to be in correct JavaScript syntax.

Getting JavaScript Code Model

Maven Artifacts

If you're using Apache Maven (or compatible build tools), please use the following dependency:

<dependency>
	<groupId>org.hisrc.jscm</groupId>
	<artifactId>js-codemodel</artifactId>
	<version>...</version>
</dependency>

JSCM is distributed via the Central Maven repository.

SourceForge-Hosted Files

You can also download JSCM files from SourceForge:

JSCM does not have any runtime dependencies. You basically only need one JAR file (js-codemodel-version.jar).

Using JavaScript Code Model

Usage is rather straightforward. Here's a small example:

// Instantiate the code model
JSCodeModel codeModel = new CodeModelImpl();
// Create the program
JSProgram program = codeModel.program();
// Add a function declaration
JSFunctionDeclaration factorial = program
	.functionDeclaration("factorial");
// Add a function parameter
JSVariable x = factorial.parameter("x");
// Create an integer literal
JSDecimalIntegerLiteral one = codeModel.integer(1);
// Add a return statement to the function body
factorial.getBody()._return(
	x.le(one).cond(
		one,
		x.mul(factorial.getFunctionExpression().i()
			.args(x.minus(one)))));

// Write the program code to the System.out
new CodeWriter(System.out).program(program);

This produces the following JavaScript code:

function factorial(x) {
  return x <= 1 ? 1 : x * factorial(x - 1);
}

Limitations

JSCM model JavaScript grammar with high precision. However there are certain things we've not implemented at the moment.

Further Information and Links

License

Maven Site:

JSCM is hosted and developed on Sourceforge.net:

Hudson:

JIRA:

Mailing list:


Browse Space

- Pages
- News
- Labels
- Attachments
- Bookmarks
- Mail
- Activity
- Advanced

Explore Confluence

- Popular Labels
- Notation Guide
- Impressum

Your Account

Log In

 

Other Features

Add Content