Bladeren bron

Finished digital watch example in browser, through Rust -> WebAssembly. Also: Re-implemented controller's event queue and timer cancellations.

Joeri Exelmans 5 jaren geleden
bovenliggende
commit
386dd1cf97

+ 1 - 0
examples/digitalwatch/codegen/.gitignore

@@ -0,0 +1 @@
+/target/

+ 13 - 0
examples/digitalwatch/codegen/Cargo.toml

@@ -0,0 +1,13 @@
+[package]
+name = "digitalwatch"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+sccd = { path = "/home/maestro/thesis/repos/SCCD/src/sccd/../../rust" }
+wasm-bindgen = "*"
+
+[lib]
+name = "digitalwatch"
+path = "digitalwatch.rs"
+

File diff suppressed because it is too large
+ 1970 - 0
examples/digitalwatch/codegen/digitalwatch.rs


examples/digitalwatch/model_digitalwatch.svg → examples/digitalwatch/digitalwatch.svg


+ 2 - 2
examples/digitalwatch/model_digitalwatch.xml

@@ -5,7 +5,7 @@
     <semantics
       big_step_maximality="take_one"
       internal_event_lifeline="next_small_step"
-      input_event_lifeline="first_small_step"
+      input_event_lifeline="whole"
     />
 
     <inport name="in">
@@ -184,7 +184,7 @@
               <onentry>
                 <raise event="increaseSelection"/>
               </onentry>
-              <transition after="100 ms" target="."/>
+              <transition after="300 ms" target="."/>
               <transition event="bottomLeftReleased" target="../Waiting"/>
             </state>
           </state>

examples/digitalwatch/model_digitalwatch_priorities.svg → examples/digitalwatch/digitalwatch_priorities.svg


+ 291 - 0
examples/digitalwatch/index.html

