ANTLR4 JavaScript Target very slow - javascript

I'm currently developing an ANTLR4 javascript listener for this Grammar.
var _require = require;
var antlr = _require('./antlr4/index');
var javaLexer = _require('./generated/JavaLexer');
var javaParser = _require('./generated/JavaParser');
var javaListener = _require('./generated/JavaListener');
declare function require(name:string);
class CodeAnalysis {
input: String;
constructor(input:String) {
this.input = input;
this.antlrStack();
}
private antlrStack() {
console.log(this.input);
var chars = new antlr.InputStream(this.input);
var lexer = new javaLexer.JavaLexer(chars);
var tokens = new antlr.CommonTokenStream(lexer);
var parser = new javaParser.JavaParser(tokens);
var listener = new javaListener.JavaListener();
parser.buildParseTrees = true;
var tree = parser.compilationUnit();
antlr.tree.ParseTreeWalker.DEFAULT.walk(listener, tree);
}
public getInput() {
return this.input;
}
}
The problem is that the performance is very bad (takes over two min) with an input like this:
import codescape.Dogbot;
public class MyDogbot extends Dogbot{
public void run() {
turnLeft();
move();
}
}
The same grammar and the same listener in Java performs a lot faster (>2 sec).
Anybody an idea why? Or how to fix it?
Bruno

Related

Use the value of a variable in another file

Currently I am using protractor and using page object, so there is a file that I get the value of an element in a variable, but I need to call this value in another file.
vehiclePage.js
/*jshint esversion: 6 */
var basePage = require('./basePage.js');
var homePage = require('./homePage.js');
var VehiclePage = function() {
this.storeVehicleData = function() {
this.pessengersRuntValue = element(by.id('preview_ocupantes_runt')).getText();
};
};
VehiclePage.prototype = basePage; // extend basePage...
module.exports = new VehiclePage();
Now I need to use the value of the above variables in another file
checkoutPage.js
/*jshint esversion: 6 */
var basePage = require('./basePage.js');
var homePage = require('./homePage.js');
var CheckoutPage = function() {
this.getRuntValue = element(by.css('.mb10'));
this.compareValues = function() {
expect(this.getRuntValue.getText()).toContain(this.pessengersRuntValue);
};
};
CheckoutPage.prototype = basePage; // extend basePage...
module.exports = new CheckoutPage();
How can I make it work?
If you are following Page Object Design Pattern, I would say that the test should not be on the page object. I will write something like this.
VehiclePage.js
var VehiclePage = function(){
// if this is a browser testing something like this
browser.get('/vehicle');
};
VehiclePage.prototype = Object.create({}, {
runt: {
get: function(){
return element(by.id('preview_ocupantes_runt'));
}
}
});
module.export = VehiclePage;
CheckOutPage.js
var CheckOutPage = function(){
// if this is a browser testing something like this
browser.get('/checkout');
};
CheckOutPage.prototype = Object.create({}, {
runt: {
get: function(){
return element(by.css('.mb10'));
}
}
});
module.export = CheckOutPage;
TheTest.js
var VehiclePage = require('VehiclePage');
var CheckOutPage = require('CheckOutPage');
describe('testing something', () => {
var vehicle = new VehiclePage();
var checkout = new CheckOutPage();
it('should contain', () => {
expect(checkout.runt.getText()).toContains(vehicle.runt.getText());
});
});
One way to do this would be to pass a state object to both pages.
var VehiclePage = require('./vehiclePage.js');
var CheckoutPage = require('./checkoutPage.js');
class StateStorage {
constructor(){
this.savedVariable = null;
}
}
var state = new StateStorage();
var vehiclePage = new VehiclePage(state);
var checkoutPage = new CheckoutPage(state);
Then you can manipulate and access the state from both new pages.

how to do antlr rewriteTokenstream in javascript

