Generating a finite state machine from legible source - Page 1
Forum section: electronics / general

author: Renate
author_rank: Super Contributor
timestamp: August 29, 2020, 09:47:37 pm
content: Finite state machines (FSM) are one of the bedrocks of computing.You define your problem with states and then come up with rules to progress from one state to another.You can have outputs that get generated with any state transition, or you can just do something useful with the states.States can be things like offline, online, failure, waiting for a closing parenthesis, pause, whatever.For instance, we can make a flip-flop using four states, A, B, C, D and one input Ck.You can diagram this out yourself.if you wrote this in C:Code:switch(state){case A:if (ck==1) then state=B;break;case B:if (ck==0) then state=C;break;case C:if (ck==1) then state=D;break;case D:if (ck==0) then state=A;break;}Ok, that was the introductory material.There's a bunch of problems with this.It's cumbersome to do all these switch cases (and this is a simple case).What if you want a reset? Do you have to put a reset clause in each switch case?Things can get quickly complicated.Your inputs could be much more complicated than a single bit.Some of the inputs could have the same effect even for a few different states.There are numerous ways besides switch cases to do the mechanics of an FSM.You could just make it a look-up table that you use the state and any inputs as the address and read out the next state (and maybe an output or two).So (I'm eventually getting to the point) my idea of a source code to FSM generator is:Use a table addressed by state and input, delivering next state and outputs.Initialize this table to all states being stable (i.e. A->A, B->B, etc)Initialize this table to no outputs for any state.Our flip flop would have 4 rules.(A, ck=1) -> B, (B, ck=0) -> C, (C, ck=1) -> D, (D, ck=0) -> AOk, that is a simple example, so there is no great benefit.Where this gets the benefit is that rules overwrite whatever is in the table.There is never a conflict between rules, they just write the table as they go along.Ifafterthose 4 rules we have (*, ck=0, res=1) -> A, (*, ck=1, res=1) -> BWe have added a reset without an explicit if to each of our 4 original rules.Notice that the first 4 rules depend on state and ck and that the last 2 rules just depend on ck and res.You could view that as a don't care. Or you could sit down and figure explicitly the action for every single combination of state and input.We would like our source code to be these simple 6 rules. We want the output to be a table.Question, are there any existing tools to do this?

author: tggzzz
author_rank: Super Contributor
timestamp: August 30, 2020, 07:22:18 am
content: There are many existing tools to convert a "readable" definition of an FSM into executable code in a standard language. Some are proprietary and some are open source. Some have been used for misson-critical behaviour. Some contain a complete runtime environment, some are embedded code fragments. One of the better known and more accessible tools ishttp://smc.sourceforge.net/All such tools have the significant problems and benefits associated with tiny domain-specific language (DSL). A useful question is whether it is better to simply write the code in a standard HLL using a recognised design pattern.One such design pattern is:each state maps onto a separate OOD classeach event maps onto a separate method implemented by the classesthe current state is a singleton instance of one of the state classessubstates are modelled by the corresponding class hierarchythe abstract superclass of all state classes contains methods for every event, with an implementation that aborts execution becauses that method should never be executedevery event is handled where appopriate in the state classeseventA is executed by invoking currentState.eventA(), and state transtions are currentState = aStateClassInstance

author: Renate
author_rank: Super Contributor
timestamp: August 30, 2020, 12:38:14 pm
content: Thanks for the pointer to SMC, it's interesting.I guess that I was thinking of lighter weight things than making everything a class.The classic FSM doesn't really "do" transitions in the sense that it only has its states and outputs.If you plumb internally into the FSM you can have it do something on a state transition.In old-skool FSM you can only flag an output to tell something external to do something.You end up writing an FSM then you have to write something to decode the FSM's outputs and do something.The table method I was speaking of is an efficient way of specifying/implementing old-skool FSM.I do write enough standard switch(state), do something, next state code for other things, mostly task-based.

author: tggzzz
author_rank: Super Contributor
timestamp: August 30, 2020, 03:02:49 pm
content: Classes aren't, on their own, heavyweight. They are no more than asparsetable of function pointers, arranged in a way that matches the way the specification is written. In many cases there is only one instance of the class, containing the state in the form of a variable of the class that matches the state. In other cases, e.g. a telephone exchange, there is one instance per call.The table method is very applicable when the FSM is sparse and unlikely to change over time. I've used that technique to convert incoming characters into a float or double number, or to convert from one 5-channel paper tape code to another.FSMs must have transitions from one state to another. Whether or not you should "do" somethingas part ofthe transition is an orthogonal decision. I have found that to be unnecessary in practice, and an "unnecessary" complexity of Harel Statecharts (i.e. UML state diagrams).In one company where I worked, a main product was effectively a runtime with an enormous if-then-else statement doing the control. Over a decade it had become a monstrosity, and the simplest change took6 monthsfrom request to acceptance. A significant part of the problem was that the if statements were nested up to 10 deep. That made it impossible to be sure exactly which line had to be changed, and that the change didn't cause a new problem. Totally braindead, of course - in that and other ways!Nonetheless, I've seen distant echoes of that problem in all but the simplest if-the-else based state machines.

author: Renate
author_rank: Super Contributor
timestamp: September 11, 2020, 06:48:24 pm
content: Well, in any case, even before I posted the first post I had already written something.My need was for a bunch of char stream FSM.I have the input definition in XML.It generates:Char map to input indexState/input array generates state/outputStub function to wrap it all

author: cdev
author_rank: Super Contributor
timestamp: September 11, 2020, 07:26:44 pm
content: https://automl.org?also scikit-learn ?

author: Renate
author_rank: Super Contributor
timestamp: September 11, 2020, 07:30:46 pm
content: Quote from: cdev on September 11, 2020, 07:26:44 pmIch mag Hannover.Actually, I wrote it all myself, or was this a suggestion?

author: cdev
author_rank: Super Contributor
timestamp: September 11, 2020, 08:16:04 pm
content: I was just speculating that automated tools (not necessarily these ones) are rapidly evolving which might be able to take a body of inputs and desired outputs and prodice a blob that would give you the deired outputs from the same inputs and when you provided a new input guess at an approriate output or vice versa..gradually infer the rules needed to do so.However it might screw up perhaps spectacularly, or interestingly, once in a while.

author: tggzzz
author_rank: Super Contributor
timestamp: September 11, 2020, 08:37:16 pm
content: Quote from: cdev on September 11, 2020, 08:16:04 pmThe problem with such machine learning techniques is that you cannot know why they work.Classicsimplecase from the early 80s was a machine to distinguish cars from tanks it worked well in the lab,but failed dismally in real world tests. Eventually they realised the training set was pictures of tanks on Luneberger Heath and cars from adverts. Yes, it was distinguishing sunny days from cloudy days.Nowadays nothing so crude would happen; it would be more subtle, and classified as a transient glitch (that killed or maimed people).

author: Renate
author_rank: Super Contributor
timestamp: September 11, 2020, 08:43:35 pm
content: It is important to have anything that is automatically generated to give a bit of insight into its logic.That's why my program throws in some comments.Code:static uint8_t code_fsm[]={// EOL * /0x00, 0x07, 0x00, 0x14, // IDLE0x00, 0x07, 0x20, 0x40, // PREFIX0x20, 0x23, 0x30, 0x20, // OPEN0x20, 0x23, 0x20, 0x02, // SUFFIX0x40, 0x03, 0x40, 0x40 // LINE};

author: tggzzz
author_rank: Super Contributor
timestamp: September 11, 2020, 08:46:30 pm
content: Quote from: Renate on September 11, 2020, 08:43:35 pmPlease convince the people that regulate Elon Musk's toys of the value of that

author: 0db
author_rank: Frequent Contributor
timestamp: September 28, 2020, 11:16:33 am
content: Quote from: tggzzz on September 11, 2020, 08:46:30 pmOT:This guy is a master in selling himself and his words. Now NASA has still a lot of problems with the new Orion missions, and that fellow is already talking about selling tickets for five days of kind of Holiday-something around the moon like if it was a kind of Disneyland amusement park.Well, before the Moon landing, Neil Armstrong Saved NASA when in one of the Gemini missions almost the whole crew fainted due to still immature technology combined with the effect of spaceflight on the human body. Almost everybody passed out except Neil Armstrong, who, with the spacecraft and crew seemingly in peril, needed to act fast.He remembered what he was said "[..] if you run into trouble and the control system fails [..] just…turn it off and take control with the spacecraft.", and thank god he didn't pass out, he remembered these words, and he fixed the problem.Now somehow everything must be AI-driven, and this kind of stuff now sounds the perfect job for an on board AI that doesn't "pass out" like humans, but we need to be careful with AI autonomous choices!And even electrical systems may fail, or worse still have malfunctions, and the AI itself can take the wrong decision, like we have already seen in science fiction when the super advanced HAL 9000 went nuts and decided to kill the crew.edit:typo "to go nuts"

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 28, 2020, 12:09:07 pm
content: Quote from: 0db on September 28, 2020, 11:16:33 amYou missed the point of the story. HAL 9000 didn't go nuts, it operated exactly as instructed. And that's the exact problem with expert systems in general.

author: 0db
author_rank: Frequent Contributor
timestamp: September 28, 2020, 01:11:26 pm
content: Quote from: Nominal Animal on September 28, 2020, 12:09:07 pmI am not sure about that.The AI received instructions, but not a precise order "kill the crew". It deducted (for a malfunctioning? or for a logical mistake in its programming?) that the crew was "expendable" due to of two considerations:completing the mission had the highest priority (this idea is also represented in the first Alien movie)on board human life was not necessary to be guaranteed, because the spaceship was built able to autonomously complete the missionHAL-9000 is science fiction, but how a similar AI-driven autonomous machine like the one Elon Musk is thinking about will react to a serious malfunction or something when it will drive a couple of tourists (aka inexpert civil persons, and not pro-astronauts) on holiday around the moon?Like Neil Armstrong during the Gemini-8 mission? Better than him? Or worse than him?

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 28, 2020, 01:24:28 pm
content: Quote from: 0db on September 28, 2020, 01:11:26 pmI don't see any error in the deduction – so no malfunction, no logical mistake. (If you place yourself in HAL's position, all its actions are logical and in line with its directives.)The only mistake is on part of humans who believe a simple set of instructions suffices. It does not; humans base their actions on a huge, unseen context, that they have developed during their lifetime. A large part of crew selection is to find the individuals whose such contexts are suitable for the task at hand. When you realize this, you realize why AI and expert systems are so hard: the integrated context that controls actions when decisions need to be made, is absolutely massive.Quote from: 0db on September 28, 2020, 01:11:26 pmIt is much simpler to develop an expert system to do a task no humans are currently doing, than to create an expert system that behaves like a human would.The error is in expecting to be able to define the operating rules for such a system in human terms, or model it after human actions.

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 28, 2020, 01:56:33 pm
content: If we circle back to the original topic from my last sentence in my previous post, I do believe that finite state machines – in general terms – fall into a similar category as expert systems: human-conversational rules do not suffice.Instead, I believe the best option is to use a domain-specific descriptive language, which can be used to generate the state machine code at one hand, and the human-readable documentation on the other hand.Personally, I would use Python for the translation, as its associative arrays (dicttype) are quite performant, and are well suited for the intermediate description of the state machine. This way, it should be possible to run full state machine traces (fully map all states and transitions) to verify each transition and each state – in particular, to find states that lead to uninterruptible cycles or dead ends. (For this, one can use graph theory, although path tracing and detecting already visited states should suffice.)Then, the question is, what should that descriptive "language" look like. That's the hard question here.Personally, I prefer a declarative structure, where a keyword at the start of a line defines the rest of the line, and a new state always begins with a line defining its identity (abstract ID, or human-readable name, used to refer to that state). Whether that works better than any others, I do not know; I only know that it maps well to an associative-array-based description of graphs, and is fast and robust to parse.

