As far as I know, Asm.js is just a strict specification of JavaScript, it uses the JavaScript features and it's not a new language.
For instance, instead of using var a = e;, it offers var a = e|0;.
My question is, if asm.js is just a definition and can be achieved by changing the way one uses and declares variables and dynamic types, what does "use asm"; actually do? Is this necessary to put this string before declaring function's body or not?
Asm.js is a very strict subset of JavaScript, that is optimized for machines rather than humans. If you want your browser to interpret certain code as asm.js code, you need to create a module wherein the following conditions apply :
all code is fully statically typed and limited to the very restrictive asm.js subset of JavaScript
your module starts with the "use asm" pragma
Additionally, an asm.js module allows only up to three optional yet very specific parameters :
a standard library object, providing access to a subset of the JavaScript standard libraries
a foreign function interface (FFI), providing access to custom external JavaScript functions
a heap buffer, providing a single ArrayBuffer to act as the asm.js heap
So, your module should basically look like this :
function MyAsmModule(stdlib, foreign, heap) {
"use asm";
// module body...
return {
export1: f1,
export2: f2,
// ...
};
}
The function parameters of your module allow asm.js to call into external JavaScript and to share its heap buffer with "normal" JavaScript. The exports object returned from the module allows external JavaScript to call into asm.js.
Leave out the "use asm", and your browser will not know that it should interpret your code as an asm.js module. It will treat your code as "ordinary" JavaScript. However, just using "use asm" is not enough for your code to be interpreted as asm.js. Fail to meet any of the other criteria mentioned hereabove, and your code will be also interpreted as "ordinary" JavaScript :
For more info on asm.js, see eg. John Resig's article from 2013 or the official specs.
"use asm" is a pragma that tells the JavaScript engine specifically how to interpret it. Although it's valid JavaScript and can be used without the pragma, FireFox can perform additional optimizations to the Asm.js subset to increase performance. To do this, it must know that it is Asm.js.
Related
The C++11 specification defined [[attributes]] which can be used to specify/influence implementation-defined behavior. Cheerp supports this for specifying whether you're writing C++ code meant to be compiled into [[cheerp::genericjs]] or [[cheerp::wasm]] code. This results in your C++ code being compiled into the .js or .wasm output of the compiler respectively. (Right?)
My question: What attributes does Cheerp know and what do they all do?
So far, I've seen the following attributes:
[[cheerp::genericjs]]
[[cheerp::wasm]]
[[cheerp::asmjs]]
[[cheerp::client_layout]]
[[cheerp::static]]
[[cheerp::jsexport]]
The ones that are meant to be used by users are:
cheerp::genericjs: compile the associated item (class/struct definition, global, or function) to JavaScript, using the object memory model
cheerp::wasm: compile the associated item (class/struct definition, global, or function) to WebAssembli OR asm.js, using the linear memory model.
cheerp::asmjs is an alias of cheerp::wasm and considered obsoleted (but kept for backward compatibility). The actual output (wasm or asm.js) depends on command line flags
client::jsexport: export the associated item (function or class/struct) so that it can be used from external JavaScript code
The other attributes you mention do exist, but you should almost never use them yourself. Their meaning is this:
cheerp::static: tell the compiler that the associated method of a client class is static (example: Date.now()). Used in the implementation of various browser apis
cheerp::client_layout: tell the compiler that this class/struct has an external layout defined in external JavaScript. You never need to use this if you inherit your client classes from client::Object (which you should), because derived classes inherit this attribute
Sorry if this is a trivial question, so if this has already been asked, please direct me to the question.
I know that the tostring method in javascript, if called on a function will print the source code (more about it: link). Is it possible to do the same thing in Java?
So if I have the following identity function definition:
public class class1 {
int f1(int x){
return x;
}
}
And the following main function:
class Main {
public static void main(String args[]) {
class1 c1 = new class1();
????
}
}
Is there anything I can put in place of '????' that would print something like
int f1(int x){
return x;
}
Disclaimer: I'm not an expert at Java, or any programming language for that matter. However, I do know how to find information online.
This concept does not seem very doable within Java. To start:
JavaScript is an interpreted language, not a compiled language. A program such as C++ or Java needs to be compiled before it is run. The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute. In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. More modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
Basically, JavaScript has the advantage of reading directly from the file with the source code, and executing it on the fly. Compiled languages such as Java won't have that sort of functionality built in by default for many reasons, including security. An application should be able to run without allowing hackers access to its source code as much as possible.
There have been attempts at doing various forms of what you're interested in, but the two easiest methods seem to be
Printing the original .java file line by line
Storing a string reference to the entire code or the method(s) required.
It also seems possible to print the method name, but not the body.
Aside from that, the only thing you might be able to get from a compiled, running java program, is bytecode, which would require a decompiler to have any hope of understanding the source behind it.
You can continue reading up on it through a few of the links here:
How do I print the method body reflectively?
Save a method into a variable, java 8
View a method's implementation (method body) using Java Reflection
Probably yes, but not a trivial one with a ready command. JavaScript is an interpreted language where the executing environment has access to the source code in its original form. That is how you can inspect it in a browser console and see the same variable names as are in the source code.
While the compiled/interpreted distinction is fuzzy for Java, it is definitely modified before execution. The bytecode used by Java's Just-in-Time compilation may be more readable than a fully compiled binary file, it is not the source. If the running program does not have access to the source code, it is less able to output it. A debugger running in an IDE can reference problems in the source; otherwise, you are limited to debugging the bytecodes.
This is why Keno Clayton suggested the question on Quine programs, which are meant to reproduce themselves. This answer outputs the source code by hard-coding it as a class attribute. You could take a similar approach with a pre-compilation script that went through all the methods and made strings out of their sources, but the result would be bulky and potentially sensitive.
Browsing the v8 tree, under the src directory, some js files were there, providing some basic JS objects like Math, Array etc. Browsing those files, I saw identifiers including a percent sign (%) in their names, i.e. %Foo. I first naively thought it was some other allowed character in JS's identifiers, but when I tried it in shell, it yelled at me, saying that I'm violating syntax rules. But if it is a syntax error, how come d8 works? Here are an example from the actual source code:
src/apinatives.js lines 44 to 47, git clone from github/v8/v8
function Instantiate(data, name) {
if (!%IsTemplate(data)) return data;
var tag = %GetTemplateField(data, kApiTagOffset);
switch (tag) {
src/apinatives.js lines 41 to 43, git clone from github/v8/v8
function SetConstructor() {
if (%_IsConstructCall()) {
%SetInitialize(this);
How come this identifiers do not yield syntax errors. All js files, including math.js and string.js and all others?:wq
It is not technically valid JavaScript. These are calls to V8 runtime functions. From that page:
Much of the JavaScript library is implemented in JavaScript code
itself, using a minimal set of C++ runtime functions callable from
JavaScript. Some of these are called using names that start with %,
and using the flag "--allow-natives-syntax". Others are only called by
code generated by the code generators, and are not visible in JS, even
using the % syntax.
If you look in parser.cc you can see some code relating to allow_natives_syntax that determines whether the parser will accept this extension to the JavaScript language that V8 is using to interact with its runtime. These files must be parsed with that option enabled.
I would speculate that V8 does not allow you to make these calls by default both because it would contradict the JavaScript standard and because it would probably allow you to do things to the runtime you should not be able to do.
I just started using TypeScript and sometimes get compiler errors "use of undeclared variable". For example the following works in plain JavaScript :
var foo = {};
foo.bar = 42;
If I try to do the same in TypeScript it won't work and give me the mentioned error above. I have to write it like that:
var foo :any = {};
foo.bar = 42;
In plain JavaScript the type definition with any is neither required nor valid, but in TypeScript this seems to be mandatory. I understand the error and the reason for it, but I always heard in Videos and read in the documentation:
typescriptlang.org:
"TypeScript is a typed superset of JavaScript [...]"
Introduction Video #minute 3:20:
"All JavaScript code is TypeScript code, simply copy and paste"
Is that a thing that changed during the development of TypeScript or do I have to pass a specific compiler setting to make this work?
The reason for TypeScript's existence is to have a compiler and language which can enforce types better than vanilla Javascript does. Any regular Javascript is valid TypeScript, syntactically. That does not mean that the compiler must be entirely happy with it. Vanilla Javascript often contains code which is problematic in terms of type security. That doesn't make it invalid TypeScript code, but it's exactly the reason why TypeScript exists and it's exactly the compiler's job to point out those problems to you.
The languages as such are still sub/supersets of one another.
Theorem: TypeScript is neither a subset nor a superset of JavaScript.
Proof:
When we say language A is a subset of language B, we mean all valid A-programs are also valid B-programs.
Here is a valid TypeScript program that is not a valid JavaScript program:
let x: number = 3;
You identified a valid JavaScript program that is not a valid TypeScript program:
var foo = {};
foo.bar = 42;
Complicating factor 1: TypeScript is almost a superset. TypeScript is intended to be a near superset of JavaScript. Most valid JS is also valid TS. What JS is not can usually be easily tweaked to compile without errors in TS. In other words, most valid JS is also valid TS.
Complicating factor 2: non-fatal errors The TypeScript compiler generates the JavaScript code you intend sometimes even if there are errors. The your example that I referenced earlier emits this error
error TS2339: Property 'bar' does not exist on type '{}'.
but also this JS code
var foo = {};
foo.bar = 42;
The TS documentation notes
You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.
I think we can call this a failed compilation (and thus invalid TypeScript) for the following reasons:
The compiler seems to use the term warning in the conventional sense, so we should interpret error in the conventional sense too: an error indicates the compilation failed.
The documentation indicates that the resulting JavaScript is not necessarily correct as to what was intended. An incorrect output seems just as bad as (if not worse than) no output. They should both be considered failed.
The TypeScript compiler exits with a non-zero status code, which conventionally indicates that the process failed in some way.
If we call any TypeScript program that outputs JavaScript "valid", then we would have to call the following TypeScript program valid, because it a dot compiles to the empty string after issuing errors:
.
Complicating factor 3: TS accepts JS files: The TypeScript compiler can passthrough files ending in .js (see compiler documentation for --allowJs). In this sense TypeScript is a superset of JS. All .js files can be compiled with TypeScript. This is probably not what people who visit this question are meaning to ask.
I think complicating factor 1 is the thing that Anders Hejlsberg is getting at. It might also justify the misleading marketing on TypeScript's homepage. The other answers have fallen prey to complicating factor 2. However the general advice given in the other answers is correct: TypeScript is a layer on top of JavaScript designed to tell you when you do something bad. They are different tools for different purposes.
No. In other answers I believe the technical reason has been well explained, but I notice an example that could immediately serve as a contradiction to the claim in the question (different semantics):
// In TypeScript
function f<A>(a: A) { return a; };
console.log(f<Function>(f)); // <-- This line. It will print the function f since it is an identify function that in this case takes self and returns self.
Comparing to the below JavaScript example
// In JavaScript
function f(a) { return a; };
console.log(f<Function>(f)); // <-- This line. This is VALID JavaScript
At first glance you might think there should be a syntax error for the JavaScript example. HOWEVER, once you examine it closely, you'll notice that actually the line is executed as
console.log((f < Function) > f); // Evaluate to false
which is completely valid in JavaScript. This essentially means the same line of code resulted in 2 completely different interpretation in JavaScript and TypeScript, therefore a counterexample to the question.
The definition
"All JavaScript code is TypeScript code, simply copy and paste"
is true. Because any JavaScript code can passed to the TypeScript compiler.
So it's sort of a Layer on top of JavaScript. So, of course the underlaying Layer (JavaScript) can be passed through the layers to the top (TypeScript), but not the other way around.
Why not?
Think of it as a bike (JavaScript) and a motorcycle (TypeScript). The basics are the same (two wheels, a frame), but the motorcycle as an engine and some enhanced features.
So, you can use your motorcycle (TypeScript) as a bike (JavaScript), but you cannot use a bike as a motorcycle.
EDIT:
If your compiler throws a warning, why does it make the
statement wrong? It just says: Hey, you are using TypeScript, and it's
more strict than what you gave me.
See this example, it compiles perfectly to JavaScript, but throws a warning.
I have come across JSHint but was hoping it would validate node.js syntax but it doesn't, for example if I do:
var server = http.createServerfunctionThatDoesNotExists(function(request, response) {....
The test passes even though there isn't a function called createServerfunctionThatDoesNotExists
What am I missing with JSHint and the node.js option?
I think it doesn't dig into CommonJS modules as they can contain virtually everything.
So even if you are require'ing http it could be your own module with any interface.
'Assume Node' means it tolerates global variables like module or exports
JSHint is basically JSLint and is more for syntax/style/JS-nonos rather than a deep-scan product that executes your JS. Fully vetting JS code (or any dynamic language, really, depending on your definition of dynamic) pretty much requires running it, since things like methods can be defined more or less anywhere, including at runtime.
JSHint does go a bit further and allow the definition of high-level constructs used by some JS libraries.