2018-06-26 12:34:11 -04:00
|
|
|
import {NetscriptFunctions} from "./NetscriptFunctions";
|
|
|
|
import {NetscriptPort} from "./NetscriptPort";
|
2018-03-03 15:05:33 -06:00
|
|
|
|
2016-11-17 16:25:40 -06:00
|
|
|
/* Environment
|
2017-08-30 12:44:29 -05:00
|
|
|
* NetScript program environment
|
2016-11-17 16:25:40 -06:00
|
|
|
*/
|
2017-06-28 11:47:42 +02:00
|
|
|
function Environment(workerScript,parent) {
|
|
|
|
if (parent){
|
2017-10-01 21:35:22 -05:00
|
|
|
//Create a copy of parent's variables
|
|
|
|
//this.vars = parent.vars;
|
|
|
|
this.vars = Object.assign({}, parent.vars);
|
2017-06-28 11:47:42 +02:00
|
|
|
} else {
|
|
|
|
this.vars = NetscriptFunctions(workerScript);
|
|
|
|
}
|
2016-11-17 16:25:40 -06:00
|
|
|
this.parent = parent;
|
2016-12-06 10:59:20 -06:00
|
|
|
this.stopFlag = false;
|
2016-11-17 16:25:40 -06:00
|
|
|
}
|
|
|
|
Environment.prototype = {
|
|
|
|
//Create a "subscope", which is a new new "sub-environment"
|
|
|
|
//The subscope is linked to this through its parent variable
|
|
|
|
extend: function() {
|
2017-09-29 10:02:33 -05:00
|
|
|
return new Environment(null, this);
|
2016-11-17 16:25:40 -06:00
|
|
|
},
|
2017-08-30 12:44:29 -05:00
|
|
|
|
2016-11-17 16:25:40 -06:00
|
|
|
//Finds the scope where the variable with the given name is defined
|
|
|
|
lookup: function(name) {
|
|
|
|
var scope = this;
|
|
|
|
while (scope) {
|
2017-10-01 21:35:22 -05:00
|
|
|
if (Object.prototype.hasOwnProperty.call(scope.vars, name)) {
|
2016-11-17 16:25:40 -06:00
|
|
|
return scope;
|
2017-10-01 21:35:22 -05:00
|
|
|
}
|
2016-11-17 16:25:40 -06:00
|
|
|
scope = scope.parent;
|
|
|
|
}
|
2017-10-01 21:35:22 -05:00
|
|
|
return null;
|
2016-11-17 16:25:40 -06:00
|
|
|
},
|
2017-08-30 12:44:29 -05:00
|
|
|
|
2016-11-17 16:25:40 -06:00
|
|
|
//Get the current value of a variable
|
|
|
|
get: function(name) {
|
2017-05-29 17:37:38 -05:00
|
|
|
if (name in this.vars) {
|
2016-11-17 16:25:40 -06:00
|
|
|
return this.vars[name];
|
2017-05-29 17:37:38 -05:00
|
|
|
}
|
2016-11-17 16:25:40 -06:00
|
|
|
throw new Error("Undefined variable " + name);
|
|
|
|
},
|
2017-08-30 12:44:29 -05:00
|
|
|
|
2016-11-17 16:25:40 -06:00
|
|
|
//Sets the value of a variable in any scope
|
|
|
|
set: function(name, value) {
|
|
|
|
var scope = this.lookup(name);
|
2017-10-01 21:35:22 -05:00
|
|
|
|
|
|
|
//If scope has a value, then this variable is already set in a higher scope, so
|
|
|
|
//set is there. Otherwise, create a new variable in the local scope
|
|
|
|
if (scope !== null) {
|
|
|
|
return scope.vars[name] = value;
|
|
|
|
} else {
|
|
|
|
return this.vars[name] = value;
|
2017-05-29 17:37:38 -05:00
|
|
|
}
|
2016-11-17 16:25:40 -06:00
|
|
|
},
|
2017-08-30 12:44:29 -05:00
|
|
|
|
2016-11-17 16:25:40 -06:00
|
|
|
//Creates (or overwrites) a variable in the current scope
|
|
|
|
def: function(name, value) {
|
|
|
|
return this.vars[name] = value;
|
2017-08-30 12:44:29 -05:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export {Environment};
|