author: Renate
author_rank: Super Contributor
timestamp: September 28, 2020, 02:17:21 pm
content: An interesting decision point is whether states have specific, pre-assigned values.Inputs have defined values, outputs have defined values.You could make things so that the numeric value of a state is not assigned and not used at all outside the FSM.States would simply be collected and assigned an arbitrary value during compilation.The one semi-exception would be initial state or you could use an explicit reset input.

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 28, 2020, 02:50:13 pm
content: Quote from: Renate on September 28, 2020, 02:17:21 pmYes; I tend to use the address of the structure (in ROM/Flash) describing the state. The reason you need some sort of an identifier or name is so that you can refer to it from the other states (when defining transitions). In C, this means that basically all states need to be declared first (static const struct fsm_statename;), followed by the definition of each of the declared states (static const struct fsm_statename= { ... };); then, you can use&nameas the identifier of each state. (The identifier is then of typeconst struct fsm_state *. For an unsigned integer, one can use(uintptr_t)(&name)as the numerical identifier.)I've prattled on about FSMs and especially Mealy machineshere(table form implementingthisgraph) andhere(Arduino menu example skeleton).

author: 0db
author_rank: Frequent Contributor
timestamp: September 28, 2020, 09:17:59 pm
content: Quote from: Nominal Animal on September 28, 2020, 02:50:13 pmWhat program did you use to create that graph? Gnome/Dia?

