├── .circleci └── config.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── doc ├── documentation.md └── fsm-traffic-light.png ├── fsm-clj.iml ├── project.clj ├── src └── fsm_clj │ ├── core.clj │ └── parser.clj └── test └── fsm_clj └── core_test.clj /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Clojure CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-clojure/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | - image: circleci/clojure:lein-2.7.1 11 | 12 | # Specify service dependencies here if necessary 13 | # CircleCI maintains a library of pre-built images 14 | # documented at https://circleci.com/docs/2.0/circleci-images/ 15 | # - image: circleci/postgres:9.4 16 | 17 | working_directory: ~/repo 18 | 19 | environment: 20 | LEIN_ROOT: "true" 21 | # Customize the JVM maximum heap limit 22 | JVM_OPTS: -Xmx3200m 23 | 24 | steps: 25 | - checkout 26 | 27 | # Download and cache dependencies 28 | - restore_cache: 29 | keys: 30 | - v1-dependencies-{{ checksum "project.clj" }} 31 | # fallback to using the latest cache if no exact match is found 32 | - v1-dependencies- 33 | 34 | - run: lein deps 35 | 36 | - save_cache: 37 | paths: 38 | - ~/.m2 39 | key: v1-dependencies-{{ checksum "project.clj" }} 40 | 41 | # run tests! 42 | - run: lein test 43 | 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .idea/ 11 | .hgignore 12 | .hg/ 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. This change log follows the conventions of [keepachangelog.com](http://keepachangelog.com/). 3 | 4 | ## [Unreleased] 5 | ### Changed 6 | - Add a new arity to `make-widget-async` to provide a different widget shape. 7 | 8 | ## [0.1.1] - 2018-09-14 9 | ### Changed 10 | - Documentation on how to make the widgets. 11 | 12 | ### Removed 13 | - `make-widget-sync` - we're all async, all the time. 14 | 15 | ### Fixed 16 | - Fixed widget maker to keep working when daylight savings switches over. 17 | 18 | ## 0.1.0 - 2018-09-14 19 | ### Added 20 | - Files from the new template. 21 | - Widget maker public API - `make-widget-sync`. 22 | 23 | [Unreleased]: https://github.com/your-name/fsm-clj/compare/0.1.1...HEAD 24 | [0.1.1]: https://github.com/your-name/fsm-clj/compare/0.1.0...0.1.1 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor to control, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fsm-clj 2 | 3 | [![Clojars Project](https://img.shields.io/clojars/v/fsm-clj.svg)](https://clojars.org/fsm-clj) 4 | 5 | A Clojure library designed to create deterministic finite state machines. 6 | 7 | - Easy to use flat one level state machine. 8 | - Define state machines that can accumulate values. 9 | - Transitions with actions and guards. 10 | - Graphically visualize the resulting state machines. 11 | 12 | Refer to the [documentation](doc/documentation.md) for more details. 13 | 14 | 15 | ## Quick Start 16 | 17 | Require the fsm-clj core name space. 18 | 19 | ```clj 20 | (:require [fsm-clj.core :refer :all]) 21 | ``` 22 | 23 | Define a simple traffic light state machine. 24 | 25 | ```clj 26 | (defsm traffic-light 27 | [[:green -> :yellow when :to-yellow] 28 | [:yellow -> :red when :to-red] 29 | [:red -> :green when :to-green]]) 30 | ``` 31 | 32 | Sending events. 33 | 34 | ```clj 35 | (-> (traffic-light) 36 | (send-event :to-yellow) 37 | :state) ;; => :yellow 38 | ``` 39 | 40 | Graphically generate the State Machine (open a Swing viewer). 41 | 42 | ```clj 43 | (show! (traffic-light)) 44 | ``` 45 | 46 | ![Traffic Light Finite State Machine](doc/fsm-traffic-light.png) 47 | 48 | ## License 49 | 50 | Distributed under the Eclipse Public License either version 1.0 or (at 51 | your option) any later version. 52 | -------------------------------------------------------------------------------- /doc/documentation.md: -------------------------------------------------------------------------------- 1 | # fsm-clj doc 2 | 3 | State machines guarantee the behaviour to be always consistent as the rules are written before the machine is started. 4 | With a predefined finite number of states, your application moves from one state to the next based on the 5 | inputs that it receives. 6 | 7 | The idea is to define high-level transitions and then rely on the state machine to manage state. The machine will be 8 | evaluated at compile time, throwing an exception in case of any parsing issue. 9 | 10 | To demonstrate the library usage the following examples will implement a state machine for a coin-operated turnstile. 11 | [more info](https://en.wikipedia.org/wiki/Finite-state_machine#Example:_coin-operated_turnstile). 12 | 13 | #### State machine definition 14 | 15 | Require the fsm-clj core name space. 16 | 17 | ```clj 18 | (:require [fsm-clj.core :refer :all]) 19 | ``` 20 | 21 | Defining the state machine with `defsm`. 22 | 23 | ```clj 24 | (defsm turnstile 25 | [[:locked -> :unlocked when :coin] 26 | [:unlocked -> :locked when :push]]) 27 | ``` 28 | 29 | #### Events 30 | 31 | An event is the input responsible for transitions between states. 32 | 33 | ```clj 34 | (-> (turnstile) 35 | (send-event :coin) 36 | :state) ;; => :unlocked 37 | ``` 38 | 39 | #### Actions and Accumulators 40 | 41 | Let suppose that every time that a coin is inserted and the turnstile state is changed to open 42 | we want to increment a counter. 43 | 44 | ```clj 45 | ;; action handler 46 | (defn inc-amount [acc _] (inc acc)) 47 | 48 | (defsm turnstile 49 | [[:locked -> :unlocked when :coin action `inc-amount] 50 | [:unlocked -> :locked when :push]]) 51 | 52 | (-> (turnstile 0) ;; start the fsm with accumulator value equals 0 53 | (send-event :coin) 54 | (send-event :push) 55 | (send-event :coin) 56 | :value) ;; => 2 57 | ``` 58 | 59 | The action handler returns the new accumulator value that will be passed forward. 60 | 61 | #### Events with payload 62 | 63 | When sending an event you can pass a message that will be injected into the action handler. 64 | 65 | For example, let's say that when a coin transition is triggered we should pass the coin value with it: 66 | 67 | ```clj 68 | ;; action handler 69 | (defn inc-amount [acc amount] (+ acc amount)) 70 | 71 | (defsm turnstile 72 | [[:locked -> :unlocked when :coin action `inc-amount] 73 | [:unlocked -> :locked when :push]]) 74 | 75 | (-> (turnstile 0) ;; start the fsm with accumulator value equals 0 76 | (send-event :coin 50) 77 | (send-event :push) 78 | (send-event :coin 100) 79 | :value) ;; => 150 80 | ``` 81 | 82 | #### Guard 83 | 84 | Guard is responsible to determine if a state should change or not. 85 | 86 | Supposing that the minimum coin value to unlock the turnstile should be 50. 87 | 88 | ```clj 89 | ;; action handler 90 | (defn inc-amount [acc amount] (+ acc amount)) 91 | 92 | (defn guard-handler [_state amount] 93 | (>= amount 50)) 94 | 95 | (defsm turnstile 96 | [[:locked -> :unlocked when :coin action `inc-amount guard `guard-handler] 97 | [:unlocked -> :locked when :push]]) 98 | 99 | (-> (turnstile 0) ;; start the fsm with accumulator value equals 0 100 | (send-event :coin 25) 101 | :state) ;; => :lock 102 | ``` 103 | 104 | The guard handler must be a function with two parameters, being the first the accumulator and the second the message 105 | sent by `send-event`. 106 | -------------------------------------------------------------------------------- /doc/fsm-traffic-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fbeline/fsm-clj/910af75972320fd20f57c8310140138eec5605e7/doc/fsm-traffic-light.png -------------------------------------------------------------------------------- /fsm-clj.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject fsm-clj "0.1.1" 2 | :description "A Clojure library designed to create deterministic finite state machines." 3 | :url "https://github.com/fbeline/fsm-clj" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.9.0"] 7 | [dorothy "0.0.6"]]) 8 | -------------------------------------------------------------------------------- /src/fsm_clj/core.clj: -------------------------------------------------------------------------------- 1 | (ns fsm-clj.core 2 | (:require [fsm-clj.parser :as p] 3 | [dorothy.core :as dorothy])) 4 | 5 | (defn- set-state [fsm state] 6 | (if ((->> fsm :transitions keys (into #{})) state) 7 | (assoc fsm :state state) 8 | fsm)) 9 | 10 | (defmacro defsm 11 | "Define a State Machine. 12 | e.g. 13 | (defsm foo 14 | [[:state1 -> :state2 when :event1] 15 | [:state2 -> state1 when :event2]]) 16 | foo will be a function that when called start the fsm. 17 | By default, the start state will be the state of the first transition. 18 | 19 | You can start it in 3 different ways: 20 | Simplest form: 21 | (foo) 22 | With accumulator: 23 | (foo 0) 24 | Starting in a different state: 25 | (foo 0 :state2)" 26 | [name transitions] 27 | `(def ~name (fn tfsm# 28 | ([] 29 | (tfsm# nil nil)) 30 | ([acc#] 31 | (tfsm# acc# nil)) 32 | ([acc# initial-state#] 33 | (-> (p/fsm ~transitions) 34 | (assoc :value acc#) 35 | (#'set-state initial-state#)))))) 36 | 37 | (defn- on-transition-triggered [fsm transition message] 38 | (if (-> transition :guard (apply [(:value fsm) message])) 39 | (-> fsm 40 | (update-in [:value] #(-> transition :action (apply [% message]))) 41 | (set-state (:target transition))) 42 | fsm)) 43 | 44 | (defn send-event 45 | ([fsm event] 46 | "Send an event to a state machine. 47 | Parameters: 48 | - fsm: State machine 49 | - event: Event name. Must be a symbol." 50 | (send-event fsm event nil)) 51 | ([fsm event message] 52 | "Send an event with a message to a state machine. 53 | Parameters: 54 | - fsm: State machine 55 | - event: Event name. Must be a symbol. 56 | - message: Message that will passed as argument to the action of the triggered transition." 57 | (let [state (:state fsm) 58 | transition (-> fsm :transitions state event)] 59 | (if transition 60 | (on-transition-triggered fsm transition message) 61 | fsm)))) 62 | 63 | (defn show! 64 | "Graphically generate the State Machine (open a Swing viewer)." 65 | [fsm] 66 | (-> fsm :graph dorothy/digraph dorothy/dot dorothy/show!)) 67 | -------------------------------------------------------------------------------- /src/fsm_clj/parser.clj: -------------------------------------------------------------------------------- 1 | (ns fsm-clj.parser 2 | (:require [clojure.spec.alpha :as s])) 3 | 4 | (s/def ::action (s/cat :_ #{'action} :handler any?)) 5 | (s/def ::guard (s/cat :_ #{'guard} :handler any?)) 6 | (s/def ::transition 7 | (s/cat 8 | :state keyword? 9 | :_-> #{'->} 10 | :target keyword? 11 | :_when #{'when} 12 | :event keyword? 13 | :opts (s/* (s/alt :action ::action :guard ::guard)))) 14 | 15 | (defn- validate-dsl! [transition] 16 | (if (s/valid? ::transition transition) 17 | transition 18 | (throw (Exception. (str "Invalid State Machine definition: " (s/explain-str ::transition transition)))))) 19 | 20 | (defmacro eval-fn [opts attr] 21 | `(if-let [v# (->> ~opts (into {}) ~attr)] 22 | @(-> v# :handler eval resolve) 23 | (fn [acc# _#] (if (= ~attr :guard) true acc#)))) 24 | 25 | (defn- parse-fsm-transition [transition] 26 | (let [{:keys [state target event opts]} (s/conform ::transition transition)] 27 | {:state state 28 | :target target 29 | :event event 30 | :action (eval-fn opts :action) 31 | :guard (eval-fn opts :guard)})) 32 | 33 | (defn- build-fsm-graph [transitions] 34 | (map (fn [{:keys [state target event]}] 35 | [state :> target {:label event}]) transitions)) 36 | 37 | (defn- build-fsm-transitions [transitions] 38 | (->> transitions 39 | (group-by :state) 40 | (map (fn [[k v]] 41 | {k (->> v 42 | (group-by :event) 43 | (map (fn [[k v]] {k (first v)})) 44 | (into {}))})) 45 | (into {}))) 46 | 47 | (defmacro fsm [transitions] 48 | `(let [transitions# (map (comp #'parse-fsm-transition #'validate-dsl!) '~transitions)] 49 | {:state (-> transitions# first :state) 50 | :transitions (#'build-fsm-transitions transitions#) 51 | :graph (#'build-fsm-graph transitions#)})) 52 | 53 | -------------------------------------------------------------------------------- /test/fsm_clj/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns fsm-clj.core-test 2 | (:require [clojure.test :refer :all] 3 | [fsm-clj.core :refer :all])) 4 | 5 | (defsm simple-turnstile 6 | [[:locked -> :unlocked when :coin] 7 | [:unlocked -> :locked when :push]]) 8 | (deftest simple-transitions 9 | (testing "Basic state transition" 10 | (is (-> (simple-turnstile) 11 | (send-event :coin) 12 | :state 13 | (= :unlocked))))) 14 | 15 | (defn inc-amount [acc _] (inc acc)) 16 | (defsm turnstile-with-accumulator 17 | [[:locked -> :unlocked when :coin action `inc-amount] 18 | [:unlocked -> :locked when :push]]) 19 | (deftest accumulators+actions 20 | (testing "The accumulator is properly calculated" 21 | (is (-> (turnstile-with-accumulator 0) 22 | (send-event :coin) 23 | (send-event :push) 24 | (send-event :coin) 25 | :value 26 | (= 2))))) 27 | 28 | (defn add-amount [acc amount] (+ acc amount)) 29 | (defsm turnstile-with-accumulator2 30 | [[:locked -> :unlocked when :coin action `add-amount] 31 | [:unlocked -> :locked when :push]]) 32 | (deftest events-with-payload 33 | (testing "" 34 | (is (-> (turnstile-with-accumulator2 0) 35 | (send-event :coin 50) 36 | (send-event :push) 37 | (send-event :coin 100) 38 | :value 39 | (= 150))))) 40 | 41 | (defn guard-handler [_state amount] 42 | (>= amount 50)) 43 | (defsm turnstile-with-guard 44 | [[:locked -> :unlocked when :coin action `add-amount guard `guard-handler] 45 | [:unlocked -> :locked when :push]]) 46 | 47 | (deftest guard 48 | (testing "An amount < than 50 should not unlock the turnstile" 49 | (is (-> (turnstile-with-guard 0) 50 | (send-event :coin 25) 51 | :state 52 | (= :locked)))) 53 | (testing "An Amount greater or equal 50 should unlock the turnstile" 54 | (is (-> (turnstile-with-guard 0) 55 | (send-event :coin 50) 56 | :state 57 | (= :unlocked))))) 58 | 59 | 60 | ;; generic traffic light fsm tests 61 | 62 | 63 | (defn inc-handler [acc message] 64 | (or message (inc acc))) 65 | (defn foo-guard [_ message] 66 | (>= message 10)) 67 | (defsm traffic-light 68 | [[:green -> :yellow when :to-yellow action `inc-handler] 69 | [:yellow -> :red when :to-red action `inc-handler] 70 | [:red -> :green when :to-green guard `foo-guard]]) 71 | 72 | (def traffic-light-fsm (traffic-light 0)) 73 | 74 | (deftest fsm-test 75 | (testing "By default first transition state is the start state" 76 | (is (-> (traffic-light) :state (= :green)))) 77 | 78 | (testing "We can set an accumulator at fsm start" 79 | (let [fsm (traffic-light 10)] 80 | (is (-> fsm :value (= 10))))) 81 | 82 | (testing "We can set initial state at fsm start" 83 | (let [fsm (traffic-light 0 :red)] 84 | (is (-> fsm :state (= :red))))) 85 | 86 | (testing "An invalid initial state should be ignored" 87 | (let [fsm (traffic-light 0 :something)] 88 | (is (-> fsm :state (= :green))))) 89 | 90 | (testing "A valid transition should change the state" 91 | (is (-> traffic-light-fsm (send-event :to-yellow) :state (= :yellow)))) 92 | 93 | (testing "An invalid transition should not change the state" 94 | (is (-> traffic-light-fsm (send-event :to-red) :state (= :green)))) 95 | 96 | (testing "The transition action should be executed" 97 | (is (-> traffic-light-fsm 98 | (send-event :to-yellow) 99 | (send-event :to-red) 100 | :value 101 | (= 2)))) 102 | 103 | (testing "We can pass message to transition in send-event" 104 | (is (-> traffic-light-fsm 105 | (send-event :to-yellow) 106 | (send-event :to-red -1) 107 | :value 108 | (= -1)))) 109 | 110 | (testing "Guard is executed before action and prevent the state to change" 111 | (is (-> traffic-light-fsm 112 | (send-event :to-yellow) 113 | (send-event :to-red) 114 | (send-event :to-green 8) 115 | :state 116 | (= :red))))) 117 | 118 | --------------------------------------------------------------------------------