| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353 |
- /**
- * Statechart core runtime.
- */
- 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);
- };
|