How to add a custom class in v8? - javascript

Thank you for reading my question.
I am trying to embbed google V8 to my game engine.
Now I need to add a Bytes(or Buffer, in node.js) class to my program. I have read the implentation of Buffer in node.js, but, that's too ugly in my mind.
The class what I want is like bytes class in python, which can decode to string and be encoded to from string, and have its own operator such as '+' and '*'.
It seems the only way is to modify the V8 itself?
I spent 2 days reading the code in V8, but getting more and more chaos. For example, the String class has 2 declarations: in v8.h and objects.h, and big diffirences exist in both. The terrible big macros are making me crazy, too.
My question is the same as this: How to add a new class to Google V8? , but yiding thinks he/she does not need to modify V8.
Then I asked the same questions, too:
Where can I find guides about modifying V8's code?
Or where can I find docs about V8's design architecture?

Related

implement infinite lists in v8

I'm a computer science student and as part of a school projet I have been asked to either find an exploit in the v8 engine, make some really good optimisation or add a new feature.
I chose to add a new feature and here it is:
function* numbers() {
i = 1;
while (true) {
yield i++;
}
}
var gen = numbers();
var l = [...gen];
var n = l[42];
Putting it in words I want to have the possibility to use the destructuring syntax to create a list that can hold an infinite number of objects and access them.
It's possible to do it in Haskell and I want to try and do the same with JavaScript.
If of the developers at v8 could point me in the right direction it would be so great.
I already have a working environment, can compile the engine, read the source code, and run the debugger on the d8 binary file with symbols.
V8 developer here.
First off: just to be clear, stackoverflow is not a machine that does your homework. (You're only asking for "the right direction", that's okay.)
Secondly: V8 implements JavaScript as spec'ed, so any arbitrary "new feature" is not going to land in our repository, please be aware of that.
Thirdly: Keith has several good points. In particular, the syntax you propose is already valid JavaScript and eagerly evaluates the generator. Was your idea to switch to lazy evaluation iff the generator produces an infinite stream of values? Take a step back and think about the implications of that idea for a minute.
Finally, if you come up with workable syntax/semantics, then it'll still be a chunk of work to do this in V8, because there's no precedent of something similar. You'd probably want to use an elements interceptor, and store the generator in a private property. I think it would be much easier to polyfill the whole thing in pure JavaScript using a Proxy.
(It might be a good idea to reconsider your choice of project, but that's up to you. It's also quite a funky project description to begin with... what do they think how hard it is to "find an exploit or make some really good optimisation"? Do let us know if you find an exploit though!)

What is a singleton typed array?

I'm trying to understand what is asm.js and what does it do, and I am reading this article here, by Alon Zakai: What asm.js is and what asm.js isn't
He first talks about emscripten.js and explains that the pattern by which it compiles C++ to JS uses a singleton-typed array to make C++ feel at home in JS:
That pattern involves using a singleton typed array to represent
memory (p. 7)
I know what a singleton object is and what the 'singleton pattern' looks like in Javascript, but what is a singleton-typed array? A Google search came up with nothing.
EDIT: I also do understand what Emscripten does and that pattern in question of implicitly-typed, but statically-typed variables (i.e. variables' types don't change throughout runtime), but still, the wording "singleton typed array" is beyond me.
I got it. It's not "singleton-typed array", but "singleton typed-array". Bah. I find English to be a vague language at certain areas. Here you go, curious ones: Typed Arrays (MDN)

Java-based interpreter for JavaScript