@@ -0,0 +1,291 @@
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>DWatch</title>
+  <style type="text/css">
+    body {
+      background-color: #000;
+      color: #fff;
+    }
+    #canvas{
+      /* center on page */
+      position: absolute;
+      top:0; left:0; bottom:0; right:0;
+      margin: auto;
+    }
+    @font-face{
+      font-family: 'digital-font';
+      src: url('font.ttf');
+    }
+    svg text{
+      font: 28px digital-font;
+    }
+    /* disable text selection */
+    svg text {
+      cursor: default;
+        -webkit-user-select: none;
+           -moz-user-select: none;
+            -ms-user-select: none;
+                user-select: none;
+    }
+  </style>
+</head>
+<body>
+  <svg version="1.1"
+     baseProfile="full"
+     width="222" height="236"
+     xmlns="http://www.w3.org/2000/svg"
+     id="canvas">
+
+    <image width="222" height="236" xlink:href="watch.gif"/>
+
+      <rect id="display" x="51" y="95" width="120" height="55" rx="2" fill="#DCDCDC">
+      </rect>
+      <text id="timeText" x="111" y="126" dominant-baseline="middle" text-anchor="middle"></text>
+      <text id="chronoText" x="111" y="126" dominant-baseline="middle" text-anchor="middle" style="display:none"></text>
+      <text id="alarmText" x="111" y="126" dominant-baseline="middle" text-anchor="middle" style="display:none"></text>
+
+    <rect id="topLeft" x="0" y="59", width="16", height="16" fill="#fff" fill-opacity="0.2" />
+    <rect id="topRight" x="206" y="57", width="16", height="16" fill="#fff" fill-opacity="0.2" />
+    <rect id="bottomLeft" x="0" y="158", width="16", height="16" fill="#fff" fill-opacity="0.2" />
+    <rect id="bottomRight" x="208" y="158", width="16", height="16" fill="#fff" fill-opacity="0.2" />
+
+    <image id="note" x="54" y="96" xlink:href="noteSmall.gif" style="display:none"/>
+  </svg>
+  <p id="log">
+  </p>
+
+  <script type="module">
+    Number.prototype.pad = function(size) {
+      let s = String(this);
+      while (s.length < (size || 2)) {s = "0" + s;}
+      return s;
+    };
+
+    class DisplayText {
+      constructor(initial, max, element) {
+        this.initial = initial;
+        this.max = max;
+        this.element = element;
+
+        this.values = [...initial];
+        this.selected = 0;
+        this.timeout = null;
+
+        this.render();
+      }
+      increment() {
+        this.values[0] += 1;
+        this.values[1] += Math.floor(this.values[0] / this.max[0]);
+        this.values[2] += Math.floor(this.values[1] / this.max[1]);
+        this.values[0] %= this.max[0];
+        this.values[1] %= this.max[1];
+        this.values[2] %= this.max[2];
+        this.render();
+      }
+      reset() {
+        this.values = [... this.initial]
+        this.render();
+      }
+      render() {
+        this.element.textContent =
+          this.values[2].pad(2) + ':' +
+          this.values[1].pad(2) + ':' +
+          this.values[0].pad(2);
+      }
+      blink0() {
+        this.element.textContent =
+          (this.selected === 2 ? "__" : this.values[2].pad(2)) + ':' +
+          (this.selected === 1 ? "__" : this.values[1].pad(2)) + ':' +
+          (this.selected === 0 ? "__" : this.values[0].pad(2));
+        this.timeout = setTimeout(this.blink1.bind(this), 500);
+      }
+      blink1() {
+        this.render();
+        this.timeout = setTimeout(this.blink0.bind(this), 500);
+      }
+      selectionStart() {
+        this.selected = 2;
+        this.blink0();
+      }
+      selectionStop() {
+        clearTimeout(this.timeout);
+        this.render();
+      }
+      selectionNext() {
+        this.selected -= 1;
+        if (this.selected < 0)
+          this.selected = 2;
+        clearTimeout(this.timeout);
+        this.blink0();
+      }
+      selectionIncrease() {
+        this.values[this.selected] += 1;
+        this.values[this.selected] %= this.max[this.selected];
+        clearTimeout(this.timeout);
+        this.blink1();
+      }
+      show() {
+        this.element.style.display = "";
+      }
+      hide() {
+        this.element.style.display = "none";
+      }
+      isVisible() {
+        return this.element.style.display !== "none";
+      }
+    }
+
+    (async () => {
+      const startedAt = new Date()
+      const timeZero = +startedAt;
+      const realtime = () => +new Date() - timeZero;
+      const [rust, outputhandler] = await Promise.all([
+        import("./wasm/pkg/dwatch.js"),
+        import("./wasm/outputhandler.js"),
+      ]);
+      const memory = await rust.default();
+      let purposefully_behind = 0;
+
+      const elementNote = document.getElementById("note");
+      const elementDisplay = document.getElementById("display");
+
+      // Time is equal to wall-clock time
+      const time = new DisplayText([startedAt.getSeconds(), startedAt.getMinutes(), startedAt.getHours()], [60, 60, 24], document.getElementById("timeText"));
+
+      // Chrono is zero
+      const chrono = new DisplayText([0, 0, 0], [100, 60, 100], document.getElementById("chronoText"));
+
+      const alarm = new DisplayText([startedAt.getSeconds(), startedAt.getMinutes(), startedAt.getHours()], [60, 60, 24], document.getElementById("alarmText"));
+
+      // Alarm is always equal to time + 10 seconds (makes it easier to test the alarm)
+      for (let i=0; i<10; i++) {
+        alarm.increment();
+      }
+
+      const onVisible = (objs, operation) => {
+        objs.forEach(obj => {
+          if (obj.isVisible()) {
+            obj[operation]();
+          }
+        })
+      }
+
+      const outHandler = new outputhandler.OutputHandler(outEvent => {
+        switch (outEvent) {
+          case rust.OutEvent.E_setAlarm:
+            // console.log("setAlarm");
+            if (elementNote.style.display === "") {
+              elementNote.style.display = "none";
+            } else {
+              elementNote.style.display = "";
+            }
+            break;
+          case rust.OutEvent.E_setIndiglo:
+            // console.log("setIndiglo");
+            elementDisplay.setAttribute("fill", "#96DCFA");
+            break;
+          case rust.OutEvent.E_unsetIndiglo:
+            // console.log("unsetIndiglo");
+            elementDisplay.setAttribute("fill", "#DCDCDC");
+            break;
+          case rust.OutEvent.E_startSelection:
+            // console.log("startSelection");
+            onVisible([time, alarm], "selectionStart")
+            break;
+          case rust.OutEvent.E_selectNext:
+            // console.log("selectNext");
+            onVisible([time, alarm], "selectionNext")
+            break;
+          case rust.OutEvent.E_stopSelection:
+            // console.log("stopSelection");
+            onVisible([time, alarm], "selectionStop")
+            break;
+          case rust.OutEvent.E_increaseSelection:
+            // console.log("increaseSelection");
+            onVisible([time, alarm], "selectionIncrease")
+            break;
+          case rust.OutEvent.E_refreshTimeDisplay:
+            // console.log("refreshTimeDisplay");
+            chrono.hide();
+            alarm.hide();
+            time.show();
+            break;
+          case rust.OutEvent.E_refreshChronoDisplay:
+            // console.log("refreshChronoDisplay");
+            time.hide();
+            alarm.hide();
+            chrono.show();
+            break;
+          case rust.OutEvent.E_refreshAlarmDisplay:
+            // console.log("refreshAlarmDisplay");
+            time.hide();
+            chrono.hide();
+            alarm.show();
+            break;
+          case rust.OutEvent.E_increaseTimeByOne:
+            // console.log("increaseTimeByOne");
+            time.increment();
+            break;
+          case rust.OutEvent.E_increaseChronoByOne:
+            // console.log("increaseChronoByOne");
+            chrono.increment();
+            break;
+          case rust.OutEvent.E_resetChrono:
+            // console.log("resetChrono");
+            chrono.reset();
+            break;
+          case rust.OutEvent.E_checkTime:
+            // console.log("checkTime");
+            for (let i=0; i<3; i++) {
+              if (alarm.values[i] !== time.values[i])
+                return;
+            }
+            setTimeout(() => {
+              rust.add_event(handle, realtime() - simtime, rust.InEvent.E_alarmStart);
+              wakeup();
+            }, 0);
+            break;
+        }
+      });
+
+      // (Soft) Real-time simulation
+      const handle = rust.setup(outHandler);
+      let timeout;
+      let simtime;
+      const wakeup = () => {
+        clearTimeout(timeout);
+        const status = rust.run_until(handle, realtime() + purposefully_behind, outHandler);
+        simtime = status.simtime;
+
+        if (status.reschedule) {
+          let sleep_duration = status.at - realtime();
+          if (sleep_duration < 0) {
+            purposefully_behind = sleep_duration;
+            sleep_duration = 0;
+          }
+          else {
+            purposefully_behind = 0;
+          }
+          timeout = setTimeout(wakeup, sleep_duration);
+        }
+      }
+      wakeup();
+
+      // Send input events
+      ["topLeft", "topRight", "bottomLeft", "bottomRight"].forEach(button => {
+        document.getElementById(button).onmousedown = () => {
+          // console.log(button + "Pressed");
+          const nextWakeup = rust.add_event(handle, realtime() - simtime, rust.InEvent["E_"+button+"Pressed"]);
+          wakeup();
+        }
+        document.getElementById(button).onmouseup = () => {
+          // console.log(button + "Released");
+          const nextWakeup = rust.add_event(handle, realtime() - simtime, rust.InEvent["E_"+button+"Released"]);
+          wakeup();
+        }
+      })
+    })();
+  </script>
+</body>
+</html>