I am trying to use antlr to generate javascript code. and use it to change the tokens (nodes) in my grammer.
I am able to visit the nodes , enter the node and print the value, or exit the node and print the node value.
I want to replace a token of a node if it is a expression.
like if expression is a+1 , I want to replace the expression to replacedString+1
/**
* #author:saurabh
* sample programme to run the parser for a sample string using antlr
*/
/**
* dependency injection
*/
var antlr4 = require('antlr4/index');
var helloListener = require('./helloListener').helloListener;
var helloLexer = require('./helloLexer');
var helloParser = require('./helloParser');
var helloVisitor = require('./helloVisitor').helloVisitor;
var toRun = function (ruleForEnterAndExitOverride,ruleForgeneratiingTree, inputExpressionString, changeTokenString) {
var chars = new antlr4.InputStream(inputExpressionString);
var lexer = new helloLexer.helloLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new helloParser.helloParser(tokens);
console.log(tokens)
//var visitor = new helloVisitor.helloVisitor();
parser.buildParseTrees = true;
var tree = parser.expression();
var keyPrinter = function () {
helloListener.call(this);
return this;
};
keyPrinter.prototype = Object.create(helloListener.prototype);
keyPrinter.prototype.constructor = keyPrinter;
//visitor
var keyVisitor = function(){
helloVisitor.call(this);
return this;
}
keyVisitor.prototype = Object.create(helloVisitor.prototype);
keyVisitor.prototype.constructor = keyVisitor;
//var tree1 = parser.prog();
//override funciton
keyPrinter.prototype["enter" + ruleForEnterAndExitOverride] = function (ctx) {
//var newVal = ctx.getText().replace(ctx.getText(),changeTokenString);
console.log("enter"+ctx.getText());
console.log("enter",ctx.start,ctx.end)
//console.log(ctx.quotedIdentifier())
return "hi";
}
keyPrinter.prototype["exit"+ ruleForEnterAndExitOverride] = function (ctx) {
//var newVal = ctx.getText().replace(ctx.getText(),changeTokenString);
console.log("exit"+ctx.getText());
}
keyVisitor.prototype["visit"+ruleForEnterAndExitOverride] = function(ctx){
console.log("visit"+ctx.getText())
//var newString = ctx.getText().replace(ctx.getText(),changeTokenString);
//return newString;
//console.log(ctx)
}
var visitor = new keyVisitor();
var test = visitor["visit"+ruleForEnterAndExitOverride](tree);
var printer = new keyPrinter();
antlr4.tree.ParseTreeWalker.DEFAULT.walk(printer, tree);
//console.log("out",test)
}
/**
* #param: ruleFor appending to the listner funciton (starts with capital character of rule name)
* #param: rule name to generate tree. without any change
* #param: expression to test
* #param: new value to be replaced from the #param3 expression
*/
toRun("QuotedIdentifier","quotedIdentifier", "`a`+1", "p");
in java doc of antlr its mentioned to use rewritabletokenstreem but I am not able to find a way to do the same in javascript.
Please help

Javascript Class Definition with Array Member

I wrote the code in Java, no problem. Here I am giving the Java code:
public class CarGallery {
static int carCounter=10;
static Gallery[] car = new Gallery[carCounter];
public static void main(String[] args) {
car[0].weight = (float) 1.25;
car[0].weight = (float) 0.87;
// ... and so on ... //
}
}
class Gallery {
public float weight;
public float height;
public int colorCode;
public int stockGallery;
};
The thing is, I want to write the same code in Javascript. Here is the code that does not work:
var cars = {weight:0 , height:0 , stock:0 , model:"..."};
var cars = new Array();
cars[0].weight=1.2;
cars[0].height=0.87;
cars[0].stock=2;
cars[0].model="320";
I read some documents and saw that there is no class definition in Javascript like Java classes.
I found class definition in JS with constructors, but I don't want to use constructors.
The member should be defined as array like:
static Gallery[] car = new Gallery[carCounter];
Thank you for your help!
The JavaScript equivalent to your Java would be.
function Gallery() {
this.weight = null;
this.height = null;
this.colorCode = null;
this.stockGallery = null;
};
var carCounter = 10;
var carGallery = new Array(carCounter);
carGallery[0] = new Gallery();
carGallery[0].weight = 1.2;
carGallery[0].height = 0.87;
carGallery[0].colorCode = 2
carGallery[0].stockGallery = 3;
carGallery[1] = new Gallery();
carGallery[1].weight = 2.2;
...

AS3: How do I get dynamic loader URL from LoaderInfo in Event Listener Function?

