Strict mode blows up on safari because jison has inline functions defined, this removes jison in favor of acorn
Yay! Less technical debt!
This commit is contained in:
Robert Plummer 2017-07-21 18:22:32 -04:00
parent 6a51f23cf5
commit d81271fb6b
15 changed files with 3301 additions and 62400 deletions

View File

@ -1,7 +1,3 @@
{
"presets": ["env"],
"ignore": [
"./src/core/parser.js",
"./src/jison/**.jison"
]
"presets": ["env"]
}

View File

@ -5,7 +5,7 @@
* GPU Accelerated JavaScript
*
* @version 0.0.0
* @date Thu Jul 20 2017 22:09:33 GMT+0530 (IST)
* @date Fri Jul 21 2017 18:16:59 GMT-0400 (EDT)
*
* @license MIT
* The MIT License

32275
bin/gpu.js

File diff suppressed because one or more lines are too long

View File

@ -1,232 +0,0 @@
if (!Object.keys) {
Object.keys = function (object) {
var keys = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
keys.push(name);
}
}
return keys;
};
}
if (!Object.defineProperty)
Object.defineProperty = function(object, property, descriptor) {
var has = Object.prototype.hasOwnProperty;
if (typeof descriptor == "object") {
if (has.call(descriptor, "value")) {
if (!object.__lookupGetter__(property) && !object.__lookupSetter__(property))
// data property defined and no pre-existing accessors
object[property] = descriptor.value;
if ((has.call(descriptor, "get") || has.call(descriptor, "set")))
// descriptor has a value property but accessor already exists
throw new TypeError("Object doesn't support this action");
}
if ( // can't implement these features; allow false but not true
!(has.call(descriptor, "writable") ? descriptor.writable : true) ||
!(has.call(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(has.call(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
else if (typeof descriptor.get == "function")
object.__defineGetter__(property, descriptor.get);
if (typeof descriptor.set == "function")
object.__defineSetter__(property, descriptor.set);
}
return object;
};
if (!Object.defineProperties) {
Object.defineProperties = function(object, properties) {
for (var property in properties) {
if (Object.prototype.hasOwnProperty.call(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
if (!Object.create) {
Object.create = function(prototype, properties) {
function Type() {};
Type.prototype = prototype;
var object = new Type();
if (typeof properties !== "undefined")
Object.defineProperties(object, properties);
return object;
};
}
// ES5 15.5.4.20
if (!String.prototype.trim) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
String.prototype.trim = function () {
return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
};
}
// Array additions.
// ES5 draft:
// http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
// ES5 15.4.3.2
if (!Array.isArray) {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
}
// ES5 15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(block, thisObject) {
var len = this.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in this) {
block.call(thisObject, this[i], i, this);
}
}
};
}
// ES5 15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
// filter
if (!Array.prototype.filter) {
Array.prototype.filter = function (block /*, thisp */) {
var values = [];
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (block.call(thisp, this[i]))
values.push(this[i]);
return values;
};
}
// every
if (!Array.prototype.every) {
Array.prototype.every = function (block /*, thisp */) {
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (!block.call(thisp, this[i]))
return false;
return true;
};
}
// some
if (!Array.prototype.some) {
Array.prototype.some = function (block /*, thisp */) {
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (block.call(thisp, this[i]))
return true;
return false;
};
}
// reduce
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(fun /*, initial*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
} while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
// reduceRight
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function(fun /*, initial*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value, empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = len - 1;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError();
} while (true);
}
for (; i >= 0; i--) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,334 +0,0 @@
/*jslint evil: true, strict: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON) {
this.JSON = {};
}
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());

View File

@ -1,142 +0,0 @@
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
'use strict';
const utils = require('../core/utils');
const parser = require('../core/parser').parser;
const acorn = require('acorn');
module.exports = class BaseFunctionNode {
@ -209,18 +209,18 @@ module.exports = class BaseFunctionNode {
return this.jsFunctionAST;
}
inParser = inParser || parser;
inParser = inParser || acorn;
if (inParser === null) {
throw 'Missing JS to AST parser';
}
const prasedObj = parser.parse('var ' + this.functionName + ' = ' + this.jsFunctionString + ';');
if (prasedObj === null) {
throw 'Failed to parse JS code via JISON';
const ast = inParser.parse('var ' + this.functionName + ' = ' + this.jsFunctionString + ';');
if (ast === null) {
throw 'Failed to parse JS code';
}
// take out the function object, outside the var declarations
const funcAST = prasedObj.body[0].declarations[0].init;
const funcAST = ast.body[0].declarations[0].init;
this.jsFunctionAST = funcAST;
return funcAST;

View File

@ -241,8 +241,8 @@ module.exports = class WebGLFunctionNode extends FunctionNodeBase {
retArr.push(') {\n');
// Body statement iteration
for (let i = 0; i < ast.body.length; ++i) {
this.astGeneric(ast.body[i], retArr, funcParam);
for (let i = 0; i < ast.body.body.length; ++i) {
this.astGeneric(ast.body.body[i], retArr, funcParam);
retArr.push('\n');
}
@ -481,15 +481,15 @@ module.exports = class WebGLFunctionNode extends FunctionNodeBase {
return retArr;
} else {
retArr.push('for (float ');
retArr.push('for (');
if (!Array.isArray(forNode.init) || forNode.init.length < 1) {
if (!Array.isArray(forNode.init.declarations) || forNode.init.declarations.length < 1) {
console.log(this.jsFunctionString);
throw new Error('Error: Incompatible for loop declaration');
}
this.astGeneric(forNode.init, retArr, funcParam);
retArr.push(';');
//retArr.push(';');
this.astGeneric(forNode.test, retArr, funcParam);
retArr.push(';');
this.astGeneric(forNode.update, retArr, funcParam);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1928
src/jison/grammar.jison vendored

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GPU.JS : FunctionBuilder unit testing</title>
<link rel="stylesheet" href="../../../node_modules/qunitjs/qunit/qunit.css">
<!-- gpu.js scripts -->
<script src="../../../bin/gpu.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="../../../node_modules/qunitjs/qunit/qunit.js"></script>
<script src="../../../node_modules/qunit-assert-close/qunit-assert-close.js"></script>
<script src="../../src/issues/31-nested-var-declare-test.js"></script>
</body>
</html>

View File

@ -1,28 +1,28 @@
QUnit.test( "Issue #116 - multiple kernels run again", function() {
const gpu = new GPU({mode: 'webgl'});
const A = [1, 2, 3, 4, 5];
const B = [1, 2, 3, 4, 5];
const sizes = [2, 5, 1];
var gpu = new GPU({mode: 'webgl'});
var A = [1, 2, 3, 4, 5];
var B = [1, 2, 3, 4, 5];
var sizes = [2, 5, 1];
function add(a, b, x){
return a[x] + b[x];
}
const layerForward = [];
var layerForward = [];
for (let i = 0; i < 2; i++) {
const kernels = gpu.createKernelMap([add],function(a, b){
for (var i = 0; i < 2; i++) {
var kernels = gpu.createKernelMap([add],function(a, b){
return add(a,b, gpu_threadX);
}).setDimensions([sizes[i + 1]]); // First: 5. Second: 1.
layerForward.push(kernels);
}
const E = layerForward[0](A, B).result;
const F = layerForward[1](A, B).result;
const G = layerForward[0](A, B).result;
var E = layerForward[0](A, B).result;
var F = layerForward[1](A, B).result;
var G = layerForward[0](A, B).result;
QUnit.assert.deepEqual(QUnit.extend([], E), [2, 4, 6, 8, 10]);
QUnit.assert.deepEqual(QUnit.extend([], F), [2]);