+ 0 - 76
examples/digitalwatch/run.html

@@ -1,76 +0,0 @@
-<html>
-<head>
-  <meta charset="utf-8">
-  <title>DWatch</title>
-  <style type="text/css">
-    body {
-      background-color: #000;
-      color: #fff;
-    }
-    #canvas{
-      /* center on page */
-      position: absolute;
-      top:0; left:0; bottom:0; right:0;
-      margin: auto;
-    }
-    @font-face{
-      font-family: 'digital-font';
-      src: url('font.ttf');
-    }
-    #displayText{
-      font: 28px digital-font;
-    }
-    /* disable text selection */
-    svg text {
-      cursor: default;
-        -webkit-user-select: none;
-           -moz-user-select: none;
-            -ms-user-select: none;
-                user-select: none;
-    }
-  </style>
-</head>
-<body>
-  <svg version="1.1"
-     baseProfile="full"
-     width="222" height="236"
-     xmlns="http://www.w3.org/2000/svg"
-     id="canvas">
-
-    <image width="222" height="236" xlink:href="watch.gif"/>
-
-      <rect id="display" x="51" y="95" width="120" height="55" rx="2" fill="#DCDCDC">
-      </rect>
-      <text id="displayText" x="111" y="126" dominant-baseline="middle" text-anchor="middle">12:00:00</text>
-
-    <rect id="topLeft" x="3" y="62", width="10", height="10" fill="#fff" fill-opacity="0.2" />
-    <rect id="topRight" x="209" y="60", width="10", height="10" fill="#fff" fill-opacity="0.2" />
-    <rect id="bottomLeft" x="2" y="161", width="10", height="10" fill="#fff" fill-opacity="0.2" />
-    <rect id="bottomRight" x="211" y="161", width="10", height="10" fill="#fff" fill-opacity="0.2" />
-
-    <image id="note" x="54" y="96" xlink:href="noteSmall.gif"/>
-  </svg>
-  <p id="log">
-  </p>
-
-  <script type="module">
-    (async () => {
-      const rust = await import("./wasm/pkg/dwatch.js");
-
-      const m = await rust.default();
-
-      m.get_statechart();
-    })();
-
-
-    function log(msg) {
-      // document.getElementById("log").innerText += msg + '\n';
-    }
-
-    ["topLeft", "topRight", "bottomLeft", "bottomRight"].forEach(button => {
-      document.getElementById(button).onmousedown = () => log(button + " pressed");
-      document.getElementById(button).onmouseup = () => log(button + " released");
-    })
-  </script>
-</body>
-</html>

+ 1 - 1
examples/digitalwatch/run.py

@@ -26,7 +26,7 @@ def main():
             method = getattr(gui.controller, event.name)
             method()
 
-    cd = load_cd("model_digitalwatch.xml")
+    cd = load_cd("digitalwatch.xml")
 
     # from sccd.statechart.static import tree
     # tree.concurrency_arena_orthogonal( cd.statechart.tree )

+ 2 - 0
examples/digitalwatch/wasm/.gitignore

@@ -0,0 +1,2 @@
+/pkg/
+/target/

+ 33 - 0
examples/digitalwatch/wasm/Cargo.toml

@@ -0,0 +1,33 @@
+[package]
+name = "wasm"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+digitalwatch = { path = "../codegen" }
+sccd = { path = "/home/maestro/thesis/repos/SCCD/src/sccd/../../rust" }
+wasm-bindgen = "^0.2"
+
+# The `console_error_panic_hook` crate provides better debugging of panics by
+# logging them with `console.error`. This is great for development, but requires
+# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
+# code size when deploying.
+console_error_panic_hook = { version = "0.1.6", optional = true }
+
+# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
+# compared to the default allocator's ~10K. It is slower than the default
+# allocator, however.
+#
+# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
+# wee_alloc = { version = "0.4.5", optional = true }
+
+[lib]
+name = "dwatch"
+path = "lib.rs"
+crate-type = ["cdylib", "rlib"]
+
+[features]
+default = ["console_error_panic_hook"]
+
+[profile.release]
+opt-level = 3

+ 74 - 0
examples/digitalwatch/wasm/lib.rs

