statecharts_core.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  1. /**
  2. * Statechart core runtime.
  3. */
  4. nextObjectId = 1;
  5. function objectId(obj) {
  6. if (obj == null) {
  7. return null;
  8. }
  9. if (obj.assignedObjectId == null) {
  10. obj.assignedObjectId = nextObjectId++;
  11. }
  12. return obj.assignedObjectId;
  13. }
  14. startTime = undefined
  15. function time() {
  16. return (new Date).getTime() - startTime;
  17. }
  18. function RuntimeException(msg) {
  19. this.msg = msg;
  20. }
  21. function InputException(msg) {
  22. RuntimeException.call(this, msg);
  23. }
  24. InputException.prototype = new RuntimeException();
  25. function AssociationException(msg) {
  26. RuntimeException.call(this, msg);
  27. }
  28. AssociationException.prototype = new RuntimeException();
  29. function AssociationReferenceException(msg) {
  30. RuntimeException.call(this, msg);
  31. }
  32. AssociationReferenceException.prototype = new RuntimeException();
  33. function ParameterException(msg) {
  34. RuntimeException.call(this, msg);
  35. }
  36. ParameterException.prototype = new RuntimeException();
  37. function EventQueueEntry(scheduledTime, theEvent) {
  38. this.scheduledTime = scheduledTime;
  39. this.theEvent = theEvent;
  40. }
  41. function EventQueue() {
  42. this.eventList = [];
  43. this.sortFunction = function (a, b) {
  44. return a.scheduledTime - b.scheduledTime
  45. }
  46. }
  47. EventQueue.prototype.isEmpty = function () {
  48. return this.eventList.length === 0;
  49. };
  50. EventQueue.prototype.getEarliestTime = function () {
  51. if (this.isEmpty()) {
  52. return Infinity;
  53. } else {
  54. return this.eventList[0].scheduledTime;
  55. }
  56. };
  57. EventQueue.prototype.add = function (theEvent) {
  58. this.eventList.push(theEvent);
  59. this.eventList.sort(this.sortFunction);
  60. return objectId(theEvent);
  61. };
  62. EventQueue.prototype.remove = function (eventId) {
  63. this.eventList = this.eventList.filter(function (el) {
  64. return objectId(el) !== eventId;
  65. }).sort()
  66. }
  67. EventQueue.prototype.pop = function () {
  68. return this.eventList.shift().theEvent
  69. };
  70. function Association(toClass, minCard, maxCard) {
  71. this.toClass = toClass;
  72. this.minCard = minCard;
  73. this.maxCard = maxCard;
  74. this.instances = {};
  75. this.size = 0;
  76. this.nextId = 0;
  77. }
  78. Association.prototype.allowedToAdd = function () {
  79. return (this.maxCard === -1 || this.size < this.maxCard);
  80. };
  81. Association.prototype.allowedToRemove = function () {
  82. return (this.minCard === -1 || this.size > this.minCard);
  83. };
  84. Association.prototype.addInstance = function (instance) {
  85. if (this.allowedToAdd()) {
  86. const id = this.nextId++;
  87. this.instances[id] = instance;
  88. return id;
  89. } else {
  90. throw new AssociationException('Not allowed to add the instance to the association.');
  91. }
  92. };
  93. Association.prototype.removeInstance = function (instance) {
  94. if (this.allowedToRemove()) {
  95. delete this.instances[this.instancesToIds[instance]]
  96. } else {
  97. throw new AssociationException('Not allowed to remove the instance to the association.');
  98. }
  99. };
  100. Association.prototype.getInstance = function (index) {
  101. const instance = this.instances[index];
  102. if (instance === undefined) {
  103. throw new AssociationException('Invalid index for fetching instance(s) from association.');
  104. }
  105. return instance;
  106. };
  107. function ObjectManagerBase(controller) {
  108. this.controller = controller;
  109. this.events = new EventQueue();
  110. this.instances = [];
  111. // this.regex = /^([a-zA-Z_]\w*)(?:\[(\d+)])?$/;
  112. this.regex = /^([a-zA-Z_]\w*)(?:\[(\d+)\])?$/;
  113. }
  114. ObjectManagerBase.prototype.addEvent = function (theEvent, timeOffset) {
  115. if (timeOffset === undefined) timeOffset = 0;
  116. this.events.add(new EventQueueEntry(this.controller.simulatedTime + timeOffset, theEvent));
  117. };
  118. ObjectManagerBase.prototype.broadcast = function (source, newEvent, timeOffset) {
  119. if (timeOffset === undefined) timeOffset = 0;
  120. for (let i in this.instances) {
  121. if (!this.instances.hasOwnProperty(i) || i === source) continue;
  122. this.instances[i].addEvent(newEvent, timeOffset);
  123. }
  124. };
  125. ObjectManagerBase.prototype.getEarliestEventTime = function () {
  126. let earliestTime = this.events.getEarliestTime();
  127. for (let i in this.instances) {
  128. if (!this.instances.hasOwnProperty(i)) continue;
  129. earliestTime = Math.min(earliestTime, this.instances[i].earliestEventTime);
  130. }
  131. return earliestTime;
  132. };
  133. ObjectManagerBase.prototype.stepAll = function () {
  134. this.step();
  135. for (let i in this.instances) {
  136. if (!this.instances.hasOwnProperty(i)) continue;
  137. let instance = this.instances[i];
  138. if (instance.active && (instance.getEarliestEventTime() <= this.controller.simulatedTime || instance.eventlessTransitions())) {
  139. instance.step();
  140. }
  141. }
  142. };
  143. ObjectManagerBase.prototype.step = function () {
  144. while (this.events.getEarliestTime() <= this.controller.simulatedTime) {
  145. this.handleEvent(this.events.pop());
  146. }
  147. };
  148. ObjectManagerBase.prototype.start = function () {
  149. for (let i in this.instances) {
  150. if (!this.instances.hasOwnProperty(i)) continue;
  151. this.instances[i].start();
  152. }
  153. };
  154. ObjectManagerBase.prototype.handleEvent = function (e) {
  155. if (e.name === 'narrowCast') {
  156. this.handleNarrowCastEvent(e.parameters);
  157. } else if (e.name === 'broadCast') {
  158. this.handleBroadcastEvent(e.parameters);
  159. } else if (e.name === 'createInstance') {
  160. this.handleCreateEvent(e.parameters);
  161. } else if (e.name === 'associateInstance') {
  162. this.handleAssociateEvent(e.parameters);
  163. } else if (e.name === 'disassociateInstance') {
  164. this.handleDisassociateEvent(e.parameters);
  165. } else if (e.name === 'startInstance') {
  166. this.handleStartInstanceEvent(e.parameters);
  167. } else if (e.name === 'deleteInstance') {
  168. this.handleDeleteInstanceEvent(e.parameters);
  169. }
  170. };
  171. ObjectManagerBase.prototype.processAssociationReference = function (inputString) {
  172. if (inputString.length === 0) {
  173. throw new AssociationReferenceException('Empty association reference.');
  174. }
  175. const pathString = inputString.split('/');
  176. let result = [];
  177. if (inputString !== '') {
  178. for (let p in pathString) {
  179. if (!pathString.hasOwnProperty(p)) continue;
  180. var m = this.regex.exec(pathString[p]);
  181. if (m) {
  182. var name = m[1];
  183. var index = m[2];
  184. if (!index) {
  185. index = -1;
  186. }
  187. result.push({name: name, index: index});
  188. } else {
  189. throw new AssociationReferenceException('Invalid entry in association reference.');
  190. }
  191. }
  192. }
  193. return result;
  194. };
  195. ObjectManagerBase.prototype.handleStartInstanceEvent = function (parameters) {
  196. if (parameters.length !== 2) {
  197. throw new ParameterException('The start instance event needs 2 parameters.');
  198. }
  199. const source = parameters[0];
  200. const traversalList = this.processAssociationReference(parameters[1]);
  201. let instances = this.getInstances(source, traversalList);
  202. for (let i in instances) {
  203. if (!instances.hasOwnProperty(i)) continue;
  204. instances[i].instance.start();
  205. }
  206. };
  207. ObjectManagerBase.prototype.handleBroadcastEvent = function (parameters) {
  208. if (parameters.length !== 2) {
  209. throw new ParameterException('The broadcast event needs 2 parameters (source of event and event name).');
  210. }
  211. this.broadcast(parameters[0], parameters[1]);
  212. };
  213. ObjectManagerBase.prototype.handleCreateEvent = function (parameters) {
  214. if (parameters.length < 2) {
  215. throw new ParameterException('The create event needs at least 2 parameters.');
  216. }
  217. const source = parameters[0];
  218. const associationName = parameters[1];
  219. let association = source.associations[associationName];
  220. if (!association) {
  221. throw new ParameterException('No such association: ' + associationName);
  222. }
  223. if (association.allowedToAdd()) {
  224. // allow subclasses to be instantiated
  225. let className = undefined;
  226. let creationParameters = undefined;
  227. if (parameters.length === 2) {
  228. className = association.toClass;
  229. creationParameters = [];
  230. } else {
  231. // 3rd parameter is class name
  232. className = parameters[2];
  233. // parameters after 3rd parameter are creation parameters
  234. creationParameters = parameters.slice(3);
  235. }
  236. let newInstance = this.createInstance(className, creationParameters);
  237. if (newInstance === undefined) {
  238. throw new ParameterException('Creating instance: no such class: ' + className);
  239. }
  240. let index = association.addInstance(newInstance);
  241. // add parent association to created instance
  242. // if a parent association is defined in the class diagram
  243. let parentAssociation = newInstance.associations['parent'];
  244. if (parentAssociation !== undefined) {
  245. parentAssociation.addInstance(source);
  246. }
  247. // TODO: maybe change order of Event constructor parameters such that we don't have to
  248. // explicitly set the port to 'undefined'?
  249. source.addEvent(new Event('instanceCreated', undefined, [associationName + '[' + index + ']']));
  250. } else {
  251. source.addEvent(new Event('instanceCreationError', undefined, [associationName]));
  252. }
  253. };
  254. ObjectManagerBase.prototype.handleDeleteInstanceEvent = function (parameters) {
  255. if (parameters.length !== 2) {
  256. throw new ParameterException('The delete instance event needs 2 parameters.');
  257. }
  258. const source = parameters[0];
  259. const traversalList = this.processAssociationReference(parameters[1]);
  260. let instances = this.getInstances(source, traversalList);
  261. for (let i in instances) {
  262. if (!instances.hasOwnProperty(i)) continue;
  263. instances[i].instance.stop();
  264. instances[i].instance.userDefinedDestructor();
  265. // delete association from source instance
  266. let associationToRemove = instances[i].ref.associations[instances[i].assocName];
  267. if (instances[i].assocIndex === -1) {
  268. // empty instances object
  269. associationToRemove.instances = {};
  270. } else {
  271. // remove property from instances object
  272. delete associationToRemove.instances[instances[i].assocIndex];
  273. }
  274. // also remove instance from Om's list of instances
  275. let index = this.instances.indexOf(instances[i].instance);
  276. this.instances.splice(index, 1);
  277. }
  278. source.addEvent(new Event('instanceDeleted', undefined, [parameters[1]]));
  279. };
  280. ObjectManagerBase.prototype.handleAssociateEvent = function (parameters) {
  281. if (parameters.length !== 3) {
  282. throw new ParameterException('The associateInstance event needs 3 parameters.');
  283. }
  284. const source = parameters[0];
  285. const sourceList = parameters[1];
  286. let traversalList = this.processAssociationReference(sourceList);
  287. let toCopyList = this.getInstances(source, traversalList);
  288. if (toCopyList.length !== 1) {
  289. throw new AssociationReferenceException('Invalid source association reference.');
  290. }
  291. let wrappedToCopyInstance = toCopyList[0].instance;
  292. let destList = this.processAssociationReference(parameters[2]);
  293. if (destList.length === 0) {
  294. throw new AssociationReferenceException('Invalid destination association reference.');
  295. }
  296. let last = destList.pop();
  297. if (last.index !== -1) {
  298. throw new AssociationReferenceException('Last association name in association reference could not be accompanied by an index.');
  299. }
  300. let instances = this.getInstances(source, destList);
  301. for (let i in instances) {
  302. if (!instances.hasOwnProperty(i)) continue;
  303. instances[i].instance.associations[last.name].addInstance(wrappedToCopyInstance);
  304. }
  305. };
  306. ObjectManagerBase.prototype.handleDisassociateEvent = function(parameters) {
  307. if (parameters.length !== 2) {
  308. throw new ParameterException('The disassociate event needs 2 parameters.');
  309. }
  310. var source = parameters[0];
  311. var traversal_list = this.processAssociationReference(parameters[1]);
  312. var instances = this.getInstances(source, traversal_list);
  313. for (var i in instances) {
  314. if (!instances.hasOwnProperty(i)) continue;
  315. // delete association from source instance
  316. var association_to_remove = instances[i].ref.associations[instances[i].assocName];
  317. if (instances[i].assocIndex === -1) {
  318. // empty instances object
  319. association_to_remove.instances = {};
  320. } else {
  321. // remove property from instances object
  322. delete association_to_remove.instances[instances[i].assocIndex];
  323. }
  324. }
  325. source.addEvent(new Event("instance_disassociated", undefined, [parameters[1]]));
  326. };
  327. ObjectManagerBase.prototype.handleNarrowCastEvent = function (parameters) {
  328. if (parameters.length !== 3) {
  329. throw new ParameterException('The narrowCast event needs 3 parameters.');
  330. }
  331. let source = parameters[0];
  332. let traversalList = this.processAssociationReference(parameters[1]);
  333. let castEvent = parameters[2];
  334. let instances = this.getInstances(source, traversalList);
  335. for (let i in instances) {
  336. if (!instances.hasOwnProperty(i)) continue;
  337. instances[i].instance.addEvent(castEvent);
  338. }
  339. };
  340. ObjectManagerBase.prototype.getInstances = function (source, traversalList) {
  341. let currents = [{
  342. instance: source,
  343. ref: null,
  344. assocName: null,
  345. assocIndex: null
  346. }];
  347. for (let t in traversalList) {
  348. if (!traversalList.hasOwnProperty(t)) continue;
  349. let name = traversalList[t].name;
  350. let index = traversalList[t].index;
  351. let nexts = [];
  352. for (var c in currents) {
  353. if (!currents.hasOwnProperty(c)) continue;
  354. let association = currents[c].instance.associations[name];
  355. if (index >= 0) {
  356. nexts.push({
  357. instance: association.getInstance(index),
  358. ref: currents[c].instance,
  359. assocName: name,
  360. assocIndex: index
  361. });
  362. } else if (index === -1) {
  363. for (let i in association.instances) {
  364. if (!association.instances.hasOwnProperty(i)) continue;
  365. nexts.push({
  366. instance: association.instances[i],
  367. ref: currents[c].instance,
  368. assocName: name,
  369. assocIndex: index
  370. });
  371. }
  372. } else {
  373. throw new AssociationReferenceException('Incorrect index in association reference.');
  374. }
  375. }
  376. currents = nexts;
  377. }
  378. return currents;
  379. };
  380. ObjectManagerBase.prototype.instantiate = function (toClass, constructParams) {
  381. // pure virtual
  382. };
  383. ObjectManagerBase.prototype.createInstance = function (toClass, constructParams) {
  384. let instance = this.instantiate(toClass, constructParams);
  385. this.instances.push(instance);
  386. return instance;
  387. };
  388. // Event
  389. function Event(name, port, parameters) {
  390. if (port === undefined) port = '';
  391. if (parameters === undefined) parameters = [];
  392. this.name = name;
  393. this.port = port;
  394. this.parameters = parameters;
  395. }
  396. function OutputListener(portNames) {
  397. this.portNames = portNames;
  398. this.queue = [];
  399. }
  400. OutputListener.prototype.add = function (theEvent) {
  401. if (this.portNames.length === 0 || this.portNames.indexOf(theEvent.port) !== -1) {
  402. this.queue.push(theEvent);
  403. }
  404. };
  405. OutputListener.prototype.fetch = function (timeout) {
  406. if (this.queue.length > 0) {
  407. return this.queue.shift();
  408. }
  409. };
  410. function ControllerBase(objectManager) {
  411. this.objectManager = objectManager;
  412. this.privatePortCounter = 0;
  413. // keep track of input ports
  414. this.inputPorts = {};
  415. this.inputQueue = new EventQueue();
  416. // keep track of output ports
  417. this.outputPorts = [];
  418. this.outputListeners = [];
  419. this.simulatedTime = null;
  420. }
  421. ControllerBase.prototype.getSimulatedTime = function () {
  422. return this.simulatedTime
  423. }
  424. ControllerBase.prototype.addInputPort = function (virtualName, instance) {
  425. let portName;
  426. if (instance === undefined) {
  427. portName = virtualName;
  428. } else {
  429. portName = 'private' + (this.privatePortCounter++) + virtualName;
  430. }
  431. this.inputPorts[portName] = {
  432. virtualName: virtualName,
  433. instance: instance
  434. };
  435. return portName;
  436. };
  437. ControllerBase.prototype.addOutputPort = function (portName) {
  438. this.outputPorts.push(portName);
  439. };
  440. ControllerBase.prototype.broadcast = function (newEvent, timeOffset) {
  441. if (timeOffset === undefined) timeOffset = 0
  442. this.objectManager.broadcast(undefined, newEvent, timeOffset);
  443. };
  444. ControllerBase.prototype.start = function () {
  445. startTime = (new Date()).getTime();
  446. this.simulatedTime = 0;
  447. this.objectManager.start();
  448. };
  449. ControllerBase.prototype.stop = function () {
  450. };
  451. ControllerBase.prototype.addInput = function (inputEventList, timeOffset) {
  452. if (timeOffset === undefined) timeOffset = 0
  453. if (!(inputEventList instanceof Array)) {
  454. inputEventList = [inputEventList];
  455. }
  456. for (let e in inputEventList) {
  457. if (!inputEventList.hasOwnProperty(e)) continue;
  458. if (inputEventList[e].name === '') {
  459. throw new InputException("Input event can't have an empty name.");
  460. }
  461. let inputPort = this.inputPorts[inputEventList[e].port];
  462. if (inputPort === undefined) {
  463. throw new InputException('Input port mismatch, no such port: ' + inputEventList[e].port + '.');
  464. }
  465. this.inputQueue.add(new EventQueueEntry((this.simulatedTime === null ? 0 : time()) + timeOffset, inputEventList[e]));
  466. }
  467. };
  468. ControllerBase.prototype.getEarliestEventTime = function () {
  469. return Math.min(this.objectManager.getEarliestEventTime(), this.inputQueue.getEarliestTime());
  470. };
  471. ControllerBase.prototype.handleInput = function () {
  472. let eventTime = this.inputQueue.getEarliestTime();
  473. while (eventTime <= this.simulatedTime) {
  474. let e = this.inputQueue.pop();
  475. inputPort = this.inputPorts[e.port];
  476. e.port = inputPort.virtualName
  477. let targetInstance = inputPort.instance;
  478. if (targetInstance === undefined) {
  479. this.broadcast(e, eventTime - this.simulatedTime);
  480. } else {
  481. targetInstance.addEvent(e, eventTime - this.simulatedTime);
  482. }
  483. eventTime = this.inputQueue.getEarliestTime();
  484. }
  485. };
  486. ControllerBase.prototype.outputEvent = function (theEvent) {
  487. for (let l in this.outputListeners) {
  488. if (!this.outputListeners.hasOwnProperty(l)) continue;
  489. this.outputListeners[l].add(theEvent);
  490. }
  491. };
  492. ControllerBase.prototype.addOutputListener = function (ports) {
  493. let listener = new OutputListener(ports);
  494. this.outputListeners.push(listener);
  495. return listener;
  496. };
  497. ControllerBase.prototype.addMyOwnOutputListener = function (listener) {
  498. this.outputListeners.push(listener);
  499. };
  500. function GameLoopControllerBase(objectManager) {
  501. ControllerBase.call(this, objectManager);
  502. }
  503. GameLoopControllerBase.prototype = new ControllerBase();
  504. GameLoopControllerBase.prototype.update = function (delta) {
  505. this.handleInput();
  506. earliestEventTime = this.getEarliestEventTime();
  507. if (earliestEventTime > time()) {
  508. this.simulatedTime = earliestEventTime;
  509. this.objectManager.stepAll();
  510. }
  511. };
  512. // EventLoop
  513. // parameters:
  514. // schedule - a callback scheduling another callback in the event loop
  515. // this callback should take 2 parameters: (callback, timeout) and return an ID
  516. // clear - a callback that clears a scheduled callback
  517. // this callback should take an ID that was returned by 'schedule'
  518. function EventLoop(schedule, clear) {
  519. this.scheduleCallback = schedule;
  520. this.clearCallback = clear;
  521. this.scheduledId = null;
  522. this.lastPrint = 0.0;
  523. }
  524. EventLoop.prototype.schedule = function (f, waitTime, behind) {
  525. if (behind === undefined) behind = false
  526. if (this.scheduledId) {
  527. // if the following error occurs, it is probably due to a flaw in the logic of EventLoopControllerBase
  528. throw new RuntimeException('EventLoop class intended to maintain at most 1 scheduled callback.');
  529. }
  530. if (waitTime !== Infinity) {
  531. this.scheduledId = this.scheduleCallback(f, waitTime, behind)
  532. }
  533. };
  534. EventLoop.prototype.clear = function () {
  535. if (this.scheduledId) {
  536. this.clearCallback(this.scheduledId);
  537. this.scheduledId = null;
  538. }
  539. };
  540. function EventLoopControllerBase(objectManager, eventLoop, finishedCallback, behindScheduleCallback) {
  541. ControllerBase.call(this, objectManager);
  542. this.eventLoop = eventLoop;
  543. this.finishedCallback = finishedCallback;
  544. this.behindScheduleCallback = behindScheduleCallback;
  545. this.lastPrintTime = 0;
  546. }
  547. EventLoopControllerBase.prototype = new ControllerBase();
  548. EventLoopControllerBase.prototype.addInput = function (inputEvent, timeOffset) {
  549. ControllerBase.prototype.addInput.call(this, inputEvent, timeOffset);
  550. this.eventLoop.clear();
  551. this.simulatedTime = ControllerBase.prototype.getEarliestEventTime.call(this);
  552. this.run();
  553. };
  554. EventLoopControllerBase.prototype.start = function () {
  555. ControllerBase.prototype.start.call(this);
  556. this.run();
  557. };
  558. EventLoopControllerBase.prototype.stop = function () {
  559. this.eventLoop.clear();
  560. ControllerBase.prototype.stop.call(this);
  561. };
  562. EventLoopControllerBase.prototype.run = function () {
  563. var startTime = time();
  564. while (true) {
  565. // clear existing timeout
  566. this.eventLoop.clear();
  567. // simulate
  568. this.handleInput();
  569. this.objectManager.stepAll();
  570. // schedule next timeout
  571. let earliestEventTime = ControllerBase.prototype.getEarliestEventTime.call(this);
  572. if (earliestEventTime === Infinity) {
  573. if (this.finishedCallback !== null) {
  574. this.finishedCallback(); // TODO: This is not necessarily correct (keepRunning necessary?)
  575. }
  576. return;
  577. }
  578. let now = time();
  579. if (now - startTime > 10 || earliestEventTime - now > 0) {
  580. this.eventLoop.schedule(this.run.bind(this), earliestEventTime - now, now - startTime > 10);
  581. if (now - earliestEventTime > 10 && now - this.lastPrintTime >= 1000) {
  582. console.log('running ' + (now - earliestEventTime) + ' ms behind schedule');
  583. this.lastPrintTime = now;
  584. }
  585. this.simulatedTime = earliestEventTime;
  586. return;
  587. } else {
  588. this.simulatedTime = earliestEventTime;
  589. }
  590. }
  591. };
  592. // JsEventLoop
  593. function JsEventLoop() {
  594. EventLoop.call(this, window.setTimeout.bind(window), window.clearTimeout.bind(window));
  595. }
  596. JsEventLoop.prototype = new EventLoop();
  597. // Enum-like construct holding statechart semantic options.
  598. StatechartSemantics = {
  599. // Big Step Maximality
  600. TakeOne: 0,
  601. TakeMany: 1,
  602. // Concurrency
  603. Single: 0,
  604. Many: 1, // not yet implemented
  605. // Preemption (unsupported)
  606. NonPreemptive: 0,
  607. Preemptive: 1,
  608. // Internal Event Lifeline
  609. Queue: 0,
  610. NextSmallStep: 1,
  611. NextComboStep: 2,
  612. // Input Event Lifeline
  613. Whole: 0,
  614. FirstSmallStep: 1,
  615. FirstComboStep: 2,
  616. // Priority
  617. SourceParent: 0,
  618. SourceChild: 1
  619. };
  620. let DefaultStatechartSemantics = function () {
  621. this.bigStepMaximality = this.TakeMany;
  622. this.concurrency = this.Single;
  623. this.internalEventLifeline = this.Queue;
  624. this.inputEventLifeline = this.FirstComboStep;
  625. this.priority = this.SourceParent;
  626. };
  627. function State(stateId, name, obj) {
  628. this.stateId = stateId;
  629. this.name = name;
  630. this.obj = obj;
  631. this.ancestors = [];
  632. this.descendants = [];
  633. this.children = [];
  634. this.myParent = null;
  635. this.enter = null;
  636. this.exit = null;
  637. this.defaultState = null;
  638. this.transitions = [];
  639. this.myHistory = [];
  640. this.hasEventlessTransitions = false;
  641. }
  642. State.prototype.getEffectiveTargetStates = function () {
  643. let targets = [this];
  644. if (this.defaultState != null) {
  645. Array.prototype.push.apply(targets, this.defaultState.getEffectiveTargetStates());
  646. }
  647. return targets;
  648. }
  649. State.prototype.fixTree = function () {
  650. for (let c of this.children) {
  651. if (c instanceof HistoryState) {
  652. this.myHistory.push(c);
  653. }
  654. c.myParent = this;
  655. c.ancestors.push(this);
  656. Array.prototype.push.apply(c.ancestors, this.ancestors);
  657. c.fixTree();
  658. }
  659. Array.prototype.push.apply(this.descendants, this.children)
  660. for (let c of this.children) {
  661. Array.prototype.push.apply(this.descendants, c.descendants)
  662. }
  663. }
  664. State.prototype.addChild = function (child) {
  665. this.children.push(child);
  666. }
  667. State.prototype.addTransition = function (transition) {
  668. this.transitions.push(transition);
  669. }
  670. State.prototype.setEnter = function (enter) {
  671. this.enter = enter.bind(this.obj);
  672. }
  673. State.prototype.setExit = function (exit) {
  674. this.exit = exit.bind(this.obj);
  675. }
  676. function HistoryState(stateId, name, obj) {
  677. State.call(this, stateId, name, obj);
  678. }
  679. HistoryState.prototype = new State();
  680. function ShallowHistoryState(stateId, name, obj) {
  681. HistoryState.call(this, stateId, name, obj);
  682. }
  683. ShallowHistoryState.prototype = new HistoryState();
  684. ShallowHistoryState.prototype.getEffectiveTargetStates = function () {
  685. if (this.stateId in this.obj.historyValues) {
  686. let targets = [];
  687. for (let hv of this.obj.historyValues[this.stateId]) {
  688. Array.prototype.push.apply(targets, hv.getEffectiveTargetStates());
  689. }
  690. return targets;
  691. } else {
  692. // TODO: is it correct that in this case, the parent itself is also entered?
  693. return this.myParent.getEffectiveTargetStates();
  694. }
  695. }
  696. function DeepHistoryState(stateId, name, obj) {
  697. HistoryState.call(this, stateId, name, obj);
  698. }
  699. DeepHistoryState.prototype = new HistoryState();
  700. DeepHistoryState.prototype.getEffectiveTargetStates = function () {
  701. if (this.stateId in this.obj.historyValues) {
  702. return this.obj.historyValues[this.stateId];
  703. } else {
  704. // TODO: is it correct that in this case, the parent itself is also entered?
  705. return this.myParent.getEffectiveTargetStates();
  706. }
  707. }
  708. function ParallelState(stateId, name, obj) {
  709. State.call(this, stateId, name, obj);
  710. }
  711. ParallelState.prototype = new State();
  712. ParallelState.prototype.getEffectiveTargetStates = function () {
  713. let targets = [this];
  714. for (let c of this.children) {
  715. if (!(c instanceof HistoryState)) {
  716. Array.prototype.push.apply(targets, c.getEffectiveTargetStates());
  717. }
  718. }
  719. return targets;
  720. }
  721. function Transition(obj, source, targets) {
  722. this.guard = null;
  723. this.action = null;
  724. this.trigger = null;
  725. this.source = source;
  726. this.targets = targets;
  727. this.obj = obj;
  728. this.enabledEvent = null; // the event that enabled this transition
  729. this.optimize();
  730. }
  731. Transition.prototype.isEnabled = function (events) {
  732. if (this.trigger === null) {
  733. this.enabledEvent = null;
  734. return (this.guard === null || this.guard([]));
  735. } else {
  736. for (let i in events) {
  737. theEvent = events[i];
  738. if ((this.trigger.name === theEvent.name && (!this.trigger.port || this.trigger.port === theEvent.port)) && (this.guard === null || this.guard(theEvent.parameters))) {
  739. this.enabledEvent = theEvent;
  740. return true;
  741. }
  742. }
  743. }
  744. }
  745. Transition.prototype.fire = function () {
  746. console.log("TRANSITION ", this.source.name, "->", this.targets[0].name)
  747. let targets = this.privateGetEffectiveTargetStates();
  748. let exitSet = this.privateExitSet(targets);
  749. for (let s of exitSet) {
  750. for (let h of s.myHistory) {
  751. let f = function (s0) {
  752. return s0.ancestors.length > 0 && s0.myParent === s;
  753. }
  754. if (h instanceof DeepHistoryState) {
  755. f = function (s0) {
  756. return s0.descendants.length === 0 && s.descendants.indexOf(s0) >= 0;
  757. }
  758. }
  759. this.obj.historyValues[h.stateId] = this.obj.configuration.filter(f);
  760. }
  761. }
  762. for (let s of exitSet) {
  763. console.log("EXIT", s.name);
  764. if (s.exit != null) {
  765. s.exit();
  766. }
  767. }
  768. this.obj.configuration = this.obj.configuration.filter(function (el) {
  769. return exitSet.indexOf(el) < 0;
  770. })
  771. // combo state changed area
  772. this.obj.comboStep.changed.push(this.lca);
  773. for (let d of this.lca.descendants) {
  774. this.obj.comboStep.changed.push(d);
  775. }
  776. // execute transition action(s)
  777. if (this.action != null) {
  778. let params = [];
  779. if (this.enabledEvent != null) params = this.enabledEvent.parameters;
  780. this.action(params);
  781. }
  782. // enter states...
  783. for (let s of this.privateEnterSet(targets)) {
  784. this.obj.configuration.push(s);
  785. console.log("ENTER", s.name);
  786. if (s.enter != null) {
  787. s.enter();
  788. }
  789. }
  790. this.obj.configuration = this.obj.configuration.sort(function (a, b) {
  791. return a.stateId - b.stateId
  792. })
  793. this.enabledEvent = null;
  794. }
  795. Transition.prototype.privateGetEffectiveTargetStates = function () {
  796. let targets = []
  797. for (let target of this.targets) {
  798. for (let effectiveTarget of target.getEffectiveTargetStates()) {
  799. if (targets.indexOf(effectiveTarget) < 0) {
  800. targets.push(effectiveTarget);
  801. }
  802. }
  803. }
  804. return targets;
  805. }
  806. Transition.prototype.privateExitSet = function (targets) {
  807. let exitSet = this.lca.descendants.slice(0).filter(function (obj) {
  808. return function (s) {
  809. return obj.obj.configuration.indexOf(s) >= 0;
  810. }
  811. }(this));
  812. exitSet.reverse();
  813. return exitSet;
  814. }
  815. Transition.prototype.privateEnterSet = function* (targets) {
  816. let target = targets[0];
  817. let reversedAncestors = target.ancestors.slice(0).reverse();
  818. for (let a of reversedAncestors) {
  819. if (this.source.ancestors.indexOf(a) >= 0) {
  820. } else {
  821. yield a;
  822. }
  823. }
  824. for (let target of targets) {
  825. yield target;
  826. }
  827. }
  828. Transition.prototype.setGuard = function (guard) {
  829. this.guard = guard.bind(this.obj);
  830. }
  831. Transition.prototype.setAction = function (action) {
  832. this.action = action.bind(this.obj);
  833. }
  834. Transition.prototype.setTrigger = function (trigger) {
  835. this.trigger = trigger;
  836. if (this.trigger === null) {
  837. this.source.hasEventlessTransitions = true;
  838. }
  839. }
  840. Transition.prototype.optimize = function () {
  841. let target = this.targets[0];
  842. this.lca = this.source.myParent;
  843. if (this.source.myParent !== target.myParent) { // external
  844. for (let a of this.source.ancestors) {
  845. if (target.ancestors.indexOf(a) >= 0) {
  846. this.lca = a;
  847. break;
  848. }
  849. }
  850. }
  851. }
  852. // RuntimeClassBase
  853. function RuntimeClassBase(controller) {
  854. this.active = false;
  855. this.privateSetStable(true);
  856. this.events = new EventQueue();
  857. this.controller = controller;
  858. this.inports = {};
  859. this.timers = {};
  860. this.states = {};
  861. this.semantics = new DefaultStatechartSemantics();
  862. }
  863. RuntimeClassBase.prototype.eventlessTransitions = function () {
  864. for (let s of this.configuration) {
  865. if (s.hasEventlessTransitions) return true;
  866. }
  867. return false;
  868. }
  869. RuntimeClassBase.prototype.start = function () {
  870. this.configuration = [];
  871. this.currentState = {};
  872. this.historyValues = {};
  873. this.timers = {};
  874. this.timersToAdd = {};
  875. this.bigStep = new BigStepState();
  876. this.comboStep = new ComboStepState();
  877. this.smallStep = new SmallStepState();
  878. this.active = true;
  879. this.privateSetStable(false);
  880. this.initializeStatechart();
  881. this.processBigStepOutput();
  882. };
  883. RuntimeClassBase.prototype.sccdYield = function () {
  884. return Math.max(0, (time() - this.controller.simulatedTime) / 1000.0);
  885. }
  886. RuntimeClassBase.prototype.getSimulatedTime = function () {
  887. return this.controller.simulatedTime;
  888. }
  889. RuntimeClassBase.prototype.updateConfiguration = function (states) {
  890. this.configuration = states.slice(0);
  891. };
  892. RuntimeClassBase.prototype.stop = function () {
  893. this.active = false;
  894. this.privateSetStable(false);
  895. };
  896. RuntimeClassBase.prototype.addTimer = function (index, timeout) {
  897. this.timersToAdd[index] = new EventQueueEntry(this.controller.simulatedTime + Math.trunc(timeout * 1000), new Event('event' + index + 'After'));
  898. };
  899. RuntimeClassBase.prototype.removeTimer = function (index) {
  900. if (index in this.timersToAdd) delete this.timersToAdd[index];
  901. this.events.remove(this.timers[index]);
  902. delete this.timers[index];
  903. };
  904. RuntimeClassBase.prototype.addEvent = function (eventList, timeOffset) {
  905. if (timeOffset === undefined) timeOffset = 0;
  906. let eventTime = this.controller.simulatedTime + timeOffset;
  907. if (eventTime < this.earliestEventTime) {
  908. this.earliestEventTime = eventTime;
  909. }
  910. if (!(eventList instanceof Array)) {
  911. eventList = [eventList];
  912. }
  913. for (let i in eventList) {
  914. if (!eventList.hasOwnProperty(i)) continue;
  915. this.events.add(new EventQueueEntry(this.controller.simulatedTime + timeOffset, eventList[i]));
  916. }
  917. };
  918. RuntimeClassBase.prototype.getEarliestEventTime = function () {
  919. return this.earliestEventTime;
  920. };
  921. RuntimeClassBase.prototype.processBigStepOutput = function () {
  922. let o = this.bigStep.outputEventsPort;
  923. let om = this.bigStep.outputEventsPm;
  924. for (let e in o) {
  925. if (!o.hasOwnProperty(e)) continue;
  926. this.controller.outputEvent(o[e]);
  927. }
  928. for (let e in om) {
  929. if (!om.hasOwnProperty(e)) continue;
  930. this.controller.objectManager.addEvent(om[e]);
  931. }
  932. };
  933. RuntimeClassBase.prototype.privateSetStable = function (stable) {
  934. this.stable = stable;
  935. // self.earliestEventTime keeps track of the earliest time this instance will execute a transition
  936. if (!this.stable) {
  937. this.earliestEventTime = 0.0;
  938. } else if (!this.active) {
  939. this.earliestEventTime = Infinity;
  940. } else {
  941. this.earliestEventTime = this.events.getEarliestTime();
  942. }
  943. }
  944. RuntimeClassBase.prototype.step = function (delta) {
  945. let stable = false;
  946. while (!stable) {
  947. let due = [];
  948. if (this.events.getEarliestTime() <= this.controller.simulatedTime) {
  949. due = [this.events.pop()];
  950. }
  951. stable = !this.performBigStep(due);
  952. this.processBigStepOutput();
  953. }
  954. for (let key in this.timersToAdd) {
  955. if (!this.timersToAdd.hasOwnProperty(key)) continue;
  956. this.timers[key] = this.events.add(this.timersToAdd[key]);
  957. }
  958. this.timersToAdd = {};
  959. this.privateSetStable(true);
  960. };
  961. RuntimeClassBase.prototype.inState = function (stateStrings) {
  962. let stateIds = [];
  963. for (let stateString of stateStrings) {
  964. stateIds.push(this.states[stateString].stateId);
  965. }
  966. for (let stateId of stateIds) {
  967. let found = false;
  968. for (let s of this.configuration) {
  969. if (s.stateId === stateId) {
  970. found = true;
  971. break;
  972. }
  973. }
  974. if (!found) return false;
  975. }
  976. return true;
  977. };
  978. RuntimeClassBase.prototype.performBigStep = function (inputEvents) {
  979. this.bigStep.next(inputEvents);
  980. this.smallStep.reset();
  981. this.comboStep.reset();
  982. while (this.performComboStep()) {
  983. this.bigStep.hasStepped = true;
  984. if (this.semantics.bigStepMaximality === StatechartSemantics.TakeOne)
  985. break;
  986. }
  987. return this.bigStep.hasStepped;
  988. };
  989. RuntimeClassBase.prototype.performComboStep = function () {
  990. this.comboStep.next();
  991. while (this.performSmallStep()) {
  992. this.comboStep.hasStepped = true;
  993. }
  994. return this.comboStep.hasStepped;
  995. };
  996. // generate transition candidates for current small step
  997. RuntimeClassBase.prototype.generateCandidates = function () {
  998. let enabledEvents = this.getEnabledEvents();
  999. let enabledTransitions = [];
  1000. for (let s of this.configuration) {
  1001. if (this.comboStep.changed.indexOf(s) < 0) {
  1002. for (let t of s.transitions) {
  1003. if (t.isEnabled(enabledEvents)) {
  1004. enabledTransitions.push(t);
  1005. }
  1006. }
  1007. }
  1008. }
  1009. return enabledTransitions;
  1010. };
  1011. RuntimeClassBase.prototype.performSmallStep = function () {
  1012. let privateYoungerThan =
  1013. function (x, y) {
  1014. if (y.source.ancestors.indexOf(x.source) >= 0) {
  1015. return 1;
  1016. } else if (x.source.ancestors.indexOf(y.source) >= 0) {
  1017. return -1;
  1018. } else {
  1019. throw new Exception('These items have no relation with each other.');
  1020. }
  1021. };
  1022. if (this.smallStep.hasStepped) {
  1023. this.smallStep.next();
  1024. }
  1025. let candidates = this.generateCandidates();
  1026. if (candidates.length > 0) {
  1027. toSkip = new Set();
  1028. conflicting = [];
  1029. for (var i in candidates) {
  1030. c1 = candidates[i];
  1031. if (!toSkip.has(c1)) {
  1032. conflict = [c1];
  1033. for (let j in candidates.slice(candidates.indexOf(c1))) {
  1034. c2 = candidates[j];
  1035. if (c1.source.ancestors.indexOf(c2.source) >= 0 || c2.source.ancestors.indexOf(c1.source) >= 0) {
  1036. conflict.push(c2);
  1037. toSkip.add(c2);
  1038. }
  1039. }
  1040. conflicting.push(conflict.sort(privateYoungerThan));
  1041. }
  1042. }
  1043. if (this.semantics.concurrency === StatechartSemantics.Single) {
  1044. let candidate = conflicting[0];
  1045. if (this.semantics.priority === StatechartSemantics.SourceParent) {
  1046. candidate[candidate.length - 1].fire();
  1047. } else {
  1048. candidate[0].fire();
  1049. }
  1050. } else if (this.semantics.concurrency === StatechartSemantics.Many) {
  1051. // TODO: Implement
  1052. }
  1053. this.smallStep.hasStepped = true;
  1054. }
  1055. return this.smallStep.hasStepped;
  1056. };
  1057. RuntimeClassBase.prototype.getEnabledEvents = function () {
  1058. let result = this.smallStep.currentEvents.concat(this.comboStep.currentEvents);
  1059. if (this.semantics.inputEventLifeline === StatechartSemantics.Whole ||
  1060. (!this.bigStep.hasStepped &&
  1061. (this.semantics.inputEventLifeline === StatechartSemantics.FirstComboStep ||
  1062. (!this.comboStep.hasStepped &&
  1063. this.semantics.inputEventLifeline === StatechartSemantics.FirstSmallStep)))) {
  1064. result = result.concat(this.bigStep.inputEvents);
  1065. }
  1066. return result;
  1067. };
  1068. RuntimeClassBase.prototype.raiseInternalEvent = function (theEvent) {
  1069. if (this.semantics.internalEventLifeline === StatechartSemantics.NextSmallStep) {
  1070. this.smallStep.addNextEvent(theEvent);
  1071. } else if (this.semantics.internalEventLifeline === StatechartSemantics.NextComboStep) {
  1072. this.comboStep.addNextEvent(theEvent);
  1073. } else if (this.semantics.internalEventLifeline === StatechartSemantics.Queue) {
  1074. this.events.add(new EventQueueEntry(0.0, theEvent));
  1075. }
  1076. };
  1077. RuntimeClassBase.prototype.initializeStatechart = function () {
  1078. this.updateConfiguration(this.defaultTargets);
  1079. for (let state of this.defaultTargets) {
  1080. if (state.enter != null) {
  1081. state.enter();
  1082. }
  1083. }
  1084. };
  1085. RuntimeClassBase.prototype.getInPortName = function (name) {
  1086. // const portName = this.inports[name];
  1087. // if ( portName != null ) {
  1088. // return portName;
  1089. // }
  1090. return name;
  1091. };
  1092. RuntimeClassBase.prototype.getOutPortName = function (name) {
  1093. // const portName = this.outports[name];
  1094. // if ( portName != null ) {
  1095. // return portName;
  1096. // }
  1097. return name;
  1098. };
  1099. let BigStepState = function () {
  1100. this.inputEvents = [];
  1101. this.outputEventsPort = [];
  1102. this.outputEventsPm = [];
  1103. this.hasStepped = true;
  1104. this.transitions = 0;
  1105. };
  1106. BigStepState.prototype.next = function (inputEvents) {
  1107. this.inputEvents = inputEvents;
  1108. this.outputEventsPort = [];
  1109. this.outputEventsPm = [];
  1110. this.hasStepped = false;
  1111. this.transitions = 0;
  1112. };
  1113. BigStepState.prototype.outputEvent = function (event) {
  1114. this.outputEventsPort.push(event);
  1115. };
  1116. BigStepState.prototype.outputEventOm = function (event) {
  1117. this.outputEventsPm.push(event);
  1118. };
  1119. let ComboStepState = function () {
  1120. this.currentEvents = [];
  1121. this.nextEvents = [];
  1122. this.changed = [];
  1123. this.hasStepped = true;
  1124. };
  1125. ComboStepState.prototype.reset = function () {
  1126. this.currentEvents = [];
  1127. this.nextEvents = [];
  1128. };
  1129. ComboStepState.prototype.next = function () {
  1130. this.currentEvents = this.nextEvents;
  1131. this.nextEvents = [];
  1132. this.changed = [];
  1133. this.hasStepped = false;
  1134. };
  1135. ComboStepState.prototype.addNextEvent = function (event) {
  1136. this.nextEvents.push(event);
  1137. };
  1138. ComboStepState.prototype.setArenaChanged = function (arena) {
  1139. this.changed.push(arena);
  1140. };
  1141. ComboStepState.prototype.isArenaChanged = function (arena) {
  1142. return (this.changed.indexOf(arena) !== -1);
  1143. };
  1144. ComboStepState.prototype.isStable = function () {
  1145. return (this.changed.length === 0);
  1146. };
  1147. let SmallStepState = function () {
  1148. this.currentEvents = [];
  1149. this.nextEvents = [];
  1150. this.candidates = [];
  1151. this.hasStepped = true;
  1152. };
  1153. SmallStepState.prototype.reset = function () {
  1154. this.currentEvents = [];
  1155. this.nextEvents = [];
  1156. };
  1157. SmallStepState.prototype.next = function () {
  1158. this.currentEvents = this.nextEvents;
  1159. this.nextEvents = [];
  1160. this.candidates = [];
  1161. this.hasStepped = false;
  1162. };
  1163. SmallStepState.prototype.addNextEvent = function (event) {
  1164. this.nextEvents.push(event);
  1165. };
  1166. SmallStepState.prototype.addCandidate = function (t, p) {
  1167. this.candidates.push({transition: t, parameters: p});
  1168. };
  1169. SmallStepState.prototype.hasCandidates = function () {
  1170. return (this.candidates.length > 0);
  1171. };