I'm loading many pictures, and am using an array to do so.
loader[i].load(new URLRequest(picture[i]));
My Event Listener function is enabled like this:
loader[i].contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
My onComplete event handler shows this:
trace(e.target); //OUTPUT: [object LoaderInfo]
I've looked for properties in LoaderInfo that might identify which loader initiated the listener (the value of "i") so that I can putz around with each one specifically, like this:
bitmapDataArr[i] = e.target.content.bitmapData;
bmVisArr[i] = new Bitmap(bitmapDataArr[i]);
But cannot determine which "i" initiated the specific instance of the listener.
Any ideas? I tried giving a name to LoaderInfo to no avail. I still can't extract the pesky little identifying number.
EDIT showing loop for loaders and onComplete function:
for (i = 0; i < 10; i++) {
loader[i] = new Loader();
loader[i].contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
loader[i].load(new URLRequest(letter[i]));
}
private function onComplete(e:Event):void {
trace("e.target",e.target); //OUTPUT: e.target [object LoaderInfo]
var LI:LoaderInfo = e.target as LoaderInfo;
var eNum:int = (????);
bitmapDataArr[eNum] = e.target.content.bitmapData;
bmVisArr[eNum] = new Bitmap(bitmapDataArr[eNum]);
}
You'll somehow need to bring i value to onComplete function. For example, in the this context or thru an argument.
P.S.: It's easier to use weak ref. Dictionaries instead of deleting properties, though I don't know much about AS3.
Here's an example that also shows how to remove the event listeners (including their callback functions):
/* An object containing callback
* functions used along with event listeners.
*/
const callbacks: Object = {};
/* This function will re-declare and hoist i
* in itself. */
private function loop(i: uint): void {
loader[i] = new Loader;
const wrapped =
callbacks[i] = function wrapper(...args) {
// Pass all arguments (respectively event and i)
onComplete.apply(null, args);
// Function#apply(thisContext, arguments)
// Rest exp. isn't implemented yet, else we could just do:
// onComplete(...args);
};
loader[i].contentLoaderInfo
.addEventListener(Event.COMPLETE, wrapped, false,
0, true);
loader[i].load(new URLRequest(letter[i]));
};
for (var i: uint = 0; i < 10; ++i) loop(i);
private function onComplete(e: Event, i: uint): void {
const loaderInfo: LoaderInfo = e.target as LoaderInfo;
bitmapDataArr[i] = e.target
.content.bitmapData;
bmVisArr[i] = new Bitmap(bitmapDataArr[i]);
loader[i].contentLoaderInfo
.removeEventListener(
Event.COMPLETE, callbacks[i]
);
// Deletes the property that stores
// the function inside callbacks
delete callbacks[i];
}
Since posting this question, I've been utilizing the following class. It takes in an integer (number pictures to load) and gives public access to an array of Sprites in the Array "ShapeArr."
Each sprite's name property is derived from its URL name. (name:"pic1" from loaded url "assets/pic1.png")
I was having trouble with the whole concept/implementation of inline functions, and have been using this approach instead.
package {
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.display.Sprite;
import flash.events.Event;
public class MultipleImageLoader extends Sprite {
{private var pic:Array = [
"assets/pic1.png", "assets/pic2.png", "assets/pic3.png", "assets/pic4.png",
]}
private var loader:Array = [];
public var ShapeArr:Array = [];
public var bitmapDataArr:Array = [];
public var bmVisArr:Array = [];
private var shapeText:Array = [];
private var picArray:Array = [];
private var count:int = 0;
private var loaderCounter:int = 0;
private var numPicsToLoad:int;
private var a:String;
public var loaded:Boolean = false;
public function MultipleImageLoader(numPics:int):void {
numPicsToLoad = numPics;
loaded = false;
init();
}
private function init(e:Event = null):void {
if (hasEventListener(Event.ADDED_TO_STAGE)) {
removeEventListener(Event.ADDED_TO_STAGE, init);
}
picArray = new Array;
for (var i:int = 0; i < numPicsToLoad; i++) {
picArray.push(i);
}
initiateLoaders();
}
private function initiateLoaders():void{
loader[loaderCounter] = new Loader;
loader[loaderCounter].contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
a = pic[picArray[loaderCounter]];
//trace("shapecolor load:", a);
shapeText[loaderCounter] = (a.substr(16, a.length - 20));
loader[loaderCounter].load(new URLRequest(a ) );
}
private function onComplete(e:Event):void {
//trace("sssssssssssssssssssssssssshapecolor");
bitmapDataArr[loaderCounter] = e.target.content.bitmapData;
bmVisArr[loaderCounter] = new Bitmap(bitmapDataArr[loaderCounter]);
bmVisArr[loaderCounter].scaleX = .1;
bmVisArr[loaderCounter].scaleY = .1;
bmVisArr[loaderCounter].x =-bmVisArr[loaderCounter].width / 2;
bmVisArr[loaderCounter].y =-bmVisArr[loaderCounter].height / 2;
ShapeArr[loaderCounter] = new Sprite();
ShapeArr[loaderCounter].name = a.substr(7,4);
trace("Name",loaderCounter,ShapeArr[loaderCounter].name );
ShapeArr[loaderCounter].addChild(bmVisArr[loaderCounter]);
loader[loaderCounter].contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
if (loaderCounter <numPicsToLoad-1) {
loaderCounter += 1;
initiateLoaders();
}
//trace("gonna count",count);
counting();
count += 1;
}
private function counting():void {
trace("tile count", count,numPicsToLoad);
if (count < numPicsToLoad-1) {
return;
}
else{
removeEventListener(Event.ENTER_FRAME, counting);
loaded = true;
count = 0;
trace("All Images LOADED");
}
}
}//end Class
}//end Package

