Thursday, May 6, 2010

Processing.js casting bug

I have been working on processing.js bug #625.

What's happening is there is some Java like code, that's being converted into JavaScript, so it can be run in a browser, and this bug deals with converting cast like syntax in java, into something usable in JavaScript.

JavaScript is typeless, what is important about this is the types between variables don't matter (for the most part) so when I create a variable of an int, I just create a variable, and make it an int, and if I need to know the type of the variable, I can check the type of what's in the variable, which would be an int. Looking at p5 append(), is what the cast is being used for in this bug.

"When using an array of objects, the data returned from the function must be cast to the object array's data type. For example: SomeClass[] items = (SomeClass[]) append(originalArray, element)."

In pjs, I don't think the cast is even needed, as append just returns an array, this is the pjs append code:


p.append = function(array, element) {
array[array.length] = element;
return array;
};


Maybe p5 (the Java version of processing) has append returning an array list, which would require the cast.

Either way, JavaScript does not need the cast.

I removed the cast in the example, and it works, but the problem still remains with parsing the cast, as it's valid code. In p5 the cast still needs to be handled by the parser, cannot just remove it. There is a way to do this currently in the parser, but it will only parse out classes inside a list.

One thing I could do is add "PVector" to the list of classes, which currently looks like this:


var classes = ["int", "float", "boolean", "String", "byte", "double", "long", "ArrayList"];


then in this code:


// Remove Casting
aCode = aCode.replace(new RegExp("\\((" + classes.join("|") + ")(\\[\\])*\\)", "g"), "");


It would find PVector, and remove the cast, without hurting anything else. Only problem I see in this is we'll have to add each and every pjs class to the list of classes, and if a new class is added to pjs, someone will have to remember to add the class to the list of classes. There must be a more dynamic way to accomplish this, which is what I want.

I thought about possibly parsing any instance of \(/w+\) and check that the match in w+ is "typeof Object" or something along those lines. Then I could remove the list of classes all together. Yes, I will try that. Thanks for the help blog.

No comments:

Post a Comment