/** * Statechart core runtime. */ nextObjectId = 1; function objectId(obj) { if (obj == null) { return null; } if (obj.assignedObjectId == null) { obj.assignedObjectId = nextObjectId++; } return obj.assignedObjectId; } startTime = undefined function time() { return (new Date).getTime() - startTime; } 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) { this.scheduledTime = scheduledTime; this.theEvent = theEvent; } 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().theEvent }; 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.start = function () { for (let i in this.instances) { if (!this.instances.hasOwnProperty(i)) continue; this.instances[i].start(); } }; ObjectManagerBase.prototype.handleEvent = function (e) { 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 === 'deleteInstance') { this.handleDeleteInstanceEvent(e.parameters); } }; 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.start(); } }; 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.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 + ']'])); } else { source.addEvent(new Event('instanceCreationError', undefined, [associationName])); } }; 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 = null; } 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 () { startTime = (new Date()).getTime(); this.simulatedTime = 0; this.objectManager.start(); }; ControllerBase.prototype.stop = function () { }; ControllerBase.prototype.addInput = function (inputEventList, timeOffset) { if (timeOffset === undefined) timeOffset = 0 if (!(inputEventList instanceof Array)) { inputEventList = [inputEventList]; } for (let e in inputEventList) { if (!inputEventList.hasOwnProperty(e)) continue; if (inputEventList[e].name === '') { throw new InputException("Input event can't have an empty name."); } let inputPort = this.inputPorts[inputEventList[e].port]; if (inputPort === undefined) { throw new InputException('Input port mismatch, no such port: ' + inputEventList[e].port + '.'); } this.inputQueue.add(new EventQueueEntry((this.simulatedTime === null ? 0 : time()) + timeOffset, inputEventList[e])); } }; ControllerBase.prototype.getEarliestEventTime = function () { return Math.min(this.objectManager.getEarliestEventTime(), this.inputQueue.getEarliestTime()); }; ControllerBase.prototype.handleInput = function () { let eventTime = this.inputQueue.getEarliestTime(); while (eventTime <= this.simulatedTime) { let e = this.inputQueue.pop(); inputPort = this.inputPorts[e.port]; e.port = inputPort.virtualName let targetInstance = inputPort.instance; if (targetInstance === undefined) { this.broadcast(e, eventTime - this.simulatedTime); } else { targetInstance.addEvent(e, eventTime - this.simulatedTime); } eventTime = this.inputQueue.getEarliestTime(); } }; ControllerBase.prototype.outputEvent = function (theEvent) { for (let l in this.outputListeners) { if (!this.outputListeners.hasOwnProperty(l)) continue; 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 (delta) { this.handleInput(); earliestEventTime = this.getEarliestEventTime(); if (earliestEventTime > time()) { this.simulatedTime = earliestEventTime; this.objectManager.stepAll(); } }; // 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, behind) { if (behind === undefined) behind = false 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, behind) } }; EventLoop.prototype.clear = function () { if (this.scheduledId) { this.clearCallback(this.scheduledId); this.scheduledId = null; } }; function EventLoopControllerBase(objectManager, eventLoop, finishedCallback, behindScheduleCallback) { ControllerBase.call(this, objectManager); this.eventLoop = eventLoop; this.finishedCallback = finishedCallback; this.behindScheduleCallback = behindScheduleCallback; this.lastPrintTime = 0; } EventLoopControllerBase.prototype = new ControllerBase(); EventLoopControllerBase.prototype.addInput = function (inputEvent, timeOffset) { ControllerBase.prototype.addInput.call(this, inputEvent, timeOffset); this.eventLoop.clear(); this.simulatedTime = ControllerBase.prototype.getEarliestEventTime.call(this); this.run(); }; EventLoopControllerBase.prototype.start = function () { ControllerBase.prototype.start.call(this); this.run(); }; EventLoopControllerBase.prototype.stop = function () { this.eventLoop.clear(); ControllerBase.prototype.stop.call(this); }; EventLoopControllerBase.prototype.run = function () { var startTime = time(); while (true) { // clear existing timeout this.eventLoop.clear(); // simulate this.handleInput(); this.objectManager.stepAll(); // schedule next timeout let earliestEventTime = ControllerBase.prototype.getEarliestEventTime.call(this); if (earliestEventTime === Infinity) { if (this.finishedCallback !== null) { this.finishedCallback(); // TODO: This is not necessarily correct (keepRunning necessary?) } return; } let now = time(); if (now - startTime > 10 || earliestEventTime - now > 0) { this.eventLoop.schedule(this.run.bind(this), earliestEventTime - now, now - startTime > 10); if (now - earliestEventTime > 10 && now - this.lastPrintTime >= 1000) { console.log('running ' + (now - earliestEventTime) + ' ms behind schedule'); this.lastPrintTime = now; } this.simulatedTime = earliestEventTime; return; } else { this.simulatedTime = earliestEventTime; } } }; // 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(); } RuntimeClassBase.prototype.eventlessTransitions = function () { for (let s of this.configuration) { if (s.hasEventlessTransitions) return true; } return false; } RuntimeClassBase.prototype.start = function () { this.configuration = []; this.currentState = {}; this.historyValues = {}; this.timers = {}; this.timersToAdd = {}; this.bigStep = new BigStepState(); this.comboStep = new ComboStepState(); this.smallStep = new SmallStepState(); 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.timersToAdd[index] = new EventQueueEntry(this.controller.simulatedTime + Math.trunc(timeout * 1000), new Event('event' + index + 'After')); }; RuntimeClassBase.prototype.removeTimer = function (index) { if (index in this.timersToAdd) delete this.timersToAdd[index]; this.events.remove(this.timers[index]); delete this.timers[index]; }; RuntimeClassBase.prototype.addEvent = function (eventList, timeOffset) { if (timeOffset === undefined) timeOffset = 0; let eventTime = this.controller.simulatedTime + timeOffset; if (eventTime < this.earliestEventTime) { this.earliestEventTime = eventTime; } if (!(eventList instanceof Array)) { eventList = [eventList]; } for (let i in eventList) { if (!eventList.hasOwnProperty(i)) continue; this.events.add(new EventQueueEntry(this.controller.simulatedTime + timeOffset, eventList[i])); } }; RuntimeClassBase.prototype.getEarliestEventTime = function () { return this.earliestEventTime; }; RuntimeClassBase.prototype.processBigStepOutput = function () { let o = this.bigStep.outputEventsPort; let om = this.bigStep.outputEventsPm; for (let e in o) { if (!o.hasOwnProperty(e)) continue; this.controller.outputEvent(o[e]); } for (let e in om) { if (!om.hasOwnProperty(e)) continue; this.controller.objectManager.addEvent(om[e]); } }; RuntimeClassBase.prototype.privateSetStable = function (stable) { this.stable = stable; // self.earliestEventTime keeps track of the earliest time this instance will execute a transition if (!this.stable) { this.earliestEventTime = 0.0; } else if (!this.active) { this.earliestEventTime = Infinity; } else { this.earliestEventTime = this.events.getEarliestTime(); } } RuntimeClassBase.prototype.step = function (delta) { 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.events.add(new EventQueueEntry(0.0, theEvent)); } }; 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); };