Detect lock screen or running screensaver with Firefox/OS X

I'm creating an extension for Firefox (SDK Add-on) in which I'll need to detect screensaver and lock-screen events so that I can set a user's availability status in a web-app.
I've managed to do this already for Windows and now need to port to OS X. For the Windows version, I was using calls to native API to find out if screen was locked, etc. Is there a similar way of getting OS information from a Firefox extension on OS X? I've tried Googling this and haven't found a solid answer - any help appreciated!
On OSX you can query a locked screen/screensaver using CGSessionCopyCurrentDictionary and looking for the presence and value of the "CGSSessionScreenIsLocked" key.
This is platform API, so one will have to use js-ctypes again and write a bunch of code to get that working.
I did get it working: The following code is a working example you can run in a privileged Scratchpad. To get a privileged one, open a pad for e.g. about:newtab.
Components.utils.import("resource://gre/modules/ctypes.jsm");
var CoreFoundation = new (function() {
this.CFNumberRef = ctypes.voidptr_t;
this.CFStringRef = ctypes.voidptr_t;
this.CFDictionaryRef = ctypes.voidptr_t;
var lib = ctypes.open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");
this.CFRelease = lib.declare(
"CFRelease",
ctypes.default_abi,
ctypes.void_t,
ctypes.voidptr_t);
var CFStringCreateWithCharacters = lib.declare(
"CFStringCreateWithCharacters",
ctypes.default_abi,
this.CFStringRef,
ctypes.voidptr_t,
ctypes.jschar.ptr,
ctypes.int32_t);
this.CFStringCreateWithCharacters = function(str) {
var rv = CFStringCreateWithCharacters(null, str, str.length);
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, this.CFRelease);
};
var CFDictionaryGetValue = lib.declare(
"CFDictionaryGetValue",
ctypes.default_abi,
this.CFNumberRef,
this.CFDictionaryRef,
this.CFStringRef);
this.CFDictionaryGetInt = function(dict, str) {
var rv = CFDictionaryGetValue(dict, this.CFStringCreateWithCharacters(str));
if (!rv || rv.isNull()) {
return null;
};
return this.CFNumberGetValue(rv);
};
var CFNumberGetValue = lib.declare(
"CFNumberGetValue",
ctypes.default_abi,
ctypes.bool,
this.CFNumberRef,
ctypes.int32_t,
ctypes.int32_t.ptr);
this.CFNumberGetValue = function(num) {
var rv = new ctypes.int32_t();
CFNumberGetValue(num, 3, rv.address());
console.log("CFNumberGetValue", rv, rv.value);
return rv.value;
};
this.close = function() {
lib.close();
};
})();
var ApplicationServices = new (function() {
var lib = ctypes.open("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices");
var CGSessionCopyCurrentDictionary = lib.declare(
"CGSessionCopyCurrentDictionary",
ctypes.default_abi,
CoreFoundation.CFDictionaryRef);
this.CGSessionCopyCurrentDictionary = function() {
var rv = CGSessionCopyCurrentDictionary();
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, CoreFoundation.CFRelease);
};
this.close = function() {
lib.close();
};
})();
setInterval(function() {
var dict = ApplicationServices.CGSessionCopyCurrentDictionary();
if (dict) {
var locked = CoreFoundation.CFDictionaryGetInt(dict, "CGSSessionScreenIsLocked");
console.log("rv", locked);
if (locked) {
// do something;
}
}
}, 500);

Categories