author: 0db
author_rank: Frequent Contributor
timestamp: September 28, 2020, 09:35:08 pm
content: For me, a simple language to describe a simple FSM, should look likeCode:state: rst, s0, s1, s2, s3, err;bininput: i0 ;output[]: o0='000',o1='001',o2='010',o3='011',oe='111';on state rst{always: state <- s0, output <- o0;}on state s0'downedge{when (i0 is '1'): state <- s1, output <- o0;when (i0 is '0'): state <- s0, output <- o3;}on state s1'downedge{when (i0 is '1'): state <- s2, output <- o1;when (i0 is '0'): state <- s1, output <- o0;}on state s2'downedge{when (i0 is '1'): state <- s3, output <- o2;when (i0 is '0'): state <- s2, output <- o1;}on state s3'downedge{when (i0 is '1'): state <- s0, output <- o0;when (i0 is '0'): state <- s2, output <- o2;}on state s4'downedge{when (i0 is '1'): state <- s1, output <- o0;}whateverelse'downedge{always: state <- err, output <- oe;}

author: tggzzz
author_rank: Super Contributor
timestamp: September 28, 2020, 10:12:40 pm
content: Quote from: 0db on September 28, 2020, 09:35:08 pmSimpleanythingis easy, by definition. It becomes more interesting when things become more complicated. Then it becomes more important to have techniques to reduce the complications.For example, consider a FSM which has (say) 20 states in "normal" operation, but if one of (say) 5 "error" events occurs inanyof those states, the FSM transitions to a "reduced capability" set of states. In one naive implementation, that would imply 5*20=100 clauses in the "normal operation" states, which all have to be implemented and kept in synchronism as the FSM evolves over time. Good luck with that.

