| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375 |
- /**
- * SCCD runtime for JavaScript. Works with 'javascript' (browser) and 'nodejs' targets.
- * For browser, you can load the script in your HTML by adding a <script> tag.
- * For NodeJS, you can require() this file.
- */
- nextObjectId = 1;
- function objectId(obj) {
- if (obj == null) {
- return null;
- }
- if (obj.assignedObjectId == null) {
- obj.assignedObjectId = nextObjectId++;
- }
- return obj.assignedObjectId;
- }
- function time() {
- return (new Date).getTime();
- }
- function RuntimeException(msg) {
- this.msg = msg;
- }
- function InputException(msg) {
- RuntimeException.call(this, msg);
- }
- InputException.prototype = new RuntimeException();
- function AssociationException(msg) {
- RuntimeException.call(this, msg);
- }
- AssociationException.prototype = new RuntimeException();
- function AssociationReferenceException(msg) {
- RuntimeException.call(this, msg);
- }
- AssociationReferenceException.prototype = new RuntimeException();
- function ParameterException(msg) {
- RuntimeException.call(this, msg);
- }
- ParameterException.prototype = new RuntimeException();
- function EventQueueEntry(scheduledTime, theEvent, instances) {
- if (!(instances instanceof Array)) {
- throw new Error("Must be array")
- }
- this.scheduledTime = scheduledTime;
- this.theEvent = theEvent;
- this.instances = instances; // list of instances to receive the event
- }
- function EventQueue() {
- this.eventList = [];
- this.sortFunction = function (a, b) {
- return a.scheduledTime - b.scheduledTime
- }
- }
- EventQueue.prototype.isEmpty = function () {
- return this.eventList.length === 0;
- };
- EventQueue.prototype.getEarliestTime = function () {
- if (this.isEmpty()) {
- return Infinity;
- } else {
- return this.eventList[0].scheduledTime;
- }
- };
- EventQueue.prototype.add = function (theEvent) {
- this.eventList.push(theEvent);
- this.eventList.sort(this.sortFunction);
- return objectId(theEvent);
- };
- EventQueue.prototype.remove = function (eventId) {
- this.eventList = this.eventList.filter(function (el) {
- return objectId(el) !== eventId;
- }).sort()
- }
- EventQueue.prototype.pop = function () {
- return this.eventList.shift()
- };
- function Association(toClass, minCard, maxCard) {
- this.toClass = toClass;
- this.minCard = minCard;
- this.maxCard = maxCard;
- this.instances = {};
- this.size = 0;
- this.nextId = 0;
- }
- Association.prototype.allowedToAdd = function () {
- return (this.maxCard === -1 || this.size < this.maxCard);
- };
- Association.prototype.allowedToRemove = function () {
- return (this.minCard === -1 || this.size > this.minCard);
- };
- Association.prototype.addInstance = function (instance) {
- if (this.allowedToAdd()) {
- const id = this.nextId++;
- this.instances[id] = instance;
- return id;
- } else {
- throw new AssociationException('Not allowed to add the instance to the association.');
- }
- };
- Association.prototype.removeInstance = function (instance) {
- if (this.allowedToRemove()) {
- delete this.instances[this.instancesToIds[instance]]
- } else {
- throw new AssociationException('Not allowed to remove the instance to the association.');
- }
- };
- Association.prototype.getInstance = function (index) {
- const instance = this.instances[index];
- if (instance === undefined) {
- throw new AssociationException('Invalid index for fetching instance(s) from association.');
- }
- return instance;
- };
- function ObjectManagerBase(controller) {
- this.controller = controller;
- // this.events = new EventQueue();
- this.instances = [];
- // this.regex = /^([a-zA-Z_]\w*)(?:\[(\d+)])?$/;
- this.regex = /^([a-zA-Z_]\w*)(?:\[(\d+)\])?$/;
- }
- // ObjectManagerBase.prototype.addEvent = function (theEvent, timeOffset) {
- // if (timeOffset === undefined) timeOffset = 0;
- // this.events.add(new EventQueueEntry(this.controller.simulatedTime + timeOffset, theEvent));
- // };
- // ObjectManagerBase.prototype.broadcast = function (source, newEvent, timeOffset) {
- // if (timeOffset === undefined) timeOffset = 0;
- // for (let i in this.instances) {
- // if (!this.instances.hasOwnProperty(i) || i === source) continue;
- // this.instances[i].addEvent(newEvent, timeOffset);
- // }
- // };
- // ObjectManagerBase.prototype.getEarliestEventTime = function () {
- // let earliestTime = this.events.getEarliestTime();
- // for (let i in this.instances) {
- // if (!this.instances.hasOwnProperty(i)) continue;
- // earliestTime = Math.min(earliestTime, this.instances[i].earliestEventTime);
- // }
- // return earliestTime;
- // };
- // ObjectManagerBase.prototype.stepAll = function () {
- // this.step();
- // for (let i in this.instances) {
- // if (!this.instances.hasOwnProperty(i)) continue;
- // let instance = this.instances[i];
- // if (instance.active && (instance.getEarliestEventTime() <= this.controller.simulatedTime || instance.eventlessTransitions())) {
- // instance.step();
- // }
- // }
- // };
- // ObjectManagerBase.prototype.step = function () {
- // while (this.events.getEarliestTime() <= this.controller.simulatedTime) {
- // this.handleEvent(this.events.pop());
- // }
- // };
- ObjectManagerBase.prototype.initializeAll = function () {
- for (const i of this.instances) {
- i.initialize();
- }
- };
- ObjectManagerBase.prototype.performBigStep = function (eventList) {
- for (const e of eventList) {
- if (e.name === 'narrowCast') {
- this.handleNarrowCastEvent(e.parameters);
- } else if (e.name === 'broadCast') {
- this.handleBroadcastEvent(e.parameters);
- } else if (e.name === 'createInstance') {
- this.handleCreateEvent(e.parameters);
- } else if (e.name === 'associateInstance') {
- this.handleAssociateEvent(e.parameters);
- } else if (e.name === 'disassociateInstance') {
- this.handleDisassociateEvent(e.parameters);
- } else if (e.name === 'startInstance') {
- this.handleStartInstanceEvent(e.parameters);
- } else if (e.name === 'createAndStartInstance') {
- this.handleCreateAndStartEvent(e.parameters);
- } else if (e.name === 'deleteInstance') {
- this.handleDeleteInstanceEvent(e.parameters);
- }
- }
- };
- // just to comply with the RuntimeClassBase interface, ducktype-wise:
- ObjectManagerBase.prototype.processBigStepOutput = function () {
- }
- ObjectManagerBase.prototype.processAssociationReference = function (inputString) {
- if (inputString.length === 0) {
- throw new AssociationReferenceException('Empty association reference.');
- }
- const pathString = inputString.split('/');
- let result = [];
- if (inputString !== '') {
- for (let p in pathString) {
- if (!pathString.hasOwnProperty(p)) continue;
- var m = this.regex.exec(pathString[p]);
- if (m) {
- var name = m[1];
- var index = m[2];
- if (!index) {
- index = -1;
- }
- result.push({name: name, index: index});
- } else {
- throw new AssociationReferenceException('Invalid entry in association reference.');
- }
- }
- }
- return result;
- };
- ObjectManagerBase.prototype.handleStartInstanceEvent = function (parameters) {
- if (parameters.length !== 2) {
- throw new ParameterException('The start instance event needs 2 parameters.');
- }
- const source = parameters[0];
- const traversalList = this.processAssociationReference(parameters[1]);
- let instances = this.getInstances(source, traversalList);
- for (let i in instances) {
- if (!instances.hasOwnProperty(i)) continue;
- instances[i].instance.initialize();
- }
- source.addEvent(new Event("instanceStarted", parameters=[parameters[1]]));
- // ^ deprecated, will be replaced by:
- // this.controller.addInputLowLevel(
- // new Event("instanceStarted", null, [parameters[1]]),
- // [source],
- // 0);
- };
- ObjectManagerBase.prototype.handleBroadcastEvent = function (parameters) {
- if (parameters.length !== 2) {
- throw new ParameterException('The broadcast event needs 2 parameters (source of event and event name).');
- }
- this.controller.addInputLowLevel(
- paramaters[0],
- this.instances,
- this.controller.simulatedTime) // time offset
- // this.broadcast(parameters[0], parameters[1]);
- };
- ObjectManagerBase.prototype.handleCreateEvent = function (parameters) {
- if (parameters.length < 2) {
- throw new ParameterException('The create event needs at least 2 parameters.');
- }
- const source = parameters[0];
- const associationName = parameters[1];
- let association = source.associations[associationName];
- if (!association) {
- throw new ParameterException('No such association: ' + associationName);
- }
- if (association.allowedToAdd()) {
- // allow subclasses to be instantiated
- let className = undefined;
- let creationParameters = undefined;
- if (parameters.length === 2) {
- className = association.toClass;
- creationParameters = [];
- } else {
- // 3rd parameter is class name
- className = parameters[2];
- // parameters after 3rd parameter are creation parameters
- creationParameters = parameters.slice(3);
- }
- let newInstance = this.createInstance(className, creationParameters);
- if (newInstance === undefined) {
- throw new ParameterException('Creating instance: no such class: ' + className);
- }
- let index = association.addInstance(newInstance);
- // add parent association to created instance
- // if a parent association is defined in the class diagram
- let parentAssociation = newInstance.associations['parent'];
- if (parentAssociation !== undefined) {
- parentAssociation.addInstance(source);
- }
- // TODO: maybe change order of Event constructor parameters such that we don't have to
- // explicitly set the port to 'undefined'?
- source.addEvent(new Event('instanceCreated', undefined, [associationName + '[' + index + ']']));
- return [source, associationName + "[" + index.toString() + "]"];
- } else {
- source.addEvent(new Event('instanceCreationError', undefined, [associationName]));
- return [];
- }
- };
- ObjectManagerBase.prototype.handleCreateAndStartEvent = function (parameters) {
- params = this.handleCreateEvent(parameters);
- if (params) {
- this.handleStartInstanceEvent(params);
- }
- }
- ObjectManagerBase.prototype.handleDeleteInstanceEvent = function (parameters) {
- if (parameters.length !== 2) {
- throw new ParameterException('The delete instance event needs 2 parameters.');
- }
- const source = parameters[0];
- const traversalList = this.processAssociationReference(parameters[1]);
- let instances = this.getInstances(source, traversalList);
- for (let i in instances) {
- if (!instances.hasOwnProperty(i)) continue;
- instances[i].instance.stop();
- instances[i].instance.userDefinedDestructor();
- // delete association from source instance
- let associationToRemove = instances[i].ref.associations[instances[i].assocName];
- if (instances[i].assocIndex === -1) {
- // empty instances object
- associationToRemove.instances = {};
- } else {
- // remove property from instances object
- delete associationToRemove.instances[instances[i].assocIndex];
- }
- // also remove instance from Om's list of instances
- let index = this.instances.indexOf(instances[i].instance);
- this.instances.splice(index, 1);
- }
- source.addEvent(new Event('instanceDeleted', undefined, [parameters[1]]));
- };
- ObjectManagerBase.prototype.handleAssociateEvent = function (parameters) {
- if (parameters.length !== 3) {
- throw new ParameterException('The associateInstance event needs 3 parameters.');
- }
- const source = parameters[0];
- const sourceList = parameters[1];
- let traversalList = this.processAssociationReference(sourceList);
- let toCopyList = this.getInstances(source, traversalList);
- if (toCopyList.length !== 1) {
- throw new AssociationReferenceException('Invalid source association reference.');
- }
- let wrappedToCopyInstance = toCopyList[0].instance;
- let destList = this.processAssociationReference(parameters[2]);
- if (destList.length === 0) {
- throw new AssociationReferenceException('Invalid destination association reference.');
- }
- let last = destList.pop();
- if (last.index !== -1) {
- throw new AssociationReferenceException('Last association name in association reference could not be accompanied by an index.');
- }
- let instances = this.getInstances(source, destList);
- for (let i in instances) {
- if (!instances.hasOwnProperty(i)) continue;
- instances[i].instance.associations[last.name].addInstance(wrappedToCopyInstance);
- }
- };
- ObjectManagerBase.prototype.handleDisassociateEvent = function(parameters) {
- if (parameters.length !== 2) {
- throw new ParameterException('The disassociate event needs 2 parameters.');
- }
- var source = parameters[0];
- var traversal_list = this.processAssociationReference(parameters[1]);
- var instances = this.getInstances(source, traversal_list);
- for (var i in instances) {
- if (!instances.hasOwnProperty(i)) continue;
- // delete association from source instance
- var association_to_remove = instances[i].ref.associations[instances[i].assocName];
- if (instances[i].assocIndex === -1) {
- // empty instances object
- association_to_remove.instances = {};
- } else {
- // remove property from instances object
- delete association_to_remove.instances[instances[i].assocIndex];
- }
- }
- source.addEvent(new Event("instance_disassociated", undefined, [parameters[1]]));
- };
- ObjectManagerBase.prototype.handleNarrowCastEvent = function (parameters) {
- if (parameters.length !== 3) {
- throw new ParameterException('The narrowCast event needs 3 parameters.');
- }
- let source = parameters[0];
- let traversalList = this.processAssociationReference(parameters[1]);
- let castEvent = parameters[2];
- let instances = this.getInstances(source, traversalList);
- for (let i in instances) {
- if (!instances.hasOwnProperty(i)) continue;
- instances[i].instance.addEvent(castEvent);
- }
- };
- ObjectManagerBase.prototype.getInstances = function (source, traversalList) {
- let currents = [{
- instance: source,
- ref: null,
- assocName: null,
- assocIndex: null
- }];
- for (let t in traversalList) {
- if (!traversalList.hasOwnProperty(t)) continue;
- let name = traversalList[t].name;
- let index = traversalList[t].index;
- let nexts = [];
- for (var c in currents) {
- if (!currents.hasOwnProperty(c)) continue;
- let association = currents[c].instance.associations[name];
- if (index >= 0) {
- nexts.push({
- instance: association.getInstance(index),
- ref: currents[c].instance,
- assocName: name,
- assocIndex: index
- });
- } else if (index === -1) {
- for (let i in association.instances) {
- if (!association.instances.hasOwnProperty(i)) continue;
- nexts.push({
- instance: association.instances[i],
- ref: currents[c].instance,
- assocName: name,
- assocIndex: index
- });
- }
- } else {
- throw new AssociationReferenceException('Incorrect index in association reference.');
- }
- }
- currents = nexts;
- }
- return currents;
- };
- ObjectManagerBase.prototype.instantiate = function (toClass, constructParams) {
- // pure virtual
- };
- ObjectManagerBase.prototype.createInstance = function (toClass, constructParams) {
- let instance = this.instantiate(toClass, constructParams);
- this.instances.push(instance);
- return instance;
- };
- // Event
- function Event(name, port, parameters) {
- if (port === undefined) port = '';
- if (parameters === undefined) parameters = [];
- this.name = name;
- this.port = port;
- this.parameters = parameters;
- }
- function OutputListener(portNames) {
- this.portNames = portNames;
- this.queue = [];
- }
- OutputListener.prototype.add = function (theEvent) {
- if (this.portNames.length === 0 || this.portNames.indexOf(theEvent.port) !== -1) {
- this.queue.push(theEvent);
- }
- };
- OutputListener.prototype.fetch = function (timeout) {
- if (this.queue.length > 0) {
- return this.queue.shift();
- }
- };
- function ControllerBase(objectManager) {
- this.objectManager = objectManager;
- this.privatePortCounter = 0;
- // keep track of input ports
- this.inputPorts = {};
- this.inputQueue = new EventQueue();
- // keep track of output ports
- this.outputPorts = [];
- this.outputListeners = [];
- this.simulatedTime = 0;
- this.startTime = 0;
- }
- ControllerBase.prototype.getSimulatedTime = function () {
- return this.simulatedTime
- }
- ControllerBase.prototype.addInputPort = function (virtualName, instance) {
- let portName;
- if (instance === undefined) {
- portName = virtualName;
- } else {
- portName = 'private' + (this.privatePortCounter++) + virtualName;
- }
- this.inputPorts[portName] = {
- virtualName: virtualName,
- instance: instance
- };
- return portName;
- };
- ControllerBase.prototype.addOutputPort = function (portName) {
- this.outputPorts.push(portName);
- };
- // ControllerBase.prototype.broadcast = function (newEvent, timeOffset) {
- // if (timeOffset === undefined) timeOffset = 0
- // this.objectManager.broadcast(undefined, newEvent, timeOffset);
- // };
- ControllerBase.prototype.start = function () {
- this.startTime = time();
- this.objectManager.initializeAll();
- };
- ControllerBase.prototype.stop = function () {
- };
- ControllerBase.prototype.wakeup = function () {
- // will be overridden
- }
- ControllerBase.prototype.portToInstanceList = function(port) {
- if (port.instance !== undefined)
- return [port.instance];
- else
- return this.objectManager.instances;
- }
- ControllerBase.prototype.wallclockToSimtime = function() {
- return time() - this.startTime;
- }
- ControllerBase.prototype.addInput = function (eventName, portName, parameters, timestamp = 0) {
- // console.log("addInput", eventName, portName, parameters);
- if (eventName === '') {
- throw new InputException("Input event can't have an empty name.");
- }
- const port = this.inputPorts[portName];
- if (port === undefined) {
- throw new InputException('Input port mismatch, no such port: ' + portName + '.');
- }
- const virtualName = port.virtualName;
- const e = new Event(eventName, port.virtualName, parameters);
- const targetInstances = this.portToInstanceList(port);
- this.inputQueue.add(new EventQueueEntry(
- timestamp,
- e,
- targetInstances));
- this.wakeup();
- };
- // Lower-level: port attribute of event ignored, instead targetInstance is given
- ControllerBase.prototype.addInputLowLevel = function (event, targetInstances, timestamp) {
- const result = this.inputQueue.add(new EventQueueEntry(
- timestamp,
- event,
- targetInstances));
- this.wakeup();
- return result;
- }
- // Blocking call. Handle input events <= until (in simtime) as fast as possible.
- ControllerBase.prototype.runUntil = function (until) {
- while (this.inputQueue.getEarliestTime() <= until) {
- const entry = this.inputQueue.pop();
- this.simulatedTime = entry.scheduledTime;
- // console.log("simTime =", this.simulatedTime);
- for (const i of entry.instances) {
- i.performBigStep([entry.theEvent]);
- i.processBigStepOutput();
- }
- }
- };
- ControllerBase.prototype.outputEvent = function (theEvent) {
- for (const l of this.outputListeners) {
- l.add(theEvent);
- }
- };
- ControllerBase.prototype.addOutputListener = function (ports) {
- let listener = new OutputListener(ports);
- this.outputListeners.push(listener);
- return listener;
- };
- ControllerBase.prototype.addMyOwnOutputListener = function (listener) {
- this.outputListeners.push(listener);
- };
- // function GameLoopControllerBase(objectManager) {
- // ControllerBase.call(this, objectManager);
- // }
- // GameLoopControllerBase.prototype = new ControllerBase();
- // GameLoopControllerBase.prototype.update = function () {
- // const until = time();
- // while (this.inputQueue.getEarliestTime() <= until) {
- // this.handleDue();
- // }
- // };
- // EventLoop
- // parameters:
- // schedule - a callback scheduling another callback in the event loop
- // this callback should take 2 parameters: (callback, timeout) and return an ID
- // clear - a callback that clears a scheduled callback
- // this callback should take an ID that was returned by 'schedule'
- function EventLoop(schedule, clear) {
- this.scheduleCallback = schedule;
- this.clearCallback = clear;
- this.scheduledId = null;
- this.lastPrint = 0.0;
- }
- EventLoop.prototype.schedule = function (f, waitTime) {
- if (this.scheduledId) {
- // if the following error occurs, it is probably due to a flaw in the logic of EventLoopControllerBase
- throw new RuntimeException('EventLoop class intended to maintain at most 1 scheduled callback.');
- }
- if (waitTime !== Infinity) {
- this.scheduledId = this.scheduleCallback(f, waitTime)
- }
- };
- EventLoop.prototype.clear = function () {
- if (this.scheduledId) {
- this.clearCallback(this.scheduledId);
- this.scheduledId = null;
- }
- };
- function EventLoopControllerBase(objectManager, eventLoop, finishedCallback) {
- ControllerBase.call(this, objectManager);
- this.eventLoop = eventLoop;
- this.finishedCallback = finishedCallback;
- // this.behindScheduleCallback = behindScheduleCallback;
- // this.lastPrintTime = 0;
- }
- EventLoopControllerBase.prototype = new ControllerBase();
- // EventLoopControllerBase.prototype.addInput = function (eventName, portName, parameters, timeOffset = 0) {
- // ControllerBase.prototype.addInput.call(this, eventName, portName, parameters, timeOffset);
- // };
- EventLoopControllerBase.prototype.start = function () {
- ControllerBase.prototype.start.call(this);
- this.wakeup();
- };
- // EventLoopControllerBase.prototype.stop = function () {
- // this.eventLoop.clear();
- // ControllerBase.prototype.stop.call(this);
- // };
- EventLoopControllerBase.prototype.wakeup = function () {
- // (re-)schedule next wakeup
- this.eventLoop.clear();
- const simTimeNow = time() - this.startTime;
- const realTimeEarliest = this.inputQueue.getEarliestTime() + this.startTime;
- const realWaitTime = realTimeEarliest - time();
- // We do not directly call 'runUntil'. It only schedules the next call (which may be with timeout zero, i.e. ASAP). Therefore, it is 100% safe to call 'wakeup' from anywhere, even from action code (most likely indirectly by a call to 'addInput').
- this.eventLoop.schedule(() => {
- this.runUntil(simTimeNow + this.purposefullyBehind);
- this.wakeup();
- }, realWaitTime);
- if (realWaitTime < 0) {
- this.purposefullyBehind = realWaitTime;
- } else {
- this.purposefullyBehind = 0;
- }
- };
- // JsEventLoop
- function JsEventLoop() {
- EventLoop.call(this, window.setTimeout.bind(window), window.clearTimeout.bind(window));
- }
- JsEventLoop.prototype = new EventLoop();
- // Enum-like construct holding statechart semantic options.
- StatechartSemantics = {
- // Big Step Maximality
- TakeOne: 0,
- TakeMany: 1,
- // Concurrency
- Single: 0,
- Many: 1, // not yet implemented
- // Preemption (unsupported)
- NonPreemptive: 0,
- Preemptive: 1,
- // Internal Event Lifeline
- Queue: 0,
- NextSmallStep: 1,
- NextComboStep: 2,
- // Input Event Lifeline
- Whole: 0,
- FirstSmallStep: 1,
- FirstComboStep: 2,
- // Priority
- SourceParent: 0,
- SourceChild: 1
- };
- let DefaultStatechartSemantics = function () {
- this.bigStepMaximality = this.TakeMany;
- this.concurrency = this.Single;
- this.internalEventLifeline = this.Queue;
- this.inputEventLifeline = this.FirstComboStep;
- this.priority = this.SourceParent;
- };
- function State(stateId, name, obj) {
- this.stateId = stateId;
- this.name = name;
- this.obj = obj;
- this.ancestors = [];
- this.descendants = [];
- this.children = [];
- this.myParent = null;
- this.enter = null;
- this.exit = null;
- this.defaultState = null;
- this.transitions = [];
- this.myHistory = [];
- this.hasEventlessTransitions = false;
- }
- State.prototype.getEffectiveTargetStates = function () {
- let targets = [this];
- if (this.defaultState != null) {
- Array.prototype.push.apply(targets, this.defaultState.getEffectiveTargetStates());
- }
- return targets;
- }
- State.prototype.fixTree = function () {
- for (let c of this.children) {
- if (c instanceof HistoryState) {
- this.myHistory.push(c);
- }
- c.myParent = this;
- c.ancestors.push(this);
- Array.prototype.push.apply(c.ancestors, this.ancestors);
- c.fixTree();
- }
- Array.prototype.push.apply(this.descendants, this.children)
- for (let c of this.children) {
- Array.prototype.push.apply(this.descendants, c.descendants)
- }
- }
- State.prototype.addChild = function (child) {
- this.children.push(child);
- }
- State.prototype.addTransition = function (transition) {
- this.transitions.push(transition);
- }
- State.prototype.setEnter = function (enter) {
- this.enter = enter.bind(this.obj);
- }
- State.prototype.setExit = function (exit) {
- this.exit = exit.bind(this.obj);
- }
- function HistoryState(stateId, name, obj) {
- State.call(this, stateId, name, obj);
- }
- HistoryState.prototype = new State();
- function ShallowHistoryState(stateId, name, obj) {
- HistoryState.call(this, stateId, name, obj);
- }
- ShallowHistoryState.prototype = new HistoryState();
- ShallowHistoryState.prototype.getEffectiveTargetStates = function () {
- if (this.stateId in this.obj.historyValues) {
- let targets = [];
- for (let hv of this.obj.historyValues[this.stateId]) {
- Array.prototype.push.apply(targets, hv.getEffectiveTargetStates());
- }
- return targets;
- } else {
- // TODO: is it correct that in this case, the parent itself is also entered?
- return this.myParent.getEffectiveTargetStates();
- }
- }
- function DeepHistoryState(stateId, name, obj) {
- HistoryState.call(this, stateId, name, obj);
- }
- DeepHistoryState.prototype = new HistoryState();
- DeepHistoryState.prototype.getEffectiveTargetStates = function () {
- if (this.stateId in this.obj.historyValues) {
- return this.obj.historyValues[this.stateId];
- } else {
- // TODO: is it correct that in this case, the parent itself is also entered?
- return this.myParent.getEffectiveTargetStates();
- }
- }
- function ParallelState(stateId, name, obj) {
- State.call(this, stateId, name, obj);
- }
- ParallelState.prototype = new State();
- ParallelState.prototype.getEffectiveTargetStates = function () {
- let targets = [this];
- for (let c of this.children) {
- if (!(c instanceof HistoryState)) {
- Array.prototype.push.apply(targets, c.getEffectiveTargetStates());
- }
- }
- return targets;
- }
- function Transition(obj, source, targets) {
- this.guard = null;
- this.action = null;
- this.trigger = null;
- this.source = source;
- this.targets = targets;
- this.obj = obj;
- this.enabledEvent = null; // the event that enabled this transition
- this.optimize();
- }
- Transition.prototype.isEnabled = function (events) {
- if (this.trigger === null) {
- this.enabledEvent = null;
- return (this.guard === null || this.guard([]));
- } else {
- for (let i in events) {
- theEvent = events[i];
- if ((this.trigger.name === theEvent.name && (!this.trigger.port || this.trigger.port === theEvent.port)) && (this.guard === null || this.guard(theEvent.parameters))) {
- this.enabledEvent = theEvent;
- return true;
- }
- }
- }
- }
- Transition.prototype.fire = function () {
- // console.log("TRANSITION ", this.source.name, "->", this.targets[0].name);
- let targets = this.privateGetEffectiveTargetStates();
- let exitSet = this.privateExitSet(targets);
- for (let s of exitSet) {
- for (let h of s.myHistory) {
- let f = function (s0) {
- return s0.ancestors.length > 0 && s0.myParent === s;
- }
- if (h instanceof DeepHistoryState) {
- f = function (s0) {
- return s0.descendants.length === 0 && s.descendants.indexOf(s0) >= 0;
- }
- }
- this.obj.historyValues[h.stateId] = this.obj.configuration.filter(f);
- }
- }
- for (let s of exitSet) {
- // console.log("EXIT", s.name);
- if (s.exit != null) {
- s.exit();
- }
- }
- this.obj.configuration = this.obj.configuration.filter(function (el) {
- return exitSet.indexOf(el) < 0;
- })
- // combo state changed area
- this.obj.comboStep.changed.push(this.lca);
- for (let d of this.lca.descendants) {
- this.obj.comboStep.changed.push(d);
- }
- // execute transition action(s)
- if (this.action != null) {
- let params = [];
- if (this.enabledEvent != null) params = this.enabledEvent.parameters;
- this.action(params);
- }
- // enter states...
- for (let s of this.privateEnterSet(targets)) {
- this.obj.configuration.push(s);
- // console.log("ENTER", s.name);
- if (s.enter != null) {
- s.enter();
- }
- }
- this.obj.configuration = this.obj.configuration.sort(function (a, b) {
- return a.stateId - b.stateId
- })
- this.enabledEvent = null;
- }
- Transition.prototype.privateGetEffectiveTargetStates = function () {
- let targets = []
- for (let target of this.targets) {
- for (let effectiveTarget of target.getEffectiveTargetStates()) {
- if (targets.indexOf(effectiveTarget) < 0) {
- targets.push(effectiveTarget);
- }
- }
- }
- return targets;
- }
- Transition.prototype.privateExitSet = function (targets) {
- let exitSet = this.lca.descendants.slice(0).filter(function (obj) {
- return function (s) {
- return obj.obj.configuration.indexOf(s) >= 0;
- }
- }(this));
- exitSet.reverse();
- return exitSet;
- }
- Transition.prototype.privateEnterSet = function* (targets) {
- let target = targets[0];
- let reversedAncestors = target.ancestors.slice(0).reverse();
- for (let a of reversedAncestors) {
- if (this.source.ancestors.indexOf(a) >= 0) {
- } else {
- yield a;
- }
- }
- for (let target of targets) {
- yield target;
- }
- }
- Transition.prototype.setGuard = function (guard) {
- this.guard = guard.bind(this.obj);
- }
- Transition.prototype.setAction = function (action) {
- this.action = action.bind(this.obj);
- }
- Transition.prototype.setTrigger = function (trigger) {
- this.trigger = trigger;
- if (this.trigger === null) {
- this.source.hasEventlessTransitions = true;
- }
- }
- Transition.prototype.optimize = function () {
- let target = this.targets[0];
- this.lca = this.source.myParent;
- if (this.source.myParent !== target.myParent) { // external
- for (let a of this.source.ancestors) {
- if (target.ancestors.indexOf(a) >= 0) {
- this.lca = a;
- break;
- }
- }
- }
- }
- // RuntimeClassBase
- function RuntimeClassBase(controller) {
- // this.active = false;
- // this.privateSetStable(true);
- // this.events = new EventQueue();
- this.controller = controller;
- this.inports = {};
- this.timers = {};
- this.states = {};
- this.semantics = new DefaultStatechartSemantics();
- this.configuration = [];
- this.currentState = {};
- this.historyValues = {};
- this.timers = {};
- // this.timersToAdd = {};
- this.bigStep = new BigStepState();
- this.comboStep = new ComboStepState();
- this.smallStep = new SmallStepState();
- }
- RuntimeClassBase.prototype.eventlessTransitions = function () {
- for (let s of this.configuration) {
- if (s.hasEventlessTransitions) return true;
- }
- return false;
- }
- RuntimeClassBase.prototype.initialize = function () {
- // this.active = true;
- // this.privateSetStable(false);
- this.initializeStatechart();
- this.processBigStepOutput();
- };
- RuntimeClassBase.prototype.sccdYield = function () {
- return Math.max(0, (time() - this.controller.simulatedTime) / 1000.0);
- }
- RuntimeClassBase.prototype.getSimulatedTime = function () {
- return this.controller.simulatedTime;
- }
- RuntimeClassBase.prototype.updateConfiguration = function (states) {
- this.configuration = states.slice(0);
- };
- // RuntimeClassBase.prototype.stop = function () {
- // this.active = false;
- // this.privateSetStable(false);
- // };
- RuntimeClassBase.prototype.addTimer = function (index, timeout) {
- this.timers[index] = this.controller.addInputLowLevel(
- new Event('event'+index+'After'),
- [this], // targets
- this.controller.simulatedTime + timeout*1000); // timestamp
- // this.timersToAdd[index] = new EventQueueEntry(this.controller.simulatedTime + Math.trunc(timeout * 1000), new Event('event' + index + 'After'));
- };
- RuntimeClassBase.prototype.removeTimer = function (index) {
- this.controller.inputQueue.remove(this.timers[index]);
- delete this.timers[index];
- // if (index in this.timersToAdd) delete this.timersToAdd[index];
- // this.controller.inputQueue.remove(this.timers[index]);
- // // this.events.remove(this.timers[index]);
- // delete this.timers[index];
- };
- RuntimeClassBase.prototype.addEvent = function (event, timeOffset = 0) {
- // console.log("DEPRECATED: RuntimeClassBase.addEvent");
- const _add = e => {
- this.controller.addInputLowLevel(e, [this], this.controller.simulatedTime + timeOffset);
- }
- if (event instanceof Array) {
- for (const e of event)
- _add(e);
- } else {
- _add(event);
- }
- };
- RuntimeClassBase.prototype.processBigStepOutput = function () {
- for (const e of this.bigStep.outputEventsPort) {
- this.controller.outputEvent(e);
- }
- let om = this.bigStep.outputEventsPm;
- for (const e of this.bigStep.outputEventsPm) {
- this.controller.addInputLowLevel(e, [this.controller.objectManager], this.controller.simulatedTime);
- }
- };
- // RuntimeClassBase.prototype.step = function () {
- // let stable = false;
- // while (!stable) {
- // let due = [];
- // if (this.events.getEarliestTime() <= this.controller.simulatedTime) {
- // due = [this.events.pop()];
- // }
- // stable = !this.performBigStep(due);
- // this.processBigStepOutput();
- // }
- // for (let key in this.timersToAdd) {
- // if (!this.timersToAdd.hasOwnProperty(key)) continue;
- // this.timers[key] = this.events.add(this.timersToAdd[key]);
- // }
- // this.timersToAdd = {};
- // this.privateSetStable(true);
- // };
- RuntimeClassBase.prototype.inState = function (stateStrings) {
- let stateIds = [];
- for (let stateString of stateStrings) {
- stateIds.push(this.states[stateString].stateId);
- }
- for (let stateId of stateIds) {
- let found = false;
- for (let s of this.configuration) {
- if (s.stateId === stateId) {
- found = true;
- break;
- }
- }
- if (!found) return false;
- }
- return true;
- };
- RuntimeClassBase.prototype.performBigStep = function (inputEvents) {
- this.bigStep.next(inputEvents);
- this.smallStep.reset();
- this.comboStep.reset();
- while (this.performComboStep()) {
- this.bigStep.hasStepped = true;
- if (this.semantics.bigStepMaximality === StatechartSemantics.TakeOne)
- break;
- }
- return this.bigStep.hasStepped;
- };
- RuntimeClassBase.prototype.performComboStep = function () {
- this.comboStep.next();
- while (this.performSmallStep()) {
- this.comboStep.hasStepped = true;
- }
- return this.comboStep.hasStepped;
- };
- // generate transition candidates for current small step
- RuntimeClassBase.prototype.generateCandidates = function () {
- let enabledEvents = this.getEnabledEvents();
- let enabledTransitions = [];
- for (let s of this.configuration) {
- if (this.comboStep.changed.indexOf(s) < 0) {
- for (let t of s.transitions) {
- if (t.isEnabled(enabledEvents)) {
- enabledTransitions.push(t);
- }
- }
- }
- }
- return enabledTransitions;
- };
- RuntimeClassBase.prototype.performSmallStep = function () {
- let privateYoungerThan =
- function (x, y) {
- if (y.source.ancestors.indexOf(x.source) >= 0) {
- return 1;
- } else if (x.source.ancestors.indexOf(y.source) >= 0) {
- return -1;
- } else {
- throw new Exception('These items have no relation with each other.');
- }
- };
- if (this.smallStep.hasStepped) {
- this.smallStep.next();
- }
- let candidates = this.generateCandidates();
- if (candidates.length > 0) {
- toSkip = new Set();
- conflicting = [];
- for (var i in candidates) {
- c1 = candidates[i];
- if (!toSkip.has(c1)) {
- conflict = [c1];
- for (let j in candidates.slice(candidates.indexOf(c1))) {
- c2 = candidates[j];
- if (c1.source.ancestors.indexOf(c2.source) >= 0 || c2.source.ancestors.indexOf(c1.source) >= 0) {
- conflict.push(c2);
- toSkip.add(c2);
- }
- }
- conflicting.push(conflict.sort(privateYoungerThan));
- }
- }
- if (this.semantics.concurrency === StatechartSemantics.Single) {
- let candidate = conflicting[0];
- if (this.semantics.priority === StatechartSemantics.SourceParent) {
- candidate[candidate.length - 1].fire();
- } else {
- candidate[0].fire();
- }
- } else if (this.semantics.concurrency === StatechartSemantics.Many) {
- // TODO: Implement
- }
- this.smallStep.hasStepped = true;
- }
- return this.smallStep.hasStepped;
- };
- RuntimeClassBase.prototype.getEnabledEvents = function () {
- let result = this.smallStep.currentEvents.concat(this.comboStep.currentEvents);
- if (this.semantics.inputEventLifeline === StatechartSemantics.Whole ||
- (!this.bigStep.hasStepped &&
- (this.semantics.inputEventLifeline === StatechartSemantics.FirstComboStep ||
- (!this.comboStep.hasStepped &&
- this.semantics.inputEventLifeline === StatechartSemantics.FirstSmallStep)))) {
- result = result.concat(this.bigStep.inputEvents);
- }
- return result;
- };
- RuntimeClassBase.prototype.raiseInternalEvent = function (theEvent) {
- if (this.semantics.internalEventLifeline === StatechartSemantics.NextSmallStep) {
- this.smallStep.addNextEvent(theEvent);
- } else if (this.semantics.internalEventLifeline === StatechartSemantics.NextComboStep) {
- this.comboStep.addNextEvent(theEvent);
- } else if (this.semantics.internalEventLifeline === StatechartSemantics.Queue) {
- this.addEvent(theEvent, 0);
- }
- };
- RuntimeClassBase.prototype.initializeStatechart = function () {
- this.updateConfiguration(this.defaultTargets);
- for (let state of this.defaultTargets) {
- if (state.enter != null) {
- state.enter();
- }
- }
- };
- RuntimeClassBase.prototype.getInPortName = function (name) {
- // const portName = this.inports[name];
- // if ( portName != null ) {
- // return portName;
- // }
- return name;
- };
- RuntimeClassBase.prototype.getOutPortName = function (name) {
- // const portName = this.outports[name];
- // if ( portName != null ) {
- // return portName;
- // }
- return name;
- };
- let BigStepState = function () {
- this.inputEvents = [];
- this.outputEventsPort = [];
- this.outputEventsPm = [];
- this.hasStepped = true;
- this.transitions = 0;
- };
- BigStepState.prototype.next = function (inputEvents) {
- this.inputEvents = inputEvents;
- this.outputEventsPort = [];
- this.outputEventsPm = [];
- this.hasStepped = false;
- this.transitions = 0;
- };
- BigStepState.prototype.outputEvent = function (event) {
- this.outputEventsPort.push(event);
- };
- BigStepState.prototype.outputEventOm = function (event) {
- this.outputEventsPm.push(event);
- };
- let ComboStepState = function () {
- this.currentEvents = [];
- this.nextEvents = [];
- this.changed = [];
- this.hasStepped = true;
- };
- ComboStepState.prototype.reset = function () {
- this.currentEvents = [];
- this.nextEvents = [];
- };
- ComboStepState.prototype.next = function () {
- this.currentEvents = this.nextEvents;
- this.nextEvents = [];
- this.changed = [];
- this.hasStepped = false;
- };
- ComboStepState.prototype.addNextEvent = function (event) {
- this.nextEvents.push(event);
- };
- ComboStepState.prototype.setArenaChanged = function (arena) {
- this.changed.push(arena);
- };
- ComboStepState.prototype.isArenaChanged = function (arena) {
- return (this.changed.indexOf(arena) !== -1);
- };
- ComboStepState.prototype.isStable = function () {
- return (this.changed.length === 0);
- };
- let SmallStepState = function () {
- this.currentEvents = [];
- this.nextEvents = [];
- this.candidates = [];
- this.hasStepped = true;
- };
- SmallStepState.prototype.reset = function () {
- this.currentEvents = [];
- this.nextEvents = [];
- };
- SmallStepState.prototype.next = function () {
- this.currentEvents = this.nextEvents;
- this.nextEvents = [];
- this.candidates = [];
- this.hasStepped = false;
- };
- SmallStepState.prototype.addNextEvent = function (event) {
- this.nextEvents.push(event);
- };
- SmallStepState.prototype.addCandidate = function (t, p) {
- this.candidates.push({transition: t, parameters: p});
- };
- SmallStepState.prototype.hasCandidates = function () {
- return (this.candidates.length > 0);
- };
- if (typeof module.exports === 'object') {
- // We're on NodeJS
- module.exports = {
- // imported by compiled code
- RuntimeClassBase,
- StatechartSemantics,
- ObjectManagerBase,
- EventLoopControllerBase,
- State,
- ParallelState,
- Transition,
- Event,
- Association,
- // imported by user of compiled code
- JsEventLoop,
- };
- }
|