As a project in school i have to make a JavaScript interpreter. (Everything incl. the entire backend has to be made by me).
Everything has to be written in Java - i use ANTLR for parsing and generating ASTs.
currently i can parse some .js code into an AST - and therefore need to translate this AST into som kind of intermediate-representation that can be executed on a bytecode machine.
I have some experience writing compilers for statically typed languages, but im very much in doubt how to proceed from here since JS is a dynamically typed language.
If you can give me some good advices on how to proceed i would be gratefull!
Personally i think i have to make the bytecode-machine first and then make the IR fit this machine afterwards. Unfortunatly i cant really find any good tutorials on how to write a bytecode-machine.
PS. im familiar with following books on the topic :
"modern compiler implementation in Java (Appel)",
"Programming language processors in Java (Watt & Brown)",
"Language implementation patterns (Parr)"
Regards Sune
If you only want to execute the javascript you do not need to transform the AST into IR and then into (some?) bytecode that would also force you to do a bytecode executer.
Why not just execute the javascript AST in a java "engine"? You can store all values as a Map<String, Object> and interpret them as you walk the AST. A new function get an environment/context (a new Map<...>).
If you cannot find a value in the current context you will have to fall back on the global context (=Map).
For the "dynamic" behaviour: If you need an double for an addition you only parse the Object.toString() value to an double using the standard way (more dynamic than that is hard to get :) ):
String value = contextMap.get(key);
Double dvalue = Double.parseDouble(value.toString());
....

Is metaprogramming possible in Javascript?