author: Renate
author_rank: Super Contributor
timestamp: September 28, 2020, 10:34:08 pm
content: Quote from: Nominal Animal on September 28, 2020, 02:50:13 pmInteresting.It's not the FSM itself, but how it's used.In your cat/dog detector you could have made it lazy.When it gets a 'c' the FSM can outputMARKand have the program save the location in the input stream.Then when you have gotten 'a', 'n' the FSM can outputFLUSHand the program will output "can".Unless of course it got 'a', 't' the FSM can outputDOGand the program will output "dog".This is not a full implementation, but gives an idea of making the program be able to print the largest sequence in a single shot.Imagine that this was a graphics program and "dog" had to be in color.

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 29, 2020, 07:03:35 am
content: Quote from: 0db on September 28, 2020, 09:17:59 pmDia, exported as SVG, with a bit of post-processing (colors, the break in one of the lines, converting text to paths, then similar strokes and fills merged) in Inkscape, then simplified, and finally extra cruft (metadata and useless attributes) removed by hand. This way, it's just eight paths and a white background rectangle, and scales to whatever size wanted. It may sound like a lot of work, but it only takes me a few minutes to do.(If you wonder why the nodes resemble so much Graphviz Dot struct nodes, wonder no more: I started by defining the graph in Graphviz DOT language to see what the overall graph looked like. Then I fired up Dia, and chose the locations of the nodes, and redrawing the graph in a few minutes, according to my own personal preferences. This is a surprisingly efficient and fast workflow, even though one ends up using several different tools and even editing SVG by hand; there is very little guesswork, as long as you write the initial graph description in DOT correctly. Which is also why that was not the first version; I realized a better way to describe the FSM (in DOT), and this was the result of that.)Quote from: Renate on September 28, 2020, 10:34:08 pmVery true. This way, it was a pure Mealy machine (transitions depending only on the current state and current input). The partially detected strings aren't "stored", they're implicit in the state, so the machine describes fully the operation without external state.I prefer Mealy-type finite state machines, as my typical FSM is for a menu system on a microcontroller. (There, the inputs are buttons (and possible error situations), and the state corresponds to the currently active menu entry; so it makes sense that the state transition only depends on the current state and inputs. Makes for predictable menu systems, really. Plus, there is minimal RAM usage, as the states can reside purely in ROM/flash. I like that.)(It isn't my intention to imply that Mealy machines are 'better' than other FSM types; it completely depends on the task at hand, in my opinion.)I believe the most widely used FSM generator from domain-specific descriptive language isflex, which generatesdeterministic finite automatons(DFA in flex documentation and internals). I never found it particularly intuitive or well-designed for its task, but practice always trumps intuition: combined with e.g.bison, you have a powerful lexer-parser used in hundreds, if not thousands of large-scale long-term projects like interpreters and compilers.If I were to design my own domain-specific language for example for implementing Mealy menus, I would ensure it generates not only sensible C/C++ (GNU C/C++ in my case), but also easily readable formatted text,andstate graphs (similar to the one shown) via Graphviz. (I'd like to have extra directives to add specific details to each state; including C/C++ hooks when entering and exiting the state – meaning, you could add literal code to the state if needed.) Unfortunately, that makes the domain rather small: just menu systems, instead of FSMs in general.

author: 0db
author_rank: Frequent Contributor
timestamp: September 29, 2020, 11:07:53 am
content: Quote from: tggzzz on September 28, 2020, 10:12:40 pmThat's the job for specialists. I am not. But I am 100% able to implement the above language which is "enough" for simple FSMs in VHDL.Quote from: tggzzz on September 28, 2020, 10:12:40 pmGreat example! I wrote the above lines to show how I would represent the legible source: how would you represent your example by legible source?

author: Renate
author_rank: Super Contributor
timestamp: September 29, 2020, 12:11:35 pm
content: Quote from: tggzzz on September 28, 2020, 10:12:40 pmWell, that was the idea of my "overwriting table" approach.You specify all your normal clauses, then your global clauses.Code:if (STATEA) -> STATEBif (STATEC) -> STATEDif (RESET) -> STATEX // global rule for all statesif (RESET && STATEC) -> STATEY // specific exception to reset rule overwrites previous ruleOr you could also write it as:Code:if (STATEA) -> STATEBif (RESET) -> STATEX // global rule for all statesif (STATEC) -> STATED // generates "clean" STATEC with no reset ruleif (RESET && STATEC) -> STATEY // new reset rule

author: 0db
author_rank: Frequent Contributor
timestamp: September 29, 2020, 12:44:39 pm
content: Code:override: or0, or1;state: or0: { srst, serr, sovr },or1: { s0, s1, s2, s3 };input: i0 ;output[]: o0='000',o1='001',o2='010',o3='011',of='xxx', // this allows custom values, not enumerated hereoo='101'; // output on override-conditionoe='111'; // output on "handled by nobody" conditionon override or0{always: null; /* never override */}on override or1{when (i0 is '11'): state <- sovr, output <- oo;whateverelse: null; /* don't override */}on state srst{always: state <- s0, output <- o0;}on state s0'downedge{when (i0 is '10'): state <- s1, output <- o0;when (i0 is '00'): state <- s0, output <- o3;}on state s1'downedge{when (i0 is '10'): state <- s2, output <- o1;when (i0 is '00'): state <- s1, output <- o0;}on state s2'downedge{when (i0 is '10'): state <- s3, output <- o2;when (i0 is '00'): state <- s2, output <- o1;}on state s3'downedge{when (i0 is '10'): state <- s0, output <- o0;when (i0 is '00'): state <- s2, output <- o2;}on state s4'downedge{when (i0 is '10'): state <- s1, output <- o0;}on state sovr{when (i0 is '00'): state <- srst;}whateverelse'downedge{always: state <- serr, output <- oe;}what do you think about this? It indirectly uses monads

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 29, 2020, 03:12:17 pm
content: As I prefer to use structures rather than switch cases in C, I have much more options on how to deal with error conditions.For example:Code:#define READONLY consttypedef struct fsm_state fsm_state;typedef struct fsm_transition fsm_transition;typedef unsigned char fsm_event;typedef unsigned char fsm_condition;enum {FSM_EVENT_END = 0,FSM_EVENT_A = 1,FSM_EVENT_B = 2,FSM_EVENT_C = 3,};enum {FSM_CONDITION_NONE = 0,FSM_CONDITION_NORMAL = 1<<0,FSM_CONDITION_PAUSED = 1<<1,FSM_CONDITION_CONFUSED = 1<<2,FSM_CONDITION_ON_FIRE = 1<<3,FSM_CONDITION_ALL = (fsm_condition)(~0),};struct fsm_transition {READONLY fsm_state *state; /* Target state */READONLY fsm_condition allow; /* Conditions allowed for this transition, 0 if end of array */READONLY fsm_event event; /* Event number or mask triggering this transition, 0 if end of array */};#define FSM_END_TRANSITIONS { (void *)0, 0, 0 }struct fsm_state {READONLY fsm_condition clear; /* Condition bits to be cleared on entering this state */READONLY fsm_condition set; /* Condition bits to be set on entering this state */READONLY fsm_transition transition[]; /* Array of transitions/events, terminated with FSM_END */};READONLY fsm_state state_foo, state_bar, state_baz;READONLY fsm_state state_foo = {.clear = FSM_CONDITION_NONE,.set = FSM_CONDITION_NONE,.transition = {{ &state_bar, FSM_CONDITION_NORMAL | FSM_CONDITION_CONFUSED, FSM_EVENT_A },{ &state_baz, FSM_CONDITION_ON_FIRE, FSM_EVENT_A },FSM_END_TRANSITIONS},};READONLY fsm_state state_bar = {.clear = FSM_CONDITION_NONE,.set = FSM_CONDITION_CONFUSED,.transition = {{ &state_foo, FSM_CONDITION_NORMAL, FSM_EVENT_B },{ &state_bar, FSM_CONDITION_ALL, FSM_EVENT_A },{ &state_baz, FSM_CONDITION_ALL, FSM_EVENT_C },FSM_END_TRANSITIONS},};READONLY fsm_state state_baz = {.clear = FSM_CONDITION_ON_FIRE,.set = FSM_CONDITION_NONE,.transition = {{ &state_foo, FSM_CONDITION_NORMAL, FSM_EVENT_A },{ &state_foo, FSM_CONDITION_NORMAL, FSM_EVENT_B },{ &state_bar, FSM_CONDITION_ALL, FSM_EVENT_A },{ &state_bar, FSM_CONDITION_ALL, FSM_EVENT_B },{ &state_bar, FSM_CONDITION_ALL, FSM_EVENT_C },FSM_END_TRANSITIONS},};Above, each state consists of changes to the condition mask (bits cleared and set when entering the state), and one or more transitions.Each transition consists of a pointer to the target state, the allowed condition mask, and the event/input that triggers this particular transition.Because the transitions are an immutable array, such a state machine is automatically deterministic: the first matching allowed transition occurs.State 'foo' does not modify the condition mask. Only event 'A' triggers a transition: in 'normal' and 'confused' conditions, to state 'bar'; in 'on fire' condition, to state 'baz'.State 'bar' always sets the 'confused' condition mask bit on entering. Event 'B' in 'normal' condition causes a transition to state 'foo'. Event 'A' in all conditions causes a transition to this state (i.e., this is a superfluous transition!). Event 'C' in all conditions causes a transition to state 'baz'.State 'baz' always clears the 'on fire' condition mask bit on entering. Event 'A' in 'normal' condition causes a transition to state 'foo', and in all other conditions to state 'bar'. Event 'B' in normal condition also causes a transition to state 'foo', and in all other conditions to state 'bar'. Event 'C' in all conditions causes a transition to state 'bar'.As you can probably imagine, this sort of structure definition is easy to convert from a domain-specific language. The "name" used to refer to each state could be the name of the C state structure variable, with e.g. a suitable prefix (keeping the namespace sane). You could add function pointers to the state (with a fixed prototype), so that custom C code (specified in the domain-specific language) would be executed when entering/exiting the state.Is this better than the others shown in this thread? I really do not have an opinion on that; I do not know. I haven't tried the others in practice. All I know is that this kind of approach has worked really well for me in implementing menus and such human interface stuff.

author: 0db
author_rank: Frequent Contributor
timestamp: September 29, 2020, 04:09:36 pm
content: Quote from: Nominal Animal on September 29, 2020, 03:12:17 pmYour approach looks great, but it's too much "C-oriented", hence much more difficult for me to implement it as meta-compiler.I haven't fully implemented it yet, but the new "monad" concept is intriguing because it practically assumes that an abnormal condition can be handled with an "override behavior", described within the same definition of state; so the abnormal behavior is now part of a variable, and that's intriguing because it reduces the number of lines the final user has to write, and it also simplifies a lot of stuff for me in this specific implementation case.It's not perfectly "legible", it tries to be legible with the compromise to also be simple to be implemented for those like me who are not specialists in writing compilers and translators.Of course it still needs some work and it's limited only for a Mealy description

author: Renate
author_rank: Super Contributor
timestamp: September 29, 2020, 04:53:10 pm
content: Quote from: Nominal Animal on September 29, 2020, 03:12:17 pmI think that everyone is hitting different applications differently.You've got states and "conditions" which could all be considered states.For what you're describing though it might simplify/clarify things.I don't want any conditions for what I was mainly doing.(Just a note, I've only been posting pseudo code as my source rules. It's actually all XML.)@0db you made me look up monad. I'm still chewing on that.

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 29, 2020, 06:11:45 pm
content: To generate the data structures and documentation from a single source, I might use an INI-file-like format:Code:label: Foonotes: On entering Foo state, we must call fsm_enter(), because bleghbok.event bar: barevent baz: bazon enter call: fsm_enterlabel: Barnotes: On entering and exiting Bar state, we must call fsm_enter()/fsm_exit(), because glarghblargh.event foo: fooevent baz: bazon enter call: fsm_enteron exit call: fsm_exitlabel: Baznotes: Cannot return directly to Foo, only via Bar. When exiting the state, fsm_exit() must be called, because glubwharf.event baz: bazon exit call: fsm_exitThe section name is the name used to refer to the state. In C, I would use a filtered version of it as the state variable name.In eachkey:valuepair, the key can consist of multiple space-separated words, with the first word being the directive.For example, function call hooks would have form "onhooknamecall:funcname".Transition specifications would have form "eventeventname:sectionname" or "eventeventnameincondition:sectionname", and so on.Note that some key:value pairs are functional (i.e., define fields in the C state structures), some informational/documentation (likenotes:), and some are only useful when drawing a state transition graph (label:).Parsing such a line-based format is dead simple. Lines without colons can be added to the value in the previous key:value pair, except ignored immediately after a new section start. We can even support escaping via e.g. \/→\ and \=→: for unambiguous escapes, leaving all other backslash-escapes intact. Most importantly, we can collect all event and condition names, and form human-readable enums for them; the structures would use those enums. Here, we have three states 'foo', 'bar', and 'baz'; and three events 'foo', 'bar', and 'baz'. While their names look the same, event 'foo' is not automagically tied to state 'foo'; the namespaces are separate.The "trick" I would apply here, is to omit e.g. function pointers if no function call hooks are used, in the state structure type. Similarly, if "conditions" are not used, they are not included in the structure type. This does mean that one needs to test the generator for each combination of optional features, but it should be relatively straightforward.The nice thing in a Python-based generator is that the parser is the same for generating code, documentation, the graphs, and even the state and transition analysis tool; and that allows for simple extensions to the generator itself.To repeat, I am not suggesting thisinstead ofanything else in this thread; just showing a model that works for me, in case anyone finds it interesting.

author: Renate
author_rank: Super Contributor
timestamp: September 29, 2020, 06:44:33 pm
content: One of the advantages of using XML as source is the inherent hierarchy.You could put multiple FSMs in a file and have them share the input/output declarations.OTOH, I can understand people who say that<boring>true</boring>is boring!

author: hamster_nz
author_rank: Super Contributor
timestamp: September 29, 2020, 10:40:06 pm
content: I might be old skool, but I feel that in general domain specific languages (DSL) are bad idea.Although interesting to design and program (and I've done a few) that I they add a level of abstraction and complexity usually adds more problems than it solves.Would only recommend if it is a user requirement for the FSM to be reconfigurable, which can't easily be achieved in the native implementation language.For other cases, find a pattern you hate the least and adopt it. The programmer that follow you (or you in 5 years time) will thank you.At the moment my standard pattern for C is function that takes a pointer to a structure with all the state in it.Code:struct state_info {int state;int foo;} s;...s.state = 0; //reset statewhile(s.state) {switch(s.state) {case 0: func_state_reset(&s); break;case 1: func_state_1(&s); break;case 2: func_state_2(&s); break;default: func_state_error(&s); break;}}For more complex FSMs, a table of function pointers is a good idea, removing the switch/case statement, but only as long as you make sure your function lookup code is bulletproof at picking up errors - nothing worse than if you index off the end of the table and your code jumps to Lala land).

author: tggzzz
author_rank: Super Contributor
timestamp: September 29, 2020, 11:33:00 pm
content: Quote from: hamster_nz on September 29, 2020, 10:40:06 pmDSLanguages are overblown; every comp sci graduate wants to invent one in the same way every EE wants to develop a processor.DSLibraries in a standard language are usually preferable.With a DSLanguage, you have to invent your own toolset, have to train staff in an unpopular nontransferable skill.

author: emece67
author_rank: Frequent Contributor
timestamp: September 30, 2020, 07:20:47 am
content: .

author: tggzzz
author_rank: Super Contributor
timestamp: September 30, 2020, 01:18:48 pm
content: Quote from: Renate on September 29, 2020, 06:44:33 pmAh yes, XML. The triumphant reinvention of a limited crap subset of Lisp

author: tggzzz
author_rank: Super Contributor
timestamp: September 30, 2020, 01:28:51 pm
content: Quote from: emece67 on September 30, 2020, 07:20:47 amPreciselyIt is a standard design pattern.QuoteJust write the effin code in your favourite OOP languageFor a standard design pattern, see the seminal "Gang of Four" "Design Patterns" book, p305.With a little taste and discipline the implementation can be easily maintained and easily accomodate "non functional" (ugh!) aspects such as logging, timing analysis etc.

author: Renate
author_rank: Super Contributor
timestamp: September 30, 2020, 01:43:51 pm
content: Quote from: tggzzz on September 30, 2020, 01:18:48 pmMmm, okay, how about doing it in JSON then?

author: freda
author_rank: Regular Contributor
timestamp: September 30, 2020, 02:29:51 pm
content: writing a fsm by hand can be fraught with legibility problem especially if complex and revisiting it in a few months...I would suggest either flex or yacc generators, in my opinion nearly any state machine that is deterministic can bemade with either if these parsers.best of all you could modify the parser skeleton in a debug version so you can see and understand whats going on.

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 30, 2020, 02:35:16 pm
content: Quote from: hamster_nz on September 29, 2020, 10:40:06 pmIn general, I agree.(I do not like to do code generation at all, if I can avoid it; and translation from one high-level procedural language to another just-as-high-level seems silly to me.)Here, however, what I am suggesting is a generator that uses a single source definition – adescriptivelanguage, not a procedural or functional one – to define human-readable documentation, visual graphs (illustrations),and the data structures used in the finite state machine.In other words, the "language" – really just a list of sections with a list of key-value paris in each section; a build-time configuration file! – defines the data structures describing the finite state machine states and transitions; not the finite state machine implementation itself.The practical problem in having the C data structures and documentation separately, is one of maintainability. Too many programmers are idiots who believe "someone" will take care of the documentation later on, thattheirtime is too valuable to waste on such trivialities. Ensuring the documentation and the data in a single DSL (or build-time configuration file) makes it easy to track those idiots: if an edit only touches the data, not the documentation (in preceding/succeeding lines), and the commit message does not explain what bug the edit fixes, the edit will be reverted and the committer talked-to. It makes for a simple rule to follow, to ensure the long-term maintainability.Note that I earlier mentioned that this applies predominantly to certain complex cases (AIs, expert systems), and that FSMs are an edge case. This is because it depends on what kind of FSM one intends to implement. Mine are typically menus and human interface stuff, so the data structure driven pattern (as opposed to switch/case pattern) works best for me; and since the data structures can easily be defined separately from the code that implements the core machine, I believe that on the balance, it is better to combine documentation and data definition in a single file.

author: tggzzz
author_rank: Super Contributor
timestamp: September 30, 2020, 04:35:55 pm
content: Quote from: Renate on September 30, 2020, 01:43:51 pmAt least that is part of a turing complete programming language.

author: tggzzz
author_rank: Super Contributor
timestamp: September 30, 2020, 04:44:27 pm
content: Quote from: freda on September 30, 2020, 02:29:51 pmSuch techniques fail w.r.t.readability, when all the events and actions are addedembeddability within the runtime environment that generates and delivers and emits eventsdebuggability, especially after deploymentefficient run-time logging, especially of state trajectory (a.k.a. how did we gethere?!)run-time tools supportquality of the FSM DSL; most DSLs are crap, and devolve into a cancerous pile of spaghetti (the FSMs implemented in such devolved DSLs are dreadful!)That's more or less true of anything that uses a conventional language as an intermediate language. Such things are very attractive to the "all turing languages are equivalent" compsci mindset, but are a pain in the backside in most environments. There are exceptions, but they are rare.