@@ -0,0 +1,74 @@
+use wasm_bindgen::prelude::*;
+
+use sccd::controller;
+use sccd::statechart;
+
+// Traits
+use sccd::statechart::SC;
+use sccd::statechart::Scheduler;
+
+
+#[wasm_bindgen]
+extern "C" {
+  #[wasm_bindgen(js_namespace = console)]
+  fn log(s: &str);
+}
+
+#[wasm_bindgen(module = "/outputhandler.js")]
+extern "C" {
+  pub type OutputHandler;
+
+  #[wasm_bindgen(method)]
+  fn handle_output(this: &OutputHandler, e: digitalwatch::OutEvent);
+}
+
+
+#[wasm_bindgen]
+extern {
+  fn alert(s: &str);
+}
+
+#[wasm_bindgen]
+pub struct Handle {
+  controller: controller::Controller<digitalwatch::InEvent>,
+  statechart: digitalwatch::Statechart<controller::TimerId<digitalwatch::InEvent>>,
+}
+
+#[wasm_bindgen]
+pub fn setup(out: &OutputHandler) -> Handle {
+  let mut controller = controller::Controller::<digitalwatch::InEvent>::new();
+  let mut statechart = digitalwatch::Statechart::<controller::TimerId<digitalwatch::InEvent>>::default();
+  statechart.init(&mut controller, &mut |e|{ out.handle_output(e) });
+
+  Handle{controller, statechart}
+}
+
+#[wasm_bindgen]
+pub fn add_event(h: &mut Handle, delay: statechart::Timestamp, i: digitalwatch::InEvent) -> RunUntilResult {
+  h.controller.set_timeout(delay, i);
+  RunUntilResult::from_controller(&h.controller)
+}
+
+#[wasm_bindgen]
+pub struct RunUntilResult {
+  pub simtime: statechart::Timestamp,
+  pub reschedule: bool,
+  pub at: statechart::Timestamp,
+}
+
+impl RunUntilResult {
+  fn from_controller(c: &controller::Controller::<digitalwatch::InEvent>) -> Self {
+    let mut result = match c.get_earliest() {
+      controller::Until::Timestamp(t) => RunUntilResult{reschedule: true, at: t, simtime: 0},
+      controller::Until::Eternity => RunUntilResult{reschedule: false, at: 0, simtime: 0},
+    };
+    result.simtime = c.get_simtime();
+    result
+  }
+}
+
+#[wasm_bindgen]
+pub fn run_until(h: &mut Handle, t: statechart::Timestamp, out: &OutputHandler) -> RunUntilResult {
+  h.controller.run_until(&mut h.statechart, controller::Until::Timestamp(t), &mut |e|{ out.handle_output(e) });
+  RunUntilResult::from_controller(&h.controller)
+}

+ 10 - 0
examples/digitalwatch/wasm/outputhandler.js

@@ -0,0 +1,10 @@
+
+export class OutputHandler {
+  constructor(cb) {
+    this.cb = cb;
+  }
+
+  handle_output(out_event) {
+    this.cb(out_event);
+  }
+}

+ 80 - 49
rust/src/controller.rs

@@ -1,8 +1,14 @@
 // Implementation of "Controller", a primitive for simulation of statecharts.
 
 use std::collections::BinaryHeap;
+use std::collections::binary_heap;
+use std::collections::HashMap;
+use std::collections::hash_map;
 use std::cmp::Ordering;
 use std::cmp::Reverse;
+use std::rc::Rc;
+use std::rc::Weak;
+use std::cell::Cell;
 
 use crate::statechart::Timestamp;
 use crate::statechart::Scheduler;
@@ -10,21 +16,23 @@ use crate::statechart::SC;
 
 pub type TimerIndex = u16;
 
+// Comparable part of QueueEntry
 #[derive(Default, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