During my routine work, i happened to write the chained javascript function which is something like LINQ expression to query the JSON result.
var Result = from(obj1).as("x").where("x.id=5").groupby("x.status").having(count("x.status") > 5).select("x.status");
It works perfectly and give the expected result.
I was wondering this looks awesome if the code is written like this (in a more readable way)
var Result = from obj1 as x where x.status
groupby x.status having count(x.status) > 5
select x.status;
is there a way to achieve this??
Cheers
Ramesh Vel
No. JavaScript doesn't support this.
But this looks quite good too:
var Result = from(obj1)
.as("x")
.where("x.id=5")
.groupby("x.status")
.having(count("x.status") > 5)
.select("x.status");
Most people insist on trying to metaprogram from inside their favorite language. That doesn't work if the language doesn't support metaprogramming well; other answers have observed that JavaScript does not.
A way around this is to do metaprogramming from outside the language, using
program transformation tools. Such tools can parse source code, and carry out arbitrary transformations on it (that's what metaprogramming does anyway) and then spit the revised program.
If you have a general purpose program transformation system, that can parse arbitrary languages, you can then do metaprogramming on/with whatever language you like. See our DMS Software Reengineering Toolkit for such a tool, that has robust front ends for C, C++, Java, C#, COBOL, PHP, and ECMAScript and a number of other programming langauges, and has been used for metaprogramming on all of these.
In your case, you want to extend the JavaScript grammar with new syntax for SQL queries, and then transform them to plain JavaScript. (This is a lot like Intentional Programming)
DMS will easily let you build a JavaScript dialect with additional rules, and then you can use its program transformation capabilities to produce the equivalent standard Javascript.
Having said, that, I'm not a great fan of "custom syntax for every programmer on the planet" which is where Intentional Programming leads IMHO.
This is a good thing to do if there is a large community of users that would find this valuable. This idea may or may not be one of them; part of the problem is you don't get to find out without doing the experiment, and it might fail to gain enough social traction to matter.
although not quite what you wanted, it is possible to write parsers in javascript, and just parse the query (stored as strings) and then execute it. e.g.,using libraries like http://jscc.jmksf.com/ (no doubt there are others out there) it shouldnt be too hard to implement.
but what you have in the question looks great already, i m not sure why you'd want it to look the way you suggested.
Considering that this question is asked some years ago, I will try to add more to it based on the current technologies.
As of ECMAScript 6, metaprogramming is now supported in a sense via Symbol, Reflect and Proxy objects.
By searching on the web, I found a series of very interesting articles on the subject, written by Keith Kirkel:
Metaprogramming in ES6: Symbols and why they're awesome
In short, Symbols are new primitives that can be added inside an object (without practically being properties) and are very handy for passing metaprogramming properties to it among others. Symbols are all about changing the behavior of existing classes by modifying them (Reflection within implementation).
Metaprogramming in ES6: Part 2 - Reflect
In short, Reflect is effectively a collection of all of those “internal methods” that were available exclusively through the JavaScript engine internals, now exposed in one single, handy object. Its usage is analogous to the Reflection capabilities of Java and C#. They are used to discover very low level information about your code (Reflection through introspection).
Metaprogramming in ES6: Part 3 - Proxies
In short, Proxies are handler objects, responsible for wrapping objects and intercepting their behaviors through traps (Reflection through intercession).
Of course, these objects provide specific metaprogramming capabilities, much more restrictive compared to metaprogramming languages, but still can provide handy ways of basic metaprogramming, mainly through Reflection practices, in fact.
In the end, it is worth mentioning that there is some worth-noticing ongoing research work on staged metaprogramming in JavaScript.
Well, in your code sample:
var Result = from(obj1)
.as("x")
.where("x.id=5")
.groupby("x.status")
.having(count("x.status") > 5)
.select("x.status");
The only problem I see (other than select used as an identifier) is that you embed a predicate as a function argument. You'd have to make it a function instead:
.having(function(x){ return x.status > 5; })
JavaScript has closures and dynamic typing, so you can do some really nifty and elegant things in it. Just letting you know.
In pure JS no you can not. But with right preprocessor it is possible.
You can do something similar with sweet.js macros or (God forgive me) GPP.
Wat you want is to change the javascript parser into an SQL parser. It wasn't created to do that, the javascript syntax doesn't allow you to.
What you have is 90% like SQL (it maps straight onto it), and a 100% valid javascript, which is a great achievement. My answer to the question in the title is: YES, metaprogramming is possible, but NO it won't give you an SQL parser, since it's bound to use javascript grammar.
Maybe you want something like JSONPath if you've got JSON data. I found this at http://www.json.org/. Lots of other tools linked to from there if it's not exactly what you need.
(this is being worked on as well: http://docs.dojocampus.org/dojox/json/query)

How to do localizable javascript?

I have a web application that uses TONS of javascript, and as usual, there are a lot of textual constants that will be displayed to the user embedded in the code itself.
What do you think is the best way to make this localizable?
I know I need to take those strings off of the code and replace them with constants, which will be defined into some external place.
For the server side, ASP.Net provides some very neat capabilities for dealing with this.
What's the best to do this in Javascript?
The best idea I have is to have a JS file with ALL the string constants of the JS of the site (i'd have different copies of this, for each language), and then on each page, I include this script first, before all the others.
This seems like the most centralized way, that also wastes the least bandwidth.
Are there any other better approaches?
Thanks!
here's how we did it (in ASP.net), pretty much along the lines of what you've mentioned:
1) Created two javascript files: one which defines all javascript functions/DOM manipulations as required by the site, and, second called Messages.js: this defines all the string literals that need to be localized, something like var ALERT_MSG = "Alert message in english".
2) Created different version of the Messages.js, one for each locale that we are supporting and localized the strings. The localized js files were named using messages.locale.js naming convention (for eg. messages.fr-FR.js).
3) Included the js files within the "ScriptManager" and provided the ResourceUICultures for the Messages.js file: this ensures that the correct localized file is embedded in the html output (if you are not using ASP.net you can build this basic functionality by doing some culture sniffing and including the appropriate js file).
4) Voila!
Your approach makes sense. Details:
I'd have the strings for each language in an object.
localized={"cat":"chat","dog":"chien"};
Then in code:
localized["cat"]
The quotations around of the keys and the array notation (rather than the more common object dot notation) are to avoid collisions with JavaScript reserved words.
There is a gettext library but I haven't used it.
Your approach sounds good enough.
If you have lots of strings and you are concerned about the bulkiness of the file you may want to consider a script that creates a single javascript file for each language by concatenating the code javascript and the locale javascript and then applying something like Minify.
You'll waste some CPU cycles on publishing but you'll save some round trips...
There's a library for localizing JavaScript applications: https://github.com/wikimedia/jquery.i18n
The strings are stored in JSON files, as pretty much everybody else suggests, but it has a few more features:
It can do parameter replacement, supports gender (clever he/she handling), number (clever plural handling, including languages that have more than one plural form), and custom grammar rules that some languages need.
The only requirement is jQuery.

Categories