11

Recently I found such cool thing as Google Closure Compiler. Are there alternatives which provide opportunities to get benefits of compiled statically-typed languages?

Update

It is not about real compilers, it is about JavaScript-JavaScript translators, which provide types verification etc, optimization, and maybe compression.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • 3
    The so-called Javascript compilers are more like Javascript optimizers. The code still needs to be executed by the Javascript engine of the browser, so it still has to be valid JS. Everything they can do is shorten all identifiers and remove whitespaces to reduce the file size and maybe do some minor optimizations on the JS layer, but they can never reach the execution speed of a compiled language. – Philipp Sep 03 '12 at 00:57
  • @Philipp So you're saying compiled languages' execution speed is faster than JS? I always thought it was the other way around (especially with my computer)... – David G Sep 03 '12 at 00:59
  • What do you mean by 'benefits of compiled statically-typed languages'? Do you mean you want to write C-style code which **compiles** into JavaScript (like [dart](http://www.dartlang.org/))? As Phillip points out, optimization isn't **compilation**. No matter what you find, you're still running JavaScript. – Joseph Yaduvanshi Sep 03 '12 at 01:00
  • 8
    Why did Google name their tool with the word compiler? That's a recipe for confusion surely. – Lee Taylor Sep 03 '12 at 01:00
  • @LeeTaylor I believe it's named that way because it compiles all of the `goog` utilities used within your code into a single sort of framework. In this case, 'compile' is more like 'aggregate'. – Joseph Yaduvanshi Sep 03 '12 at 01:02
  • 1
    @David - Yes, compiled code runs faster than JS - why wouldn't it? Why do you think it is the other way around on your computer? – nnnnnn Sep 03 '12 at 01:23
  • @nnnnnn I think it's specific to my computer because when I want to build and run C++ it takes quite a while to compile (I recently discovered it's because I'm including . When I take it out it runs much faster). When I use jsfiddle for javascript it runs noticeably faster. – David G Sep 03 '12 at 01:30
  • @SperanskyDanil Sorry I didn't know that. But is execution the same thing as what we call "runtime"? – David G Sep 03 '12 at 01:40
  • 1
    @SperanskyDanil "Cannot"? That's a tall claim. Keep in mind that state-of-the-art JavaScript interpreters are able to rewrite the machine code they generate to optimize for commonly used pathways, after observing real-world characteristics. That's something your C++ compiler can't do, and it's 100% believable that there exist corner cases in which it will result in better runtime performance; modern JIT compilation engines can do some damned impressive things that AOT compilers can't. – Charles Duffy Sep 03 '12 at 02:31
  • 1
    @SperanskyDanil Parsing only matters for startup time, not for runtime performance. As for "optimizing for commonly used pathways", an AOT compiler has to guess ahead-of-time; it has no way to adjust its behavior if this guess is wrong. A JIT compiler, by contrast, can modify the generated machine code after-the-fact if analyzing the behavior of the code contradicts the initial guess. Mind you, one can have an ahead-of-time compiler compile to bytecode, and a JIT compiler going from bytecode to native instructions -- see all modern JVMs. – Charles Duffy Sep 03 '12 at 03:40
  • 1
    @SperanskyDanil There is overhead, especially at startup -- but a good JIT will eventually optimize for the pathway where something is the expected type, and only go through full introspection when that code path fails. – Charles Duffy Sep 03 '12 at 03:59
  • 7
    The Closure Compiler is called a Compiler because it performs all the functions you would expected from say a C++ compiler (type check, dead code elimination, function and variable inlining, etc) the only difference is rather than generating machine code it generates JavaScript. JavaC doesn't produce machine code either, it produces Bytecode and JavaC does little beyond type checking and producing Bytecode (it leaves almost all optimizations to the JVM). In concept, the Closure Compiler is actually closer to an optimizing C++ compiler than the Java compiler. – John Sep 04 '12 at 05:09

4 Answers4

6

From your comment:

I am interested in type checking, interface checking, private fields checking etc, all things allows you to write safety code, not only minimizer.

JavaScript is a dynamically-typed language that does not have built-in support for classes, interfaces, or access modifiers. Closure Compiler supports various extralinguistic features such as interfaces and access modifiers by using information embedded in JSDoc comments. Several IDEs also provide static analysis using JSDoc tag information, for example, see WebStorm & PhpStorm Blog: New in 5.0: Google Closure Compiler JSDoc annotations.

In the area of JavaScript minifiers there are numerous options such as YUI Compressor, UglifyJS, dojo shrinksafe, Microsoft Ajax Minifier, and JSMIN. However, none of these tools provide the same level of support for JSDoc-based analysis as Closure Compiler.

Related stack overflow questions:

  1. Which Javascript minifier (cruncher) does the same things that the one Google uses for its JS APIs?
  2. What are some good css and js minimizers for production code?
  3. Type checker for JavaScript?
  4. Is there a good JavaScript minimizer?
  5. JavaScript and CSS minimizer
  6. JavaScript compression
  7. What is the current state of JavaScript static type checking?
Community
  • 1
  • 1
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
2

Closure compiler (Google) is a true compiler for javascript. Alternatives include typescript (Microsoft) and Flow (facebook). Closure compiler uses jsdoc comments to annotate types. Typescript uses a different syntax than es3/es5 to provide type annotations that compiles to plain javascript. Flow piggybacks onto the OCaml language (which excels in type inference) to infer as much type information as possible, but can consume annotations in a comment syntax as well. Closure compiler is also working on better type inference, but it is not ready for production.

In response to @EASI: The closure compiler is a true compiler, not just a minifier. It works by:

  1. Parsing a set of input .js files and a set of extern files (that defined interfaces for ecma 3,5,6 and common browser objects like Window, etc) into an abstract syntax tree (AST).

  2. Running a series of compiler passes over the AST to rewrite, transform, eliminate dead code etc.

  3. Emit the AST back into js source code. It will either concatenate the files back together with comments stripped out (WHITESPACE_ONLY), rename and minify symbols within function definitions (SIMPLE), or rename and rewrite all symbols into a minified and obfuscated form (ADVANCED).

Here's a list of compiler passes, for those that are interested. As you can see, there is a lot going on:

AliasExternals.java AliasStrings.java AmbiguateProperties.java AnalyzeNameReferences.java AnalyzePrototypeProperties.java AstValidator.java CallGraph.java ChainCalls.java CheckConformance.java CheckDebuggerStatement.java CheckEventfulObjectDisposal.java CheckGlobalNames.java CheckMissingGetCssName.java CheckRegExp.java CheckSideEffects.java ClosureCodeRemoval.java ClosureOptimizePrimitives.java CollapseAnonymousFunctions.java CollapseProperties.java CollapseVariableDeclarations.java ConstCheck.java ConstParamCheck.java ConvertDeclaredTypesToJSDoc.java ConvertToDottedProperties.java ConvertToTypedES6.java CoverageInstrumentationPass.java CreateSyntheticBlocks.java CrossModuleCodeMotion.java CrossModuleMethodMotion.java DeclaredGlobalExternsOnWindow.java DefaultPassConfig.java Denormalize.java DisambiguateProperties.java ErrorPass.java Es6ToEs3ClassSideInheritance.java ExpandJqueryAliases.java ExportTestFunctions.java ExternExportsPass.java ExtractPrototypeMemberDeclarations.java FlowSensitiveInlineVariables.java FunctionNames.java FunctionRewriter.java GatherExternProperties.java GatherRawExports.java GenerateExports.java GlobalNamespace.java GlobalTypeInfo.java GroupVariableDeclarations.java ImplicitNullabilityCheck.java InferConsts.java InjectEs6RuntimeLibrary.java InlineFunctions.java InlineObjectLiterals.java InlineProperties.java InlineVariables.java InstrumentFunctions.java JsMessageVisitor.java MarkNoSideEffectCalls.java MethodCompilerPass.java MinimizeExitPoints.java NameAnalyzer.java NameAnonymousFunctions.java NameAnonymousFunctionsMapped.java NameReferenceGraphConstruction.java NewTypeInference.java Normalize.java ObjectPropertyStringPostprocess.java ObjectPropertyStringPreprocess.java OptimizeArgumentsArray.java OptimizeCalls.java OptimizeParameters.java PeepholeOptimizationsPass.java PhaseOptimizer.java PrepareAst.java ProcessCommonJSModules.java ProcessDefines.java ProcessTweaks.java PureFunctionIdentifier.java RecordFunctionInformation.java RemoveUnusedClassProperties.java RemoveUnusedNames.java RemoveUnusedPrototypeProperties.java RemoveUnusedVars.java RenameLabels.java RenameProperties.java RenamePrototypes.java RenameVars.java ReplaceCssNames.java ReplaceIdGenerators.java ReplaceStrings.java RescopeGlobalSymbols.java RuntimeTypeCheck.java SanityCheck.java ShadowVariables.java SideEffectsAnalysis.java SimpleDefinitionFinder.java StrictModeCheck.java StripCode.java SymbolTable.java TransformAMDToCJSModule.java TypeInferencePass.java TypedScopeCreator.java UnreachableCodeElimination.java VariableVisibilityAnalysis.java

Paul
  • 595
  • 6
  • 6
  • I may be splitting hairs (as the saying goes), but I think the 3rd item you listed pretty much nullifies your argument. A compiler generally takes a human readable language and converts it into machine code. When the Closure "Compiler" converts all of its work back into JavaScript, isn't that new code just going to be run on an ordinary JavaScript engine? I'm not saying that what the Closure "Compiler" is doing isn't extensive and very close to the same thing that a regular compiler does, but in the end it's just restructuring JavaScript, not 'compiling' it. – Quantium Aug 09 '15 at 10:36
0

Yes,

There are Java, JS, PHP, CSS, and HTML "minifiers". For example, when you use Google GWT Java for programming, the code is generated as a minimization of JS.


They use the term compiler, but it is not correct. Compilers turn one human readable language code into a object code that only interpreters or machines can read. What this google tool does is to optimize your code so it can be read faster by the interpreter. Script languages needs interpreters to be executed. Programs compiled into machine language are executed faster than any interpreter could. But of course that any program speed depends on it's execution flow project and the experience of the developing team.


New:

Have you tryed to make your JavaScript codes in a specialized IDE? If you're looking for type cheking, you could try one of these:

  • NuSphere PhpED Professional v7 (best)
  • phpDesigner 8
  • Aptana Studio
  • Zend Studio
  • DreamWeaver CS6

They have a greater support now, not only for PHP, but for JavaScript, with Code Auto-Complete, Type Verification, Dynamic Syntax Highlighting, Multiple Language Syntax Highlighting and Oriented Object Analysis and Auto Complete as you type.

NaN
  • 8,596
  • 20
  • 79
  • 153
  • 5
    The Closure Compiler acts as a "minimizer" in basic mode, but in advanced mode it really _does_ act very much like a genuine compiler, but which happens to have JavaScript, rather than bytecode or machine code as its target language. There's not just a peephole optimizer but codepath/reachability analysis, function inlining, and all the other things you expect a good optimizing compiler to do. – Charles Duffy Sep 03 '12 at 01:27
  • @SperanskyDanil, Try http://fmarcia.info/jsmin/test.html – NaN Sep 03 '12 at 01:30
  • 1
    @CharlesDuffy, GCC is the state of the art programming. It's like some robot reading your software and then rebuild it 5x better. It's how google makes it's Gmail a great Web 2.0 service. – NaN Sep 03 '12 at 01:32
  • +1. GWT is an excellent example of having a static language compile into js. – gideon Sep 03 '12 at 05:33
  • Sorry, @CharlesDuffy. It was really pointed to you. – NaN Sep 04 '12 at 13:35
  • @EASI Then we're in violent agreement -- which is to say: we're saying the same thing; I don't understand why you would feel a need to contradict. – Charles Duffy Sep 04 '12 at 13:41
  • @SperanskyDanil, I have edited my answer to include some software that helps you in the type verification, interface checking (aptana) etc. – NaN Sep 04 '12 at 13:44
  • @EASI The Closure Compiler has type verification, interface checking, and the like on its own in advanced mode, if one is using appropriate annotations. You might consider some links on that topic as well. – Charles Duffy Sep 04 '12 at 13:45
  • Sorry that I did not. I will put the official site of each because there they explain all about it. – NaN Sep 05 '12 at 14:20
  • 6
    People, please don't call Google Closure Compiler "GCC". Unix has its own GCC (GNU Compiler Collection) which might cause confusion. – Camilo Martin Sep 05 '12 at 18:56
0

I think that furiascript.com can be the interesting option.