-pub struct TimerId {
+struct EntryCmp {
   timestamp: Timestamp,
 
   // This field maintains FIFO order for equally timestamped entries.
-  n: TimerIndex,
+  idx: TimerIndex,
 }
-
 pub struct QueueEntry<InEvent> {
-  id: TimerId,
+  cmp: EntryCmp,
+  canceled: Cell<bool>, // mutable, even if QueueEntry is immutable
   event: InEvent,
 }
+
 impl<InEvent> Ord for QueueEntry<InEvent> {
   fn cmp(&self, other: &Self) -> Ordering {
-    self.id.cmp(&other.id)
+    self.cmp.cmp(&other.cmp)
   }
 }
 impl<InEvent> PartialOrd for QueueEntry<InEvent> {
@@ -34,34 +42,39 @@ impl<InEvent> PartialOrd for QueueEntry<InEvent> {
 }
 impl<InEvent> PartialEq for QueueEntry<InEvent> {
   fn eq(&self, other: &Self) -> bool {
-    self.id == other.id
+    self.cmp == other.cmp
   }
 }
 impl<InEvent> Eq for QueueEntry<InEvent> {}
 
-
 pub struct Controller<InEvent> {
   simtime: Timestamp,
-  next_id: TimerIndex,
-  queue: BinaryHeap<Reverse<QueueEntry<InEvent>>>,
 
-  // Right now, removed queue entries are put into a second BinaryHeap.
-  // This is not very efficient. Queue entries should be allocated on the heap,
-  // (preferrably using a pool allocator), and directly marked as "removed".
-  // Optionally, if the number of removed items exceeds a threshold, a sweep could remove "removed" entries.
-  removed: BinaryHeap<Reverse<TimerId>>,
+  // Queue entries allocated on the heap.
+  // Reverse<T> turns BinaryHeap into a min-heap.
+  queue: BinaryHeap<Reverse<Rc<QueueEntry<InEvent>>>>,
+  idxs: HashMap<Timestamp, TimerIndex>,
 }
 
-impl<InEvent> Scheduler<InEvent, TimerId> for Controller<InEvent> {
-  fn set_timeout(&mut self, delay: Timestamp, event: InEvent) -> TimerId {
-    let id = TimerId{ timestamp: self.simtime + delay, n: self.next_id };
-    let entry = QueueEntry::<InEvent>{ id, event };
+pub type TimerId<InEvent> = Weak<QueueEntry<InEvent>>;
+
+impl<InEvent> Scheduler<InEvent, TimerId<InEvent>> for Controller<InEvent> {
+  fn set_timeout(&mut self, delay: Timestamp, event: InEvent) -> TimerId<InEvent> {
+    let timestamp = self.simtime + delay;
+    let idx_ref = self.idxs.entry(timestamp).or_default();
+    let idx = *idx_ref;
+    *idx_ref += 1;
+    let cmp = EntryCmp{ timestamp, idx };
+    let entry = Rc::new(QueueEntry::<InEvent>{ cmp, event, canceled: Cell::new(false) });
+    let weak = Rc::downgrade(&entry);
     self.queue.push(Reverse(entry));
-    self.next_id += 1; // TODO: will overflow eventually :(
-    return id
+
+    weak
   }
-  fn unset_timeout(&mut self, id: TimerId) {
-    self.removed.push(Reverse(id));
+  fn unset_timeout(&mut self, weak: &TimerId<InEvent>) {
+    if let Some(strong) = weak.upgrade() {
+      strong.canceled.set(true);
+    }
   }
 }
 
@@ -74,38 +87,56 @@ impl<InEvent: Copy> Controller<InEvent> {
   pub fn new() -> Self {
     Self {
       simtime: 0,
-      next_id: 0,
-      queue: BinaryHeap::with_capacity(8),
-      removed: BinaryHeap::with_capacity(4),
+      queue: BinaryHeap::with_capacity(16),
+      idxs: HashMap::<Timestamp, TimerIndex>::with_capacity(16),
     }
   }
-  pub fn run_until<StatechartType: SC<InEvent, TimerId, Controller<InEvent>, OutputCallback>, OutEvent, OutputCallback: FnMut(OutEvent)>(&mut self, sc: &mut StatechartType, until: Until, output: &mut OutputCallback) {
-    'running: loop {
-      if let Some(Reverse(entry)) = self.queue.peek() {
-        // Check if event was removed
-        if let Some(Reverse(removed)) = self.removed.peek() {
-          if entry.id == *removed {
-            self.queue.pop();
-            self.removed.pop();
-            continue;
-          }
+  pub fn get_simtime(&self) -> Timestamp {
+    self.simtime
+  }
+  pub fn get_earliest(&self) -> Until {
+    match self.queue.peek() {
+      None => Until::Eternity,
+      Some(Reverse(entry)) => Until::Timestamp(entry.cmp.timestamp),
+    }
+  }
+  fn cleanup_idx(map: &mut HashMap<Timestamp, TimerIndex>, entry: &QueueEntry<InEvent>) {
+    if let hash_map::Entry::Occupied(o) = map.entry(entry.cmp.timestamp) {
+      if *o.get() == entry.cmp.idx+1 {
+        o.remove_entry();
+      }
+    };
+  }
+  pub fn run_until<StatechartType: SC<InEvent, Weak<QueueEntry<InEvent>>, Controller<InEvent>, OutputCallback>, OutEvent, OutputCallback: FnMut(OutEvent)>(&mut self, sc: &mut StatechartType, until: Until, output: &mut OutputCallback) -> Until
+  {
+    loop {
+      let Reverse(entry) = if let Some(peek_mut) = self.queue.peek_mut() {
+        let Reverse(ref entry) = *peek_mut;
+
+        // Check if event was canceled
+        if entry.canceled.get() {
+          Self::cleanup_idx(&mut self.idxs, entry);
+          binary_heap::PeekMut::pop(peek_mut);
+          continue;
         }
         // Check if event too far in the future
         if let Until::Timestamp(t) = until {
-          if entry.id.timestamp > t {
-            println!("break, timestamp {}, t {}", entry.id.timestamp, t);
-            break 'running;
+          if entry.cmp.timestamp > t {
+            return until; // return next wakeup
           }
-        }
-        // OK, handle event
-        self.simtime = entry.id.timestamp;
-        // eprintln!("time is now {}", self.simtime);
-        sc.big_step(Some(entry.event), self, output);
-        self.queue.pop();
-      }
-      else {
-        break 'running;
-      }
-    }
+        };
+        // OK, we'll handle the event
+        Self::cleanup_idx(&mut self.idxs, entry);
+        binary_heap::PeekMut::pop(peek_mut) // the return value of this call is the result of our 'if' expression :)
+      } else {
+        break;
+      };
+
+      // Handle event
+      println!("time is now {}", self.simtime);
+      self.simtime = entry.cmp.timestamp;
+      sc.big_step(Some(entry.event), self, output);
+    };
+    Until::Eternity
   }
 }

+ 1 - 1
rust/src/statechart.rs

@@ -79,7 +79,7 @@ pub type Timestamp = u32;
 // scheduler (event queue) implementation.
 pub trait Scheduler<InEvent, TimerId> {
   fn set_timeout(&mut self, delay: Timestamp, event: InEvent) -> TimerId;
-  fn unset_timeout(&mut self, id: TimerId);
+  fn unset_timeout(&mut self, id: &TimerId);
 }
 
 // Generated statechart types will implement this trait.

+ 2 - 2
src/sccd/cd/parser/xml.py

@@ -27,6 +27,6 @@ def cd_parser_rules(statechart_parser_rules, default_delta = duration(100, Micro
 # This is usually how you would want to load a class diagram:
 def load_cd(src):
   import os
-  sc_rules = functools.partial(statechart_parser_rules, path=os.path.dirname(src))
-  cd_rules = cd_parser_rules(sc_rules)
+  sc_rules = functools.partial(statechart_parser_rules, path=os.path.dirname(src), load_external=True)
+  cd_rules = { "single_instance_cd": cd_parser_rules(sc_rules) }
   return parse_f(src, rules=cd_rules)

+ 43 - 28
src/sccd/statechart/codegen/rust.py

@@ -7,6 +7,7 @@ from sccd.statechart.static.statechart import *
 from sccd.statechart.static.globals import *
 from sccd.statechart.static import priority
 from sccd.util.indenting_writer import *
+from sccd.util.wasm import *
 
 # Hardcoded limit on number of sub-rounds of combo and big step to detect never-ending superrounds.
 # TODO: make this a model parameter, also allowing for +infinity
@@ -182,13 +183,15 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         # TODO: evaluate event parameters
         if DEBUG:
             self.w.writeln("eprintln!(\"raise out %s:%s\");" % (event.outport, event.name))
-        self.w.writeln("(output)(OutEvent::%s(%s{}));" % (ident_event_enum_variant(event.name), ident_event_type(event.name)))
+        # self.w.writeln("(output)(OutEvent::%s(%s{}));" % (ident_event_enum_variant(event.name), ident_event_type(event.name)))
+        self.w.writeln("(output)(OutEvent::%s);" % (ident_event_enum_variant(event.name)))
 
     def visit_RaiseInternalEvent(self, event):
         if DEBUG:
             self.w.writeln("eprintln!(\"raise internal %s\");" % (event.name))
         if self.internal_queue:
-            self.w.writeln("sched.set_timeout(%d, InEvent::%s(%s{}));" % (0, ident_event_enum_variant(event.name), ident_event_type(event.name)))
+            # self.w.writeln("sched.set_timeout(%d, InEvent::%s(%s{}));" % (0, ident_event_enum_variant(event.name), ident_event_type(event.name)))
+            self.w.writeln("sched.set_timeout(%d, InEvent::%s);" % (0, ident_event_enum_variant(event.name)))
         else:
             self.w.writeln("internal.raise().%s = Some(%s{});" % (ident_event_field(event.name), (ident_event_type(event.name))))
 
@@ -239,7 +242,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         self.w.writeln("impl %s {" % ident_type(state))
 
         # Enter actions: Executes enter actions of only this state
-        self.w.writeln("  fn enter_actions<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
+        self.w.writeln("  fn enter_actions<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
         if DEBUG:
             self.w.writeln("    eprintln!(\"enter %s\");" % state.full_name);
         self.w.writeln("    let scope = data;")
@@ -248,14 +251,15 @@ class StatechartRustGenerator(ActionLangRustGenerator):
             a.accept(self)
         self.w.dedent(); self.w.dedent()
         for a in state.after_triggers:
-            self.w.writeln("    timers[%d] = sched.set_timeout(%d, InEvent::%s(%s{}));" % (a.after_id, a.delay.opt, ident_event_enum_variant(a.enabling[0].name), ident_event_type(a.enabling[0].name)))
+            # self.w.writeln("    timers[%d] = sched.set_timeout(%d, InEvent::%s(%s{}));" % (a.after_id, a.delay.opt, ident_event_enum_variant(a.enabling[0].name), ident_event_type(a.enabling[0].name)))
+            self.w.writeln("    timers[%d] = sched.set_timeout(%d, InEvent::%s);" % (a.after_id, a.delay.opt, ident_event_enum_variant(a.enabling[0].name)))
         self.w.writeln("  }")
 
         # Enter actions: Executes exit actions of only this state
-        self.w.writeln("  fn exit_actions<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
+        self.w.writeln("  fn exit_actions<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
         self.w.writeln("    let scope = data;")
         for a in state.after_triggers:
-            self.w.writeln("    sched.unset_timeout(timers[%d]);" % (a.after_id))
+            self.w.writeln("    sched.unset_timeout(&timers[%d]);" % (a.after_id))
         self.w.indent(); self.w.indent()
         for a in state.exit:
             a.accept(self)
@@ -265,7 +269,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         self.w.writeln("  }")
 
         # Enter default: Executes enter actions of entering this state and its default substates, recursively
-        self.w.writeln("  fn enter_default<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
+        self.w.writeln("  fn enter_default<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
         self.w.writeln("    %s::enter_actions(timers, data, internal, sched, output);" % (ident_type(state)))
         if isinstance(state.type, AndState):
             for child in state.real_children:
@@ -275,7 +279,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         self.w.writeln("  }")
 
         # Exit current: Executes exit actions of this state and current children, recursively
-        self.w.writeln("  fn exit_current<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(&self, timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
+        self.w.writeln("  fn exit_current<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(&self, timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
         # first, children (recursion):
         if isinstance(state.type, AndState):
             for child in state.real_children:
@@ -290,7 +294,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         self.w.writeln("  }")
 
         # Exit current: Executes enter actions of this state and current children, recursively
-        self.w.writeln("  fn enter_current<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(&self, timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
+        self.w.writeln("  fn enter_current<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(&self, timers: &mut Timers<TimerId>, data: &mut DataModel, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback) {")
         # first, parent:
         self.w.writeln("    %s::enter_actions(timers, data, internal, sched, output);" % (ident_type(state)))
         # then, children (recursion):
@@ -353,16 +357,21 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         # Until we implement event parameters, event types are just empty structs
 
         self.w.writeln("// Input Events")
-        for event_name in input_event_names:
-            self.w.writeln("#[derive(Copy, Clone, Debug)]")
-            self.w.writeln("pub struct %s {" % ident_event_type(event_name))
-            self.w.writeln("  // TODO: input event parameters")
-            self.w.writeln("}")
-
+        # for event_name in input_event_names:
+        #     if WASM:
+        #         self.w.writeln("#[wasm_bindgen]")
+        #     self.w.writeln("#[derive(Copy, Clone, Debug)]")
+        #     self.w.writeln("pub struct %s {" % ident_event_type(event_name))
+        #     self.w.writeln("  // TODO: input event parameters")
+        #     self.w.writeln("}")
+
+        if WASM:
+            self.w.writeln("#[wasm_bindgen]")
         self.w.writeln("#[derive(Copy, Clone, Debug)]")
         self.w.writeln("pub enum InEvent {")
         for event_name in input_event_names:
-            self.w.writeln("  %s(%s)," % (ident_event_enum_variant(event_name), ident_event_type(event_name)))
+            # self.w.writeln("  %s(%s)," % (ident_event_enum_variant(event_name), ident_event_type(event_name)))
+            self.w.writeln("  %s," % (ident_event_enum_variant(event_name)))
         self.w.writeln("}")
         self.w.writeln()
 
@@ -392,16 +401,21 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         # Output events
         output_event_names = self.globals.out_events.names
         self.w.writeln("// Output Events")
-        for event_name in output_event_names:
-            self.w.writeln("#[derive(Copy, Clone, Debug, PartialEq, Eq)]")
-            self.w.writeln("pub struct %s {" % ident_event_type(event_name))
-            self.w.writeln("  // TODO: output event parameters")
-            self.w.writeln("}")
-
+        # for event_name in output_event_names:
+        #     if WASM:
+        #         self.w.writeln("#[wasm_bindgen]")
+        #     self.w.writeln("#[derive(Copy, Clone, Debug, PartialEq, Eq)]")
+        #     self.w.writeln("pub struct %s {" % ident_event_type(event_name))
+        #     self.w.writeln("  // TODO: output event parameters")
+        #     self.w.writeln("}")
+
+        if WASM:
+            self.w.writeln("#[wasm_bindgen]")
         self.w.writeln("#[derive(Copy, Clone, Debug, PartialEq, Eq)]")
         self.w.writeln("pub enum OutEvent {")
         for event_name in output_event_names:
-            self.w.writeln("  %s(%s)," % (ident_event_enum_variant(event_name), ident_event_type(event_name)))
+            # self.w.writeln("  %s(%s)," % (ident_event_enum_variant(event_name), ident_event_type(event_name)))
+            self.w.writeln("  %s," % (ident_event_enum_variant(event_name)))
         self.w.writeln("}")
         self.w.writeln()
 
@@ -463,7 +477,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         self.w.writeln()
 
         # Function fair_step: a single "Take One" Maximality 'round' (= nonoverlapping arenas allowed to fire 1 transition)
-        self.w.writeln("fn fair_step<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(sc: &mut Statechart<TimerId>, input: &mut Option<InEvent>, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback, dirty: Arenas) -> Arenas {")
+        self.w.writeln("fn fair_step<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(sc: &mut Statechart<TimerId>, input: &mut Option<InEvent>, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback, dirty: Arenas) -> Arenas {")
         self.w.writeln("  let mut fired: Arenas = ARENA_NONE;")
         self.w.writeln("  let mut scope = &mut sc.data;")
         self.w.writeln("  let %s = &mut sc.configuration;" % ident_var(tree.root))
@@ -610,7 +624,8 @@ class StatechartRustGenerator(ActionLangRustGenerator):
                         condition = []
                         for e in t.trigger.enabling:
                             if bit(e.id) & input_events:
-                                condition.append("let Some(InEvent::%s(%s{})) = &input" % (ident_event_enum_variant(e.name), ident_event_type(e.name)))
+                                # condition.append("let Some(InEvent::%s(%s{})) = &input" % (ident_event_enum_variant(e.name), ident_event_type(e.name)))
+                                condition.append("let Some(InEvent::%s) = &input" % (ident_event_enum_variant(e.name)))
                             elif bit(e.id) & internal_events:
                                 condition.append("let Some(%s) = &internal.current().%s" % (ident_event_type(e.name), ident_event_field(e.name)))
                             else:
@@ -755,7 +770,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
 
         # Write combo step and big step function
         def write_stepping_function(name: str, title: str, maximality: Maximality, substep: str, cycle_input: bool, cycle_internal: bool):
-            self.w.writeln("fn %s<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(sc: &mut Statechart<TimerId>, input: &mut Option<InEvent>, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback, dirty: Arenas) -> Arenas {" % (name))
+            self.w.writeln("fn %s<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)>(sc: &mut Statechart<TimerId>, input: &mut Option<InEvent>, internal: &mut InternalLifeline, sched: &mut Sched, output: &mut OutputCallback, dirty: Arenas) -> Arenas {" % (name))
             self.w.writeln("  // %s Maximality: %s" % (title, maximality))
             if maximality == Maximality.TAKE_ONE:
                 self.w.writeln("  %s(sc, input, internal, sched, output, dirty)" % (substep))
@@ -801,7 +816,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
         self.w.writeln()
 
         # Implement 'SC' trait
-        self.w.writeln("impl<TimerId: Copy, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)> statechart::SC<InEvent, TimerId, Sched, OutputCallback> for Statechart<TimerId> {")
+        self.w.writeln("impl<TimerId: Default, Sched: statechart::Scheduler<InEvent, TimerId>, OutputCallback: FnMut(OutEvent)> statechart::SC<InEvent, TimerId, Sched, OutputCallback> for Statechart<TimerId> {")
         self.w.writeln("  fn init(&mut self, sched: &mut Sched, output: &mut OutputCallback) {")
         self.w.writeln("    %s::enter_default(&mut self.timers, &mut self.data, &mut Default::default(), sched, output)" % (ident_type(tree.root)))
         self.w.writeln("  }")
@@ -819,7 +834,7 @@ class StatechartRustGenerator(ActionLangRustGenerator):
 
         if DEBUG:
             self.w.writeln("use std::mem::size_of;")
-            self.w.writeln("fn debug_print_sizes<TimerId: Copy>() {")
+            self.w.writeln("fn debug_print_sizes<TimerId: Default>() {")
             self.w.writeln("  eprintln!(\"------------------------\");")
             self.w.writeln("  eprintln!(\"Semantics: %s\");" % sc.semantics)
             self.w.writeln("  eprintln!(\"------------------------\");")

+ 6 - 4
src/sccd/test/codegen/rust.py

@@ -19,7 +19,7 @@ class TestRustGenerator(ClassDiagramRustGenerator):
         self.w.writeln("use sccd::statechart::SC;")
         self.w.writeln("use sccd::statechart::Scheduler;")
         if DEBUG:
-            self.w.writeln("debug_print_sizes::<controller::TimerId>();")
+            self.w.writeln("debug_print_sizes::<controller::TimerId<InEvent>>();")
         self.w.writeln();
 
         self.w.writeln("// Setup ...")
@@ -28,7 +28,7 @@ class TestRustGenerator(ClassDiagramRustGenerator):
         self.w.writeln("  raised.push(out);")
         self.w.writeln("};")
         self.w.writeln("let mut controller = controller::Controller::<InEvent>::new();")
-        self.w.writeln("let mut sc: Statechart::<controller::TimerId> = Default::default();")
+        self.w.writeln("let mut sc: Statechart::<controller::TimerId<InEvent>> = Default::default();")
         self.w.writeln()
         self.w.writeln("// Initialize statechart (execute actions of entering default states)")
         self.w.writeln("sc.init(&mut controller, &mut output);")
@@ -39,14 +39,16 @@ class TestRustGenerator(ClassDiagramRustGenerator):
                 raise UnsupportedFeature("Multiple simultaneous input events not supported")
             elif len(i.events) == 0:
                 raise UnsupportedFeature("Test declares empty bag of input events")
-            self.w.writeln("controller.set_timeout(%d, InEvent::%s(%s{}));" % (i.timestamp.opt, ident_event_enum_variant(i.events[0].name), ident_event_type(i.events[0].name)))
+            # self.w.writeln("controller.set_timeout(%d, InEvent::%s(%s{}));" % (i.timestamp.opt, ident_event_enum_variant(i.events[0].name), ident_event_type(i.events[0].name)))
+            self.w.writeln("controller.set_timeout(%d, InEvent::%s);" % (i.timestamp.opt, ident_event_enum_variant(i.events[0].name)))
         self.w.writeln()
 
         self.w.writeln("// Run simulation, as-fast-as-possible")
         self.w.writeln("controller.run_until(&mut sc, controller::Until::Eternity, &mut output);")
         self.w.writeln()
         self.w.writeln("// Check if output is correct")
-        self.w.writeln("assert_eq!(raised, [%s]);" % ", ".join("OutEvent::%s(%s{})" % (ident_event_enum_variant(e.name), ident_event_type(e.name)) for o in variant.output for e in o))
+        # self.w.writeln("assert_eq!(raised, [%s]);" % ", ".join("OutEvent::%s(%s{})" % (ident_event_enum_variant(e.name), ident_event_type(e.name)) for o in variant.output for e in o))
+        self.w.writeln("assert_eq!(raised, [%s]);" % ", ".join("OutEvent::%s" % (ident_event_enum_variant(e.name)) for o in variant.output for e in o))
 
         self.w.dedent()
         self.w.writeln("}")

+ 7 - 0
src/sccd/test/codegen/write_crate.py

@@ -2,6 +2,7 @@ from sccd.cd.parser.xml import *
 from sccd.test.parser.xml import *
 from sccd.util.indenting_writer import *
 from functools import partial
+from sccd.util.wasm import *
 
 import sccd
 RUST_DIR = os.path.dirname(sccd.__file__) + "/../../rust"
@@ -41,6 +42,10 @@ def write_crate(src, target):
         w.writeln("#![allow(unused_imports)]")
         w.writeln()
 
+        if WASM:
+            w.writeln("use wasm_bindgen::prelude::*;")
+            w.writeln()
+
         if isinstance(parsed, Statechart):
             from sccd.statechart.codegen.rust import StatechartRustGenerator
 
@@ -64,6 +69,8 @@ def write_crate(src, target):
         w.writeln()
         w.writeln("[dependencies]")
         w.writeln("sccd = { path = \"%s\" }" % RUST_DIR)
+        if WASM:
+            w.writeln("wasm-bindgen = \"*\"")
         w.writeln()
         if isinstance(parsed, Test):
             # Tests are compiled to binaries

+ 6 - 0
src/sccd/util/wasm.py

@@ -0,0 +1,6 @@
+import os
+
+try:
+  WASM = bool(os.environ['SCCDWASM']=="1")
+except KeyError:
+  WASM = False