{'fraction_non_alphanumeric': 0.03490461708598286, 'fraction_numerical': 0.006116947746751452, 'mean_word_length': 4.55199539524175, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Extending a User Interface Prototyping Tool with Automatic MISRA C Code Generation

We are concerned with systems, particularly safety-critical systems, that involve interaction between users and devices, such as the user interface of medical devices. We therefore developed a MISRA C code generator for formal models expressed in the PVSio-web prototyping toolkit. PVSio-web allows developers to rapidly generate realistic interactive prototypes for verifying usability and safety requirements in human-machine interfaces. The visual appearance of the prototypes is based on a picture of a physical device, and the behaviour of the prototype is defined by an executable formal model. Our approach transforms the PVSio-web prototyping tool into a model-based engineering toolkit that, starting from a formally verified user interface design model, will produce MISRA C code that can be compiled and linked into a final product. An initial validation of our tool is presented for the data entry system of an actual medical device.


Introduction
Formal methods are important for developing and understanding safe and secure systems. The PVSio-web framework [20,21,22,26] allows developers to use formal methods in a friendly and appealing way as it provides realistic animations and is integrated with a graphical editor for the Emucharts language [23]. (Emucharts is a state machine formalism with guards and actions associated with transitions; it is explained further in Sect. 3

.4 below.)
PVSio-web uses the formal modelling language of the Prototype Verification System (PVS) [27], including the PVSio extension [24]. PVS is an industrial-strength theorem proving system that allows formal verification of safety and reliability properties of hardware and software systems [5,31]. Although PVS itself is very effective, it is not widely used for model-based development and analysis of user interfaces, as the tool has a steep learning curve. PVSio-web softens this learning curve, making the tool more user-friendly and accessible, providing developers with a graphical modelling environment, and a toolbox for developing realistic visual prototypes of user interfaces.
The applications of embedded software in safety-critical applications increase continuously. Taking this into account, together with the requirements to reduce time and overall production costs, automatic code generation plays an essential role. Automatic code generation guarantees a smooth conversion from model to code and reduces the debugging and testing required for source code, provided that the correctness of code generation and of the high-level model have been verified.
We therefore present an extension to PVSio-web that generates C code. Specifically, our extension generates MISRA C [1], a safety-oriented subset of C developed by the Motor Industry Software Reliability Association (MISRA). MISRA C is commonly used in safety-critical subsystems, such as car braking in automotive systems.
With this new extension, formal PVS specifications generated from Emucharts diagrams are automatically converted to C, significantly shortening project development time. Because of the approach, the semantics of generated C code is equivalent to the formal models, and therefore the code retains the reliability and safety properties formally verified for the PVS model.
In summary, our main contribution is an approach to software development that integrates logicand state machine-based formal modelling, validation by simulation, and automatic implementation by generating production code to be run on the actual system hardware, all based on an industrial-strength formal methods toolkit.

Related work
Model-based approaches are commonly used in the field of human computer interaction, for example [13]. Most approaches are focused on describing user interfaces and their implementations at various levels of abstraction. Developers of user interfaces for interactive systems also have to address heterogeneity and adaptation to the context of use. For example, in [29], a model-based declarative language for the design of interactive applications based on Web services in ubiquitous environments was presented. In contrast to these familiar approaches, the present work proposes a framework enabling a formal verification of user interaction. The framework is meant for safety analysis of safety-critical devices and not with user interface design issues as discussed in [29], Similarly to our approach, formal models were used in [6] to describe functionality and component interactions, where they were combined with user interface models in order to get the entire model of the system. Moreover, an Android emulator application was generated, using Java and XML technologies. Presentation models and presentation interaction models were used in [9] to model interactive software systems; these models were shown to be usable with a formal specification of the system functionality. In [7] the same formalisms were used to model user manuals of modal medical devices, proving that the user manual may be not always consistent with actual device behaviour.
In [17], model checking was used to model and prove properties of specifications of interactive systems so that possibly unexpected consequences of interface mode changes can be checked early in the design process. In [19], the complementary role of model checking and theorem proving in the analysis of interactive devices was considered. Recent work [16] explored the paths that a user will take in interacting with medical devices for the analysis of properties of the behaviour of safety-critical devices. A model-checking approach has also been used to analyse hardware behaviour [4].
A discussion of production code generation in model-based development can be found in [11]. Many papers deal with specific code generators, for example TargetLink [3]. Code generators specifically designed for medical systems are described in [2] and [28].

PVS, model-driven development and Emucharts
This section provides background information on the PVSio-web framework and its relationship to model-driven development.

PVS, the Prototype Verification System
The PVS is an interactive theorem prover for a typed higher-order logic language, providing an extensive set of inference rules based on the sequent calculus [30]. Its PVSio extension is a ground evaluator that can compute the results of ground function applications, that is PVS expressions consisting of a function name applied to variable-free arguments. PVS functions are purely declarative definitions of mathematical mappings, without any procedural information on how to compute them, but the PVSio package can derive and execute an algorithm to evaluate a ground function application, turning it into a procedure call. The PVSio package also provides functions with side effects, such as input and output, which do not interfere with the semantics of a theory.
A system is modelled in PVS as a theory, a collection of logical statements and definitions about the structural and behavioural aspects of the system. The system's required properties are expressed as theorems to be verified with the PVS theorem prover. If the behavioural aspects are expressed as functions, the system can also be simulated with the PVSio extension. The same logical model can then be used both for verification and simulation.

Model-driven development
Model-driven development (MDD) is based on creating an executable system model by assembling functional blocks. An executable model makes it possible both to simulate the system and to generate production software to control it. Together with the naturalness of the graphic language of functional blocks, these features make MDD very attractive to developers. However, this approach has two limits: first, functional blocks lend themselves to building design models, but not specification ones; and secondly, formal verification of a block-based model is tedious, and in fact it is uncommon in industrial practice.
A formal approach can be used to create both specification and design models and intrinsically lends itself to rigorous verification of system properties. In particular, logic specification languages, such as PVS, are supported by automatic or interactive theorem provers used by developers to check if system requirements, expressed as logical formulas, are implied by a system's description expressed in a logic theory. However, formal methods require expertise in languages and methods that are not widely known in the wider developer community. Further, most formal languages abstract from the familiar procedure-oriented computation model of popular programming languages, making it harder to generate executable software.
It is then desirable to have tools and methods providing developers with the features of both approaches. The present work is part of a research effort aimed at this goal. With the PVSio-web framework, a developer can build a model in a graphical state-machine language or a logic language, or both (Sect. 3). The graphical model is translated into the logic language automatically, and the resulting translation is both verifiable and executable using the PVSio ground evaluator, which acts as an interpreter for the PVS language. The PVSio-web framework thus provides features of the formal approach: A formal specification language and a verification tool, and features of MDD, thus providing a full graphical modelling language and a simulation engine. A translator from Emucharts to C makes it possible to generate code from a state machine-based model that can be validated by simulation and verified by theorem proving. The other important feature of MDD -generation of production code capable to be run on the actual system hardware -is a key contribution of this paper.

PVSio-web
The PVSio-web framework is a set of tools, co-ordinated by a web-based interface, for prototyping and simulation of interactive devices. Its main components are, besides PVS with its PVSio extension: (i) the Prototype Builder, a graphical tool used to choose a picture of an existing or anticipated device's front panel and to associate PVS functions with active areas of the picture representing device inputs (e.g., buttons or keys) and outputs (e.g., alphanumeric displays or lights); (ii) the Model Editor, a textual interface to write PVS code; (iii) the Emucharts Editor, a graphical tool to draw Emucharts state machine diagrams; (iv) a Simulation Environment; and (v) Code Generators for PVS and other formal languages (currently Presentation Interaction Models [8], Modal Action Logic [15], and Vienna Development Method [12]) -and for MISRA C, as presented in this paper.
PVSio-web can be used to prototype a new device interface, or to create a reverse-engineered model of an existing one. In either case, a developer creates formal descriptions of the device's responses to user actions, using the model and Emucharts editors, and associates these descriptions with the active areas of the simulated interface, using the prototype builder. In the simulation environment, the developer, or a domain expert or a potential user, interacts with the prototype clicking on the input widgets. These actions are translated to PVS function calls executed by the PVSio interpreter.

Emucharts
An Emucharts diagram is the representation of an extended state machine in the form of a directed graph composed of labelled nodes and transitions. Transitions are labelled with triples of the form trigger[guard]{action}, where trigger is the name of an event, guard is an enabling Boolean expression, and action is a set of assignments to typed variables declared in the state machine's context. The default guard is the true value and the default action is a no-operation. The state of the machine is defined by the current node and the current values of the context variables.
The code generator for PVS produces a theory containing functions that define the state machine behaviour on the occurrence of trigger events. Since an Emucharts diagram usually represents a device response to user actions, such events represent user actions, such as pressing a button on a control panel. During simulation on a PC, a user click on an active area of the device picture causes the simulator to generate a function application expression that is passed to the PVSio ground evaluator.

From Emucharts to safe C
The aim of programming code generation in the PVSio-web framework is producing a module that implements the user interface of a device, which can be compiled and linked into the device software without any particular assumptions on its architecture. In this way, the user interface module can be used without forcing design choices on the rest of the software. In our approach, the generated module contains a set of C functions. The main ones are, for each Emucharts trigger: (i) a permission function, to check if the trigger event is permitted, i.e., whether it is associated with any transition from the current state, and (ii) a transition function that, according to the current state, updates it, provided that the guard condition of an outgoing transition holds. The code includes logically redundant tests (assert macros) to improve robustness.
To generate production-quality code fit for safety-critical applications we adopt MISRA guidelines. The MISRA guidelines for the C language, originally conceived for the automotive industry, enforce programming practices to improve maintainability and portability and, above all, to reduce the risk of malfunction due to implementation-or platform-dependent aspects of the C language. For instance, there are rules that bar the use of constructs such as goto, and rules requiring that numeric literals be suffixed to indicate their type explicitly. The generated code currently complies with the first version of the 1998 MISRA C guidelines.

Code generation
Our MISRA C code generator was implemented in JavaScript using Handlebars [14], a macro-expansion tool for web applications. A Handlebars template is a piece of text containing "Handlebar expressions," which refer to elements of the surrounding context, typically an HTML document. A Handlebars expression specifies a character string as a function of context elements, which is compiled into a JavaScript function that returns the template text with the substitutions computed by the Handlebars expressions. For example, a template fragment for a C preprocessor #include directive is #include "{{filename}}.h", where the Handlebars expression {{filename}} contains the filename parameter that will be replaced by the actual name of the file to be included. The code generator produces a header file, an implementation file, a makefile, a simple test driver file, and a documentation manual.
The structure of the header file is defined by the grammar in Table 1. The header file contains, among other items, the declarations (typedef_definitions in the grammar) for types with explicit representation of size and sign, e.g., UC_8, for eight-bit unsigned char, the declaration (state_labels_enum) for an enumeration type defining the node labels, and the declaration (state_structure) for the state structure type representing the state of the Emucharts model. This structure contains one context field for each variable defined in the Emucharts context, and two more fields (curr_node and prev_node) contain the labels of the current and the previous node.
The declarations are followed by the function prototypes of the two utility functions enter and leave, the init function, and, for each trigger, one permission and one transition function. The functions receive a pointer to a structure of type state passed by a calling program. The enter and leave functions, called by the init and transition functions, update the curr_node and prev_node fields, respectively, with the target and source node label of the executed transition. The leave function has been introduced to allow future versions to implement checkpointing algorithms. The init function initialises the state's context fields with the values of the context variables specified in the Emucharts diagram, and the curr_node field with the label of the initial node. As mentioned above, each permission function checks if the current node has a transition labelled by the respective event. Then, the matching transition function chooses among the transitions triggered by that event, according to the respective guards (assumed to be mutually exclusive).
The implementation file contains the function definitions. For example, consider the Emucharts diagram of the data entry system of the Medtronic MiniMed 530G System shown in Figure 3. The diagram has a context variable display of type double represented on 64 bits, which holds the value shown on the device's display. The node labels and the state type are defined as  A proof of the correctness of this translation schema is shown in Appendix A.

Case study
The Alaris GP, made by Becton Dickinson and Company, was used as a case study for the MISRA C code generator.
This volumetric infusion pump is a medical device used for controlled automatic delivery of fluid medication or blood transfusion to patients, with an infusion rate range between 1 ml/h and 1200 ml/h. It has a monochrome dot matrix display with three significant digits, and has 14 buttons for operating the device (see Figure 4). The pump has a rather complex user interface, with different modes of operation and ways of entering data, including the possibility of choosing from a list of preloaded treatments. For simplicity, in this paper only the essential part of the data entry interface, concerning numerical input and display, is considered.
Numerical input is done through the chevrons buttons: upward and downward chevrons increase and decrease, respectively, the displayed value. The amount by which the value is increased or decreased depends on whether a single or double chevron is pressed, and on the current displayed value. More precisely, the displayed value is changed as follows: (i) If the displayed value is below 100, the value changes by 0.1 units for a single chevron, and steps up or down to the next decade for a double chevron (e.g., from 9.1 to 10.0); (ii) if the displayed value is between 100 and 1, 000, the value changes by 1 unit for a single chevron, and steps up or down to a value equal to the next hundred plus the decade of the displayed value for a double chevron (e.g., from 310 or 315 to 410); (iii) if the displayed value is 1, 000 or above, the value changes by 10 units for a single chevron, and steps up or down to a value equal to the next hundred for a double chevron (e.g., from 1, 010 or 1, 080 to 1, 100).
The Emucharts diagram for the numeric data entry is shown in Fig. 5. Triggers click_alaris_up and click_alaris_dn represent clicks on the upward and downward single-chevron buttons, respectively, and triggers click_alaris_UP and click_alaris_DN represent clicks on the double-chevron ones. For each event, combinations of guards and actions specify the rules described above.
The PVS code generator translates the diagram into an executable logic theory, and the C code generator produces permission and transition functions for each trigger, as explained previously.

Mobile applications
The PVSio-web framework uses a standard web interface to integrate its tools: this approach offers a uniform interface that a developer can access with any web browser.
Our framework has been extended by providing the possibility to run simulations on a mobile device. Smartphones and tablets improve usability and help make user interaction similar to actual device operation. For example, mobile devices could be used in a hospital environment to train medical personnel and patients.
An interactive device can be simulated using the C source code produced by the PVSio-web generator, compiled and linked with a mobile device-specific application. For example, the code for the user interface of the Alaris infusion pump has been ported to the Android [10] platform using the Android NDK [25] toolset, which can embed C code in a Java project, relying on the Java Native Interface (JNI) [18].

Conclusions
We presented the implementation of our MISRA C code generator for the PVSio-web prototyping toolkit. Automatic code generation significantly reduces project development time. Our approach eliminates a human-performed step in the development process: user interface software engineers no longer need to convert the design specifications into executable target code.
Our tool improves the development of safe and dependable user interfaces, as it greatly facilitates using formal methods easily and reliably with real UIs, which we demonstrated with the medical device examples in this paper.
Current and future directions include improving this initial integration with other features of C, still conformant to MISRA C under the most recent 2012 rules. We plan to develop code generators for programming languages such as C++, Java and ADA.

A Correctness of code generation
In order to assess the correctness of the generated code, the Emucharts diagram is taken as the reference model, and a correspondence is established between the evolution of the model and that of the executed code.

A.1 Transition system for an Emucharts diagram
As discussed above (section 4), an Emucharts diagram is a graph of nodes and labelled transitions, extended with a set of typed context variables, each one with an initial value. Its semantics is given by a transition system. Let the following be defined: • A set N = {n 1 , . . . , n i } of nodes; • a set X = {x 1 , . . . , x j } of context variables (for simplicity, assumed to be typeless); • a set V of values; • a set E = { 1 , . . . , k } of events; • a set G = {g 1 , . . . , g l } of guards, i.e., Boolean expressions involving variables, constants from V, arithmetic and relational operators; • a denumerable set V of valuations, i.e., functions from X to V; • a set A = {a 1 , . . . , a l } of arcs, i.e., 5-tuples of the form (s, t, e, g, v), where s, t ∈ N are the arc's source and target node, e ∈ E, g ∈ G, and v ∈ V is the valuation defined by the action labelling the corresponding transition in the diagram; more precisely, v is the valuation obtained by overriding the previous valuation with the assignments in the action associated with the arc; • a set Q of states of the form n, v , with n ∈ N and v ∈ V; arc , (p, q, e, g, v ); = e ∧ n = p ∧ v | = g n, v → q, v idle , (p, q, e, g, v ); e ∨ n p ∨ v | = g n, v → n, v Figure 6: Emucharts operational semantics.
• a transition relation → ⊆ Q × Q, defined by the semantic rules in Figure 6, where the premises contain an event , an arc label, and a logical condition, and the consequences contain a member of the transition relation that is enabled if the condition holds.
With the above definitions, the associated transition system T is the tuple (Q, →, q 0 ), where q 0 = n 0 , v 0 is the initial state. Since the diagram is deterministic, given a sequence of event occurrences e 1 , . . . , e k , . . ., the transition system has only one sequential path. If an event cannot affect a state (either it is not permitted or no guard prefixed by the event is satisfied), the system does not change state. The operational semantics are given in Figure 6.

A.2 Transition system for the generated code
The generated functions are used within a more complex system, which is responsible for catching events at the real or simulated user interface and for calling the respective functions according to an appropriate protocol: the init function must have been called previously, then, when an event is catched, the permission function of the corresponding trigger is called, and only if it returns true can the respective transition function be executed.
Assume that the data entry subsystem of the device is controlled by a program P that responds to input events by calling the respective functions. These function will take the device to the next state.
Also the program P can be modelled as a transition system T P based on the following sets, each one being isomorphic ( ) to the corresponding set in T , or an extension to that set: (i) A set N P N of node labels, each represented by an enumerator of the node_label type in P; (ii) a set X P = X c ∪ {x curr } of variables, where X c X, each variable in X c represents a context field of the state structure in P, and x curr represents the curr_node of the state structure; (iii) a set V P = V c ∪ N P of values, where V c = V; (iv) a set E P E of events, each one associated with one permission function and one transition function in P; (v) a set G P G of guards, each implemented as the condition of an if statement in P; (vi) a denumerable set V P = V c ∪ V n of valuations from X P to V P , where V c V and V n : {x curr } → N P ; (vii) a set A P A of arcs, where each arc has the form (v n (x curr ), v n (x curr ), e, g, v c ), and each arc represents an if statement in the transition function for event e having guard g as its condition and valuation v = v n ∪ v c as its controlled statement, with v n implemented by the enter function and v c by the assignments specified in the Emucharts diagram.
With the above definitions, let Q P be a set of states where each state is a pair v n , v c , with v n ∈ V n , v c ∈ V c . The transition relation P −→ ⊆ Q P × Q P is defined by the semantic rules in figure 7 applied to elements of the above sets, and implemented by the permission functions, which check for each event e if the condition v n (x curr ) = p holds or not, and by the transition functions, which check if the current values of the variables satisfy the guards, and update node and variables accordingly. The associated transition system T P is the tuple (Q P , P −→, q P0 ), where q P0 is the state defined by the initial values of x curr and of the context variables, set by the init function. The operational semantics are given in Fig. 7.

A.3 Equivalence of the transition systems
To prove the correctness of the generated code, we introduce the definition of equivalence between Emucharts states and the program states. Definition 1. A member m of one of the sets N, X, V, E, defined in T , is equivalent (∼) to the member m P paired to m by the isomorphism between the set containing m and the corresponding set in T P . Definition 2. A state q = n, v , q ∈ Q, is equivalent (∼) to a state q P = v n , v c , q P ∈ Q P iff n ∼ v n (x curr )so the value of x curr is equivalent to node n, and ∀ x∈X v(x) = v c (x P ) (i.e., matching variables in q and q P have the same values).
The proof of correctness for the generated code is by induction on the length of computation. We assume that T and T P are the transition systems modelling, respectively, an Emucharts diagram and a program that uses the generated code, respecting the previously introduced protocol, and accepts a sequence of input events. Theorem 1. Let T and T P be the transition systems introduced in the above paragraphs, and e = e 1 , e 2 . . . be a sequence of input event sequences. Let σ = q 0 , q 1 , . . . and σ P = q P0 , q P1 , . . . be sequences of states, with q i → q (i+1) and q Pi P −→q P(i+1) . We prove that, at each step of the computation, q i ∼ q Pi : Induction base. q 0 ∼ q P0 by construction.
Induction step. Let q j ∼ q P j at step j. On the occurrence of an event e, let q j → q ( j+1) and q P j P −→q P( j+1) . We can prove that q ( j+1) ∼ q P( j+1) by case analysis: (1) e not permitted in q j ; (2) e permitted and guard not satisfied; and (3) e permitted and guard satisfied. Case 1: e not permitted. If the event is not permitted in the current state, rules idle and idle P apply to T and T P , respectively, so that q ( j+1) = q j and q P( j+1) = q P j , equivalent by induction hypothesis. Recall that the permission function for e returns false in this case, and by hypothesis program P does not call the corresponding transition function. Case 2: e permitted and guard not satisfied. Also in this case, rules idle and idle P apply to the transition systems. The if statements in P check that the guard does not hold, and the respective controlled statements are not executed. Case 3: e permitted and guard satisfied. In this case, Rules arc and arc P apply to both transition systems, therefore (i) T moves from state q j = n, v to state q ( j+1) = n , v , or (ii) T P moves from state q P j = v n , v c to state q P( j+1) = v n , v c . Valuation v n maps x curr to a node label equivalent by definition to n , and v c maps the context variables in T P to values equivalent by definition to those assigned by v to the context variables in T .
The new states in the two transition systems are therefore equivalent.