W3C

State Chart XML (SCXML): State Machine Notation for Control Abstraction

W3C Working Draft 21 February 2007 16 May 2008

This version:
http://www.w3.org/TR/2007/WD-scxml-20070221/ http://www.w3.org/TR/2008/WD-scxml-20080516/
Latest version:
http://www.w3.org/TR/scxml/
Previous version:
http://www.w3.org/TR/2006/WD-scxml-20060124/ http://www.w3.org/TR/2007/WD-scxml-20070221/
Editors:
Jim Barnett, Aspect Software (Editor-in-Chief)
Rahul Akolkar, IBM
R J Auburn, Voxeo
Michael Bodell, Tellme Networks Microsoft
Dan Daniel C. Burnett, Nuance Voxeo
Jerry Carter, Nuance
Scott McGlashan, HP
Torbjörn Lager, Invited Expert
Mark Helbing, (until 2006, when at Nuance)
Rafah Hosn, IBM (until 2008, when at IBM)
T.V. Raman, (until 2005, when at IBM)
Klaus Reifenrath, (until 2006, when at Nuance)

Abstract

This document describes SCXML, or the "State Chart extensible Markup Language". SCXML provides a generic state-machine based execution environment based on CCXML and Harel State Tables.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is the third fourth Public Working Draft of SCXML published on 16 May 2008 for review by W3C Members and other interested parties, and has been developed by the Voice Browser Working Group (W3C Members Only) as part of the W3C Voice Browser Activity . The most significant changes since main differences from the last previous draft are are:

Please note that most sections have been modified because of above changes, the editors would like readers to read the whole document carefully and give comments.

Comments for this specification are welcomed to www-voice@w3.org ( archives ).

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy . W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy .

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

Table of Contents

1 Terminology
2 Overview
3 Basic State Notation Core Module
    3.1 <scxml>
        3.1.1 Attribute Details
        3.1.2 Children
    3.2 <state>
        3.2.1 Attribute Details
        3.2.2 Children
    3.3 <transition>
        3.3.1 Attribute Details
        3.3.2 Children
    3.4 <parallel>
        3.4.1 Attribute Details
        3.4.2 Children
    3.5 <final> <initial>
        3.5.1 Attribute Details
        3.5.2 Children
    3.6 <onentry> <final>
        3.6.1 Attribute Details
        3.6.2 Children
    3.7 <onexit> <onentry>
        3.7.1 Attribute Details
        3.7.2 Children
4 Pseudo-States     3.8 <onexit>
    4.1 <initial>         3.8.1 Attribute Details
        4.1.1         3.8.2 Children
    3.9 <history>
        3.9.1 Attribute Details
        4.1.2         3.9.2 Children
    4.2 <history>     3.10 Executable Content
        4.2.1         3.10.1 <event>
            3.10.1.1 Attribute Details
        4.2.2             3.10.1.2 Children
5         3.10.2 <if>
            3.10.2.1 Attribute Details
            3.10.2.2 Children
        3.10.3 <elseif>
            3.10.3.1 Overview
            3.10.3.2 Attribute Details
        3.10.4 <else>
            3.10.4.1 Overview
            3.10.4.2 Attribute Details
        3.10.5 <log>
            3.10.5.1 Overview
            3.10.5.2 Attribute Details
        3.10.6 Extensibility of Executable Content
    3.11 Referencing External Files
6 Extensions to the Basic State Machine Model     3.12 SCXML Events
    6.1 4 External Communications Module
    4.1 <send>
        4.1.1 Overview
        4.1.2 Attribute Details
    4.2 <invoke>
        6.1.1         4.2.1 Attribute Details
        6.1.2         4.2.2 Children
    6.2     4.3 <param>
        6.2.1         4.3.1 Attribute Details
        6.2.2         4.3.2 Children
    6.3     4.4 <finalize>
        6.3.1         4.4.1 Attribute Details
        6.3.2         4.4.2 Children
    6.4     4.5 <content>
        6.4.1         4.5.1 Attribute Details
        6.4.2         4.5.2 Children
    6.5 <anchor> 5 Data Module
        6.5.1     5.1 <datamodel>
        5.1.1 Attribute Details
        6.5.2         5.1.2 Children
7     5.2 Data Model <data>
    7.1 Overview of Data Model         5.2.1 Attribute Details
    7.2 <datamodel>         5.2.2 Children
        7.2.1     5.3 <assign>
        5.3.1 Attribute Details
        7.2.2         5.3.2 Children
    7.3 <data>     5.4 <validate>
        7.3.1         5.4.1 Attribute Details
        7.3.2         5.4.2 Children
8 Executable Content     5.5 System Variables
    8.1 Data Model Operations 6 Script Module
        8.1.1 <assign>     6.1 <script>
            8.1.1.1         6.1.1 Attribute Details
            8.1.1.2         6.1.2 Children
        8.1.2 _eventdata 7 Anchor Module
        8.1.3 <validate>     7.1 <anchor>
            8.1.3.1         7.1.1 Attribute Details
            8.1.3.2         7.1.2 Children
8 Expressions
    8.1 Conditional Expressions
    8.2 Event Generation Location Expressions
        8.2.1 <event>     8.3 Legal Data Values and Value Expressions
            8.2.1.1 Attribute Details     8.4 Errors in Expressions
            8.2.1.2 Children 9 Profiles
        8.2.2 <send>     9.1 The Minimal Profile
            8.2.2.1 Overview         9.1.1 Conformance
            8.2.2.2 Attribute Details         9.1.2 Core Module Requirements
    8.3 Flow Control Elements             9.1.2.1 Conditional Expressions
        8.3.1 <if>     9.2 The ECMAScript Profile
            8.3.1.1 Overview         9.2.1 Conformance
            8.3.1.2 Attribute Details         9.2.2 Core Module Requirements
        8.3.2 <elseif>             9.2.2.1 Conditional Expressions
            8.3.2.1 Overview         9.2.3 Data Module Requirements
            8.3.2.2 Attribute Details             9.2.3.1 Location Expressions
        8.3.3 <else>             9.2.3.2 Value Expressions
            8.3.3.1 Overview             9.2.3.3 System Variables
            8.3.3.2 Attribute Details         9.2.4 Script Module Requirements
    8.4 Debugging Elements         9.2.5 Additional Requirements
        8.4.1 <log>             9.2.5.1 The In() predicate
            8.4.1.1 Overview         9.2.6 Examples
            8.4.1.2 Attribute Details     9.3 The XPath Profile
    8.5 Custom Action Elements         9.3.1 Conformance
9 Boolean         9.3.2 Core Module Requirements
            9.3.2.1 Conditional Expressions
    9.1 In         9.3.3 Data Module Requirements
        9.1.1 Overview             9.3.3.1 Location Expressions
        9.1.2 Attribute Details             9.3.3.2 Value Expressions
10 SCXML Events             9.3.3.3 System Variables
11         9.3.4 Additional Requirements
            9.3.4.1 The In() predicate
            9.3.4.2 The instance() function
        9.3.5 Examples
10 Related Work

Appendices

A Contributors Open Issues
B Open Issues     A.1 Event Processors
    B.1 undefined behavior in algorithm     A.2 Alternative Notation
    B.2     A.3 parallel transition order
    B.3     A.4 error handling
    B.4 session ID     B.5     A.5 do we need <returndata>
    B.6 Task Logging     B.7 updates to external data sources C B Algorithm for SCXML Interpretation
    C.1 Initialization Phase     C.2 Immediately Enabled Transitions Phase     C.3 Invoke Phase     C.4 Wait External Event Phase     C.5 Execute Transitions Phase         C.5.1 Remove Conflicting Transitions Phase     B.1 Semantics of <anchor>
        C.5.2 Exit C Probabilistic State Phase         C.5.3 Execute Content Phase Machines
        C.5.4 Enter State Phase D Schemas
    C.6     D.1 Utility Functions         C.6.1 SelectTransitions(event) Schemas
        C.6.2 findStatesToExit(trans)     D.2 Schema for Core Module
        C.6.3 findLeastCommonAncestor(state-list)     D.3 Schema for External Module
        C.6.4 addDefaultStatesToEnter(state, rootState, [in/out]stateList, [in/out]defaultEntryList)     D.4 Schema for Data Module
        C.6.5 EnterState(state, rollbackArray, defaultEntryList, currentEvent)     D.5 Schema for Script Module
        C.6.6 Miscellaneous Functions     D.6 Anchor Module Schema
    C.7 Semantics of <anchor>     D.7 Minimal Profile Schema
D Probabilistic State Machines     D.8 ECMAScript Profile Schema
E     D.9 XPath Profile Schema
F E Examples
    F.1     E.1 Language Overview
    F.2     E.2 Shale Example
    F.3     E.3 Examples of Invoke and finalize
    E.4 Custom Action Elements
F Conformance
G References


1 Terminology

[ Definition : The key words must , must not , required , shall , shall not , should , should not , recommended , may , and optional in this specification are to be interpreted as described in [IETF RFC 2119] .]

The terms base URI and relative URI are used in this specification as they are defined in [IETF RFC 2396] .

2 Overview

This document outlines State Chart XML (SCXML), which is a general-purpose event-based state machine language that can be used in many ways, including:

SCXML combines concepts from CCXML and Harel State Tables. CCXML [W3C CCXML 1.0] is an event-based state machine language designed to support call control features in Voice Applications (specifically including VoiceXML but not limited to it). The CCXML 1.0 specification defines both a state machine and event handing syntax and a standardized set of call control elements. Harel State Tables are a state machine notation that was developed by the mathematician David Harel [Harel and Politi] and is included in UML [UML 2.0] . They offer a clean and well-thought out semantics for sophisticated constructs such as a parallel states. They have been defined as a graphical specification language, however, and hence do not have an XML representation. The goal of this document is to combine Harel semantics with an XML syntax that is a logical extension of CCXML's state and event notation.

3 Basic State Notation Core Module

The Core Module contains the elements that define the basic Harel state machine. The Core Module can be used by itself (see 9.1 The Minimal Profile ), but it will not be able to communicate with external entities or maintain an internal data model. The schema for the core module can be found at D.2 Schema for Core Module .

3.1 <scxml>

The top-level root element, state, which carries version information etc.

3.1.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
initialstate initial true false ID IDREFS none Valid The IDs of one or more state ID or parallel elements contained in this state machine The id of the initial state state(s) for the document. The statemachine will This attribute is shorthand for an <initial> child with a transition to containing an unconditional transition.
name false NMTOKEN none Any valid NMTOKEN The name of this state as the last step in document initialization. machine. It is for purely informational purposes.
xmlns false URI none If specified, the value must be "http://www.w3.org/2005/07/scxml".
version false true decimal none The only legal value is "1.0"
profile false NMTOKEN none "minimum", "ecmascript", "xpath" or other platform-defined values. The SCXML profile that this document requires. "min" denotes the Minimal Profile, "ecma" the ECMAScript Profile, and "xpath" the XPath Profile, as defined in 9 Profiles .
exmode false NMTOKEN "lax" "lax" or "strict" The execution mode of the interpreter. This defines how the interpreter should behave if it encounters an element or attribute that it does not understand. If exmode is "lax", the interpreter will silently ignore element or attribute. If exmode is "strict", the interpreter still not process the element or attribute, but will also raise the error error.unsupportedelement.

3.1.2 Children

  • <initial> An optional child which identifies the initial state for the state machine. The state machine will take the transition contained in this element as the last step in document initialization. Occurs zero or one times. See 3.5 <initial>

  • <state> A compound or atomic state. Occurs zero or more times. See 3.2 <state> for details.

  • <parallel> A parallel state. Occurs zero or more times. See 3.4 <parallel> for details.

  • <final> A top-level final state in the state machine. Occurs one zero or more times. When the state machine reaches a top-level final state (i.e., one that is an immediate child of <scxml>), it has finished processing and will terminate. See 3.5 3.6 <final> for details.

<datamodel> A data model. Occurs 0 state machine must specify either an "initial" attribute or 1 times. See 7 Data Model for details. an <initial> element, but not both. Either notation can be used to specify the state that the machine will transition to at the start of processing. The only difference between the two notations is that the <initial> element contains a <transition> element which may in turn contain executable content which will be executed before the initial state is entered. If the "initial" attribute is specified instead, the specified state will be entered, but no executable content will be executed.

3.2 <state>

Holds the representation of a state.

3.2.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
id true id ID none Valid state A valid id as defined in [XML Schema] Identifier The identifier for this state. It MUST be unique within the document.
src false URI none Any URI URI of a file containing material to be inserted into this state. See 5 3.11 Referencing External Files for details.
task initial False false Boolean IDREFS False none Boolean The IDs of one or more state or parallel elements contained in this state. If true the state is considered to be a task for reporting purposes and entry and exit will be logged automatically. The logging shall include at least the state's ID and the status upon exit. The legal status values are 'success' and 'failure' where 'success' indicates that the task ran to completion, while 'failure' indicates that the task did not reach completion. By default, the task will be considered to have completed successfully if id of the default initial state reaches a final substate while any other exit will be considered failure. Implementations are encouraged to include more detailed information in addition to status, such as reason for failure, etc. this state. This attribute may occur only on complex states, i.e., those with <state> or <parallel> children. is shorthand for an <initial> child containing an unconditional transition.

3.2.2 Children

  • <onentry> Optional element holding executable content to be run upon entering this <state>. Occurs 0 or 1 times. See 8 3.10 Executable Content

  • <onexit> Optional element holding executable content to be run when exiting this <state>. Occurs 0 or 1 times. See 8 3.10 Executable Content

  • <transition> Defines an outgoing transition from this <state>. state. Occurs 0 or more times. See 3.3 <transition>

  • <initial> A In states that have substates, an optional child which identifies the default initial state. Any transition which takes the parent state for state machines that have substates. This child is MUST occur if and only if as its target will result in the machine has one or more <state> or <parallel> children. statemachine also taking the transition contained inside the <initial> element. See 4.1 3.5 <initial>

  • <state> Defines a sequential substate of the parent state. Occurs 0 or more times.

  • <parallel> Defines a parallel substate. Occurs 0 or more times. See 3.4 <parallel>

  • <final>. Defines a final substate. Occurs 0 or more times. When the state machine enters a final substate, an event "ParentID.done" is generated, where 'ParentID' is the ID of the final state's parent state. This event indicates that the parent state has reached completion. See 3.5 3.6 <final> .

  • <history> A child which represents the descendant state that the parent state was in the last time the system transitioned from the parent. A transition with this state as its target is in fact a transition to one of the other descendant states of the parent. May occur 0 or more times. See 4.2 3.9 <history> .

  • <anchor> Marks a milestone in the interaction to which the state machine may return. May appear 0 or more times. See 6.5 <anchor> <datamodel> Optional specification of a datamodel. See 7 Data Model for details. <invoke> Used to invoke external components. Occurs 0 or 1 times. For further details, see 6.1 <invoke>

<invoke> occurs only in atomic states, A complex state, namely those one that do not have has <state> or <parallel> children. Thus, a state may have children, must specify either <state> and <parallel> children or an <invoke> child,but "initial" attribute or am <initial> element, but not both. Either notation can be used to specify the state's default initial state. See 3.5 <initial> for a discussion of the difference between the two notations.

3.3 <transition>

Transitions between states are triggered by events and conditionalized via guard-conditions. The optional attribute "target" specifies the destination of the transition, which may be a <state> or a <parallel> region. If the "target" on a <transition> is omitted, then taking the transition has the effect of leaving the machine in the same state after invoking any executable content that is included in the transition. Such a transition is equivalent to an 'event' handler in Harel State Table notation. Note that this is different from a <transition> whose "target" is its source state. In the latter case, the state is exited and reentered, triggering execution of its <onentry> and <onexit> executable content.

Any executable content contained in a transition is executed after the <onexit> handlers of the source state and before the <onentry> handlers of the target state. Within both the 'cond' attribute of the transition and the executable content, the special variable '_eventdata' can be used to access data contained within the triggering event. See 8.1.2 _eventdata for details. An anchor MAY be specified instead of a "target" for the transition. In this case, the system transitions to the last state visited containing an <anchor> whose "type" matches the "anchor" specified in the transition. See Section 6.5 <anchor> for details.

3.3.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
event false String NMTOKEN none Any event name. The wildcard '*' is permitted. See 10 3.12 SCXML Events for details. The event trigger for this transition. The transition will be taken only when the event is generated. See C B Algorithm for SCXML Interpretation for details on how transitions are selected.
cond false Boolean expression none Any boolean expression. Guard condition for this transition. If it is present, the transition is taken only if the guard condition evaluates to true . See 9 Boolean 8.1 Conditional Expressions for details.
target false state or parallel region ID IDREFS none Whitespace separated list of state IDs in the current state machine. If multiple states are specified all must be descendants of the same <parallel> element. The identifier(s) of the state or parallel region to transition to.
anchor false NMTOKEN none Any anchor type The type of the anchor to transition to. See 6.5 7.1 <anchor> for details.

Only one of "target" and "anchor" may be specified.

3.3.2 Children

  • Immediate children of <transition> above are executable content that is run after the <onexit> handler for this state and before the <onentry> handler in the target state. See 8 3.10 Executable Content

If a transition has both "event" and "cond" attributes, it will be taken only if an event is raised that matches the "event" pattern and the "cond" condition evaluates to true. If the "event" clause is missing, the transition is taken whenever the "cond" evaluates to true. If the "cond" clause is also empty, the transition is taken as soon as the state is entered. Note that the data model can be changed only by the execution of <invoke> or executable content. Therefore transitions with empty "event" conditions need be checked only 1) upon arrival into a state, after the completion of all <onentry> handlers and 2) after an event has been processed (since it may have triggered executable content which could have updated the data model). See C B Algorithm for SCXML Interpretation for details.

3.4 <parallel>

A wrapper element state that encapsulates a set of parallel states . The <parallel> element has <onentry> and <onexit> and <transition> elements analogous to <state>. In addition, the <parallel> element holds a set of <state> elements that execute in parallel and join at the <onexit> handler of the <parallel> element. In particular, when all of the parallel substates reach final states, a completion event "ID.done" is generated, where "ID" is the "id" of the <parallel> element. Either the <parallel> element or one of its ancestors can trigger a transition off this event, at which time the <onexit> handler of the element will be executed.

When the state machine enters the parent <parallel> element, state, it simultaneously enters each child state. Transitions within the individual child elements operate normally. However any of the child elements may take a transition outside the <parallel> element. When this happens, the <parallel> element and all of its child elements are exited and the corresponding <onexit> handlers are executed. The handlers for the child elements execute first, in document order , followed by those of the parent <parallel> element, followed by an action expression in the <transition> element, and then the <onentry> handlers in the "target" state. See C B Algorithm for SCXML Interpretation for a detailed description of the semantics <parallel> and the rest of SCXML.

3.4.1 Attribute Details

task False Boolean false Boolean If true the parallel is considered to be a task for reporting purposes and entry and exit will be logged automatically. The legal status values are 'success' and 'failure' where 'success' indicates that the task ran to completion, while 'failure' indicates that the task did not reach completion. By default, the task will be considered to have completed successfully if the state reaches a final substate while any other exit will be considered failure. Implementations are encouraged to include more detailed information in addition to status, such as reason for failure, etc.
Name Required Attribute Constraints Type Default Value Valid Values Description
id true ID none Valid state ID A valid id as defined in [XML Schema] Indicates the name of the parallel The identifier for this state. It MUST be unique within the document.
src false URI none Any URI URI of a file containing material to be inserted into this state. See 5 3.11 Referencing External Files for details.

3.4.2 Children

  • <onentry> Holds executable content to be run upon entering the <parallel> element. Occurs 0 or one times . See 8 3.10 Executable Content

  • <onexit> Holds executable content to be run when exiting this element. Occurs 0 or one times . See 8 3.10 Executable Content

  • <transition> Defines an outgoing transition from this state. Occurs 0 or more times. See 3.3 <transition>

  • <state> Defines a parallel substate region. Occurs 1 0 or more times.

  • <parallel> Defines a nested set of parallel regions. Occurs 1 0 or more times.

  • <history> A child which represents the state configuration that this state was in the last time the system transitioned from it. A transition with this history pseudo-state as its target is in fact a transition to the set of descendant states that were active the last time this state was exited. Occurs 0 or more times. See 4.2 3.9 <history> .

3.5 <initial>

<anchor> Marks This element represents the default initial state for a milestone complex state with sequential substates. Suppose <state> S1 has child states S11, S12, and S13. If the system is in S1, it must also be in one (and only one) of S11, S12, or S13. A <transition> in a distinct <state> S2 may take S11, S12, or S13 as its "target", but it may also simply specify the interaction to parent S1. In that case, the <initial> child of S1 specifies which of S11, S12, or S13 the state machine system should transition to.

The only difference between the <initial> element and the 'initial' attribute is that the <initial> element contains a <transition> element which may return. Occurs 0 or more times. See in turn contain executable content which will be executed before the default state is entered. If the "initial" attribute is specified instead, the specified state will be entered, but no executable content will be executed. As an example, suppose that parent state S contains child states S1 and S2. If S specifies S1 as its default initial state via the "initial" attribute, then any transition that specifies S as its target will result in S entering S1 as well as S. In this case, the result is exactly the same as if the transition had taken S1 as its target. If, on the other hand, S specifies S1 as its default initial state via the <initial> tag containing a <transition> with S1 as its target, the <transition> can contain executable content which will execute before the default entry into S1. In this case, there is a difference between a transition that takes S as its target and one that takes S1 as its target. In the former case, but not in the latter, the executable content inside the <initial> transition will be executed.

6.5 <anchor> 3.5.1 Attribute Details

None

3.5.2 Children

  • <datamodel> Optional specification <transition> A conditionless transition (i.e., one without a "cond" or "event" attribute). Such a transition is always enabled and will be taken as soon as the state is entered. The "target" of the transition must be a data model. See 7 Data Model for details. descendant of the <initial> element's parent <state>.

3.5 3.6 <final>

<final> repesents represents a final state of a compound state. When the system reaches a final state, it means that its parent state has completed its activity. Upon entry to the final state, the event "ParentID.done" is generated, where 'ParentID' is the ID of the parent state. Note that even though the parent state has run to completion, more remote ancestors may still be active. When the state machine reaches a top-level final state (namely one that is a child of <scxml>), it has finished processing and will terminate.

3.5.1 3.6.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
id true id ID none Valid state A valid id as defined in [XML Schema] Indicates the name of the final The identifier for this state. It MUST be unique within the document.

3.5.2 3.6.2 Children

  • None <onentry> Optional element holding executable content to be run upon entering this state. Occurs 0 or 1 times. See 3.10 Executable Content

  • <onexit> Optional element holding executable content to be run when exiting this state. Occurs 0 or 1 times. See 3.10 Executable Content

3.6 3.7 <onentry>

3.6.1 3.7.1 Attribute Details

None.

3.6.2 3.7.2 Children

The children of the <onentry> handler consist of executable content as defined in 8 3.10 Executable Content

3.7 3.8 <onexit>

3.7.1 3.8.1 Attribute Details

None.

3.7.2 3.8.2 Children

The children of the <onexit> handler consist of executable content as defined in 8 3.10 Executable Content

4 Pseudo-States The following elements are called 'pseudo-states' because they do not have the full properties of states (for example they lack <onentry> and <onexit> handlers) and do not map to states in the underlying semantics of the language. However, they can be used like states in many places. In particular, they can often be the "target" of <transition>. They are a notational shorthand allowing the simple statement of some sophisticated control constructs. 4.1 <initial> This element represents the default initial state for a complex state with sequential substates. Suppose <state> S1 has child states S11, S12, and S13. If the system is in S1, it must also be in one (and only one) of S11, S12, or S13. A <transition> in a distinct <state> S2 may take S11, S12, or S13 as its "target", but it may also simply specify the parent S1. In that case, the <initial> child of S1 specifies which of S11, S12, or S13 the system should transition to. 4.1.1 Attribute Details Name Required Attribute Constraints Type Default Value Valid Values Description id true id none Valid state id Identifier for this pseudo-state. It MUST be unique within the document. 4.1.2 Children <transition> A conditionless transition (i.e., one without a "cond" or "event" attribute). Such a transition is always enabled and will be taken as soon as the state is entered. The "target" of the transition must be a descendant of the <initial> element's parent <state>. If <state>S1 has an <initial>child with a <transition> with no executable content and "target" S12, there is no semantic difference between the following three transitions: a) one that takes S1 as its "target" b) one that takes S1's <initial> child as a "target" c) one that takes S12 as its "target". The result in all three cases is that the system enters both S1 and S12 as an atomic action, executing the <onentry> handlers of first S1 and then S12. Note, however, that it is possible to put executable content inside the <transition> in <initial>. If such executable content is present, then cases a) and b) are different from c) because in a) and b) the default <initial> <transition>'s executable content will be executed, while in case c) it will not.

4.2 3.9 <history>

The <history> pseudo-state allows for 'pause and resume' control flow. Whenever a complex <state> is exited, its <history> pseudo-state, if present, records the state configuration at exit. Later a <transition> taking the <history> state as its "target" allows the <state> to pick up where it left off. If the state containing the <history> state is a compound state, then the history value will be a single state. However, if the parent state is a <parallel> state, the history value will be a set of states, one for each parallel child region.

4.2.1 3.9.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
id true id ID none Valid state A valid id as defined in [XML Schema] Identifier for this pseudo-state. It MUST be unique within the document.
type false string NMTOKEN shallow "deep" or "shallow" If the value is 'shallow' then this state records only the immediate children of the parent <state>. In this case a <transition> with the history pseudo-state as its "target" will end up in the immediate child state that the parent was in the last time it was exited. On the other hand, if this attribute is set to 'deep', the history pseudo-state will remember nested states. In this case a <transition> with the history pseudo-state as its "target" will end up in the most deeply nested descendant <state> the parent was in the last time it was exited.

4.2.2 3.9.2 Children

  • <transition> A conditionless transition (i.e., one without a "cond" or "event"; attribute). Such a transition is always enabled and may be taken as soon as the state is entered. This <transition> represents the default history state and indicates the <state> to transition to if the parent <state> has never been entered before. if "type" is 'shallow', then the "target" of this <transition> must be an immediate child of the parent <state>. Otherwise it can be any descendant <state>. If the parent of the <history> state is a <parallel> state, then this transition may take multiple targets (each much be in a distinct parallel child state).

3.10 Executable Content

Executable content consists of actions that are performed as part of taking transitions and entering and leaving states (<onentry> and <onexit>, etc.) Executable content occurs in blocks, meaning that wherever executable content may occur, an arbitrary number of elements may occur. These elements in a block are processed in document order. If the processing of an element causes an error to be raised, the remaining elements of the block are not processed and the error event is placed on the internal event queue and processed like any other event (see B Algorithm for SCXML Interpretation ). In particular, the error event will not be removed from the queue and processed until all events preceding it in the queue have been processed.

Note that 4 External Communications Module ,5 Data Module and 6 Script Module all define additional elements of executable content beyond those listed here. Thus the exact set of executable content available depends on the profile (see 9 Profiles for examples).

3.10.1 <event>

The <event> element may be used to raise an event in the current SCXML session. The event will be added to the session's internal event queue, but will not be processed until later, following the algorithm specified in B Algorithm for SCXML Interpretation .Note in particular that the event cannot be processed until all current executable content has been executed. For example, if the <event> element occurs in the the <onentry> handlers of a state, at the very least the event will not be processed until all the executable content in the <onentry> handler has completed.

3.10.1.1 Attribute Details
Name Required Attribute Constraints Type Default Value Valid Values Description
name true NMTOKEN none Specifies the name of the event. This will be matched against the 'event' attribute of transitions.
3.10.1.2 Children

None.

3.10.2 <if>

<if> is a container for conditionally executed elements. <elseif> and <else> can optionally appear within an <if> as immediate children, and serve to partition the elements within the <if>. <else> and <elseif> have no content. <else/> is equivalent to an <elseif > element whose "cond" always evaluates to true.<else> must occur after all <elseif> tags.

Each partition within an <if> is preceded by an element having a "cond" attribute. The initial partition is preceded by the <if> and subsequent partitions by <elseif>s (or <else>). The first partition in document order with a "cond" that evaluates to true is selected. <else> always evaluates to true. A partition MAY be empty.

If an <if> has no immediate <elseif> or <else> children, the full contents of the <if> will be selected when the "cond" attribute evaluates to true.

<else> was chosen to match similar concepts in other languages, and supports examples such as


<if cond="cond1">
  <!-- selected when "cond1" is true -->
<elseif cond="cond2"/>
  <!-- selected when "cond1" is false and "cond2" is true -->
<elseif cond="cond3"/>
  <!-- selected when "cond1" and "cond2" are false and "cond3" is true -->
<else/>
  <!-- selected when "cond1", "cond2", and "cond3" are false -->
</if>
            

3.10.2.1 Attribute Details
Name Required Attribute Constraints Type Default Value Valid Values Description
cond true Conditional expression none A valid conditional expression A boolean expression. See 8.1 Conditional Expressions for details.
3.10.2.2 Children

3.10.3 <elseif>

3.10.3.1 Overview

An <elseif> partitions the content of an <if>, and provides a condition that determines the selection of the partition it begins. The executable content following the <elseif> will be executed if the <elseif>'s "cond" evaluates to true and all preceding "cond"s evaluate to false.

3.10.3.2 Attribute Details
Name Required Attribute Constraints Type Default Value Valid Values Description
cond true Conditional expression none A valid conditional expression An boolean expression. See 8.1 Conditional Expressions for details.

3.10.4 <else>

3.10.4.1 Overview

<else> is equivalent to an <elseif/> with a "cond" that always evaluates to true. Thus the executable content in an <else>'s partition will be executed if and only if all preceding "cond"s evaluate to false. <else> must occur after all <elseif> partitions.

3.10.4.2 Attribute Details

None. <else> is a synonym for <elseif cond="true">.

3.10.5 <log>

3.10.5.1 Overview

<log> allows an application to generate a logging or debug message which a developer can use to help in application development or post-execution analysis of application performance. The manner in which the message is displayed or logged is platform-dependent. The usage of label is platform-dependent. The use of <log> MUST have no other side-effects on interpretation. <log>is an empty element.

3.10.5.2 Attribute Details
Name Required Attribute Constraints Type Default Value Valid Values Description
label false string none A character string which may be used to indicate the purpose of the log.
expr true Value expression none An expression returning the value to be logged. See 8.3 Legal Data Values and Value Expressions for details. The nature of the logging mechanism is implementation-dependent, so the platform may convert this value to a convenient format before logging it.
level false positiveInteger 1 This information will be logged only if the system's log level is at this level or higher. The mechanism for specifying the log level and its legal values will be specified in a future version of this document.

3.10.6 Extensibility of Executable Content

The content presented in this specification represents a flexible, powerful, minimum set that all applications can rely on. Platforms are free to provide additional executable content corresponding to special features of their implementations. The functionality of such platform-specific content is not restricted, except that it may not cause transitions or any form of change of state, except indirectly, by raising events that are then caught by transitions. It is important to remember that SCXML treats executable content as a single blocking atomic operation and that no events are processed until all executable content has completed. For example, upon entering a state, the SCXML processor will not process any events or take any transitions until all <onentry> handlers have finished. Thus all executable content, including platform-specific extensions, SHOULD complete quickly under all circumstances. A general method for implementing extensions using the <send> element is presented in E.4 Custom Action Elements below.

Platform-specific extensions to executable content SHOULD be defined in a separate namespace, not in the 'scxml' namespace. Note that the schema D Schemas allows elements from arbitrary namespaces inside blocks of executable content. The following example shows the incorporation of CCXML functionality (see [W3C CCXML 1.0] ) into SCXML. In particular an <accept> element in the 'ccxml' namespace is invoked as executable content inside a transition.


<transition event="ccxml:connection.alerting">
  <ccxml:accept connectionid="eventdata.connectionid"/>
</transition>

This markup is legal on any SCXML interpreter, but the interpretation of the <accept> element is platform-dependent. Platforms that do not support the element will either ignore it or signal an error, depending on the value of the 'exmode' attribute on the <scxml> element (see 3.1.1 Attribute Details ).

5 3.11 Referencing External Files

The "src" attribute on <state> and <parallel> contains a URL which is used to reference an external file containing all or part of the definition of the state. The file must contain a document that matches the SCXML schema but it need not match the extra-schematic constraints contained in this specification. (For example, the document may contain transitions that reference state IDs that are not defined within it.) The exact treatment of the file depends on the format of the URL. If it ends with '#' followed by a string, the string is taken to be the ID of an element in the file and the children of that element are inserted into the state's definition before any other material contained in the <state>. Thus the state is incorporating the definition of a state defined within the file. If, on the other hand, the URL does not contain '#', the contents of the <scxml> element are inserted into the definition of the state before any other material in the state, along with an <initial> element whose <transition> takes as its target the value of the <scxml> element's 'initial' attribute. Thus in this case the contents of the entire state machine are inserted into the definiiton definition of the state.

Suppose that the file at "someURL" looks as follows:

<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initialstate="someState">
<state id="someState">
  <transition event="foo" target="someOtherState"/>
</state>
<state id="someOtherState">
  <transition event="bar" target="finalState"/>
</state>
</scxml>

A 'src' expression referencing 'someOtherState' will result in 'someOtherState's contents being inserted into the state's definition, as shown below. The following markup:

<state id="state1" src="someURL#someOtherState">
   <transition event="state1.Done" target="yetAnotherState"/>
   <final id="finalState"/>
</state>

will expand to:

<state id="state1">
   <transition event="bar" target="finalState"/>   
   <transition event="state1.Done" target="yetOtherState"/>
   <final id="finalState"/>
</state>

On the other hand, a 'src' expression referencing the whole file will result in both 'someState' and 'someOther' state being inserted into the state's definition, along with the appropriate <initial> element. Thus

<state id="state1" src="someURL">
   <transition event="state1.Done" target="yetOtherState"/>
   <final id="finalState"/>
</state>

becomes

 
 <state id="state1">
  <initial>
    <transition target="someState"/>
  </initial>
  <state id="someState">
    <transition event="foo" target="someOtherState"/>
  </state>
  <state id="someOtherState">
    <transition event="bar" target="finalState"/>
  </state>   
  <transition event="state1.Done" target="yetOtherState"/>
  <final id="finalState"/>
</state>

File inclusion takes place at load time. Implementations are free to perform document validation by any method they choose as long as the result is logically equivalent to a single pass of validation occurring after the material from the external file has been incorporated. (Note that implementations are not required to validate the external file. All that is required is that the document resulting from the incorporation be valid.)

3.12 SCXML Events

Events are one of the basic concepts in SCXML since they drive most transitions. The internal structure of events is platform-specific as long as the following external interface is observed:

  • Events have names which are matched against the "event" attribute of transitions. These names are strings consisting of alphanumeric characters plus the character '.' which is used to segment names into tokens. The "event" attribute of a transition may end with the wildcard '.*', which will match zero or more tokens at the end of the processed event's name. Thus a transition with an "event" attribute of 'error.*' will match 'error', 'error.send', 'error.send.failed', etc. Furthermore, a transition with an "event" attribute consisting solely of '*' will match any event.

  • Events optionally contain data organized into XML trees. If data is present, it must be able to be accessed via the 'event' variable, as specified in 5.5 System Variables .

  • Events are immutable read-only data structures. Neither the browser's processing nor the user's markup may modify an event once it is placed in queue. Note that this implies that modifications to the event structure are not permitted.

There is a class of error events whose names begin with 'error.'. They may be raised by the platform, as specified in this document, or under application control. They are placed in the internal event queue and processed like any other event. In particular, they are not processed immediately if there are other events in the queueand they are ignored if no transition is found that matches them. Note however that authors can arrange for otherwise unhandled errors to cause the interpreter to exit by creating a transition with "event" attribute of 'error.*' and a target of any top-level final state (i.e. one that is a child of <scxml>). If such a transition T is placed in a state S, it will cause the state machine to terminate on any error that is raised in S or one of its substates and is not handled by another transition that is placed in a substate of S or in S and preceding T in document order.

In many applications, it is important for SCXML to receive events from external entities (for example those which it contacted with <invoke> and <send>.) Such applications should use profiles that include 4 External Communications Module .

For the most part, the set of events raised during the execution of an SCXML document is application-specific and generated under author control by use of the <event> and <send> elements. However, certain events are mandatory and generated automatically by the interpreter. In this version of the specification, in addition to error events, there is only the 'Cancel' event which is sent if the state machine leaves the containing state after executing the <invoke> element but before receiving the 'Done' event. Note that there are also mandatory events that invoked components must return to the invoking SCXML state machine. In this version of the specification, there are two such events, namely 'Done' and 'CancelResponse'. We may well change or expand this set of mandatory events in future drafts of this specification. Furthermore, it is likely that there will be distinct profiles of SCXML for specific applications, such as the Multi-modal Interaction Framework [W3C MMI] and VoiceXML 3.0. These profiles will define extensions to the core language and will likely extend the set of mandatory events with additional events appropriate to the specific application.

6 Extensions 4 External Communications Module

[N.B. In a future draft, the contents of this section will be updated to deal with the Basic State Machine Model fact that different profiles may use different data models or possibly no data model at all.]

The External Communications Module adds the capability of sending and receiving events from external entities, as well as invoking external services. Its schema can be found at D.3 Schema for External Module .

Profiles that include the External Communications module MUST:

4.1 <send>

4.1.1 Overview

<send> is used to send events and data to external systems, including external SCXML Interpreters, or to raise external events in the current SCXML session.

The target of <send> is specified using the "target" and "targettype" attributes. These attributes control how the platform should dispatch the event to its final destination.

The "target" attribute specifies the unique identifier of the event target that the system should send the event to. This section can be the session ID of another SCXML session. In other cases the value of this attribute will depend on the type of the target. (For example a SIP URL for SIP-INFO messages or a HTTP URL for Web Services). If no "target" attribute is specified the default target is the current SCXML session. If the value of the "target" attribute is not supported, invalid or unreachable by the platform, the system will raise an error.send.targetunavailable event.

The "targettype" attribute describes extensions the type of the event target and is used in conjunction with the "target" attribute to determine how to connect to the target. The default value of this attribute is 'scxml'. If the event "targettype" specified is not supported, the platform will raise an error.send.targettypeinvalid event.

A platform must support the following value for the "targettype" attribute:

Value Details
"scxml" Target is an SCXML session.

Support for HTTP POST is optional, however platforms that support it must use the following value for the "targettype" attribute:

Value Details
"basichttp" Target is a URL. Data is sent via HTTP POST

Platforms may support other types of Event I/O Processors, for example: Web-services, SIP or basic HTTP GET. However, platforms SHOULD name the targettype beginning with "x-" to signify that they are platform dependent.

Note that <event> is used to raise internal events in the current SCXML has session. Thus both <send> and <event> may be used to raise events in the current session, the only difference being whether the event is added to the basic Harel state machine model. session's internal event queue or external event queue. This difference may produce subtle differences in timing between the two methods since external events are processed only when the internal event queue is empty. See B Algorithm for SCXML Interpretation for details.

<send> also specifies the content of the message to be sent. <send> may specify message content in one of the two following mutually exclusive ways:

  • "event" attribute with an optional "namelist";

    • The "event" attribute specifies an expression that returns the name of the event.

    • The "namelist" attribute specifies a space separated list of data model locations to be included with the message.

    
    <datamodel>
    <data ID="target" expr="'tel:+18005551212'"/>
    <data ID="content" expr="'http://www.example.com/mycontent.txt'"/>
    </datamodel>
       ...
    <send target="target" targettype="'x-messaging'" event="'fax.SEND'" namelist="content"/>
    
    
  • "xmlns" attribute with explicit inline XML content specifying the message to send. The xmlns:{namespace} defines a namespace for the inline content

    
    <send target="'csta://csta-server.example.com/'"
          targettype="'x-csta'"
          xmlns:csta="http://www.ecma.ch/standards/ecma-323/csta">
          <csta:MakeCall>
            <csta:callingDevice>22343</callingDevice>
            <csta:calledDirectoryNumber>18005551212</csta:calledDirectoryNumber>
          </csta:MakeCall>
    </send>
    
    

If an explicit namespace is provided as in the "xmlns" attribute of the <send>, this namespace can be used to validate the content of the <send>. A namespace specified on a <send> applies only to the attributes and content of the <send>. Multiple namespaces may be included in the <send> to associate message content with more than one namespace.

When an explicit namespace is specified for the <send>, the content of the <send> is parsed but can be ignored by the sending SCXML interpreter until the <send> is executed. XML namespace identifiers contained in the <send> must be preserved and it is the responsibility of the platform to parse the incoming message and remove the namespace prefix, if required by the <send> target.

The sending SCXML Interpreter MUST not alter the content of the <send> and must send all the data contained within the message to the destination specified in the target attribute of <send>.

If the "targettype" specified in the <send> is not supported, the platform will raise an error event send.failed.targettypenotsupported.stateID.sendID, where 'stateID' is the "id" of the <state> containing the <send>, and 'sendID' is the automatically generated ID for this instance of <send>. If no "sendID" is specified in the <send> element, this part of the event name will be omitted. If the "targettype" is valid, but the platform is still unable to send the message for other reasons, the platform will raise an error event send.failed.targetnotfound.stateID.sendID, where 'stateID' and 'sendID' have the same significance as in the targettypenotsupported event. In the case of <send> elements with a "delay" attribute, these errors will be raised when the delay interval has passed and the platform actually attempts to send the event. Note that the absence of any error events does not mean that the event was successfully delivered to its target, but only that the platform was able to dispatch the event.

4.1.2 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
event false This attribute may not be specified in conjunction with inline content Value expression none A value expression which returns a character string that indicates the type of event being generated. See 8.3 Legal Data Values and Value Expressions for details. The event type may include alphanumeric characters and the "." (dot) character. The first character may not be a dot or a digit. Event type names are case-insensitive. If neither the event attribute or in-line content is specified, an error.fetch event will be thrown. If used in conjunction with the inline content, an error.fetch will be thrown.
target false Value expression none A valid target URL A value expression returning a unique identifier of the event target that the platform should send the event to. See 8.3 Legal Data Values and Value Expressions for details.
targettype false Value expression 'scxml' scxml basichttp A value expression which returns a character string that specifies the type of the event target. See 8.3 Legal Data Values and Value Expressions for details. Values defined by the specification are:
  • scxml

  • basichttp

sendid false Location expression none Any valid location expression Any data model expression evaluating to a data model location. See 8.2 Location Expressions for details. The location's value will be set to an internally generated unique string identifier to be associated with the event being sent. If this attribute is not specified, the event identifier is dropped.
delay false Value expression '0s' A value expression which returns a time designation as defined in CSS2 [CSS2] format The character string returned is interpreted as a time interval. The send tag will return immediately, but the event is not dispatched until the delay interval elapses. Timers are useful for a wide variety of programming tasks, and can be implemented using this attribute. Note: The queue for sending events is maintained locally. Any events waiting to be sent will be purged when the session that issued this request terminates.
xmlns:[YourNameSpacePrefix] false string none This returns a namespace identifying the contained message format. More than one xmlns attribute may be included.
namelist false This attribute may not be specified in conjunction with inline content List of location expressions none List of data model locations A list of zero or more data model locations to be included with the event. See 8.2 Location Expressions for details. If used in conjunction with the inline content, an error.fetch will be thrown.
hints false Value expression none A value expression. The data returned contains information which may be used by the implementing platform to optimize message transmission. The meaning of these hints is platform-specific.

6.1 4.2 <invoke>

<invoke> and its child <finalize> are useful in states that model the behavior of an external service. The <invoke> element is executed immediately after the state's <onentry> element and sends an event invoking the external service. The <param> element may be used to pass data to the service. Any events that are received by the state machine from the invoked component during the invocation are preprocessed by the <finalize> handler before transitions are selected. The <finalize> code is used to normalize the form of the returned data and to update the data model before the transitions' "event" and "cond" clauses are evaluated . evaluated.

When the <invoke> element is executed, the platform MUST start a new logical instance of the external service specified in "targettype" and pass it the data specified by "src", "srcexpr", <content>, or <param>. The service instance MAY be local or remote. In addition to the explicit arguments, the platform MUST pass a unique id to the external service . The external service MUST include the same id in all events that it returns to the invoking machine. (Syntax TBD.)

The external service MAY generate multiple events while it is processing, but it MUST generate a special ' 'id. Done' ''id.Done' event , (where the 'id' is the id for this invocation) once it has finished processing. It MUST not generate any other events afterwards. If the invoking state machine takes a transition out of the state containing the <invoke> before it receives the 'Done' event, it MUST automatically send a 'Cancel' event to the invoked component to notify it that it may stop its processing. The 'Cancel' event will be sent as if it were the final <onexit> handler in the invoking state. The invoked component MUST respond to the 'Cancel' event with a 'CancelResponse' event (syntax of both events TBD). The invoking state machine will take its transition without waiting for the CancelResponse event, which will be processed like any other external event.

Note that the <invoke> element can be used to invoke an external SCXML interpreter to execute a different state machine. In this case, the external state machine acts in certain respects as if it were a set of substates of the invoking state. The behavior is thus similar to a complex state defined with <state> child elements. The most important difference is that in the <invoke> case, the external state machine does not share context with or event queueswith the invoking machine. In particular, the invoked machine cannot access any variables declared in the invoking machine and data can be shared only by being explicitly passed via the <param> element. Similarly, events received or generated in one state machine are not seen by the other, though the two machines may exchange events via the <send> tag. Furthermore, state IDs need not be distinct across the two machines (though they must, of course, be distinct within each machine.) The <invoke> element thus provides a means of well-encapsulated code reuse.

When parallel states invoke the same external service concurrently, separate instances of the external service will be started. They can be distinguished by the id which is passed with the invocation. Similarly, the id contained in the events returned from the external services can be used to determine which events are responses to which invocation. Each event that is returned will be processed only by the <finalize> in the state that invoked it, but that event is then processed like any other event that the state machine receives. The finalize code can thus be thought of as a preprocessing stage that applies before the event is added to the event queue. Note that the event will be passed to all parallel states simultaneously to check for transitions.

<invoke> occurs only in atomic states, namely those that do not have <state> or <parallel> children. Thus, a state may have either <state> and <parallel> children or an <invoke> child,but not both.

6.1.1 4.2.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
targettype true string NMTOKEN 'scxml' 'scxml', 'vxml', 'ccxml', plus other platform-specific values. A string specifying the type of the external service. Default value is 'scxml'. 'vxml'indicates Platforms MUST support 'scxml' as a value. Platforms MAY support 'vxml2', which indicates a VoiceXML 2.x interpreter, while 'ccxml'indicates 'vxml3' which indicates a VoiceXML 3.x interpreter, and 'ccxml', which indicates a CCXML 1.0 interpreter. Platforms may provide MAY support additional values. However, platforms values, but they SHOULD name the values beginning with "x-" to signify that they are platform dependent.
src false URI none Any valid URI A URL that will be passed to the external service when it is invoked. If "targettype" is one of the predefined types, the document at the URI will contain the corresponding markup to execute (i.e., an SCXML, VoiceXML, or CCXML document). In other cases, the content of the document will depend on the external service.
srcexpr false Expression None Any expression evaluating to a valid URI. A data model value expression that will be evaluated at the time that invoke is executed to produce the URI to pass to the external service. See 8.3 Legal Data Values and Value Expressions for details.

6.1.2 4.2.2 Children

  • <param>. Optional child element Element containing data to be passed to the external service. Occurs 0 or more times. See 6.2 4.3 <param> .

  • <finalize>. Optional element Element containing executable content to massage the data returned from the invoked component. Occurs 0 or 1 times. See 6.3 4.4 <finalize> for details.

  • <content>. Optional element Element containing arbitrary material to be passed to the invoked component. The material may consist of non-XML markup or XML markup in any namespace. Occurs 0 or 1 times. See 6.4 4.5 <content> for details.

At most one of "src" and "srcexpr" and <content>may be specified.

<invoke> MUST not be a sibling of the <state> or <parallel> elements. It thus occurs only in atomic states, namely those which do not have substates.

6.2 4.3 <param>

6.2.1 4.3.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
name true Data model expression none Valid data model path expression The name of the parameter. It will be passed unmodified to the external service. It need not specify a node in the surrounding data model.
expr false Data model expression none Valid data model expression An optional value expression in (see 8.3 Legal Data Values and Value Expressions ). If provided, this expression specifies the data model language which evaluates value to pass to an XML tree. The tree may be part of the data model of the surrounding state machine or may be specified in-line. invoked component. Normal data model scoping rules apply as specified in 7 Data Model 5.2 <data> . .

If the "expr" attribute is missing, the "name" attribute will be taken as a data model expression referring to a location within the data model expression (see 8.2 Location Expressions ) and the corresponding data model tree value at that location will be passed to the invoked component. If the "name" attribute does not refer to a location in the data model, an error error.illegalalloc will be generated. Normal data model access and scoping rules apply as specified in 7 Data Model .

6.2.2 4.3.2 Children

None.

6.3 4.4 <finalize>

6.3.1 4.4.1 Attribute Details

None.

6.3.2 4.4.2 Children

<finalize>'s children consist of executable content. The content will be invoked on any event that the external service returns after <invoke> has been executed. In the case of parallel states, only the finalize code in the original invoking state will be executed Within the executable content, the special variable '_eventdata' 'event' may be used to refer to the data contained in the event which is being finalized.

If no executable content is specified, a default canonicalization handler will be invoked which will update the data model with any return values corresponding to <param> elements with missing "expr" attributes. Thus the effect of a <param> element with an empty "expr" attribute coupled with an empty <finalize> element is first to send all or part of the data model to the invoked component and then to update that part of the state machine's data model with the returned values. Note that the automatic update does not take place if the <finalize> element is absent as opposed to empty.

The purpose of the executable content is to normalize the format of data and update the data model before transitions are selected. <finalize> code may only massage data. It may not raise events or invoke external actions.

6.4 4.5 <content>

6.4.1 4.5.1 Attribute Details

None.

6.4.2 4.5.2 Children

The child elements of <content> consist of arbitrary markup which will be passed unmodified to the invoked service. The markup may be consist of text, XML from any namespace and need not be XML. namespace, or a mixture of both.

6.5 <anchor> 5 Data Module

The <anchor> element is intended to provide 'go back' or 'redo' functionality that is useful in some applications. When a state containing an <anchor> element is entered, a snapshot of the data model is taken before the state's <onentry> handler is executed. The default is to snapshot the entire datamodel, but the application author can restrict Data Module offers the snapshot to part capability of the datamodel using the 'snapshot' attribute. When storing, reading, and modifying a transition set of data that is taken with an 'anchor' as its target, the state machine returns internal to the most recently-visited state with machine. Its schema may be found at D.4 Schema for Data Module . As an <anchor> whose 'type' attribute matches authoring convenience, the 'anchor' Data Module can read in the transition. In the course of the transition, before the state containing the anchor element is entered, the datamodel is restored data from the snapshot. The effect an external source at load time, but at run time it is thus restricted to jump back and restart processing at operating on its internal model. Note, however, that state. As 4 External Communications Module allows SCXML to interact with external entities at run time, to exchange data as part of this restart, all intermediate anchors are erased. Intermediate anchors are those that were set between the time the anchor state was last visited and the point at which the transition with the anchor state as target is taken. Note interaction.

Profiles that all these anchors must have a different type from include the one that is Data Module MUST:

None. For examples of how to do this, see 9.2 The ECMAScript Profile 7 Data Model N.B. This section is provisional and may end up being part of a separate specification. In either case, the definition of the data model may change significantly in the future. 9.3 The XPath Profile .

7.1 Overview of Data Model 5.1 <datamodel>

To provide a uniform method of access to both local and remote data, we introduce a <datamodel> element which encapsulates any number of <data> elements. Each such element defines a single data element whose value is an XML tree. object. The XML tree exact nature of the data object depends on the data model language used. The data object may be fetched from an external source or specified in-line. Note that atomic variable values are simply degenerate XML trees consisting of In cases where the data object specified is not a single leaf, so that legal instance of the <data> element subsumes data model language, implementations MAY translate it into a legal expression, and MUST signal an error if the <var> element of CCXML. cannot do so.

Data accessed created via the <data> element is local to the SCXML interpreter and not shared with any external resource. However, the local data model, or parts of it, may be sent to an external resource via the <send> element. (See 8.2.2 4.1 <send> .) Existing data values may be modified with the <assign> element. (See 8.1.1 5.3 <assign> ).

Logically, there is a single globally visible data model for the entire state machine. As an authoring convenience, however, we allow <datamodel> as a child of any <state>, thus allowing parts of the data model to be distributed throughout the document closer to the locations where the data will be accessed. However, all instances of the <data> element are created and initialized when the state machine is instantiated and may be accessed from any state at any time.

As a further authoring convenience, ambiguous data references will be resolved by standard lexical scoping rules. For example, suppose <state> S has a child S1, S1 has children S11 and S12, and that both S1 and S11 contain <data> elements defining a data tree called 'foo'. References to 'foo' in both S1 and S12 will refer to S1's definition, while a reference inside S11 will refer to S11's definition. A reference to 'foo' in root state S would result in an error because no instance of 'foo' is declared in any surrounding scope. To avoid such errors and override the default scoping rules, the <data> element's name may be prefixed with the ID of the state in which it is declared. Thus in any of the above states, 'S1.foo' will unambiguously refer to the instance of 'foo' defined in S1, while 'S11.foo' will refer to the instance defined in S11. <data> elements defined at the top level under the <scxml> element may be unambiguously designated by using the '_dm.' prefix. 7.2 <datamodel>

7.2.1 5.1.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
schema false URI none Location of the schema for this datamodel URL of the schema for this datamodel. See 8.1.3 5.4 <validate> for its use. This attribute may occur only on the highest-level <datamodel> element, namely the one that is a child of <scxml> <scxml>. The exact nature of the schema depends on the data model language being used.

7.2.2 5.1.2 Children

  • <data> Occurs 0 or more times. Each instance defines a named XML data tree. Trees element.Data elements are created when the document is loaded.

7.3 5.2 <data>

The <data> element is used to declare and populate portions of the datamodel. All <data> tags are evaluated exactly once, at load time. Implementations thus MUST evaluate <data> elements at load time but MAY do so in any order they choose. Ordering dependencies among <data> elements are thus not permitted. Suppose, for example, that the declaration of element "a" precedes the declaration of element "b" in a document. It is not safe to assume that "a" will be instantiated and have a value when the declaration of "b" is executed. Therefore the "expr" in "b" cannot reference the value of "a" (and vice-versa).

7.3.1 5.2.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
name ID true string ID none Any valid string The name of the data item. It MUST be unique within the <state> but need not be unique within the document.
src false URI none Any URI referencing a valid XML tree legal data value. See 8.3 Legal Data Values and Value Expressions for details. Gives the location from which the data XML tree object should be downloaded.
expr false Expression none Any valid value expression Evaluates to provide the value of the data item. Implementations MUST support ECMAScript as an expression language See 8.3 Legal Data Values and MAY support other languages. Value Expressions for details.

7.3.2 5.2.2 Children

The children of the <data> element consist of zero or more XML trees, which represent an in-line specification of the value of the element. data object.

At most one of "src" and "expr" may occur. If either is present, then the element MUST not have any children. Thus "src", "expr" and XML tree children are mutually exclusive inside the <data> element.

In addition to the "src" attribute and in-line child elements, values for the top-level <data> elements can be provided by the environment at instantiation time. The exact mechanism for this is implementation dependent, but values provided at instantiation time override those contained in the <scxml> element, whether they are specified in-line or via the "src" attribute.

8 Executable Content

Executable content consists of actions that are performed as part of taking transitions and entering and leaving states (<onentry> and <onexit>, etc.) In general, such content needs to be able to modify the data model, raise events, and invoke functionality in the underlying platform. On If the other hand, executable content cannot cause transitions value specified (by 'src', children, or any form of change of state, except indirectly, by raising events that are then caught by transitions. The content presented here represents a flexible, powerful, minimum set that all applications can rely on. Platforms are free to provide additional executable content corresponding to special features of their implementations. Such extensions SHOULD be defined in a separate namespace, not in the 'scxml' namespace. It environment) is important to remember that SCXML treats executable content as a single blocking atomic operation and that no events are processed until all executable content has completed. For example, upon entering a state, the SCXML processor will not process any events or take any transitions until all <onentry> handlers have finished. Thus all executable content, including platform-specific extensions, SHOULD complete quickly under all circumstances. A general method for implementing extensions using a legal data value, the <send> error error.invaliddata is raised at load time, and an empty data element is presented created in the data model with the specified ID. Note that what constitutes a legal data value depends on the data model language used. See 8.5 Custom Action Elements 9 Profiles below. for details.

8.1 Data Model Operations

The <assign> element may be used to modify the data model.

8.1.1 5.3 <assign>

8.1.1.1 5.3.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
location true path expression none Any valid path expression denoting a location in the data model expression. The location in the data model into which to insert the new value. Standard lexical scoping rules apply. It See 8.2 Location Expressions for details. Note that in the case of an XML data model (see ), it is not required to assign to the root of a tree (i.e., the "name" value in a <data> tag), since the path expression can reach down into the tree to assign a new value to an internal node. Implementations MUST support XPath [XPath] as a path expression language and MAY support other languages if they choose.
src dataID false URI idref none Any URI referencing a valid XML tree The ID of any <data> element in the document The location from which 'id' of a <data> element. If it is provided, the new value should be read. 'location' expression is interpreted as applying to the children of this <data> element. If the 'dataID' is not specified, the 'location' expression is interpreted as applying to the children of the <datamodel> element. This attribute allows a more succinct notation when XPath is used as the expression language, as indicated in and in the examples below.
expr false data model language value expression none Any expression evaluating to a valid XML tree value expression An expression returning the value to be assigned. Only one of src and expr may be specified. Implementations MUST support ECMAScript as a data model language See 8.3 Legal Data Values and MAY support other languages if they choose. Value Expressions for details. If 'expr' is specified, no children are permitted.

8.1.1.2 5.3.2 Children

The children of the <assign>element consist provide an in-line specification of zero or more XML trees, which represent the legal data value of (see 8.3 Legal Data Values and Value Expressions ) to be inserted into the element. datamodel at the specified location.

At most one of "src" and "expr" may occur. If either "expr" is present, then the element MUST not have any children. Thus "src", "expr" and XML tree children are mutually exclusive inside the <assign> element.

Assignment to a data model is done by using an XPath a location expression to denote the location in part of the data model where the change is to be made. There are three categories of assignments: Assignment to an element node. In this case assignment replaces the children of the referenced node. If the "expr" value is an empty string, the child nodes of the referenced node are removed. Assignment to an attribute. An attribute of an SCXML data model element can be changed if we assign it a "string". Any other type will be flagged as an error. Assignment to a nodeset. In this case, we iterate over the nodes in the nodeset and replace their children with the location expression does not denote a valid location in the assignment. The behavior is thus a generalization of assignment to datamodel an element node. Suppose we have a data model of error error.illegalalloc is raised. If the following form: <data name="cart"> <myCart> <books> <book> <title>The Zen Mind </title> </book> <book> <title>Freakonomics </title> </book> </books> <cds> <cd name="something"/> </cds> </myCart> </data> Here value specified (by 'expr' or children) is an example of assignment of not a string to an element node. <assign location="/data[@name=\"cart\"]/myCart/books/book[0]/title" expr="'My favorite book'"/> results in <data name="cart"> <myCart> <books> <book> <title>My favorite book </title> </book> <book>> <title>Freakonomics </title> </book> ... </data> Now suppose we assign an xml structure to an element node. The following assignment statement would have the effect of replacing the children of the element "/data[@name='cart']/myCart/books/book[0]" by the XML tree rooted in <bookinfo>. <assign location="/data[@name='cart']/myCart/books/book[0]"> <bookinfo> <isdn>12334455</isdn> <author>some author</author> </bookinfo> </assign> results in <data name="cart"> <myCart> <books> <book> <bookinfo> <isdn>12334455</isdn> <author>some author</author> </bookinfo> </book> <book>> <title>Freakonomics </title> </book> ... </data> Here are examples of legal and illegal assignment to an attribute: <!-- Legal assignment: --> <assign location="/data[@name='cart']/myCart/cds/cd/@name" expr"'Something Else'"/> <!-- Illegal assignment: --> <assign location="/data[@name='cart']/myCart/cds/cd/@name" > <foo> <boo> </foo> </assign> Now suppose we assign a string to a nodeset. The following assignment statement would have the effect of replacing the text child of element of each node in value for the nodeset /myCart/books/book with location specified, the string "The Zen Mind": <assign location="/data[@name='cart']/myCart/books/book" expr="'The Zen Mind'"/> produces <data name="cart"> <myCart> <books> <book>The Zen Mind <title>...</title> </book> <book>The Zen Mind <title>..</title> </book> </books>> ... </data> Finally suppose we assign a structure to error error.invaliddata is raised. Note that what constitutes a nodeset. The following statement would iterate over the elements in the <book> nodeset and replace each text child with legal value depends on the <price> structure: <assign location="/data[@name='cart']/myCart/books/book"> <price>20.0</price> </assign> yields <data name="cart"> <myCart> <books> <book> <title>...</title> <price>20.0</price> </book> <book>> <title>..</title> <price>20.0</price> </book> </books> ... </data> data model language used. See 9 Profiles 8.1.2 _eventdata SCXML events carry data and executable content needs to be able to access that data in order to update the data model. The special variable '_eventdata' can be used within executable content to access the data in the current event. In the executable content of <onentry>, <onexit> and <transition> elements, the 'current event' is defined to be the event that triggered the transition. If there is no such event or the event contains no data, _eventdata is undefined. In the "cond" attribute of <transition>, the current event is the one that is currently being matched against the transition. In all other locations, '_eventdata' is undefined. If '_eventdata' is defined, but the event in question contains no data, '_eventdata' will be an empty XML tree. for details.

8.1.3 5.4 <validate>

The <validate> element causes the datamodel to be validated. Note that validation of the datamodel occurs only when explicitly invoked by this element.

8.1.3.1 5.4.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
location false Path location expression none Any valid path location expression. The location of the subtree to validate. If it is not present, the entire datamodel is validated. Implementations MUST support XPath [XPath] See 8.2 Location Expressions as a path language and MAY support other languages if they choose. for details.
schema false URI none Any valid URI The location of the schema to use for validation. If this attribute is not present, the schema specified in the top-level <datamodel> is used. It is an An error error.validate.validationfailure will be raised at document load time if no schema is specified in either element.

8.1.3.2 5.4.2 Children

None.

8.2 Event Generation 5.5 System Variables

8.2.1 <event>

The <event> element Data Module maintains a protected portion of the data model containing information that may be used useful to raise an event applications. We refer to the items in this special part of the data model as 'system variables'. Implementations that include the Data Module MUST provide the following system variables, and MAY support others.

  • _event .The variable 'event' is bound to a structure containing the current SCXML session. event's name and any data contained in the event. The exact nature of the structure depends on the datamodel being used. See 9 Profiles for details. In the executable content of <onentry>, <onexit> and <transition> elements, the current event will is defined to be added the event that triggered the transition, if there is one. In the "cond" attribute of <transition>, the current event is the one that is currently being matched against the transition, if there is one. In all other locations, 'event' is undefined. Note, in particular, that 'event' is not bound when the system is evaluating or taking a transition that lacks an "event" attribute.

    If the data in the event is not a legal instance of the data model language, and the system cannot translate it into one, then at the point at which the system attempts to bind 'event', the error error.invaliddata will be raised and the session's internal event queue, but data part of the 'event' structure will not be processed bound. The event's name will still be available, however. Processing of both the original event and the error event will proceed as usual.

  • _sessionID .The variable 'sessionID' is bound at load time to the system-generated ID for the current SCXML session. It remains bound until later, following the algorithm session terminates.

  • _name .The variable 'name' is bound at load time to the name of the state machine, which is specified in the "name" attribute of the <scxml> element. It remains bound until the session terminates.

The set of system variables may be expanded in a future version of this specification. Therefore developers SHOULD NOT use IDs beginning with '_' in the <data> element since this may cause forwards-compatibility problems.

The concrete realization of these variables in a specific data model depends on the language used. For the exact location of these variables in an XML data model, see C Algorithm for SCXML Interpretation 9.3 The XPath Profile . Note All system variables are protected and any attempt to change their values MUST fail and result in particular that the event cannot error error.illegalassign being raised.

6 Script Module

6.1 <script>

The Script Module adds scripting capability to the state machine. Its schema may be processed until all current found at D.5 Schema for Script Module .Profiles including the Script Module MUST:

  • Redefine the executable content has been executed. group to include the <script> tag.

For example, if an example of how to do this, see 9.2 The ECMAScript Profile .

6.1.1 Attribute Details

None.

6.1.2 Children

The children of the <event> <script> element occurs represent the script code to be executed.

7 Anchor Module

The <anchor> module is intended to provide 'go back' or 'redo' functionality that is useful in some applications. An anchor MAY be specified instead of a "target" for the transition. In this case, the system transitions to the last state visited containing an <anchor> whose "type" matches the "anchor" specified in the transition.

When a state containing an <anchor> element is entered, a snapshot of the data model is taken before the state's <onentry> handlers handler is executed. The default is to snapshot the entire datamodel, but the application author can restrict the snapshot to part of the datamodel using the 'snapshot' attribute. When a state, transition is taken with an 'anchor' as its target, the state machine returns to the most recently-visited state with an <anchor> whose 'type' attribute matches the 'anchor' in the transition. In the course of the transition, before the state containing the anchor element is entered, the datamodel is restored from the snapshot. The effect is thus to jump back and restart processing at that state. As part of this restart, all intermediate anchors are erased. Intermediate anchors are those that were set between the very least time the event will not be processed until anchor state was last visited and the point at which the transition with the anchor state as target is taken. Note that all these anchors must have a different type from the executable content in one that is the <onentry> handler target of the transition. If no state with a matching <anchor> type has completed. been visited, the current state is exited and re- entered. For a complete definition of the semantics of <anchor>, see B Algorithm for SCXML Interpretation .For the schema of the Anchor Module, see D.6 Anchor Module Schema .

The ability to reset the datamodel may lead to accidental, unterminated loops in the state machine. The interpreter context MAY detect these and exit.

Profiles that includ the Anchor Module MUST:

8.2.1.1 7.1 <anchor>

7.1.1 Attribute Details

Name Required Attribute Constraints Type Default Value Valid Values Description
name type true NMTOKEN xsd:NMTOKEN none Specifies Defines the name type of this anchor instance.
snapshot false path expression none Any expression denoting a node in the event. This will be matched against data model. A location in the 'event' attribute of transitions. datamodel to snapshot. If no snapshot value is provided, the entire data model is copied. Implementations MUST support XPath [XPath] as a path expression language and MAY support other languages if they choose.

8.2.1.2 7.1.2 Children

None.

8.2.2 <send> 8 Expressions

SCXML contains three types of expressions, as described below. Different profiles of SCXML will support different languages for these expression types, but certain properties of the expressions are constant across profiles and are defined here.

Expressions MUST not contain side effects that would effect the datamodel or the execution of the state machine. Implementations MAY assume that expressions do not have side effects when optimizing expression evaluation. Thus expressions may not be evaluated as often as indicated in B Algorithm for SCXML Interpretation 8.2.2.1 Overview or at the same points in the algorithm.

8.1 Conditional Expressions

<send> is Conditional expressions are used to send events inside the 'cond' attribute of <transition>, <if> and data <elseif>. If a conditional expression does not evaluate to external systems, including external SCXML Interpreters, a boolean value ('true' or to raise external events 'false'), the error 'error.illegalcond' is raised. The set of operators in conditional expressions varies depending on the current SCXML session. profile, but all profiles must support the 'In()' predicate, which is used to test whether the state machine is in a given state. This predicate allows coordination among parallel regions.

8.2 Location Expressions

Location expressions are used to specify a location in the datamodel as part of the <assign>element. The target exact nature of <send> is specified using a location depends on the "target" and "targettype" attributes. These attributes control how profile. For example, in the platform should dispatch XPath Profile ( 9.3 The XPath Profile ), the event underlying datamodel is an XML tree and a location expression must evaluate to its final destination. an existing node or nodeset in the datamodel. If a location expression does not evaluate to a legal location, an error error.illegalalloc is raised.

8.3 Legal Data Values and Value Expressions

The "target" attribute specifies Any profile that includes the unique identifier Data Module must specify the structure of the event target that underlying data model. For example, the system should send XPath Profile ( 9.3 The XPath Profile ) defines the event to. This data model to be an XML tree. Such a specification of the data model implicitly defines a set of "legal data values", namely the objects that can be part of such a data model. For an XML data model, the session ID set of another SCXML session. legal data values consists of XML trees and subtrees, plus strings (as values of attributes or text children). In other cases conjunction with this, the Profile must define a set of value expressions which can be evaluated at runtime to return legal data values. If a value expression does not return a legal data value, the error error.illegalvalue is raised.

8.4 Errors in Expressions

Implementations MAY raise errors caused by syntactically ill-formed expressions at document load time, or they MAY wait and raise these errors at runtime when the expressions are evaluated. Implementations MUST raise errors caused by expressions returning illegal values at the points at which B Algorithm for SCXML Interpretation indicates that the expressions are to be evaluated. Note that this requirement holds even if the implementation is optimizing expression evaluation.

9 Profiles

To define a profile, you must first specify the list of modules that the profile includes. This list MUST include the Core module and MAY include other ones. In addition to this attribute will depend on list you must:

9.1 The Minimal Profile

9.1.1 Conformance

The Minimal profile defines a <error.send.targetunavailable> event. stripped down state machine with no external communications or data model, but with full Harel semantics. Conformant SCXML processors must implement the following modules:

  • The "targettype" attribute describes SCXML core module: see 3 Core Module

For the type schema of theMinimal profile, see D.7 Minimal Profile Schema .

9.1.2 Core Module Requirements

No elements or attributes are extended or redefined. For the schema of the event target and Minimal Profile, see D.7 Minimal Profile Schema .

9.1.2.1 Conditional Expressions

The boolean expression language consists of the In predicate only .It has the form 'In( id )', where id is used the id of a state in conjunction with the "target" attribute to determine how to connect enclosing state machine.

9.2 The ECMAScript Profile

9.2.1 Conformance

This section contains information which is specific to the target. The default SCXML ECMAScript profile. In particular, it defines the semantics of using ECMAScript in binding expressions for data model access, conditional evaluation, and value expressions in SCXML. It also defines use of this attribute is 'scxml'. If the event "targettype" specified is not supported, the platform will throw a <error.send.targettypeinvalid> event. <script> element in this profile.

A platform Conformant SCXML processors must support implement the following modules from SCXML:

  • core module
  • data module
  • script module

Conformant documents must specify a value for of profile="ecmascript" on the "targettype" attribute: root <scxml> element.

Value Details "scxml" Target is an SCXML session.

Support In addition, conformant implementations of the ECMAScript Profile for HTTP POST is optional, however platforms that support it SCXML 1.0 must use support ECMAScript Compact Profile [ECMASCRIPT-327] ,a strict subset of the following value third edition of ECMAScript [ECMASCRIPT-262] .A conformant implementation may support ECMAScript for the "targettype" attribute: XML (E4X) [E4X] .

Value Details "basichttp" Target is a URL. Data is sent via HTTP POST
Editorial note  

Platforms may support other types A later version of Event I/O Processors, for example: Web-services, SIP or basic HTTP GET. However, platforms SHOULD name the targettype beginning with "x-" to signify that they this specification will clarify how XML data can accessed, manipulated and generated using this profile. Apart from E4X, we are platform dependent. also considering DOM access functions and ECMAScript 4.0 (4th edition of ECMAScript 262).

Note that <event> ECMAScript 4.0 is used to raise internal events in still under development. The specifications are not yet public. An overview has been published. Many elements of the current SCXML session. Thus both <send> and <event> may new language will be used familiar to raise events Action Script developers. There are early implementation from Mozilla and on ecmascript.org .

9.2.2 Core Module Requirements

9.2.2.1 Conditional Expressions

ECMAScript expressions used in conditional expressions are converted into their effective boolean value using the current session, the only difference being whether the event ToBoolean operator as described in Section 9.2 of [ECMASCRIPT-262] .The expression is added evaluated in its own local scope, and allows (read only) access to the session's internal event queue or external event queue. This difference may produce subtle differences variables and functions in timing between the two methods since external events are processed only when global scope, including the internal event queue is empty. See data model (see C Algorithm for SCXML Interpretation 9.2.3 Data Module Requirements for details. scoping model).

<send> also specifies The following example illustrates this usage.

Example: Use of a boolean expression to determine whether or not a transition is taken.

<state id="errorSwitch">
  <datamodel>
   <data ID="time"/>
  </datamodel>
        
  <onentry>
    <assign location="_data.time" expr="currentDateTime()"/>
  </onentry>
          
  <transition cond="yearFromDatetime(_data.time) > 2009" target="newBehavior"/>
 
  <transition target="currentBehavior"/>
</state>

Any errors which arise during the content processing of a conditional expression must be mapped into an SCXML error.illegalcond. errortype event where the message optional errortype indicates the ECMAScript error type as specified in Section 15.11.6 of [ECMASCRIPT-262] .For instance, an ECMAScript expression which attempts to be sent. <send> may specify message content assign a value to a variable defined in one the global scope would generate an error.illegalcond event.

Conditional expressions may take advantage of the two following mutually exclusive ways: In() predicate. Additional detail appears in 9.2.5.1 The In() predicate .

9.2.3 Data Module Requirements

"event" attribute with an optional "namelist"; The underlying data model is the subset of the ECMAScript object model as defined by JSON [RFC4627] .SCXML data model expressions are evaluated as ECMAScript expressions in global or local scope as described later in this section.

The "event" attribute specifies SCXML datamodel is implemented as an expression that returns ECMAScript object with the name of the event. _data .

In a <datamodel> element, each <data> child is bound to a property of the _data object. The "namelist" property name is the value of the ID attribute specifies a space separated list of data model locations to be included with <data> .The value of the message. property is assigned by the evaluation one of the following expressions:

<datamodel> <data name="target" expr="'tel:+18005551212'"/> <data name="content" expr="'http://www.example.com/mycontent.txt'"/> </datamodel> ... <send target="target" targettype="'x-messaging'" event="'fax.SEND'" namelist="content"/>
  • "xmlns" value of the expr attribute with explicit inline XML content specifying
  • resource referenced by the message to send. The xmlns:{namespace} defines a namespace for value of the src attribute. JSON resources have the mime type application/json .
  • inline content <send target="'csta://csta-server.example.com/'" targettype="'x-csta'" xmlns:csta="http://www.ecma.ch/standards/ecma-323/csta"> <csta:MakeCall> <csta:callingDevice>22343</callingDevice> <csta:calledDirectoryNumber>18005551212</csta:calledDirectoryNumber> </csta:MakeCall> </send>
If an explicit namespace no value is provided as in the "xmlns" attribute of assigned, the <send>, this namespace can be used to validate property has the content default value ECMAScript undefined.

Evaluation of the <send>. A namespace specified on a <send> applies only to the attributes JSON expressions must be supported and content evaluation of the <send>. Multiple namespaces XML expressions may be included in the <send> to associate message content with more than one namespace. supported.

When an explicit namespace is specified for the <send>, The _data object must be created by the content processor upon initialization of the <send> is parsed but can SCXML document. Any errors which arise during initialization must be ignored by the sending mapped into an SCXML interpreter until error.illegaldata .errortypeevent where the <send> is executed. XML namespace identifiers contained optional errortype indicates an ECMAScript error type as specified in the <send> must Section 15.11.6 of [ECMASCRIPT-262] .For example, an error will be preserved and it raised if the <data> element's ID attribute is not a valid ECMAScript variable name or if the responsibility evaluation of the platform to parse expr attribute value fails.

Example: Datamodel <data> initialization

<scxml version="1.0" profile="ecmascript">
  <datamodel>
   <data ID="employees" src="http://example.com/employees.json"/>
   <data ID="year" expr="2008"/>
   <data ID="CEO" expr="\"Mr Big\""/>
   <data ID="profitable" expr="true"/>
  </datamodel>
</scxml>

This profile uses ECMAScript scoping. Elements in the incoming message SCXML document are associated with ECMAScript scopes which themselves are chained together. Scopes are created when the SCXML processor enters specific elements, and remove the namespace prefix, if required by scope is destroyed when processor exits the <send> target. element. This profiles defines two ECMAScript scopes: global and local.

A global scope must be defined for each SCXML session. The sending global scope is created when the SCXML Interpreter MUST not alter session is created. The SCXML datamodel is contained within the content of global scope. The global scope has no parent scope.

The SCXML elements <state> ,<parallel> ,<final> and <transition> ,as well as cond attributes, are each associated with an ECMAScript local scope. The local scope always has the <send> global scope as its parent. Consequently, variables and send all function prototypes in the data contained within global scope are accessible through this scope chain.

Variable bindings take place in the message local scope except for bindings to the destination specified variables defined in the target attribute of <send>. When <send> is used with inline XML content, and the target is a SCXML session, the mapping of that XML content global scope. Consequently, bindings to event object properties is implementation-specific, and outside the scope of this specification. datamodel ( _data object) are applied at global scope.

When a message is successfully sent References to variables in the target, global and local scopes can be disambiguated by explicit scope designation: prepending the platform will raise scope name plus "." to the variable name. For example, global.time identifies a <send.successful> event. Note that this does not mean that variable with the target processed name time in global scope, while local.time identifies a variable the message successfully. It is up to same name in local scope. A variable reference without an explicit scope designation, references a variable in the target to generate events specific to local scope if defined, otherwise references a variable in the message. These events are application specific. global scope.

If Variables bindings are defined for the send request fails, an "error.send.failed" event will be raised. lifecycle of the respective scope.

Editorial note  

We solicit feedback on whether only two scopes, local and global, are sufficient for applications.

8.2.2.2 Attribute Details 9.2.3.1 Location Expressions
Name Required Attribute Constraints Type Default Value Valid Values Description event false This

ECMAScript left-hand-side expressions are used to select an object (or sub-property of an object) from the data model by providing a binding expression. The following example illustrates this usage:

Example: Use of the location attribute may not be specified in conjunction with inline content Expression none of the assign to update the salary of an employee.

<state id="errorSwitch">
    <datamodel>
      <data ID="employees" src="http://example.com/employees.json"/>
    </datamodel>
    
    <onentry>
        <assign location="_data.employees.employee[12].salary" expr="42000"/>
    </onentry>
</state>

An expression

Any errors which returns a character string that indicates arise during the type processing of event being generated. The event type may include alphanumeric characters and the "." (dot) character. The first character may not be a dot or a digit. Event type names are case-insensitive. If neither the event attribue or in-line content is specified, location expression must be mapped into an SCXML error.fetch error.illegalalloc. errortype event will be thrown. If used in conjunction with where the inline content, optional errortype indicates the ECMAScript error type as specified in Section 15.11.6 of [ECMASCRIPT-262] .For example, an error.fetch error will be thrown. target false arise if there is an attempt to assign a value to a system variable ( Expression none A valid target URL An 9.2.3.3 System Variables ).

9.2.3.2 Value Expressions

The result of any ECMAScript expression returning may be used in a unique identifier of the value expression.

Example: Copying event target that data into the platform should send local data model for the event to. targettype false state.

<state id="processEvent">
    <datamodel>
        <data ID="myEvent"/>
    </datamodel>
    
    <onentry>
        <assign location="_data.myEvent" expr="_data._event"/>
    </onentry>
</state>

Expression scxml scxml webservice An expression

Any errors which returns a character string that specifies arise during the type processing of the event target. Values defined by the specification are: scxml webservice sendid false Left Hand Side Expression none Variable Any data model expression evaluating to a data model location. The location's value will expression must be set to mapped into an internally generated unique string identifier to be associated with the SCXML error.illegalvalue. errortype event being sent. If this attribute is not specified, where the event identifier is dropped. delay false Expression '0s' An expression which returns a character string optional errortype indicates the ECMAScript error type as specified in CSS2 [CSS2] Section 15.11.6 of [ECMASCRIPT-262] .

format The character string returned is interpreted 9.2.3.3 System Variables

System variables are defined as a time interval. ECMAScript read-only variables in global scope. The send _event tag will return immediately, but the event system variable is not dispatched until the delay interval elapses. Timers are useful defined as an object with two properties: name (String value) for a wide variety the name of programming tasks, the event; and can be implemented using this attribute. Note: data The queue for sending events is maintained locally. Any events waiting to be sent will be purged when the session that issued this request terminates. xmlns:[YourNameSpacePrefix] false string none This returns a namespace identifying (Object value) exposing the contained message format. More than one event data payload. The xmlns _sessionID attribute may be included. namelist false This attribute may not be specified in conjunction and _name system variables are defined as variables with inline content Var List none List of data model locations A list of zero or more data model locations to ECMAScript String values.

The _event value must be included with the event. If used assigned by processor before triggering executable content in conjunction with the inline content, an <onentry>, <onexit>, and <transition> elements which may reference the variable. The processor must clear the value by setting error.fetch _event will be thrown. hints false Expression none An expression. to ECMAScript undefined values when event processing has completed.

The data returned contains information which may _sessionID and _name values must be used set by the implementing platform to optimize message transmission. The meaning of these hints is platform-specific. processor at session start.

8.3 Flow Control Elements Example: Accessing system _event name in a condition

<state id="checkSessionID">
    <transition cond="_event.name=='connector.sip.invite'" target="nextState">
     ...
    </transition>
</state>

8.3.1 <if> 9.2.4 Script Module Requirements

Editorial note 8.3.1.1 Overview  

<if> This section is a container for conditionally executed elements. <else> tentative and <elseif> can optionally appear within subject to revision in a later version of this specification.

In this profile, the inline content of the <script> is an <if> ECMAScript program as immediate children, and serve defined in Section 14 of [ECMASCRIPT-262] .

This profile allows <script> elements to partition the occur as children of <scxml> elements within an <if>. <else> and <elseif> have no within executable content. <else/> is a synonym for <elseif cond="true"/>.

Each partition within an <if> is preceded by an element having When a "cond" attribute. The initial partition <script> element is preceded by the <if> and subsequent partitions by <elseif>s (or <else>s). The first partition a child of <scxml> its contents are evaluated in global scope at document order with a "cond" that evaluates to true is selected. <else> always evaluates load time. Defined variables and functions are available through the scope chain to true. A partition MAY be empty. expressions in local scope.

If an <if> has no immediate <elseif> or <else> children, When a <script> element occurs within executable content it is evaluated in the full contents of local scope associated with the <if> will containing element (or its ancestor).

Any errors which arise during processing of <script> content must be selected when mapped into an SCXML error.script. errortype event where the "cond" attribute evaluates to true. optional errortype indicates the ECMAScript error type as specified in Section 15.11.6 of [ECMASCRIPT-262] .

<else> was chosen to match similar concepts
Example: <script> in other languages, <scxml> to define global variable and supports examples such as function
<if cond="...">
  <!-- selected when <if cond> is true -->
  <else/>
  <!-- selected when <if cond> is false -->
</if>
            

<scxml version="1.0" profile="ecmascript">
  <script>
       var globalCounter = 0;
       function updateCounter() {
        globalCounter++;
       }
  </script>
</scxml>

However, <else> is a synonym for <elseif cond="true"/>, so an example such as: <if cond="..."> <!-- selected when <if cond> is true --> <else/> <!-- selected when <if cond> is false --> <else/> <!-- never selected --> </if>
Example: <script> in executable content to manipulate the data model
is also possible and MUST be interpreted as:
<if cond="...">
  <!-- selected when <if cond> is true -->
  <elseif cond="true"/>
  <!-- selected when <if cond> is false -->
  <elseif cond="true"/>
  <!-- never selected -->
</if>

<state id="updateDM">
    <onentry>
      <script>
        _data.myDate = new Date(); 
        updateCounter();
      </script>
    </onentry>
</state>

With this definition for <else>, a valid XML [XML] document is also a valid SCXML document.
8.3.1.2 Attribute Details Name Required Attribute Constraints Type Default Value Valid Values Description cond true Expression none A valid expression A boolean expression. See
9 Boolean Expressions Editorial note for details.  

A later version will clarify how inline ECMAScript interacts with fetched ECMAScript programs (where external fetching takes place at document initialization, evaluation when the element is executed).

8.3.2 <elseif> 9.2.5 Additional Requirements

8.3.2.1 Overview 9.2.5.1 The In() predicate

An <elseif> partitions the content of A conformant SCXML processor must add an <if>, and provides a condition ECMAScript function to the SCXML namespace that determines implements the selection In() semantics described in section 8.1 of the partition it begins. <elseif> can appear optionally [SCXML1] specification.

Function signature: In($arg as xs:string?) as xs:boolean

Returns an immediate child xs:boolean indicating whether or not one of an <if>. the current active states matches the value of $arg .

8.3.2.2 Attribute Details Name Required Attribute Constraints Type Default Value Valid Values Description 9.2.6 Examples

cond true Expression none A valid expression An boolean expression. See
9 Boolean Expressions Editorial note for details.  

Detailed examples will be provided in a later version of this specification.

8.3.3 <else> 9.3 The XPath Profile

8.3.3.1 Overview 9.3.1 Conformance

<else> This specification contains information which is a synonym specific to the SCXML XPath profile. In particular, it defines the semantics of using XPath in binding expressions for <elseif cond="true"/>. data model access, conditional evaluation, and value expressions in SCXML.

Conformant SCXML processors must implement the following modules from SCXML

  • SCXML core module:see 3 Core Module 8.3.3.2 Attribute Details Name Required Attribute Constraints Type Default Value Valid Values Description none

  • SCXML data module: see 5 Data Module none else is

Conformant documents must specify a synonym value of profile="xpath" on the root <scxml> element.

In addition, conformant implementations of the XPath Profile for elseif cond="true". SCXML 1.0 must support [XPath 2.0] .

For the schema of the XPath profile, see D.9 XPath Profile Schema 8.4 Debugging Elements .

8.4.1 <log> 9.3.2 Core Module Requirements

8.4.1.1 Overview 9.3.2.1 Conditional Expressions

<log> allows an application to generate a logging or debug message which a developer can use to help XPath 2.0 expressions used in application development or post-execution analysis of application performance. The manner conditional expressions are converted into their effective boolean value as described in which the message is displayed or logged is platform-dependent. The usage section 2.4.3 of label is platform-dependent. the [XPath 2.0] specification. The use of <log> MUST have no other side-effects on interpretation. <log>is an empty element. following example illustrates this usage.

8.4.1.2 Attribute Details Name Required Attribute Constraints Type Default Value Valid Values Description label false Expression none An Example: Use of a boolean expression which returns to determine whether or not a character string transition is taken.

<state id="errorSwitch" xmlns:fn="http://www.w3.org/2005/xpath-functions">
  <datamodel>
    <data ID="time"/>
  </datamodel>
          
  <onentry>
    <assign location="instance('time')" expr="fn:current-dateTime()"/>
  </onentry>
          
  <transition cond="fn:year-from-dateTime(/data[@ID='time']) > 2009" target="newBehavior"/>
  <transition target="currentBehavior"/>
</state>
        

Any errors which may be used, for example, to indicate arise during the purpose processing of the log. expr true Expression none An expression evaluating to a string to conditional expression must be logged. level false mapped into an SCXML error.illegalcond. TBD TBD TBD This information will be logged only if errorcode event where the system's log level errorcode is at this level or higher. The mechanism for specifying the log level and its legal values will be value specified in [XPath 2.0] and related specifications such as the [XPath 2.0 Functions and Operators] .For instance, an XPath expression which attempts to use a future version component having an undefined value would generate an error.illegalcond.XPST0001 event.

Conditional expressions may take advantage of this document. the In() predicate. Additional detail appears in 9.3.4.1 The In() predicate .

8.5 Custom Action Elements 9.3.3 Data Module Requirements

9.3.3.1 Location Expressions

Custom Action Elements can be defined in other specifications/namespaces and XPath 2.0 expressions are responsible for performing actions on behalf of custom components. Logically Custom Action Elements can be thought of as a collection of actions and handlers used to perform specific tasks. An example of this is select a CCXML <accept> element that is node-set from the data model by providing a Custom Action Element: binding expression. The following example illustrates this usage:

<transition event="ccxml:connection.alerting"> <ccxml:accept connectionid="_eventdata.connectionid"/> </transition>
This could be written using a <send> element using Example: Use of the following syntax: location attribute of the assign to update the count for both Boston and New York.
<datamodel>
<data name="connectionid"/>
</datamodel>
<transition event="ccxml:connection.alerting">
  <assign name="connectionid" expr="_eventdata.connectionid"/>
  <send targettype="ccxml" event="ccxml:accept" namelist="connectionid"/>
</transition>

<state id="errorSwitch">
    <datamodel>
        <data ID="cities">
            <city id="nyc" count="0">New York</city>
            <city id="bos" count="0">Boston</city>
        </data>
    </datamodel>
    
    <onentry>
        <assign location="instance('cities')/city/@count" expr="1"/>
    </onentry>
</state>

A more complicated example might be Any errors which arise during the processing of a CCXML <createcall> location expression must be mapped into an SCXML error.illegalalloc. errorcode event where you are both providing variables and getting values back that using only the <send> syntax would be more complex errorcode is the value specified in [XPath 2.0] and related specifications such as it would need to be broken over several steps. For example: the [XPath 2.0 Functions and Operators] .

<onentry> <ccxml:createcall dest="'tel:+18315552020'" connectionid="myConnectionID"/> </onentry>
9.3.3.2 Value Expressions

Would need to The result of any XPath expression may be modeled used in two steps using <send> as you would need to do something like a value expression. If the following: result of the value expression is a node-set, a deep copy of the subtree rooted at each node is made.

Example: Copying event data into the local data model for the state.
<datamodel>
  <data name="dest" expr="'tel:+18315552020'"/>
  <data name="connectionid"/>
</datamodel>
<onentry>
  <send targettype="ccxml" event="ccxml:createcall" namelist="dest"/>
</onentry>
<transition event="ccxml:createcall.success">
   <assign name="connectionid" expr="_eventdata.connectionid"/>
</transition>

<state id="processEvent">
    <datamodel>
        <data ID="myEventData"/>
    </datamodel>
    
    <onentry>
        <assign location="instance('myEventData')" expr="/data[@ID='_event']"/>
    </onentry>
</state>

The exact mappings between Custom Action Elements and <send> actions are to Any errors which arise during the processing of a value expression must be defined mapped into an SCXML error.illegalvalue. errorcode event where the errorcode is the value specified in [XPath 2.0] and related specifications such as the individual Custom Action Element specifications. [XPath 2.0 Functions and Operators] .

9 Boolean Expressions 9.3.3.3 System Variables

This section describes Within the content that can be placed in "cond" attributes. In general, a restricted subset of data model expressions is permitted, namely those which evaluate to a boolean and do not have side effects. Data model expressions may refer Model, three implicit <data> elements are defined to hold the special variable '_eventdata', system variables as described in 8.1.2 _eventdata and to section 5.6 of the special predicate In as described in 9.1 In [XPath 2.0] . specification. These are named _event ,_sessionID ,and _name .

Implementations The _event value must support ECMAScript [ECMAScript] as a boolean expression language, be assigned by processor before triggering executable content in the <onentry>, <onexit>, and <transition> elements which may support additional languages if they choose. reference the variable. The processor must clear the value by setting its child elements <name> and <data> to empty XML elements when event processing has completed.

9.1 In 9.1.1 Overview

The In predicate allows a guard condition in one state to test whether _sessionID and _name values must be set by the processor at session start.

The following SCXML shows the structure of the system is also variables in another state. This the XPath profile.


<scxml name="myName" profile="xpath" ...>
   <datamodel>
       <data ID="_name">mySCXMLMachine</data>
       <data ID="_sessionID">12343</data>
       <data ID="_event">
           <name/>
           <data/>
       </data>
   </datamodel>
   ...
</scxml>

Here is useful an example of accessing the _sessionID in <parallel> regions. a transition.

<state id="checkSessionID">
    <transition cond="/data[@ID='_sessionID'] = '12343'" target="nextState"/>
    ...
</state>

9.1.2 Attribute Details 9.3.4 Additional Requirements

Name Required Attribute Constraints Type Default Value Valid Values Description state true
state ID none A valid stateID The ID of a state in the current document. 9.3.4.1 The In() predicate evalutes

A conformant SCXML processor must add an XPath function to 'true' if that state is currently active. 10 the SCXML Events Events are one of namespace that implements the basic concepts In() semantics described in SCXML since they drive most transitions. The internal structure section 8.1 of events is platform-specific the [SCXML1] specification.

Function signature: In($arg as long xs:string?) as the following external interface is observed: xs:boolean

Events have names which are matched against the "event" attribute of transitions. These names are strings consisting of alphanumeric characters plus the character '.' which is used to segment names into tokens. The "event" attribute of a transition may end with the wildcard '.*', which will match zero Returns an xs:boolean indicating whether or more tokens at the end not one of the processed event's name. Thus a transition with an "event" attribute current active states matches the value of 'error.*' will match 'error', 'error.send', 'error.send.failed', etc. Furthermore, a transition with $arg .

9.3.4.2 The instance() function

Function signature: instance($arg as xs:string?) as xs:node-set

Returns an "event" attribute xs:node-set consisting solely of '*' will match any event. those elements in the data model whose ID matches $arg .

Events optionally contain data organized into XML trees. If data the argument is present, it must be able omitted or is equal to be accessed via the '_eventdata' variable, as specified in 8.1.2 _eventdata . If the event does not contain data, '_eventdata' is an empty XML tree. Events are immutable read-only data structures. Neither the browser's processing nor string, then the user's markup may modify an event once it root element node is placed returned for the default instance in queue. Note that this implies the model that modifications to contains the _eventdata structure are not permitted. current context node.

There Otherwise, the argument is converted to a class of error events whose names begin with 'error.'. They may be raised string as if by a call to the platform, string function. This string is treated as specified in this document, or under application control. They are placed an IDREF, which is matched against instance elements in the event queue containing document. If a match is located, and processed like any other event. In particular, they are ignored if no transition the matching instance data is found that matches them. Note however that authors can arrange for otherwise unhandled errors to cause associated with the interpreter to exit by creating same model as the current context node, this function returns a transition with "event" attribute node-set containing just the root element node of 'error.*' and a target the referenced instance data. In all other cases, an empty node-set is returned.

Note:

The definition of any top-level final state (i.e. one this function intentionally parallels that is a child of <scxml>). If such a transition T is placed in a state S, it will cause the state machine to terminate on any error that is raised in S or one [XFORMS11] specification.

9.3.5 Examples

The following examples show various aspects of its substates and is not handled by another transition that is placed assignment in the XPath profile. Suppose we have a substate data model of S or in S and preceding T in document order. the following form:

<data ID="cart">  
  <myCart>
   <books>
    <book>
     <title>The Zen Mind </title>
   </book>
   <book>
    <title>Freakonomics </title>
  </book>
 </books>
 <cds>
  <cd name="something"/>
 </cds>
</myCart>
</data>

In many applications, it Here is important for SCXML to receive events from external entities (for an example those which it contacted with <invoke> and <send>.) For the moment, the delivery of external events to SCXML is left as assignment of a platform-specific detail, but it may be specified string to an element node.


 
<assign location="instance('cart')/myCart/books/book[0]/title"  expr="'My favorite book'"/>

results in a future version of this document. In any case, external events must be placed

<data ID="cart">
 <myCart>
   <books>
    <book>
     <title>My favorite book </title>
   </book>
   <book>>
    <title>Freakonomics </title>
  </book>
   ...
</data>

Note that in this example, since we are using XPath, we could have omitted the event queue for processing instance function and must obey written the external interface specified above. following equivalent expression:

 
<assign location="/data[@ID='cart']/myCart/books/book[0]/title"  expr="'My favorite book'"/>

For the most part, Now suppose we assign an xml structure to an element node. The following assignment statement would have the set effect of events raised during replacing the execution children of an SCXML document is application-specific and generated under author control the element "/data[@ID='cart']/myCart/books/book[0]" by use of the <event> and <send> elements. However, certain events XML tree rooted in <bookinfo>.


<assign location="instance('cart')/myCart/books/book[0]">
  <bookinfo>
   <isdn>12334455</isdn>
   <author>some author</author>
  </bookinfo>
</assign>

results in


<data ID="cart">
 <myCart>
   <books>
    <book>
     <bookinfo>
      <isdn>12334455</isdn>
      <author>some author</author>
     </bookinfo>
   </book>
   <book>>
    <title>Freakonomics </title>
  </book>
   ...
</data>

Here are mandatory examples of legal and generated automatically by illegal assignment to an attribute:


<!-- Legal assignment: -->
<assign location="instance('cart')/myCart/cds/cd/@name" expr"'Something Else'"/>
<!-- Illegal assignment: -->
<assign  location="instance('cart')/myCart/cds/cd/@name" >
  <foo>
   <boo>
  </foo>
</assign>

Now suppose we assign a string to a nodeset. The following assignment statement would have the interpeter. In this version effect of replacing the specification, children of each node in addition to error events, there is only the 'Cancel' event which is sent if nodeset /myCart/books/book with the state machine leaves string "The Zen Mind":


<assign location="instance('cart')/myCart/books/book" expr="'The Zen Mind'"/>
 

results in


<data ID="cart">
  <myCart>
   <books>
    <book>The Zen Mind</book>
    <book>The Zen Mind</book>
  </books>>
  ...
</data>

Finally suppose we assign a structure to a nodeset. The following statement would iterate over the containing state after executing elements in the <invoke> element but before receiving nodeset of <book> elements and replace their children with the 'Done' event. Note that there are also mandatory events that invoked components must return to <price> structure:


<assign location="instance('cart')/myCart/books/book">
 <price>20.0</price> </assign>

results in


<data ID="cart">
  <myCart>
   <books>
    <book>
      <price>20.0</price>
    </book>
    <book>>
      <price>20.0</price>
    </book>
  </books>
  ...
</data>

If the invoking SCXML state machine. In this version evaluation of the specification, there are two such events, namely 'Done' and 'CancelResponse'. We may well change or expand this set any of mandatory events the expressions in future drafts of this specification. Furthermore, it is likely that there will an <assign> element causes an error to be distinct profiles raised, evaluation of SCXML for specific applications, such as the Multi-modal Interaction Framework [W3C MMI] element terminates immediately and VoiceXML 3.0. These profiles will define extensions to the core language and will likely extend <assign> has no effect. For example, the set of mandatory events with additional events appropriate to following assignment statement would raise an error because the specific application. sample datamodel we are using does not have an <isbn> node as a child of <book>:

 
<assign location="instance('cart')/myCart/books/book[0]/ISBN"  expr="'....'"/>

11 10 Related Work

A number of other XML-based state machine notations have been developed, but none serves the same purpose as SCXML. XMI [UML XMI] is a notation developed for representing UML diagrams, including Harel State charts. However it is intended as a machine interchange format and is not readily authorable by humans. ebXML [OASIS ebXML] is a language for business process specification intended to support B2B e-commerce applications. It contains a state machine language that is in some ways similar to the one presented here, but its syntax and semantics are closely tied to its intended use in e-commerce. It is therefore not suitable as a general-purpose state machine language. XTND [XTND] , also called XML Transition Network Definition, is a notation for simple finite state machines but lacks Harel's notions of hierarchical and parallel states and are thus not suitable for a general-purpose state machine that is semantically equivalent to Harel statecharts.

A Contributors Open Issues

A.1 Event Processors

Issue ():

The following people contributed We need to the development define a set of this specification. R.J. Auburn Marc Helbing I/O processors for the External Communications Module and specify the interactions between them and the Data Module for different profiles.

T.V. Raman

Resolution:

Klaus Reifenrath None recorded.

B Open Issues

B.1 undefined behavior in algorithm A.2 Alternative Notation

Issue (undefined_behavior): (alternative_notation):

The It could be argued that the current algorithm leaves choice of names of SCXML elements and attributes is not optimal. Often rather long words are used (e.g. "transition", "target" and "location"), making lines longer than necessary, and contributing to the system's behavior undefined size of SCXML documents. Also, abbreviations are used in some cases (e.g. "expr" and "cond") but not in others, which may give the case impression of 'sideways' transitions between parallel siblings. Suppose <parallel> element P has children S1 and S2. The undefined behavior arises if S1 and S2 a language not well thought out. Moreover, conventions for how to order the attributes within elements are both active lacking, which may make SCXML documents harder than necessary to read and S1 takes understand.

We are considering redesigning this aspect of SCXML. For example, what is now written as follows:


 <transition event="e" cond="x>1" target="s">
    <assign location="/a/b" expr="2"/>
    <send event="e" target="t" expr="5" delay="2s"/>  </transition>

could instead be written like so:


 <go to="s" on="e" if="x>1">
    <assign data="2" to="/a/b"/>
    <send event="e2" data="5" to="t" after="2s"/>  </go>

Note that the latter notation (but not so much the former) suggests a transition T very natural translation into English, e.g. as follows:

"go to s on e if x is bigger than one, assign two to /a/b and send e2 with a target in S2. The current algorithm allows this transition payload of five to t after 2 seconds" It seems there might be taken, but that can result in two states being active inside S2 (namely T's target state a way to name elements and whatever state was already active in S2). This attributes that 1) avoids abbreviations, 2) yet uses less space, 3) is easier to write, 4) is easier to read (since it is closer to English) and 5) suggests an undefined situation. There are two possible ways natural order of resolving the issue. The first would be to follow attributes within elements, based on how the UML specification and forbid element reads when it is translated into English.

Would such transitions. The second solution would a change of naming conventions be an improvement? Could it serve to permit such transitions, but define them as exiting and then re-entering P. By exiting P, we attract more new users to SCXML? Or would intially exit both S1 and S2, it break to much with "tradition" and upon reentry only T's target state would be active in S2. thus repel some current users? We solicit feedback on these possible solutions. this matter.

Resolution:

None recorded.

B.2 A.3 parallel transition order

Issue (transitionOrder):

In the current algorithm, when case of transitions are taken in parallel states, they are taken 'in lockstep', meaning that first all source states and their children are exited for all the transitions, then all executable content selected from all parallel regions, the transitions current algorithm completely specifies a) which transition is executed, then all target states are entered. It might be simpler to execute the transitions one at a time (i.e., exit source state, perform executable content, and enter target states for first transition, then exit source state, perform executable content and enter target states for second transition, etc.). There would be subtle differences selected in the value case of the In() predicate and conflicts (see isPreempted? in B Algorithm for SCXML Interpretation ) and b) the values order in which those transitions should be taken (see microstep in B Algorithm for SCXML Interpretation ). However, we could avoid completely specifying one or both of the datamodel, these choices. This would give implementations greater flexibility, but would impair the resulting state configuration portability of applications, which would be not necessarily behave the same. same way on different platforms. We solicit feedback on these alternatives.

Resolution:

None recorded.

B.3 A.4 error handling

Issue ():

We need to specify the full set of errors that the platform may raise.

Resolution:

None recorded.

B.4 session ID Issue (): We need to specify how SCXML session IDs are created an accessed. Resolution: None recorded. B.5 A.5 do we need <returndata>

Issue (returndata):

Do we need a <returndata> element separate from <send>?

Resolution:

None recorded.

B.6 Task Logging Issue (logging): How can a state with <task> set to true override the default values for success or failure? Do we want to allow this attribute to occur on atomic state? It wouldn't make much sense, but the restriction to complex states may be hard to enforce. Resolution: None recorded. B.7 updates to external data sources Issue (updates): We need to explain in more detail how <send> can be used to update external data sources - message protocols and formats, etc. Resolution: None recorded.

C B Algorithm for SCXML Interpretation

This section presents a normative algorithm for the interpretation of an SCXML docment. document. Implementations are free to implement SCXML intepreters interpreters in any way they choose, but they must behave as if they were using the algorithm defined here.

N.B.: in the following algorithm, we define The fact that SCXML implements a variant of the source state Statechart formalism does not as such determine a semantics for SCXML. Many different Statechart variants have been proposed, each with its own semantics. This section presents an informal semantics of SCXML documents, as well as a transition to be the state normative algorithm for the transition is leaving interpretation of SCXML documents.

Informal Semantics

The following definitions and the target state highlevel principles and constraint are intended to provide a background to be the one it is entering. Furthermore, <state>, <parallel>, <history> <final> normative algorithm, and <scxml> are all considered to be states. (Note that they all can be targets serve as a guide for the proper understanding of transitions.) it.

C.1 Initialization Phase Preliminary definitions

Load and parse the SCXML
state machine and any included
An element of type <state>, <parallel>, <final> or <scxml>.
pseudo state machine documents. Instantiate the data model, loading any external data variables and then updating the model
An element of type <initial> or <history>.
transition target
A state, or an element of type <history>.
atomic state
A state of type <state> with any data passed in no child states, or a state of type <final>.
compound state
A state of type <state> with at least one child state, or a state of type <scxml>.
start state
A dummy state equipped with a transition which when triggered by the invoking context. Initiate 2 different currently empty FIFO Run event queues: one for internal events and one for external events. Throughout processing, any events received from external sources are added leads to the external event queue. Create initial state(s). Added by the interpreter with an (initally empty) list id guaranteed to be unique within the statemachine. The only role of ActiveStates. Create an array associating invocations with the start state is to simplify the algorithm.
configuration
The maximal consistent set of states (including parallel and final states) that invoked them. Create a two dimensional array to hold DataModel snapshots for the <anchor> element. Create an activeTransitions list containing machine is currently in. We note that if a single transition whose source state s is in the <scxml> element and whose target configuration c, it is always the machines 'initialState'. Goto the Enter State Phase. // Global Data Structures: environment env; // represents the data passed in from the environment, the URL of the script, etc. state SCXML; // structure representing the parsed state machine list<state> ActiveStates; //list of currently active states queue<event> InternalEvents; //FIFO event queue queue<event> ExternalEvents; //FIFO event queue datamodel DataModel; // the data model. Details will depend on the model chosen stateID InvokeIDArray[]; //array associating ids of invocations with the ids of states that executed the invocations. invocationID InvokeStateArray[];//array associating state ids with the ids of currently active invocations that // they have executed. dataValues DataSnapshots[][];//array associating tuple of state ID and anchor type with a subtree of the DataModel. //Data Passing Structures - the following variables are used to pass //data between phases and could be replaced by parameters list<transition> activeTransitions;//list of transitions to take list <state> newlyEnteredAtomicStates;// list of states entered as a result of the most recent set of transitions event currentEvent;// the event that triggered activeTransitions. SCXML = loadAndParseStateMachine(env); // load the state machine DataModel = buildDataModel(env, SCXML);//initialize data model activeTransitions = new List(new Transition(source = getAttribute(SCXML, 'id')), target = getAttribute(SCXML, 'initialState')); goto Enter_State_Phase; C.2 Immediately Enabled Transitions Phase Call SelectTransitions with Null event. If any transitions are found, set ActiveTransitions and goto case that the Execute Transitions Phase. Otherwise, see if there parent of s (if any) is an event on the internal or external event queues also in c. Note, however, that triggers <scxml> is not a(n explicit) member of the configuration.
source state
The source state of a transition. If there is, set activeTransitions and goto transition is the Execute Transitions Phase. Otherwise there are no immediately enabled transitions, so goto atomic state from which the Invoke Phase. label Immediately_Enabled_Transitions_Phase; currentEvent = NULL; selectedTransitions = SelectTransitions(NULL); if (!empty(selectedTransitions)){ goto Execute_Transitions_Phase;} while (!empty(InternalEvents) { currentEvent = pop(InternalEvents); activeTransitions = SelectTransitions(currentEvent); if (!empty(activeTransitions)) { goto Execute_Transitions_Phase;} } // while (!empty(ExternalEvents)) { currentEvent = pop(ExternalEvents); activeTransitions = SelectTransitions(currentEvent); if (!empty(activeTransitions)) { goto Execute_Transitions_Phase; } } // //if we get here, there are no immediately enabled transitions goto Invoke_Phase; C.3 Invoke Phase For transition is leaving.
target state in newlyEnteredAtomicStates, execute
A target state of a transition is a state that the invoke element if any. When all newlyEnteredAtomicStates transition is entering. Note that a transition can have been visited, goto the Wait External Event Phase. label Invoke_Phase for(state in newlyEnteredAtomicStates){ if (getChild(state, 'invoke') != NULL) { invokeID = executeInvoke(getChild(state, 'invoke')); // record that state triggered this invocation. This will be used later for <finalize> processing. InvokeIDArray[invokeId] = getID(state); // record that this invocation is active in this state; InvokeStateArray[getID(state)] = invokeID; } // } // goto Wait_External_Event_Phase; C.4 Wait External Event Phase . Clear zero or more target states.
targetless transition
A transition having zero target states.
eventless transition
A transition lacking the newlyActiveAtomicStates list. Wait until an 'event' attribute.
external event appears on
An SCXML event appearing in the external event queue. When one appears, remove it from See section ? for details.
internal event
An event appearing in the internal event queue. If it It's exact representation is implementation dependent, but a return simple string would work.
macrostep
An external event from causes an <invoke>, pass it to the <finalize> handler (if any) of the SCXML state that invoked it. Then call SelectTransitions on it. If any transitions are found, goto the Execute Transitions Phase. Otherwise return machine to the Wait External Event Phase. label Wait_External_Event_Phase; local id invokeID; newlyActiveAtomicStates = NULL; wait (!empty(ExternalEvents)) { // following code executes once ExternalEvents is not empty currentEvent = pop(ExternalEvents); // if this is an event generated by an <invoke>, execute the <finalize> code invokeID = getAttribute(currentEvent, 'invokeID'); if (invokeID != NULL) { processFinalize(currentEvent, InvokeArray[invokeID], DataModel); // if this is a Done event, clean up the InvokeArrays; if(getAttribute(currentEvent, 'name')) == "invokeID.done") { deleteArrayElement(InvokeStateArray, InvokeIDArray[invokeID]); deleteArrayElement(InvokeIDArray, invokeID); }// }// activeTransitions = SelectTransitions(currentEvent); if (!empty(activeTransitions)) { goto Execute_Transitions_Phase; } else { goto Wait_External_Event_Phase; } } // C.5 Execute Transitions Phase Note: in this phase we treat all transitions as take exactly one macrostep. A macrostep consists of a sequence (a chain) of microsteps. However, if the external event does not enable any 'anchor' attributes have been used to set transitions, no microstep will be taken, and the corresponding 'target' in macrostep will be empty.
microstep
If an external event enables one or (in the transition. See Section C.7 Semantics case of <anchor> for parallel states) more transitions, a microstep is taken, involving the explanation processing of this interpretation. The Execute Transitions Phase consists each of four sub-phases. First we resolve conflicts among transitions. Then we exit all states that the transitions leave, executing their <onexit> handlers. Then we execute enabled transitions. This microstep may change the executable content included in the transitions. Then we enter all states that current configuration, update the datamodel and/or generate new (internal and/or external) events. This, by causality, may in turn enable additional transitions enter, executing their <onentry> handlers. Note that there which will be multiple transitions on activeTransitions only if handled in the state machine is next microstep in a parallel region. In all other cases, activeTransitions will contain only a single item and the Remove Conflicting Transitions Phase may be skipped. sequence, and so on.

C.5.1 Remove Conflicting Transitions Phase Principles and Constraints

Two transitions conflict if We state here some principles and constraints, on the sets level of states semantics, that they exit have SCXML adheres to:

Encapsulation
An SCXML processor is a non-null intersection. To resolve conflicts, we first sort the transition list in document order. Then we pick the first transition pure event processor .The only way to get data into an SCXML statemachine is to send external events to it. The only way to get data out is to receive events from it.
Causality
There shall be a causal justification of why events are (or are not) returned back to the ActiveTransitions list and form its conflict set by finding all transitions that conflict with it (there may not environment, which can be any). We then resolve traced back to the (possible) conflict events provided by selecting one member of the conflict set. We then remove all members of system environment.
Determinism
An SCXML statemachine which does not invoke any external event processor must always react with the conflict from consideration and iterate on same behavior (i.e. the rest same sequence of the ActiveTransitions list until all members have been tested for conflicts. The criterion for selection within a conflict set is first scope and then document order. That is, we chose transition T1 over T2 if a) T1's source state is output events) to a descendant given sequence of T2's or b) if neither transition's source state is a descendant input events (unless, of course, the other's and T1 precedes T2 in document order. label Execute_Transitions_Phase; label Remove_Conflicting_Transitions_Phase; list<transition> transitionsToTest = sort(activeTransitions, 'documentOrder'); //we will rebuild the activeTransitions list as we examine transitionsToTest activeTransitions = NULL; while(transitionsToTest){ transition currentTr = first(transitionsToTest); list<transition> conflictSet = new list(currentTr); for restTrans in rest(transitionsToTest) { if (intersection(getStatesToExit(restTrans), getStatesToExit(currentTr) != NULL) { push(restTrans, conflictSet);} }// //now choose one member from the conflict set. Note that this is trivial for sets of size one. for trans in sort(conflictSet, 'documentOrder') { boolean narrowScope = true; for otherTrans in remove(trans, conflictSet) { if (isDescendant(getSourceState(trans), getSourceState(otherTrans))) { narrowScope = false; break; }// }// //this is the first transition in document order such that there is no more narrowly scoped transition // in this conflict set. if (narrowScope) { push(trans, activeTransitions); break; // }// //now remove all transitions in conflictSet from transitionsToTest. transitionsToTest gets smaller // on each iteration so the while loop is guaranteed to terminate. for trans in conflictSet { delete(trans, transitionsToTest); } }// activeTransitions = sort(activeTransitions, 'documentOrder'); goto Exit_State_Phase; C.5.2 Exit State Phase Create a statesToExit List. For each transition T in activeTransitions, if T has no target state, go on statemachine is explicitly programmed to exhibit an non-deterministic behavior). In particular, the next transition. Otherwise, let LCA be the least common ancestor state of the target states availability of T and the active descendents <parallel> element must not introduce any non-determinism of the source kind often associated with concurrency. Note that observable determinism does not necessarily hold for state of T. Add to the statesToExit list of all active states machines that are descendents of LCA. Now sort invoke other event processors.
Completeness
An SCXML interpreter must always treat an SCXML document as completely specifying the list so that state S1 proceeds S2 if 1) S1 is a descendant behavior of S2 or 2) S1 preceeds S2 in document order. Finally, for each state S a statemachine. In particular, SCXML is designed to use priorities (based on document order) to resolve situations which other statemachine frameworks would allow to remain under-specified (and thus non-deterministic, although in a different sense from the list, 1) if S has above).
Run to completion
SCXML adheres to a shallow history state, sets its value run to completion semantics in the sense that an external event can only be processed when the list processing of the previous external event has completed, i.e. when all immediate children of S microsteps (involving all triggered transitions) have been completely taken.
Termination
A microstep always terminates. A macrostep may not. A macrostep that are active 2) if S has a deep history state, set its value to does not terminate may be the list said to consist of all atomic descendants an infinitely long sequence of S that microsteps. This is currently allowed.

Algorithm

This section presents a normative algorithm for the interpretation of SCXML documents. Implementations are active 3)if S has an ongoing invocation,cancel it, 4) perform S's <onexit> actions 4) remove S from free to implement SCXML interpreters in any way they choose, but they must behave as if they were using the ActiveStates list. algorithm defined here.

Datatypes

Goto Execute Content Phase. These are the abstract datatypes that are used in the algorithm.

label Exit_State_Phase;
list<state> statesToExit;
for trans in activeTransitions {
   statesToExit = append(statesToExit, getStatesToExit(trans)); }
statesToExit = sort(statesToExit, 'exitOrder');
for state in statesToExit {
   list<state> activeChildren;
   list<state> activeAtomicDescendents;
   
   // record currently active descendents for use as possible history values
   for activeState in ActiveStates {
      if(getParent(activeState) == state) {
         push(activeState activeChildren);}
      if(isAtomic(activeState) && isDescendent(activeState, state)) {
         push(activeState activeAtomicDescendents); }
   //
   // update history states     
   for histState in getHistoryStates(state) {
      if(getAttribute(histState, 'type') == 'deep') {
         setHistoryValue(histState, activeChildren); 
      } else (setHistoryValue(histState, activeAtomicDescendents); }
   }//

datatype List
   function head()      // Returns the head of the list   function tail()      // Returns the tail of the list   function append(l)   // Returns the list appended with l   function filter(f)   // Returns the list of elements that satisfy the predicate f   function some(f)     // Returns true if some element in the list satisfies the predicate f   function every(f)    // Returns true if every element in the list satisfies the predicate f
  // now the executable content
   if(getElement(state, 'onexit')) {
     executeContent(getChildren(getElement(state, 'onexit')) currentEvent);}
  
  // cancel any ongoing invocation
   if(InvokeStateArray[getID(state)] != NULL; {
   //cancel ongoing invocation and clean up Invoke Arrays;
      cancelInvoke(InvokeStateArray[getID(state)];
      deleteArrayElement(InvokeIDArray, InvokeStateArray[getID(state)]);
      deleteArrayElement(InvokeStateArray, getID(state);
   }//
   
  // make state inactive
   delete(state, ActiveStates);
}//

datatype Set
   procedure add(e)     // Adds e to the set   procedure delete(e)  // Deletes e from the set   function member(e)   // Is e a member of set?   function isEmpty()   // Is the set empty?   function toList()    // Converts the set to a list
goto Execute_Content_Phase; 

datatype Queue
   procedure enqueue(e) // Puts e last in the queue   function dequeue()   // Removes and returns first element in queue   function isEmpty()   // Is the queue empty?
datatype BlockingQueue
   procedure enqueue(e) // Puts e last in the queue   function dequeue()   // Removes and returns first element in queue, blocks if queue is empty

C.5.3 Execute Content Phase Global variables

For each transition The following variables are global from the point of view of the algorithm. Their values will be set in the activeTransitions list, execute its executable content. Then goto Enter State Phase. procedure interpret() .

label Execute_Content_Phase;
for transition in activeTransitions {
   executeContent(getChildren(transition), currentEvent);}

global datamodel;
global configuration;
global internalQueue;
global externalQueue;
global historyValue;
global continue
 

Procedures and Functions

This section defines the procedures and functions that make up the core of the SCXML interpreter.

C.5.4 Enter State Phase procedure interpret(scxml,id)

Create a Target State list, The purpose of this procedure is to initialize the interpreter. It is called with a States parsed representation of an SCXML document.

In order to Enter List, interpret an SCXML document, first perform inplace expansions of states by including SCXML source referenced by URIs (see 3.11 Referencing External Files ) and a Default Entry List. Also create a Rollback array associating stateIDs with anchors change initial attributes to be rolled back. For each transition T in ActiveTransitions, if T has no target state, go on initial container children with empty transitions to the next transition. If T was originally specified by an anchor element, add T's target state from the attribute. Then (optionally) validate the resulting SCXML, and throw an exception if validation fails. Create an empty configuration complete with a new populated instance of the anchor name data model and a execute the global scripts. Create the two queues to handle events and set the Rollback array. Set Target State list global continue variable to be true. Call executeTransitionContent on the list of T's target states. If any member of Target States initial transition that is a history state, replace it on Target States with its history value. For each state in Target States, child of scxml. Then call addDefaultStatesToEnter enterState on state, the least common ancestor initial transition. Finally, start the interpreter's event loop.

procedure interpret(doc):
   expandScxmlSource(doc)
   if (!valid(doc)) {fail with error}
   configuration = new Set()
   datamodel = new Datamodel(doc)
   executeGlobalScriptElements(doc)
   internalQueue = new Queue()
   externalQueue = new BlockingQueue()
   continue = true
   executeTransitionContent([doc.initial.transition])
   enterState([doc.initial.transition])
   startEventLoop()

procedure startEventLoop()

The interpreter's event loop has two main parts. First it selects enabled transitions. Then it executes the selected transitions. It stays in a continuous loop of T's source selecting and target states, executing transitions until the States interpreter is finished. The details of how it selects transitions are specified to Enter List achieve the desired run to completion semantics and final processing.

The interpreter's event loop enforces the Default Entry list. (Note that run to completion semantics by only breaking at the end of handling all of the microsteps associated with any given event. It accomplishes this modifies by each and every time through the states loop enforcing an ordering on which transitions are selected. First the interpreter checks to Enter see if there are any eventless transitions that need to be taken. If there are any then they are executed by the microstep being performed and the Default Entry List.) Sort next iteration of the States loop continues. If there were no eventless transitions to Enter list so that S1 preceeds S2 execute then the internal event queue is checked and if 1) S1 there is an ancestor of S2 or 2) S1 preceeds S2 in document order. Call EnterState internal event then transitions are selected based on each state S this event. If there were transitions selected based on this event then these are executed by the States to Enter List along with the RollBack List microstep being performed and the Default Entry List. Finally next iteration of the loop continues. If there were no transitions enabled then we check if we have reached a top-level final state, exit state by checking if continue is true. If continue is false the interpreter. Otherwise goto statemachine is done and we break out of the Immediately Enabled Transitions phase. startEventLoop. If continue is true then we grab an external event from the external event queue, blocking if necessary. Once we have the external event we perform the appropriate data model manipulation related to finalizing the event and modifying the data model with the event information. Finally we select transitions that were enabled by this event. If there were transitions enabled by the event we execute them by the microstep function and start the next iteration of the loop. If there were no transitions selected by the external event we also start the next iteration of the loop.

list <state> targetStates;
list <state> statesToEnter;
<state> statesToRollback[];
list <state> statesForDefaultEntry;
for trans in activeTransitions {
   if (getTargetStates(trans) != NULL) {
   
      if (getAttribute(trans, 'anchor')){
      // transitions with anchors always have a single target
         statesToRollback[first(getTargetStates(trans)] = getAttribute(trans, 'anchor');}
      
      targetStates = getTargetStates(trans);
      for state in targetStates {
         if(isHistoryState(state)) {
            delete(state, targetStates);
            if(getHistoryValue(state) != NULL) {
               targetStates = append(targetStates, getHistoryValue(state));
           // if state has no history value, use default history value
            } else {
                targetStates = append(targetStates, getHistoryDefault(state)); 
            }//
         }//
      }//
      
      state LCA = findLeastCommonAncestor(add(getSourceState(trans), getTargetStates(trans));
      for state in targetStates {
         addDefaultStatesToEnter(state, LCA, statesToEnterList, statesForDefaultEntry);}
          
}//
statesToEnter = sort(statesToEnter, 'entryOrder');

procedure procedure startEventLoop():
   while (true):
      enabledTransitions = selectTransitions(null)
      if (enabledTransitions.isEmpty() && !internalQueue.isEmpty()):
         enabledTransitions = selectTransitions(internalQueue.dequeue())
      if (enabledTransitions.isEmpty()enabledTransitions.isEmpty() && !internalQueue.isEmpty():         if (continue):
            ee = externalQueue.dequeue()
            datamodel.assignID("event",ee)
            enabledTransitions = selectTransitions(ee)
         else:            break      if (!enabledTransitions.isEmpty()):
         microstep(enabledTransitions.toList())

for state in statesToEnter {
   EnterState(state, statesToRollback, statesForDefaultEntry, currentEvent);}

for state in ActiveStates { if (isFinal(state) && getParent(state>) == SCXML){ exitInterpreter();} }// goto Immediately_Enabled_Transistions_Phase; procedure exitInterpreter()

The purpose of this procedure is to exit the current SCXML process by halting the interpreter's event loop. It does so by setting the global variable continue to false C.6 Utility Functions . This will terminate the outer as well as the inner loop. Note, however, that any current microstep will first be completely taken.

procedure exitInterpreter():
   continue = false

C.6.1 SelectTransitions( event ) function selectTransitions(event)

The purpose of the selectTransitions() procedure is to collect the transitions that are enabled in a given configuration.

Create an empty set of enabledTransitions . For each atomic state in ActiveStates in document order, the configuration, first test if the state has been preempted by a transition that has already been selected and that will cause the state to be exited when the transition is taken. If the state has not been preempted, find a transition whose "event" 'event' attribute is either empty or matches event and whose condition evaluates to true. true . (N.B. If event is null only transitions with empty event attributes match it.) If multiple matching transitions are present, take the first in document order. If none are present, search in the state's ancestors in ancestory oder order until one is found. As soon as such a transition is found, add it to the back of the ActiveTransitions list, enabledTransitions , and proceed to the next atomic state in ActiveStates. the configuration. If no such transition is found in the state or its ancestors, proceed to the next state in ActiveStates. the configuration. When all atomic states have been visited and transitions selected, return the list set of selected enabled transitions.

transition_list SelectTransitions(event) {
   list <state> atomicStates = ();
   list <transition> transitions = ();
   
   for state in ActiveStates {
      if (isAtomic(state)) {
          push(state, atomicStates);
          }
   }//
   atomicStates = sort(atomicStates, 'documentOrder');
   
   for state in atomicStates {
      transition tr = findTransitionMatchingEvent(event, state);
      if (tr != NULL && !member(tr, transitions)) {
          push(tr, transitions);
     }//
   }//
    
return transitions;
}
transition findTransitionMatchingEvent(event, state) {
    transition matchingTransition = NULL;
    
    for trans in getTransitions(state) {
       if ((event == NULL || nameMatch(event, transition))
                &&
           conditionMatch(event, transition)) {
           
          return trans; // return as soon as we find a transition that matches
          }
    }//
    
    // if no transition found in this state, check parent recursively
    if (getParent(state) !== NULL) {
       return findTransitionMatchingEvent(event, getParent(state); 
    } else { return NULL; }
}
           
      
      

function selectTransitions(event):
   enabledTransitions = new Set()
   atomicStates = configuration.toList().filter(isAtomicState)
   for state in atomicStates:
      if !(isPreempted(s, enabledTransitions)):
         loop: for s in [state].append(getProperAncestors(state,null)):
            for t in s.transition:               if ((event == null && t.attribute('event') == null && conditionMatch(t)) ||
                   (event != null && nameMatch(event,t) && conditionMatch(t))):
               enabledTransitions.add(t)
               break loop   return enabledTransitions

C.6.2 findStatesToExit( trans ) procedure isPreempted?(s transitionList)

Return true if a list transition T in transitionList exits an ancestor of all states state s. In this case, taking T will pull the state machine out of s and we say that it preempts the selection of a transition from s. Such preemption will be existed when trans occur only if s is taken. These are all a descendant of a parallel region and T exits that region. If we did not do this preemption check, we could end up in an illegal configuration, namely one in which there were multiple active states that are descendents were not all descendants of a common parallel ancestor.

procedureisPreempted?(s transitionList):
   boolean preempted = false
   for t in transitionList:
      if (t.attribute('target') != null):
         LCA = findLCA([t.parent()].append(getTargetStates(t)))
            if (isDescendant(s,LCA)):
               preempted = true
               break;
   return preempted

procedure microstep(enabledTransitions)

The purpose of the microstep procedure is to process the set of transitions enabled by an external event, an internal event, or by the presence or absence of certain values in the datamodel at the current point in time. The processing of the enabled transitions must be done in parallel ('lock step') in the sense that their source states must first be exited, then their actions must be executed, and finally their target states entered.

procedure microstep(enabledTransitions):
   exitStates(enabledTransitions)
   executeTransitionContent(enabledTransitions)
   enterStates(enabledTransitions)

procedure exitStates(enabledTransitions)

Create an empty statesToExit set. For each transition t in enabledTransitions ,if t is targetless then do nothing, else let LCA be the least common ancestor state of the source state and target states of trans. t .Add to the statesToExit set all states in the configuration that are descendants of LCA .Convert the statesToExit set to a list and sort it in exitOrder .

For each state s in the list, if s has a deep history state h ,set the history value of h to be the list of all atomic descendants of s that are members in the current configuration, else set its value to be the list of all immediate children of s that are members of the current configuration. Again for each state s in the list, first execute any onexit handlers, then cancel any ongoing invocations, and finally remove s from the current configuration.

list<state> getStatesToExit(transition trans) {
   list<state> transitionStates = NULL;
   list<state> statesToExit = NULL;
   
   //if trans has no target state, no states will be exited
   if (getTargetStates(trans) != NULL) {
      push (getSourceState(trans), getTargetStates(trans));
      
      state LCA = getLeastCommonAncestor(transitionStates);
      for state in ActiveStates {
         if(isDescendant(state, LCA)) {
            push(state statesToExit); }
      }//
   }//
   
   return statesToExit;
}

procedure exitStates(enabledTransitions):
   statesToExit = new Set()
   for t in enabledTransitions:      if (t.attribute('target') != null):
         LCA = findLCA([t.parent()].append(getTargetStates(t)))
         for s in configuration.toList():            if (isDescendant(s,LCA)):
               statesToExit.add(s)
   statesToExit = statesToExit.toList().sort(exitOrder)
   for s in statesToExit:      for h in s.history:
         f = (h.attribute('type') == "deep") ?
             lambda(s0): isAtomicState(s0) && isDescendant(s0,s) :
             lambda(s0): s0.parent() == s
         historyValue[h.attribute('id')] = configuration.toList().filter(f)
   for s in statesToExit:      for content in s.onexit:
         executeContent(content)
      for inv in s.invoke:
         cancelInvoke(inv)
      configuration.delete(s)

C.6.3 findLeastCommonAncestor( state-list ) procedure executeTransitionContent(enabledTransitions)

Return For each transition in the state S such that 1) S is list of enabledTransitions ,execute its executable content.

procedure executeTransitions(enabledTransitions):   for t in enabledTransitions:
      executeContent(t)

procedure enterStates(enabledTransitions)

Create an empty statesToEnter set, and an empty statesForDefaultEntry set. For each transition t in enabledTransitions ,if t is targetless then do nothing, else let LCA be the least common ancestor all states on state-list state of the source state and 2) no descendent target states of S has this property. Note that there t .For each target state s ,if s is guaranteed to be such a history state since then add either the <scxml> element (which we treat as history values associated with s or s 's default target to statesToEnter .Else (if s is not a history state), add s to statesToEnter .Convert statesToEnter to a list and sort it in enterOrder .

For each state here) s in the list, first add s to the current configuration, then invoke any external processes specified in <invoke> elements and assign their sessionID s to the datamodel, keyed on the <invoke> element's ID, then execute any onentry handlers, and finally, if s is a common ancestor of all states. final state, generate relevant Done events. If we have reached a top-level final state, exit the interpreter.

state findLeastCommonAncestor(state-list) {
  state LCA;
  
   if (isNull(state-list)) {
      LCA = SCXML;
   } else {
      LCA = first(state-list);
      for state in rest(state-list) {
         LCA = findLeastCommonAncestor(LCA, state);}
   }//
  return LCA;
}
state findLeastCommonAncestor(state1, state2) {
   if (isDescendent(state2, state1)) {
     return state1; 
   } elsif(isDescendent(state1, state2)) {
     return state2; 
   } elsif (state1 == state2) {
     return state1; 
   } else 
       for anc in listAncestors(state1, SCXML) {
         if (isDescendant(state2, anc)){ 
            return anc;}
      }//
   //
}

procedure enterStates(enabledTransitions):
   statesToEnter = new Set()
   statesForDefaultEntry = new Set()
   for t in enabledTransitions:      if (t.attribute('target') != null):
         LCA = findLCA([t.parent()].append(getTargetStates(t)))
         for s in getTargetStates(t):            if (isHistoryState(s)):               if (historyValue[s.attribute('id')] != null):                  for s0 in historyValue[s.attribute('id')]:
                     addStatesToEnter(s0,LCA,statesToEnter,statesForDefaultEntry)
               else:                  for s0 in getTargetStates(s.transition):
                     addStatesToEnter(s0,LCA,statesToEnter,statesForDefaultEntry)
            else:
               addStatesToEnter(s,LCA,statesToEnter,statesForDefaultEntry)
   statesToEnte   for anc in getProperAncestors(stateList.head(),null):
r = statesToEnter.toList().sort(enterOrder)
   for s in statesToEnter:
      configuration.add(s)
      for inv in s.invoke:
         sessionID = executeInvoke(inv)
         datamodel.assignValue(inv.attribute('ID'),sessionID)
      for content in s.onentry:
         executeContent(content)
      if (statesForDefaultEntry.member(s)):
         executeContent(s.initial.transition.children())
      if (isFinalState(s)):
         parent = s.parent()
         grandparent = parent.parent()
         internalQueue.enqueue(parent.attribute('id') + ".Done")
         if (isParallelState(grandparent)):            if (getChildStates(grandparent).every(isInFinalState)):
               internalQueue.enqueue(grandparent.attribute('id') + ".Done")
   for s in configuration.toList():      if (isFinalState(s) && isScxmlState(s.parent())):
         exitInterpreter()

C.6.4 addDefaultStatesToEnter( state , rootState , [in/out]stateList , [in/out]defaultEntryList ) procedure addStatesToEnter(s,root,statesToEnter,statesForDefaultEntry)

The purpose of this routine procedure is to add to stateList statesToEnter all states that must be entered as a result of entering state . s . These include ancestors of state , s , parallel siblings of state s or its ancestors, and state s 's default children, if it s is a parallel or compound state. Note that this procedure permanently modifies both stateList statesToEnter and defaultEntryList . statesForDefaultEntry .

For all parallel states S between state and rootState , for each parallel child that does not have a descendant on stateList , call addDefaultStatesToEnter on the child with S as the rootState . Now, First, add state ito StateList s to statesToEnter .Then, if it is not already there. If state s is a parallel state, call addDefaultStatesToEnter on add each of its s 's children with state as the rootState. Otherwise to statesToEnter .Else, if state s is a compond compound state, add it s to defaultEntryList . Call addDefaultStatesToEnter on statesForDefaultEntry and add its default initial state with state as the rootState. Finally add all of state 's ancestors up to but not including rootState statesToEnter .Finally, for each ancestor anc of s ,add anc to stateList if they are not already there. void addDefaultStatesToEnter(state, rootState, [in/out]stateList, [in/out]defaultEntryList) { for ancestor in getAncestors(state, rootState) { if(isParallel(ancestor)) { for pChild in getChildStates(ancestor) { boolean descendentPresent = false; for enterState in stateList { if (isDescendent(enterState, ancestor)) { descendentPresent = true; } }// if(!descendentPresent) { addDefaultStatesToEnter(pChild, ancestor, stateList, defaultEntryList); } // // // if (!member(state, stateList)) { push(state, stateList); } if (isParallel(state)) { for child in getChildStates(state) { addDefaultStatesToEnter(child, state, stateList, defaultEntryList); } } elsif (isCompound(state)) { push(state, defaultEntryList); addDefaultStatesToEnter(getDefaultInitialState(state), state, stateList, defaultEntryList); }// for ancestor in getAncestors(state, rootState) { if(!member(ancestor, stateList)) { push(ancestor, stateList); } }// } C.6.5 EnterState( state , rollbackArray , defaultEntryList , currentEvent ) 1) statesToEnter and if state contains one or more anchors, take the corresponding snapshots. 2) If state has an entry on the rollbackArray , rollback the datamodel using the anchor recorded in the rollbackArray . 3) Now store the new snapshots in state . 4) Add state to the ActiveStates list. 5) Execute state 's <onentry> handlers 6) If state is on defaultEntryList , execute the executable content in the transition's state 's <initial> element. 7) If state anc is a final parallel state, then generate a Done event for its parent <state>. 8) Then if add the parent's parent is a <parallel> state and all its children are in final states, generate the Done event for the parent's parent. Exit. of anc that does not have a descendant on statesToEnter to statesToEnter .

void EnterState(state, rollbackArray, defaultEntryList) {
dataValue tempArray[];
for ancElement in getElements(state, 'anchor') {
   tempArray[getAttribute(ancElement), 'anchortype'] = getDMValue(DataModel, getAttribute(ancElement, 'snapshot'); 
}
if(rollbackArray[getID(state)] != NULL) {
   anchor rollback;
   // find the corresponding anchor in state
   for ancElement in getElements(state, 'anchor')) {
      if (getAttriubte(ancElement, 'anchortype') == rollbackArray[getID(state)]) {
         rollback = ancElement; }
   }//
   // roll back the data model 
   setDMValue(DataModel, getAttribute(ancElement, 'snapshot'), 
          DataSnapshots[getID(state)][getAttribute(ancElement, 'anchortype')]; 
}//
   
// now update snapshot array with values from before the rollback
for key and value in tempArray {
   DataSnapshots[getID(state)][key] = value; 
}
// now make state active
push(state, ActiveStates);
if(getElement(state, 'onentry')) {
   executeContent(getChildren(getElement(state, 'onentry')), currentEvent);
   
if(member(state, defaultEntryList)) {
   transition trans = getElement(getElement(state, 'initial'), 'transition'));
   executeContent(getChildren(transition), currentEvent); 
}//
if(isFinal(state)) {
   state parent = getParent(state);
   state grandparent = getParent(parent);
   
   event parentDoneEvent = createEvent(concat(getID(parent), ".Done"));
   push(parentDoneEvent, InternalEvents);
   
   if(isParallel(grandparent)) {
      boolean allFinal = true;
      for state in getChildren(grandparent) {
         if (!isInFinalState(state)) {
            allFinal = false;
            break;
         }//
      }//
      
      if (allFinal) {
        event grandparentDoneEvent = createEvent(concat(getID(grandparent), ".Done"));
        push grandparentDoneEvent, InternalEvents);
      {//
}//
}

procedure addStatesToEnter(s,root,statesToEnter,statesForDefaultEntry):
   statesToEnter.add(s)
   if (isParallelState(s)):      for child in getChildStates(s):
         addStatesToEnter(child,s,statesToEnter,statesForDefaultEntry)
   elif (isCompoundState(s)):
      statesForDefaultEntry.add(s)
      addStatesToEnter(getDefaultInitialState(s),s,statesToEnter,statesForDefaultEntry)
   for anc in getProperAncestors(s,root):
      statesToEnter.add(anc)
      if (isParallelState(anc)):         for pChild in getChildStates(anc):            if (!statesToEnter.toList().some(lambda(s): isDescendant(s,anc))):
               addStatesToEnter(pChild,anc,statesToEnter,statesForDefaultEntry)

C.6.6.1 isInFinalState( state ) procedure isInFinalState(s)

Return true if a) state s is a compound <state> and one of its children is a <final> state and is on a member of the ActiveState list configuration, or b) state if s is a <parallel> state and isInFinalState is true of all its children.

boolean isInFinalState(state) {
  if(isCompound(state)) {
    boolean finalChildActive = false;
    for child in getChildren(state) {
       if (isFinal(child) && member(child, ActiveStates)) {
          finalChildActive = true;
          break;} 
    }//
    
    if (finalChildActive) return true;
    else return false;
  }//
  
  elsif(isParallel(state)) {
    boolean allFinal = true;
    for child in getChildren(state) {
      if(! isInFinalState(child)) {
         allFinal = false;
         break;
      }//
    }//
    
    if (allFinal) return true;
    else return false; 
   }//
   
   else return false;
}
   
       

function isInFinalState(s):
   if (isCompoundState(s)):
      return getChildStates(s).some(lambda(s): isFinalState(s) && configuration.member(s))
   elif (isParallelState(s)):
      return getChildStates(s).every(isInFinalState)
   else:
      return false

C.6.6.2 Sorting Order Functions function findLCA(stateList)

We assume that Return the sorting order functions take two arguments state s such that s is a proper ancestor of all states on stateList and return the one no descendant of s has this property. Note that comes first in the resulting order. We take there is guaranteed to be such a state since the 'documentOrder' sorting function <scxml> element (which we treat as given (it returns whichever a state here) is a common ancestor of the two states all states. Note also that since we are speaking of proper ancestor (parent or transitions comes first in parent of a parent, etc.) the defining document.) LCA is never a member of stateList .

state exitOrder(state1, state2) {
   if(isDescendent(state1, state2)) {
     return state1; }
   elsif(isDescendent(state2, state1) {
     return state2;
   else return first(sort(list(state1, state2), 'documentOrder'));
}
state enterOrder(state1, state2) {
   if(isDescendent(state1, state2)) {
     return state2; }
   elsif(isDescendent(state2, state1) {
     return state1;
   else return first(sort(list(state1, state2), 'documentOrder'));
}
C.6.6
Miscellaneous
Functions
id executeInvoke( is the parsed representation of the <invoke> element.
// this function invokes the service specified in  passing any parameters specified by <param> elements  
//plus the value of 'src' or 'srcexpr'.  This function must generate and return a unique id that will be used to track 
//this invocation.
void cancelInvoke(.  This id was returned by an earlier 
//call to executeInvoke;
void processFinalize() {
// is the ID of the state that executed the <invoke>. 
// This function should use  to find the executable content in <finalize> element (if it is present) and update 
// the data model accordingly.  It is an error if the executable content tries to raise events or takes an action 
//other than updating the datamodel.
//void executeContent();
//Execute the items in  in document order.  Each item must complete before
//the execution of the next one.  The special variable '_eventData' should be bound to the data contained in 
//before execution takes place.  If  is NULL or contains no data, '_eventData' should be set to the empty string. 
//Afterwards, '_eventData' should be set back to 'undefined'. Exit when all items have completed. 
//NOTE: executable content items must execute in their own 'sandbox' where they cannot modify any of the internal data 
//structures defined in this algorithm, except for the data model.
boolean nameMatch();
// return true if .  The wildcard '*'
//in 's "event" attribute matches any string of 0 or more characters.
boolean conditionMatch();
//return true if  has an empty 'cond' attribute or if its 'cond' attribute is non-empty and evaluates to 
//'true' in DataModel. The special variable '_eventData' should be bound to the data contained in  before 
//the evaluation takes place.  If  is NULL or contains no data, '_eventData' should be set to the empty string. 
//Afterwards, it should be set back to 'undefined'. 
dataValue getDMValue( is NULL, 
//return whole  to 
//have value  is NULL,
//replace the whole . 
state list getAncestors(); 
// return all ancestors of  is NULL 
// or not an ancestor of  up to but not includig the root <scxml> element.  
// States on the returned list are sorted so that children preceed ancestors.  Note that if  equals 
//, the empty list is returned.  
state loadAndParseStateMachine(env); // load and parse the state machine, including any 
datamodel = buildDataModel(env, state);//initialize data model
void addElement(.  Called only during the intitialization phase
// to add default behaviors.  Once the state machine starts running, it may not be modified.
ID getID( Id attribute. 
transition list getTransitions( in document order.
boolean isAtomic( is atomic (i.e. has no child <state> or <parallel> elements.)
boolean isCompound( has <state> children
boolean isParallel( is defined by a <parallel> element.
boolean isFinal( is a <final> state.
boolean isHistoryState( is a history pseudo-state.
state getParent( if any, otherwise NULL;
boolean isDescendant(.
attribute getAttribute(.
element getElement(.
list<element> getElements( that are an immediate children
//of .
list<element> getChildren(.
list <state> getChildStates(.
list <state> getHistoryStates( should be
//'deep' or 'shallow'.
list<state> getHistoryValue(, if any, otherwise NULL;
void setHistoryValue(.
list<state> getHistoryDefault('s <transition> child.
list<anchor> getAnchors(.
state getDefaultInitialState(.
state getSourceState(.
list<state> getTargetStates(.
void exitInterpreter();// causes the interpreter to terminate.
event createEvent(.
boolean empty( is empty
item pop(.
void push(
list delete(.
//the following list functions are all non-destructive and do not modify the list that is passed to them
list add(.
sitem first(
list rest( except the first.
list tail( is not 
//a member of .
list append(.
list remove(.
boolean member(.
void deleteArrayElement(.
string concat(

function findLCA(stateList):
    for anc in getProperAncestors(stateList.head(),null):
      if (stateList.tail().every(lambda(s): isDescendant(s,anc))):
         return anc

C.7 B.1 Semantics of <anchor>

There are a number of ways of defining the semantics of <anchor>. We choose the following because it shows that, except for the rollback of the data model, <anchor> can be viewed as a syntactic shortcut that does not extend the basic Harel semantics. We emphasize that implementations are required only to behave as if they assigned the following intepretation interpretation to <anchor> and that simpler and more efficient implementations are possible.

First, we add a special branch 'anchors' to the data model, with a child for each anchor type defined in the document. Thus if the document defines anchor types "foo" and "bar", the data model will have paths 'anchors.foo' and 'anchors.bar'. Whenever the state machine enters a state with an <anchor> element, it sets the value of the corresponding anchor entry in the datamodel to the ID of that state. Thus if a <state> with ID 'state27' defines an <anchor> with 'type' "foo", whenever the state machine visits this state, it sets 'anchors.foo; to 'state27'. Furthermore, the state machine automatically adds the 'anchors' branch to the snapshot specified in the <anchor> element.

Now any <transition> which specifies an 'anchor' is replaced with a set of <transition>s, one for each <state> that defines that <anchor>. Each of the <transition>s takes as its 'target' one of the <state>s that defines the <anchor>. Furthermore, an extra clause is added to the 'cond' of the original <transition>, specifying that the corresponding location in the data model match the target <state>'s ID. Finally, a default transition is added reentering the current <state>. For example, if the anchor type "foo" is defined in <state>s 'state27' and 'state33', then in <state> 'thisState', a transition with "event" "someEvent", "cond" "someCond" and "anchor" 'foo' will be replaced by three transitions, as shown below:

<transition event="someEvent" cond="someCond" anchor="foo"/>

is equivalent to

<transition event="someEvent" cond="datamodel.anchors.foo==state27 && someCond" target="state27"/>    
<transition event="someEvent" cond="datamodel.anchors.foo==state33 && someCond" target="state33"/> 
<transition event="someEvent" cond="someCond" target="state33"/> target="thisState"/>

At runtime when "someEvent" is raised and "someCond" is true, if either state27 or state33 has been visited, 'datamodel.anchors.foo' will have the corresponding stateID as its value and the corresponding transition will be selected. The only complication is that the transitions must retain the original 'anchor' attribute, so that the datamodel must be rolled back to the snapshot specified in the corresponding <anchor> element. Note that the 'anchors' branch must be automatically added to this snapshot, so that it will be automatically rolled back as well. (This has the effect of erasing any intermediate anchors that have been visited since the target state was exited.) If neither state27 nor state33 has been visited, the third transition will be taken, causing the state machine to exit and reenter 'thisState' without any rollback of the datamodel.

D C Probabilistic State Machines

In some applications, it is useful for a state machine to behave non-deterministically according to a probability distribution. For example, we may want to have a state S1 which transitions to S2 30% of the time and to S3 70% of the time. Such behavior can be modelled modeled in SCXML as long as the executable content includes a random number generator. In the example below, we use ECMAScript to generate a random number between 0.0 and 1.0 in the <onentry> handler of state S1. S1 has two transitions, both triggered by E1, going to states S2 and S3. S1 takes the first transition if the variable <rand> is 0.3 but the second transition if <rand> is > 0.3. Since <rand> is evenly distributed between 0.0 and 1.0, S1 will transition to S2 30% of the time and S3 70% of the time on event E1. Note that it is important that the random number generation take place outside the <cond> clause of the transition since there are no guarantees of when or how often that will be evaluated.

    <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initalstate="S1">

    <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initialstate="S1">

  
  <state id="S1">
    <datamodel>
      <data name="rand">
    </datamodel>
    <onentry>
      <assign name="rand" expr="Math.random()"/>
    </onentry>
    <transition event="E1" cond="rand <= 0.3" target="S2"/>

    <transition event="E1" cond="rand ‹= 0.3" target="S2"/>

    <transition event="E1" cond="rand > 0.3" target="S3">
  </state>
  
  <state id="S2"/>
  <state id="S3"/>
  
</scxml>
    

E Schema D Schemas

D.1 Utility Schemas

SCXML.xsd The following schemas contain common definitions that are used by the schemas for specific modules and profiles.

scxml-datatypes.xsd

      <?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3.org/2005/07/scxml"
        xmlns="http://www.w3.org/2005/07/scxml">

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">

        <xsd:annotation>
                <xsd:documentation>State Chart XML Schema (20060118)</xsd:documentation>

                <xsd:documentation>
                         XML Schema datatypes for SCXML
                        Defines containers for the SCXML datatypes, many of these
                        imported from other specifications and standards.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd" />
        </xsd:annotation>
        <xsd:simpleType name="Exmode.datatype">
                <xsd:annotation>
                        <xsd:documentation>
             execution mode     
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:NMTOKEN">
                        <xsd:enumeration value="lax" />
                        <xsd:enumeration value="strict" />                        
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="ExprLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
             expression language 
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:NMTOKEN">
                        <xsd:enumeration value="XPath20"/>
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="Profile.datatype">
                <xsd:annotation>
                        <xsd:documentation>
            profile 
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:NMTOKEN">
                        <xsd:enumeration value="minimum"/>
                        <xsd:enumeration value="xpath"/>
                        <xsd:enumeration value="ecmascript"/>
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="HistoryType.datatype">
                <xsd:restriction base="xsd:string">
                        <xsd:enumeration value="shallow" />
                        <xsd:enumeration value="deep" />
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="Boolean.datatype">
                <xsd:annotation>
                        <xsd:documentation>
                                Boolean: true or false only
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:NMTOKENS">
                        <xsd:enumeration value="true" />
                        <xsd:enumeration value="false" />
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="URI.datatype">
                <xsd:annotation>
                        <xsd:documentation>
                                The xsd:anyURI type and thus URI references in SCXML
                                documents may contain a wide array of international
                                characters. Implementers should reference RFC 3987 and
                                the "Character Model for the World Wide Web 1.0:
                                Resource Identifiers" in order to provide appropriate
                                support for these characters in VoiceXML documents and
                                when processing values of this type or mapping them to
                                URIs.
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:anyURI" />
        </xsd:simpleType>
        <xsd:simpleType name="Integer.datatype">
                <xsd:annotation>
                        <xsd:documentation>Non-negative integer</xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:nonNegativeInteger" />
        </xsd:simpleType>
        <xsd:simpleType name="Duration.datatype">
                <xsd:annotation>
                        <xsd:documentation>
                                Time designation following Time [CSS2]; negative numbers
                                not allowed 
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string">
                        <xsd:pattern value="(\+)?([0-9]*\.)?[0-9]+(ms|s)" />
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="ContentType.datatype">
                <xsd:annotation>
                        <xsd:documentation>Content type [RFC2045]</xsd:documentation>
                </xsd:annotation>
                <xsd:list itemType="xsd:token" />
        </xsd:simpleType>
</xsd:schema>

scxml-attribs.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 elementFormDefault="qualified">
    <xsd:annotation>
        <xsd:documentation>
      This is the XML Schema common attributes for SCXML
    </xsd:documentation>
        <xsd:documentation source="scxml-copyright.xsd"/>
    </xsd:annotation>
  <xsd:import namespace="http://www.w3.org/XML/1998/namespace"
             schemaLocation="http://www.w3.org/2001/xml.xsd">
        <xsd:annotation>
            <xsd:documentation>
        This import brings in the XML namespace attributes
        The module itself does not provide the schemaLocation
        and expects the driver schema to provide the
        actual SchemaLocation.
      </xsd:documentation>
        </xsd:annotation>
    </xsd:import>
  <xsd:include schemaLocation="scxml-datatypes.xsd">
        <xsd:annotation>
            <xsd:documentation>
        This include  brings in the SCXML datatypes.
      </xsd:documentation>
        </xsd:annotation>
    </xsd:include>
    <xsd:attributeGroup name="scxml.extra.attribs">
        <xsd:annotation>
            <xsd:documentation>group allowing attributes from other namespaces</xsd:documentation>
        </xsd:annotation>
                <xsd:anyAttribute namespace="##other" processContents="lax" />
    </xsd:attributeGroup>
    <xsd:attributeGroup name="Fetchtimeout.attrib">
        <xsd:annotation>
            <xsd:documentation>Used in Cache.attribs</xsd:documentation>
        </xsd:annotation>
        <xsd:attribute name="Fetchtimeout" type="Duration.datatype"/>
    </xsd:attributeGroup>
    <xsd:attributeGroup name="Maxage.attrib">
        <xsd:annotation>
            <xsd:documentation>Used in Cache.attribs</xsd:documentation>
        </xsd:annotation>
        <xsd:attribute name="maxage" type="Integer.datatype"/>
    </xsd:attributeGroup>
    <xsd:attributeGroup name="Maxstale.attrib">
        <xsd:annotation>
            <xsd:documentation>Used in Cache attribs</xsd:documentation>

        </xsd:annotation>
        <xsd:attribute name="maxstale" type="Integer.datatype"/>
    </xsd:attributeGroup>
    <xsd:attributeGroup name="Cache.attribs">
        <xsd:annotation>
         <xsd:documentation>Cache attributes to control caching behavior</xsd:documentation>
        </xsd:annotation>
        <xsd:attributeGroup ref="Fetchtimeout.attrib"/>
        <xsd:attributeGroup ref="Maxage.attrib"/>
        <xsd:attributeGroup ref="Maxstale.attrib"/>
    </xsd:attributeGroup>
</xsd:schema>

scxml-contentmodels.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">

        <xsd:annotation>
                <xsd:documentation>
                Copyright 1998-2006 W3C (MIT, ERCIM, Keio), All Rights Reserved. Permission to
                use, copy, modify and distribute the VoiceXML schema and its accompanying
                documentation for any purpose and without fee is hereby granted in perpetuity,
                provided that the above copyright notice and this paragraph appear in all
                copies.  The copyright holders make no representation about the suitability of
                the schema for any purpose. It is provided "as is" without expressed or
                implied warranty.
        </xsd:documentation>

                        XML Schema content models for SCXML
                        * scxml.extra.content 
                        Defines SCXML shared content models.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd" />

        </xsd:annotation>
        <xsd:element name="scxml">
                <xsd:complexType>
                        <xsd:choice  minOccurs="1" maxOccurs="unbounded">
                                <xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="state" minOccurs="0" maxOccurs="unbounded" />
                                <xsd:element ref="parallel" minOccurs="0" maxOccurs="unbounded" />
                                <xsd:element ref="final" minOccurs="0" maxOccurs="unbounded" />
                        </xsd:choice>
                        <xsd:attribute name="version" type="xsd:string" fixed="1.0" />
                        <xsd:attribute name="initialstate" type="xsd:IDREF" use="required" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="datamodel">
                <xsd:complexType>
                        <xsd:sequence>
                                <xsd:element ref="data" minOccurs="0" maxOccurs="unbounded" />
                        </xsd:sequence>
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="data">
                <xsd:complexType>
                        <xsd:sequence>
                                <xsd:any processContents="lax" minOccurs="0" maxOccurs="unbounded" />
                        </xsd:sequence>
                        <xsd:attribute name="src" type="xsd:anyURI" />
                        <xsd:attribute name="expr" type="xsd:string" />
                        <xsd:attribute name="name" type="xsd:NMTOKEN" use="required" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="state">
                <xsd:complexType>

        <xsd:group name="scxml.extra.content">
        <xsd:annotation>
                <xsd:documentation>
        group allowing elements from other namespaces
                </xsd:documentation>
        </xsd:annotation>
                <xsd:sequence>
                        <xsd:any namespace="##other" minOccurs="0"
                                maxOccurs="unbounded" processContents="lax"/>
        </xsd:sequence>
        </xsd:group>
</xsd:schema>

D.2 Schema for Core Module

scxml-module-core.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">
        <xsd:annotation>
                <xsd:documentation>
                        This is the XML Schema core module for SCXML
                        * scxml
            * state 
            * initial 
            * onexit
            * onentry 
            * transition
            * parallel
            * final 
            * history 
            * if
            * elseif
            * else
            * event 
            * log
                        The core module defines these elements and their
                        attributes.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd" />
        </xsd:annotation>
        <xsd:include schemaLocation="scxml-datatypes.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                Includes common SCXML datatypes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:include schemaLocation="scxml-attribs.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                Includes common SCXML attributes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
    <!-- core executable content model -->
        <xsd:group name="scxml.core.executablecontent">
       <xsd:choice>
                 <xsd:group ref="scxml.extra.content"/>
                 <xsd:element ref="event"/>
                 <xsd:element ref="if"/>
                 <xsd:element ref="log"/>         
       </xsd:choice>
        </xsd:group>
<!-- scxml -->
        <xsd:attributeGroup name="scxml.scxml.attlist">
                <xsd:attribute name="initial" type="xsd:IDREFS"/>
                <xsd:attribute name="name" type="xsd:NMTOKEN"/>
                <xsd:attribute name="version" type="xsd:string" fixed="1.0" 
                       use="required"/>
                <xsd:attribute name="profile" type="Profile.datatype"/>
                <xsd:attribute name="exmode" type="Exmode.datatype" default="lax"/>               
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.scxml.content">
                <xsd:sequence>
                        <xsd:choice minOccurs="1" maxOccurs="unbounded">
                                <xsd:element ref="initial" minOccurs="0"
                                        maxOccurs="1" />
                                <xsd:element ref="state" minOccurs="0"
                                        maxOccurs="unbounded" />
                                <xsd:element ref="parallel" minOccurs="0"
                                        maxOccurs="unbounded" />
                                <xsd:element ref="final" minOccurs="0"
                                        maxOccurs="unbounded" />
            <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded" />
                        </xsd:choice>                     
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.scxml.type">
                <xsd:group ref="scxml.scxml.content" />
                <xsd:attributeGroup ref="scxml.scxml.attlist" />
        </xsd:complexType>
        <xsd:element name="scxml" type="scxml.scxml.type" />
<!-- state -->
        <xsd:attributeGroup name="scxml.state.attlist">
                <xsd:attribute name="id" type="xsd:ID" use="required" />
        <xsd:attribute name="src" type="URI.datatype" />
                <xsd:attribute name="initial" type="xsd:IDREFS"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
    <xsd:group name="scxml.state.mix">
     <xsd:choice>
        <xsd:element ref="onentry" minOccurs="0" maxOccurs="1" />
                <xsd:element ref="onexit" minOccurs="0" maxOccurs="1" />
                <xsd:element ref="transition" minOccurs="0" maxOccurs="unbounded"/>
                <xsd:element ref="initial" minOccurs="0" maxOccurs="1"/>
                <xsd:element ref="state" minOccurs="0" maxOccurs="unbounded"/>
                <xsd:element ref="parallel" minOccurs="0" maxOccurs="unbounded"/>
                <xsd:element ref="final" minOccurs="0" maxOccurs="unbounded"/>
                <xsd:element ref="history" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:group ref="scxml.extra.content" minOccurs="0" maxOccurs="unbounded" />
     </xsd:choice>
        </xsd:group>
        <xsd:group name="scxml.state.content">
     <xsd:sequence> 
          <xsd:group ref="scxml.state.mix" minOccurs="0" maxOccurs="unbounded" />
     </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.state.type">
     <xsd:sequence>
                <xsd:group ref="scxml.state.content"/>
     </xsd:sequence>
                <xsd:attributeGroup ref="scxml.state.attlist" />
        </xsd:complexType>
        <xsd:element name="state" type="scxml.state.type" />
<!-- initial -->
        <xsd:attributeGroup name="scxml.initial.attlist">
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.initial.mix">
      <xsd:choice>
                <xsd:element ref="transition" minOccurs="1"
                                        maxOccurs="1" />
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
      </xsd:choice>
        </xsd:group>
        <xsd:group name="scxml.initial.content">
      <xsd:sequence>
        <xsd:group ref="scxml.initial.mix" 
                   minOccurs="0" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:group>
        <xsd:complexType name="scxml.initial.type" >
                <xsd:group ref="scxml.initial.content" />
                <xsd:attributeGroup ref="scxml.initial.attlist" />
        </xsd:complexType>
        <xsd:element name="initial" type="scxml.initial.type" />
        
<!-- onentry -->
        <xsd:attributeGroup name="scxml.onentry.attlist">
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.onentry.content">
                <xsd:sequence>
                <xsd:group ref="scxml.core.executablecontent" minOccurs="0"
                                maxOccurs="unbounded" />
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.onentry.type" >
                <xsd:group ref="scxml.onentry.content" />
                <xsd:attributeGroup ref="scxml.onentry.attlist" />
        </xsd:complexType>
        <xsd:element name="onentry" type="scxml.onentry.type" />
<!-- onexit -->
        <xsd:attributeGroup name="scxml.onexit.attlist">
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.onexit.content">
                <xsd:sequence>
                <xsd:group ref="scxml.core.executablecontent" minOccurs="0"
                                maxOccurs="unbounded" />
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.onexit.type" >
                <xsd:group ref="scxml.onexit.content" />
                <xsd:attributeGroup ref="scxml.onexit.attlist" />
        </xsd:complexType>
        <xsd:element name="onexit" type="scxml.onexit.type" />
<!-- transition -->
        <xsd:attributeGroup name="scxml.transition.attlist">
                        <xsd:attribute name="event" type="xsd:NMTOKEN" />
                        <xsd:attribute name="cond" type="CondLang.datatype" />
                        <xsd:attribute name="target" type="xsd:IDREFS" />
                        <xsd:attribute name="anchor" type="xsd:NMTOKEN" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.transition.content">
                <xsd:sequence>
                                <xsd:group ref="scxml.core.executablecontent" minOccurs="0"
                                        maxOccurs="unbounded" />
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.transition.type" >
                <xsd:group ref="scxml.transition.content" />
                <xsd:attributeGroup ref="scxml.transition.attlist" />
        </xsd:complexType>
        <xsd:element name="transition" type="scxml.transition.type" />
<!-- parallel -->
        <xsd:attributeGroup name="scxml.parallel.attlist">
                        <xsd:attribute name="id" type="xsd:ID" use="required" />
                        <xsd:attribute name="src" type="URI.datatype" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.parallel.content">
                <xsd:sequence>

                        <xsd:choice minOccurs="0" maxOccurs="unbounded">
                                <xsd:element ref="onentry" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="invoke" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="transition" minOccurs="0" />
                                <xsd:element ref="initial" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="state" minOccurs="0" />
                                <xsd:element ref="history" minOccurs="0" />
                                <xsd:element ref="parallel" minOccurs="0" maxOccurs="unbounded" />
                          <xsd:element ref="anchor" minOccurs="0" maxOccurs="unbounded" />

                                <xsd:element ref="onexit" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />
                        </xsd:choice>
                        <xsd:attribute name="id" type="xsd:ID" use="required" />
                        <xsd:attribute name="src" type="xsd:anyURI" />
                        <xsd:attribute name="final" type="xsd:boolean" />
                        <xsd:attribute name="task" type="xsd:boolean" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="initial">
                <xsd:complexType>
                        <xsd:sequence>
                                <xsd:element ref="transition" minOccurs="1" maxOccurs="1"/>
                        </xsd:sequence>
                        <xsd:attribute name="id" type="xsd:ID" use="optional" />
                        <xsd:attribute name="src" type="xsd:anyURI" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="onentry">
                <xsd:complexType>
                        <xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="onexit">
                <xsd:complexType>
                        <xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="transition">
                <xsd:complexType>
                        <xsd:sequence>
                                <xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
                        </xsd:sequence>
                        <xsd:attribute name="event" type="xsd:string" />
                        <xsd:attribute name="cond" type="xsd:string" />
                        <xsd:attribute name="target" type="xsd:IDREF" />
                        <xsd:attribute name="anchor" type="NMTOKEN"/>
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="invoke">
                <xsd:complexType>
                        <xsd:choice>
                                <xsd:element ref="param" minOccurs="0" maxOccurs="unbounded" />
                                <xsd:element ref="finalize" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="content" minOccurs="0" maxOccurs="1"/>

                                <xsd:element ref="transition" minOccurs="0"
                                        maxOccurs="unbounded" />
                                <xsd:element ref="state" minOccurs="0"
                                        maxOccurs="unbounded" />
                                <xsd:element ref="parallel" minOccurs="0"
                                        maxOccurs="unbounded" />
                                <xsd:element ref="history" minOccurs="0"
                                        maxOccurs="1" />
                <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>

                        </xsd:choice>
                        <xsd:attribute name="src" type="xsd:anyURI" />
                        <xsd:attribute name="srcexpr" type="xsd:string" />
                        <xsd:attribute name="targettype" type="targettype" use="required" />
                </xsd:complexType>
        </xsd:choice minOcccurs="0" maxOccurs="unbounded">
        <xsd:element name="finalize">
                <xsd:complexType>
                        <xsd:group ref="executablecontent" minOccurs="0" maxOccurs="unbounded" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="content">
                <xsd:complexType>
                        <xsd:sequence>
                                <xsd:complexType mixed="true"></xsd:complexType>
                        </xsd:sequence>
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="parallel">
                <xsd:complexType>

                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.parallel.type" >
                <xsd:group ref="scxml.parallel.content" />
                <xsd:attributeGroup ref="scxml.parallel.attlist" />
        </xsd:complexType>
        <xsd:element name="parallel" type="scxml.parallel.type" />
<!-- final -->
        <xsd:attributeGroup name="scxml.final.attlist">
          <xsd:attribute name="id" type="xsd:ID" use="required" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.final.content">
                <xsd:sequence>

                        <xsd:choice minOccurs="0" maxOccurs="unbounded">
                                <xsd:element ref="onentry" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="onexit" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="state" minOccurs="0" maxOccurs="unbounded" />
                                <xsd:element ref="parallel" minOccurs="0" maxOccurs="unbounded" />
                                <xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="join" minOccurs="0" />
                        </xsd:choice>
                        <xsd:attribute name="id" type="xsd:ID" use="required" />
                        <xsd:attribute name="src" type="xsd:anyURI" />
                        <xsd:attribute name="task" type="xsd:boolean" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="final">
                <xsd:complexType>
                        <xsd:attribute name="id" type="xsd:ID" use="optional" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="history">
                <xsd:complexType>
                        <xsd:sequence minOccurs="1" maxOccurs="1">
                                <xsd:element ref="transition" />
                        </xsd:sequence>
                        <xsd:attribute name="id" type="xsd:ID" use="required" />
                        <xsd:attribute name="src" type="xsd:anyURI" />
                        <xsd:attribute name="type" type="historytype" />
                </xsd:complexType>
        </xsd:element> <!-- possible values for the 'type' attribute of the 'history' element -->
        <xsd:simpleType name="historytype">
                <xsd:restriction base="xsd:string">
                        <xsd:enumeration value="shallow" />
                        <xsd:enumeration value="deep" />
                </xsd:restriction>
        </xsd:simpleType>
        <xsd:element name="anchor">
                <xsd:complexType>
                        <xsd:attribute name="type" type="NMTOKEN" use="required"/>
                        <xsd:attribute name="snapshot" type="xpathExpr"/>
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="param">
                <xsd:complexType>
                        <xsd:attribute name="name" type="xsd:Name" use="required" />
                        <xsd:attribute name="expr" type="xsd:string" />
                </xsd:complexType>
        </xsd:element>
<!-- all declarations for executable content go in this group --> 
<!-- those elements are declared after this group -->
        <xsd:group name="executablecontent">
                <xsd:choice>
                        <xsd:element ref="assign" minOccurs="0" maxOccurs="unbounded" />
                        <xsd:element ref="send" minOccurs="0" maxOccurs="unbounded" />
                        <xsd:element ref="event" minOccurs="0" maxOccurs="unbounded" />
                        <xsd:element ref="if" minOccurs="0" maxOccurs="unbounded" />
                        <xsd:element ref="log" minOccurs="0" maxOccurs="unbounded" />
                        <xsd:any minOccurs="0" maxOccurs="unbounded" />
                </xsd:choice>

                <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
             </xsd:choice>
                </xsd:sequence>

        </xsd:group>
        <xsd:element name="assign">
                <xsd:complexType>
                        <xsd:sequence>
                                <xsd:any processContents="lax" minOccurs="0" maxOccurs="unbounded" />
                        </xsd:sequence>
                        <xsd:attribute name="location" type="xpathExpr" use="required" />
                        <xsd:attribute name="src" type="xsd:anyURI" />
                        <xsd:attribute name="expr" type="xsd:string" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="send">
                <xsd:complexType>
                        <xsd:attribute name="event" type="xsd:string" />
                        <xsd:attribute name="target" type="xsd:anyURI" />
                        <xsd:attribute name="targettype" type="xsd:string" default="scxml" />
                        <xsd:attribute name="sendid" type="xsd:string" /> 
                        <!-- attention: "xsd:string" is not the proper type for the following attribute,
                                   rather a string in CSS2 format is required -->
                        <xsd:attribute name="delay" type="xsd:string" default="'0s'" />
                        <xsd:attribute name="namelist" type="xsd:string" />
                        <xsd:attribute name="hints" type="xsd:string" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="if">
                <xsd:complexType>

        <xsd:complexType name="scxml.final.type" >
                <xsd:group ref="scxml.final.content" />
                <xsd:attributeGroup ref="scxml.final.attlist" />
        </xsd:complexType>
        <xsd:element name="final" type="scxml.final.type" />
<!-- history -->
        <xsd:attributeGroup name="scxml.history.attlist">
        <xsd:attribute name="id" type="xsd:ID" use="required" />
    <xsd:attribute name="type" type="HistoryType.datatype" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.history.content">
       <xsd:sequence>

                        <xsd:choice minOccurs="0" maxOccurs="unbounded">
                                <xsd:element ref="elseif" />
                                <xsd:element ref="else" />
                                <xsd:group ref="executablecontent" />

                 <xsd:element ref="transition" minOccurs="1" maxOccurs="1" />
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
            </xsd:choice>
           </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.history.type" >
                <xsd:group ref="scxml.history.content" />
                <xsd:attributeGroup ref="scxml.history.attlist" />
        </xsd:complexType>
        <xsd:element name="history" type="scxml.history.type" />
<!-- if -->
        <xsd:attributeGroup name="scxml.if.attlist">
        <xsd:attribute name="cond" type="CondLang.datatype" use="required"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.if.content">
                <xsd:sequence>
                        <xsd:choice minOccurs="0" maxOccurs="unbounded">
                                <xsd:element ref="elseif" minOccurs="0" maxOccurs="unbounded"/>
                                <xsd:element ref="else" minOccurs="0" maxOccurs="1"/>
                                <xsd:group ref="scxml.core.executablecontent"/>

                        </xsd:choice>
                        <xsd:attribute name="cond" type="xsd:string" use="required" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="elseif">
                <xsd:complexType>

                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.if.type" >
                <xsd:group ref="scxml.if.content" />
                <xsd:attributeGroup ref="scxml.if.attlist" />
        </xsd:complexType>
        <xsd:element name="if" type="scxml.if.type" />
<!-- elseif -->
        <xsd:attributeGroup name="scxml.elseif.attlist">
                <xsd:attribute name="cond" type="CondLang.datatype" use="required"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.elseif.content">
                <xsd:sequence>

                        <xsd:choice>
                                <xsd:group ref="executablecontent" />

                                <xsd:group ref="scxml.core.executablecontent" />

                        </xsd:choice>
                        <xsd:attribute name="cond" type="xsd:string" use="required" />
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="else">
                <xsd:complexType>

                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.elseif.type" >
                <xsd:group ref="scxml.elseif.content" />
                <xsd:attributeGroup ref="scxml.elseif.attlist" />
        </xsd:complexType>
        <xsd:element name="elseif" type="scxml.elseif.type" />
<!-- else -->
        <xsd:attributeGroup name="scxml.else.attlist">
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.else.content">
                <xsd:sequence>

                        <xsd:choice>
                                <xsd:group ref="executablecontent" />

                                <xsd:group ref="scxml.core.executablecontent" />

                        </xsd:choice>
                </xsd:complexType>
        </xsd:element>
        <xsd:element name="event">
                <xsd:complexType>
                        <xsd:attribute name="name" type="NMTOKEN" />
                </xsd:complexType>
        </xsd:element>
                <xsd:element name="log">
                <xsd:complexType>

                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.else.type" >
                <xsd:group ref="scxml.else.content" />
                <xsd:attributeGroup ref="scxml.else.attlist" />
        </xsd:complexType>
        <xsd:element name="else" type="scxml.else.type" />
<!-- event -->
        <xsd:attributeGroup name="scxml.event.attlist">
            <xsd:attribute name="name" type="xsd:NMTOKEN" use="required"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.event.content">
                <xsd:sequence>
          <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.event.type" >
                <xsd:group ref="scxml.event.content" />
                <xsd:attributeGroup ref="scxml.event.attlist" />
        </xsd:complexType>
        <xsd:element name="event" type="scxml.event.type" />
<!-- log -->
        <xsd:attributeGroup name="scxml.log.attlist">

                        <xsd:attribute name="label" type="xsd:string" />
                        <xsd:attribute name="expr" type="xsd:string" use="required" />
                        <xsd:attribute name="level" type="loglevel" />
                </xsd:complexType>
        </xsd:element>
<!-- log levels are TBD; values below are taken from Java Commons Logging -->
        <xsd:simpleType name="loglevel">
                <xsd:restriction base="xsd:string">
                        <xsd:enumeration value="trace" />
                        <xsd:enumeration value="debug" />
                        <xsd:enumeration value="info" />
                        <xsd:enumeration value="warn" />
                        <xsd:enumeration value="error" />
                        <xsd:enumeration value="fatal" />
                </xsd:restriction>

                        <xsd:attribute name="level" type="xsd:positiveInteger"
                        default="1"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.log.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.log.type">
                <xsd:group ref="scxml.log.content" />
                <xsd:attributeGroup ref="scxml.log.attlist" />
        </xsd:complexType>
        <xsd:element name="log" type="scxml.log.type" />
</xsd:schema>
      

D.3 Schema for External Module

scxml-module-external.xsd


 <?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">
        <xsd:annotation>
                <xsd:documentation>
                        This is the XML Schema external module for SCXML
                        * send 
            * invoke
            * finalize 
            * param
            * content 
                        The external module defines these elements and their
                        attributes.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd" />
        </xsd:annotation>
        <xsd:include schemaLocation="scxml-datatypes.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                This module defines SCXML Attribute DataTypes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:include schemaLocation="scxml-attribs.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                This module defines Common attributes for SCXML
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:attributeGroup name="scxml.send.attlist">
                        <xsd:attribute name="event" type="ValueLang.datatype"/>
                        <xsd:attribute name="target" type="ValueLang.datatype" />
                        <xsd:attribute name="targettype" type="ValueLang.datatype"
                                default="'scxml'" />
                        <xsd:attribute name="sendid" type="LocLang.datatype" />
                        <xsd:attribute name="delay" type="ValueLang.datatype"
                                default="'0s'" />
                        <xsd:attribute name="namelist" type="xsd:string" />
                        <xsd:attribute name="hints" type="ValueLang.datatype" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.send.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.send.type" >
                <xsd:group ref="scxml.send.content" />
                <xsd:attributeGroup ref="scxml.send.attlist" />
        </xsd:complexType>
        <xsd:element name="send" type="scxml.send.type" />
        <xsd:attributeGroup name="scxml.invoke.attlist">
                        <xsd:attribute name="src" type="URI.datatype" />
                        <xsd:attribute name="srcexpr" type="ValueLang.datatype" />
                        <xsd:attribute name="targettype" type="xsd:NMTOKEN"
                                use="required" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.invoke.content">
                <xsd:sequence>
                        <xsd:choice minOccurs="0" maxOccurs="unbounded">
                                <xsd:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
                                <xsd:element ref="finalize" minOccurs="0" maxOccurs="1" />
                                <xsd:element ref="content" minOccurs="0" maxOccurs="1"/>
                <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                        </xsd:choice>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.invoke.type" >
                <xsd:group ref="scxml.invoke.content" />
                <xsd:attributeGroup ref="scxml.invoke.attlist" />
        </xsd:complexType>
        <xsd:element name="invoke" type="scxml.invoke.type" />
        <xsd:attributeGroup name="scxml.finalize.attlist">
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.finalize.content">
                <xsd:sequence>
                        <xsd:group ref="scxml.core.executablecontent" minOccurs="0"
                                maxOccurs="unbounded" />
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.finalize.type">
                <xsd:group ref="scxml.finalize.content" />
                <xsd:attributeGroup ref="scxml.finalize.attlist" />
        </xsd:complexType>
        <xsd:element name="finalize" type="scxml.finalize.type" />
        <xsd:attributeGroup name="scxml.param.attlist">
                        <xsd:attribute name="name" type="xsd:string" use="required" />
                        <xsd:attribute name="expr" type="ValueLang.datatype" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.param.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.param.type" >
                <xsd:group ref="scxml.param.content" />
                <xsd:attributeGroup ref="scxml.param.attlist" />
        </xsd:complexType>
        <xsd:element name="param" type="scxml.param.type" />
<!-- content -->
        <xsd:attributeGroup name="scxml.content.attlist">
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.content.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
    <xsd:complexType name="scxml.content.type" mixed="true">
                <xsd:group ref="scxml.content.content" />
                <xsd:attributeGroup ref="scxml.content.attlist" />
        </xsd:complexType>
        <xsd:element name="content" type="scxml.content.type" />
</xsd:schema>
      

D.4 Schema for Data Module

scxml-module-data.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">
        <xsd:annotation>
                <xsd:documentation>
                        This is the XML Schema data module for SCXML
                        * datamodel 
                        * data
            * assign
            * validate
                        The anchor module defines these elements and their
                        attributes.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd"/>
        </xsd:annotation>
        <xsd:include schemaLocation="scxml-datatypes.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                This module defines SCXML Attribute DataTypes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:include schemaLocation="scxml-attribs.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                This module defines Common attributes for SCXML
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        
        
<!-- datamodel -->
        <xsd:attributeGroup name="scxml.datamodel.attlist">
      <xsd:attribute name="schema" type="URI.datatype"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.datamodel.content">
                <xsd:sequence>
                  <xsd:element name="data"  minOccurs="0"
                                        maxOccurs="unbounded"/>
            <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
       </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.datamodel.type">
                <xsd:group ref="scxml.datamodel.content"/>
                <xsd:attributeGroup ref="scxml.datamodel.attlist" />
        </xsd:complexType>
        <xsd:element name="datamodel" type="scxml.datamodel.type" />
        
        
<!-- data -->     
        <xsd:attributeGroup name="scxml.data.attlist">
                <xsd:attribute name="ID" type="xsd:ID" use="required" />
                <xsd:attribute name="src" type="URI.datatype" />
                <xsd:attribute name="expr" type="ValueLang.datatype" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.data.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                   maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.data.type" mixed="true">
                <xsd:group ref="scxml.data.content" />
                <xsd:attributeGroup ref="scxml.data.attlist" />
        </xsd:complexType>
        <xsd:element name="data" type="scxml.data.type"/>
<!--  assign  -->
        <xsd:attributeGroup name="scxml.assign.attlist">
                        <xsd:attribute name="location" type="LocLang.datatype"
                           use="required"/>
                        <xsd:attribute name="dataID" type="xsd:IDREF" />
                        <xsd:attribute name="expr" type="ValueLang.datatype" />
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.assign.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.assign.type" mixed="true">
                <xsd:group ref="scxml.assign.content" />
                <xsd:attributeGroup ref="scxml.assign.attlist" />
        </xsd:complexType>
        <xsd:element name="assign" type="scxml.assign.type" />
<!--  validate  --> 
        <xsd:attributeGroup name="scxml.validate.attlist">
                <xsd:attribute name="location" type="LocLang.datatype"/>
                <xsd:attribute name="schema" type="URI.datatype" />       
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.validate.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.validate.type">
                <xsd:group ref="scxml.validate.content" />
                <xsd:attributeGroup ref="scxml.validate.attlist" />
        </xsd:complexType>
        <xsd:element name="validate" type="scxml.validate.type" />
        
</xsd:schema>
      

D.5 Schema for Script Module

scxml-module-script.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">
        <xsd:annotation>
                <xsd:documentation>
                        This is the XML Schema script module for SCXML
                        * script
                        The script module defines these elements and their
                        attributes.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd" />
        </xsd:annotation>
        <xsd:include schemaLocation="scxml-datatypes.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                Includes common SCXML datatypes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:include schemaLocation="scxml-attribs.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                Includes common SCXML attributes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:attributeGroup name="scxml.script.attlist">
      <xsd:attribute name="src" type="URI.datatype"/>
      <xsd:attribute name="srcexpr" type="ValueLang.datatype"/>
      <xsd:attribute name="charset" type="xsd:string"/>
      <xsd:attributeGroup ref="Cache.attribs"/>
          <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.script.content">
          <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
      </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.script.type" mixed="true">
                <xsd:group ref="scxml.script.content" />
                <xsd:attributeGroup ref="scxml.script.attlist" />
        </xsd:complexType>
        <xsd:element name="script" type="scxml.script.type" />
</xsd:schema>
      

D.6 Anchor Module Schema

scxml-module-anchor.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        elementFormDefault="qualified">
        <xsd:annotation>
                <xsd:documentation>
                        This is the XML Schema anchor module for SCXML
                        * anchor
                        The anchor module defines these elements and their
                        attributes.
                </xsd:documentation>
                <xsd:documentation source="scxml-copyright.xsd" />
        </xsd:annotation>
        <xsd:include schemaLocation="scxml-datatypes.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                This module defines SCXML Attribute DataTypes
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:include schemaLocation="scxml-attribs.xsd">
                <xsd:annotation>
                        <xsd:documentation>
                                This module defines Common attributes for SCXML
                        </xsd:documentation>
                </xsd:annotation>
        </xsd:include>
        <xsd:attributeGroup name="scxml.anchor.attlist">
      <xsd:attribute name="type" type="xsd:NMTOKEN"
                                use="required"/>
          <xsd:attribute name="snapshot" type="LocLang.datatype"/>
                <xsd:attributeGroup ref="scxml.extra.attribs"/>
        </xsd:attributeGroup>
        <xsd:group name="scxml.anchor.content">
                <xsd:sequence>
        <xsd:group ref="scxml.extra.content" minOccurs="0"
                                        maxOccurs="unbounded"/>
                </xsd:sequence>
        </xsd:group>
        <xsd:complexType name="scxml.anchor.type" >
                <xsd:group ref="scxml.anchor.content" />
                <xsd:attributeGroup ref="scxml.anchor.attlist" />
        </xsd:complexType>
        <xsd:element name="anchor" type="scxml.anchor.type" />
</xsd:schema>
      

D.7 Minimal Profile Schema

scxml-profile-minimum.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.w3.org/2005/07/scxml"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.w3.org/2005/07/scxml"
           blockDefault="#all">
  <xsd:annotation>
    <xsd:documentation>
      This is the XML Schema driver for SCXML 1.0, minimum profile.
      Please use this namespace for SCXML 1.0 elements:
        "http://www.w3.org/2005/07/scxml"
    </xsd:documentation>
    <xsd:documentation source="scxml-copyright.xsd"/>
  </xsd:annotation>
  <xsd:annotation>
    <xsd:documentation>
      This is the Schema Driver file for SCXML 1.0, minimum profile
     This schema
        + sets the namespace for SCXML 1.0 minimum profile 
        + imports external schemas (xml.xsd)
        + imports SCXML common datatypes, attributes and common models
        + imports schema modules 
          SCXML 1.0 includes the following Modules
           
           * SCXML core module 
    </xsd:documentation>
  </xsd:annotation>
  <xsd:import namespace="http://www.w3.org/XML/1998/namespace"
             schemaLocation="http://www.w3.org/2001/xml.xsd">
     <xsd:annotation>
       <xsd:documentation>
         This import brings in the XML namespace attributes
         The XML attributes are used by various modules.
       </xsd:documentation>
     </xsd:annotation>
  </xsd:import>
  <xsd:include schemaLocation="scxml-datatypes.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports brings in the common datatypes
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-attribs.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports brings in the common attributes
         for SCXML.
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-contentmodels.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports the common content models. 
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-module-core.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the core module for SCXML
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>  
    <!--
        Defines the CondLang datatype for this
        profile.
     -->
        <xsd:simpleType name="CondLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Conditional language only consists of In(ID) where ID is
              the XML ID type identify an SCXML state.  The function 
              must evaluate to Boolean True or False.  
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>

        </xsd:simpleType>
        <xsd:simpleType name="xpathExpr">
                <xsd:restriction base="xs:token"/>

</xsd:schema>
      

D.8 ECMAScript Profile Schema

scxml-profile-ecmascript.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.w3.org/2005/07/scxml"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.w3.org/2005/07/scxml"
           xmlns:scxml="http://www.w3.org/2005/07/scxml"
           blockDefault="#all">
  <xsd:annotation>
    <xsd:documentation>
      This is the XML Schema driver for SCXML 1.0, ecma profile.
      Please use this namespace for SCXML 1.0 elements:
        "http://www.w3.org/2005/07/scxml"
    </xsd:documentation>
    <xsd:documentation source="scxml-copyright.xsd"/>
  </xsd:annotation>
  <xsd:annotation>
    <xsd:documentation>
      This is the Schema Driver file for SCXML 1.0, ecma profile
     This schema
        + sets the namespace for SCXML 1.0 basic profile 
        + imports external schemas (xml.xsd)
        + imports SCXML common datatypes, attributes and content models
        + imports schema modules 
          SCXML 1.0 includes the following Modules
           SCXML core module 
           SCXML data module
           SCXML script module
           SCXML external module 
    </xsd:documentation>
  </xsd:annotation>
  <xsd:import namespace="http://www.w3.org/XML/1998/namespace"
             schemaLocation="http://www.w3.org/2001/xml.xsd">
     <xsd:annotation>
       <xsd:documentation>
         This import brings in the XML namespace attributes
         The XML attributes are used by various modules.
       </xsd:documentation>
     </xsd:annotation>
  </xsd:import>
  <xsd:include schemaLocation="scxml-datatypes.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports brings in the common datatypes
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-attribs.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports brings in the common attributes
         for SCXML.
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-module-data.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the data module for SCXML
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>  
  <xsd:include schemaLocation="scxml-module-script.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the script module for SCXML
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>  
  <xsd:include schemaLocation="scxml-module-external.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the external module for SCXML
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>  
  <xsd:redefine schemaLocation="scxml-contentmodels.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports the common content models. 
      </xsd:documentation>
    </xsd:annotation>
  </xsd:redefine>
  
  <xsd:redefine schemaLocation="scxml-module-core.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the core module for SCXML.
        [1] Redefines executable content to allow 
            send, assign and script elements
        [2] Redefines state mix group to allow 
            invoke
        [3] Redefines datamodel element to allow data elements        
      </xsd:documentation>
    </xsd:annotation>
        <xsd:group name="scxml.core.executablecontent">
       <xsd:choice>
         <xsd:group ref="scxml.core.executablecontent"/>
                 <xsd:element ref="send"/>
                 <xsd:element ref="assign"/>
                 <xsd:element ref="script"/>         
       </xsd:choice>
        </xsd:group>
     <xsd:group name="scxml.state.mix">
       <xsd:choice>
         <xsd:group ref="scxml.state.mix"/>
         <xsd:element ref="invoke" minOccurs="0" maxOccurs="1" />
        </xsd:choice>
     </xsd:group>    
     <xsd:group name="scxml.datamodel.content">
      <xsd:sequence>
       <xsd:choice>
         <xsd:group ref="scxml.datamodel.content"/>
         <xsd:element ref="data" minOccurs="0" maxOccurs="unbounded"/>
       </xsd:choice>
      </xsd:sequence>
    </xsd:group>    
  </xsd:redefine>  
    <!--
        Defines the CondLang datatype for this
        profile.
     -->
        <xsd:simpleType name="CondLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Conditional language is ECMAScript expression 
              which must evaluate to Boolean True or False. 
              The expression language must define In(stateID) 
              as a valid expression.
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>
        </xsd:simpleType>
    <!--
        Defines the LocLang datatype for this
        profile. 
     -->
        <xsd:simpleType name="LocLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Location language is ECMAScript expression
              identifying a location in the datamodel. 
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>
        </xsd:simpleType>
    <!--
        Defines the ValueLang datatype for this
        profile. 
     -->
        <xsd:simpleType name="ValueLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Value language is ECMAScript expression
              return a value.
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>
        </xsd:simpleType>
</xsd:schema>
      

D.9 XPath Profile Schema

scxml-profile-xpath.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.w3.org/2005/07/scxml"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns="http://www.w3.org/2005/07/scxml"
           xmlns:scxml="http://www.w3.org/2005/07/scxml"
           blockDefault="#all">
  <xsd:annotation>
    <xsd:documentation>
      This is the XML Schema driver for SCXML 1.0, xpath profile.
      Please use this namespace for SCXML 1.0 elements:
        "http://www.w3.org/2005/07/scxml"
    </xsd:documentation>
    <xsd:documentation source="scxml-copyright.xsd"/>
  </xsd:annotation>
  <xsd:annotation>
    <xsd:documentation>
      This is the Schema Driver file for SCXML 1.0, xpath profile
     This schema
        + sets the namespace for SCXML 1.0 xpath profile 
        + imports external schemas (xml.xsd)
        + imports SCXML common datatypes, attributes and content models
        + imports schema modules 
          SCXML 1.0 includes the following Modules
           SCXML core module 
           SCXML data module
           SCXML external module 
    </xsd:documentation>
  </xsd:annotation>
  <xsd:import namespace="http://www.w3.org/XML/1998/namespace"
             schemaLocation="http://www.w3.org/2001/xml.xsd">
     <xsd:annotation>
       <xsd:documentation>
         This import brings in the XML namespace attributes
         The XML attributes are used by various modules.
       </xsd:documentation>
     </xsd:annotation>
  </xsd:import>
  <xsd:include schemaLocation="scxml-datatypes.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports brings in the common datatypes
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-attribs.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports brings in the common attributes
         for SCXML.
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>
  <xsd:include schemaLocation="scxml-module-data.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the data module for SCXML
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>  
  <xsd:include schemaLocation="scxml-module-external.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the external module for SCXML
      </xsd:documentation>
    </xsd:annotation>
  </xsd:include>  
  <xsd:redefine schemaLocation="scxml-contentmodels.xsd">
    <xsd:annotation>
      <xsd:documentation>
         This imports the common content models. 
      </xsd:documentation>
    </xsd:annotation>
  </xsd:redefine>
  
  <xsd:redefine schemaLocation="scxml-module-core.xsd">
    <xsd:annotation>
      <xsd:documentation>
        This imports the core module for SCXML.
        [1] Redefines executable content to allow 
            send, assign and validate elements
        [2] Redefines state element to allow 
            invoke and datamodel 
        [3] Redefines scxml element allow 
            datamodel element
        [4] Redefines parallel element to 
            allow datamodel element
      </xsd:documentation>
    </xsd:annotation>
        <xsd:group name="scxml.core.executablecontent">
       <xsd:choice>
         <xsd:group ref="scxml.core.executablecontent"/>
                 <xsd:element ref="send"/>
                 <xsd:element ref="assign"/>
                 <xsd:element ref="validate"/>         
       </xsd:choice>
        </xsd:group>
        
  <xsd:group name="scxml.state.mix">
       <xsd:choice>
         <xsd:group ref="scxml.state.mix"/>
         <xsd:element ref="invoke" minOccurs="0" maxOccurs="1" />
                 <xsd:element ref="datamodel" minOccurs="0" maxOccurs="1" />         
        </xsd:choice>
     </xsd:group>    
     <xsd:group name="scxml.scxml.content">
      <xsd:sequence>
       <xsd:choice minOccurs="0" maxOccurs="unbounded" >
         <xsd:group ref="scxml.scxml.content"/>
         <xsd:element ref="datamodel" minOccurs="0" maxOccurs="1"/>                  
       </xsd:choice>
      </xsd:sequence>
    </xsd:group>  
    
    
    <xsd:group name="scxml.parallel.content">
      <xsd:sequence>
       <xsd:choice minOccurs="0" maxOccurs="unbounded" >
         <xsd:group ref="scxml.parallel.content"/>
         <xsd:element ref="datamodel" minOccurs="0" maxOccurs="1"/>
       </xsd:choice>
      </xsd:sequence>
    </xsd:group>  
      
  </xsd:redefine>  
    <!--
        Defines the CondLang datatype for this
        profile.
     -->
        <xsd:simpleType name="CondLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Conditional language is XPath expression 
              which must evaluate to Boolean True or False. 
              The expression language must define In(stateID) 
              as a valid expression.
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>
        </xsd:simpleType>
    <!--
        Defines the LocLang datatype for this
        profile. 
     -->
        <xsd:simpleType name="LocLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Location language is XPath expression
              identifying a location in the datamodel. 
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>

        </xsd:simpleType>
    <!--
        Defines the ValueLang datatype for this
        profile. 
     -->
        <xsd:simpleType name="ValueLang.datatype">
                <xsd:annotation>
                        <xsd:documentation>
              Value language is XPath expression
              returning a value.
                        </xsd:documentation>
                </xsd:annotation>
                <xsd:restriction base="xsd:string"/>
        </xsd:simpleType>

</xsd:schema>
      

F E Examples

F.1 E.1 Language Overview

This SCXML document gives an overview of the SCXML language and shows the use of its state machine transition flows:

Example: Main.scxml
<?xml version="1.0" encoding="us-ascii"?>
<!-- A wrapper state that contains all other states in this file
- it represents the complete state machine -->
<scxml xmlns="http://www.w3.org/2005/07/scxml"
       version="1.0"
       initialstate="Main">  

       initial="Main">  

  <state id="Main">
    <!-- its initial state is Test1 -->
    <initial>
      <transition target="Test1"/>
    </initial>
    <!-- Really simple state showing the basic syntax. -->
    <state id="Test1">
      <initial>
        <transition target="Test1Sub1"/>
      </initial>
      <!-- Runs before we go into the substate -->
      <onentry> 
        <log expr="'Inside Test1'"/>
      </onentry>
      <!-- Here is our first substate -->
      <state id="Test1Sub1">
        <onentry>
          <log expr="'Inside Test1Sub1.'"/>
        </onentry>
        <onexit>
          <log expr="'Leaving Test1Sub1'"/>
        </onexit>
        <!-- Go to Sub2 on Event1 -->
        <transition event="Event1" target="Test1Sub2"/>
      </state>
      <!-- Here is the second substate 
           It is final, so Test1 is done when we get here -->
      <final id="Test1Sub2"/>
      <!-- We get this event when we reach Test1Sub2. -->
      <transition event="Test1.done" target="Test2"/>
      <!-- We run this on the way out of Test1 -->
      <onexit>
        <log expr="'Leaving Test1...'"/>
      </onexit>
    </state>
    <state id="Test2">
      <initial>
        <transition target="Test2Sub1"/>
      </initial>
      <!-- This time we reference a state 
           defined in an external file.  Note that we could have
           loaded the entire file by leaving off the #Test2Sub1,
           but in that case we would need to rename one of the
           Test2Sub1 states (here or in the external file) to
           avoid the name collision -->
      <state id="Test2Sub1" src="External.scxml#Test2Sub1"/>
  
      <final id="Test2Sub2"/>
      <!-- Test2Sub2 is defined as final, so this
           event is generated when we reach it -->
      <transition event="Test2.done" next="Test3"/>
    </state>
    <state id="Test3">
      <initial>
        <transition target="Test3Sub1"/>
      </initial>
      <state id="Test3Sub1">
        <onentry>
          <log expr="'Inside Test3Sub1...'"/>
          <!-- Send our self an event in 5s -->
          <send event="Timer"  delay="5s"/>
        </onentry>
        <!-- Transition on to Test4.
             This will exit both us and our parent. -->
        <transition event="Timer" target="Test4"/>
        <onexit>
          <log expr="'Leaving Test3Sub1...'"/>
        </onexit>
      </state>
      <onexit>
        <log expr="'Leaving Test3...'"/>
      </onexit>
    </state>
    
    <state id="Test4">
      <onentry>
        <log expr="'Inside Test4...'"/>
      </onentry>
      <initial>
        <transition target="Test4Sub1"/>
      </initial>
      <state id="Test4Sub1">
        <onexit>
          <log expr="'Leaving Test4Sub1...'"/>
        </onexit>
        <!-- This transition causes the state to exit immediately
             after entering Test4Sub1.  The transition has no event
             or guard so it is always active -->
        <transition target="Test5"/>
      </state>
    </state>
       
    <state id="Test5">
      <onentry>
        <log expr="'Inside Test5...'"/>
      </onentry>
      <initial>
        <transition target="Test5P"/>
      </initial>
      <!-- Fire off our parallel states -->
      <parallel id="Test5P">
        <final id="Test5PSub1"/>
        <final id="Test5PSub2"/>
        <onexit>
          <log expr="'all parallel states done'"/>
        </onexit>
      </parallel>
      <!-- The parallel states are all final, so this
           event is generated immediately.  Although not shown,
           compound states (i.e., <state>s with content)
           are permitted within <parallel> as well. -->
      <transition event="Test5P.done" target="Test6"/>
    </state>
    <!-- 
         - This state shows invocation of an external component.
         - We will use CCXML + VoiceXML actions as an example 
         - as it is a good smoke test to show how it all 
         - fits together. 
         - Note: In a real app you would likely 
         - split this over several states but we 
         - are trying to keep it simple here. 
    -->
    <state id="Test6"
           xmlns:ccxml="http://www.w3.org/2002/09/ccxml"
           xmlns:v3="http://www.w3.org/2005/07/vxml3">
      <datamodel>
        <data name="ccxmlid" expr="32459"/>
        <date name="v3id" expr="17620"/>
        <data name="dest" expr="'tel:+18315552020'"/>
        <data name="src" expr="'helloworld2.vxml'"/>
        <data name="id" expr="'HelloWorld'"/>
      </datamodel>
      <onentry>
        <!-- Use <send> to run a createcall using the 
             CCXML component / Event I/O Processor -->
        <send target="ccxmlid" targettype="ccxml" event="ccxml:createcall" namelist="dest"/>
      </onentry>
      <transition event="ccxml:connection.connected">      
        <!-- Here as a platform-specific extension we use example V3 
             Custom Action Elements instead of send. -->
        <v3:form id="HelloWorld">
          <v3:block><v3:prompt>Hello World!</v3:prompt></v3:block>          
        </v3:form>
      </transition>
      <transition event="v3:HelloWorld.done">
        <!-- Here we are using the low level <send> 
             element to run a v3 form. Note that the event "v3:HelloWorld.done" 
             is assumed either to be set/sent explicitly by the v3:form code or 
             implicitly by some process outside of the v3:form -->
        <send target="v3id" targettype="v3" event="v3:formstart" namelist="src id"/>
      </transition>
      <transition event="v3:HelloWorld2.done">
        <!-- we use _eventdata to access data in the event we're processing.
             Again we assume the v3:HelloWorld2.done is set/sent from outside
             this document -->
        <ccxml:disconnect connectionid="_eventdata.connectionid"/>      
      </transition>
      <transition event="ccxml:connection.disconnected" target="Done"/>
  
      <!-- Now some transitions to handle events generated by the component -->
      <transition event="send.successful">
        <!-- Component invoked successfully. This transition has no target 
             so Test6 is not exited.
             We are just going to log that we were able to send an event. -->
        <log expr="'Event was able to be sent'"/>
      </transition>
      <transition event="error.send" target="Done">
        <!-- If we get an error event we move to the Done state that 
             is a final state. -->
        <log expr="'Sending to and External component failed'"/>
      </transition>
      <onexit>
        <log expr="'Finished with external component'"/>
      </onexit>
    </state>
    <!-- This final state is an immediate child of Main
         -  when we get here, Main.done is generated. -->
    <final id="Done"/>
    <!-- End of Main > -->
  </state>
</scxml>
Example: Test2Sub1.scxml
<?xml version="1.0" encoding="us-ascii"?>
<scxml version="1.0" xmlns="http://www.w3.org/2005/07/scxml" initialstate="Test2Sub1"> 
  <!-- 
  -

  - This is an example substate defined in
  - an external file referenced by Main.scxml. 
  -

  - an external file referenced by Main.scxml.

  -->
  <state id="Test2Sub1">
    <onentry>
      <log expr="'Inside Test2Sub1'"/>
    </onentry>
    <transition event="Event2" target="Test2Sub2"/>
  </state>
</scxml>

F.2 E.2 Shale Example

The example below, which is from the Apache Shale Project. Shale is a web application framework based on JavaServer Faces (JSF). It's composed of loosely coupled services that provide functionality such as application event callbacks, dialogs with conversation-scoped state, a view technology called Clay, annotation-based functionality to reduce configuration requirements and support for remoting. For more information on Shale please see http://shale.apache.org/ . SCXML is used as a "dialog manager" service in Shale (for details on the integration of SCXML in Shale please see http://shale.apache.org/shale-dialog-scxml/index.html ). It allows Shale application authors to express navigation across multiple JSF views and/or other conversations with users of a JSF application using the SCXML markup notation. The example below describes how the navigation across multiple JSF views can be expressed using SCXML. It also shows how a submachine (edit-profile-config.scxml) can be used within an SCXML file. The binding language used in these examples is EL [EL] , which is the expression language supported in the JSF environment.

Example: log-on-config.scxml
UML diagram for this example
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2005-2006 The Apache Software Foundation.
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
      http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  $Id: WD-scxml-20080516diff.html,v 1.1 2008/05/16 18:11:53 ashimura Exp $
-->

<!--
  Dialog definitions for Shale Use Cases Example Web Application
  written out as SCXML to demonstrate use of Commons SCXML as one
  of Shale's Dialog Manager implementations.
  Related artifacts from <dialog name="Log On">...</dialog>
  in original dialogs definition file from Shale nightlies.

  For details, see: http://shale.apache.org/shale-dialog-scxml/

-->
<scxml xmlns="http://www.w3.org/2005/07/scxml" xmlns:my="http://scxml.example.org/"
       version="1.0" initial="checkCookie" profile="el" >

<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"  
       initialstate="checkCookie">
  <state                 id="checkCookie">

  <state id="checkCookie">

    <onentry>
      <var             name="cookieOutcome"
                       expr="#{profile$logon.check}" />

      <my:var name="cookieOutcome" expr="#{profile$logon.check}" />

    </onentry>
    <transition        cond="${cookieOutcome eq 'authenticated'}"
                       target="exit"/>
    <transition        cond="${cookieOutcome eq 'unauthenticated'}"
                       target="logon"/>

    <transition cond="${cookieOutcome eq 'authenticated'}" target="exit"/>
    <transition cond="${cookieOutcome eq 'unauthenticated'}" target="logon"/>

  </state>
  <state                 id="logon">
    <transition       event="faces.outcome"
                       cond="${outcome eq 'authenticated'}"
                       target="exit"/>
    <transition       event="faces.outcome"
                       cond="${outcome eq 'create'}"
                       target="createProfile"/>

  <state id="logon">
    <transition event="faces.outcome" cond="${outcome eq 'authenticated'}" target="exit"/>
    <transition event="faces.outcome" cond="${outcome eq 'create'}" target="createProfile"/>

  </state>
  <state                 id="createProfile"
                        src="edit-profile-config.xml" >
      <transition     event="createProfile.done"
                       cond="${outcome eq 'success' or outcome eq 'cancel'}"
                       target="exit"/>

  <state id="createProfile" src="edit-profile-config.xml" >
      <transition event="createProfile.done" cond="${outcome eq 'success' or outcome eq 'cancel'}" target="exit"/>

  </state>
  <final                 id="exit"/>

  <final id="exit"/>

</scxml>
Example: edit-profile-config.scxml
UML diagram for this example
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2005-2006 The Apache Software Foundation.
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
      http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  $Id: WD-scxml-20080516diff.html,v 1.1 2008/05/16 18:11:53 ashimura Exp $
-->

<!--
  Dialog definitions for Shale Use Cases Example Web Application
  written out as SCXML to demonstrate use of Commons SCXML as one
  of Shale's Dialog Manager implementations.
  Related artifacts from <dialog name="Edit Profile">...</dialog>
  in original dialogs definition file from Shale nightlies.

  For details, see: http://shale.apache.org/shale-dialog-scxml/

-->
<scxml xmlns="http://www.w3.org/2005/07/scxml" xmlns:my="http://scxml.example.org/"
       version="1.0" initial="edit" profile="el">

<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"  
       initialstate="edit">
  <state                id="edit">

  <state id="edit">

    <initial>
      <transition target="setup"/>
    </initial>
    <!-- global transitions (within state "edit") -->
    <transition event="faces.outcome" cond="${outcome eq 'cancel'}" target="cancel"/>
    <transition event="faces.outcome" cond="${outcome eq 'finish'}" target="finish"/>

    <transition      event="faces.outcome"
                      cond="${outcome eq 'cancel'}"
                      target="cancel"/>
    <transition      event="faces.outcome"
                      cond="${outcome eq 'finish'}"
                      target="finish"/>
    <state              id="setup">

    <state id="setup">

      <onentry>
        <var          name="setupOutcome"
                      expr="#{profile$edit.setup}" />

        <my:var name="setupOutcome" expr="#{profile$edit.setup}" />

      </onentry>
      <transition     cond="${setupOutcome eq 'success'}"
                      target="page1"/>

      <transition cond="${setupOutcome eq 'success'}" target="page1"/>

    </state>
    <state              id="page1">
      <transition    event="faces.outcome"
                      cond="${outcome eq 'next'}"
                      target="page2"/>

    <state id="page1">
      <transition event="faces.outcome" cond="${outcome eq 'next'}" target="page2"/>

    </state>
    <state              id="page2">
      <transition    event="faces.outcome"
                      cond="${outcome eq 'previous'}"
                      target="page1"/>

    <state id="page2">

      <transition    event="faces.outcome"
                      cond="${outcome eq 'next'}"
                      target="page3"/>

      <transition event="faces.outcome" cond="${outcome eq 'previous'}" target="page1"/>
      <transition event="faces.outcome" cond="${outcome eq 'next'}" target="page3"/>

    </state>
    <state              id="page3">
      <transition    event="faces.outcome"
                      cond="${outcome eq 'previous'}"
                      target="page2"/>
      <transition    event="faces.outcome"
                      cond="${outcome eq 'next'}"
                      target="editExit"/>

    <state id="page3">
      <transition event="faces.outcome" cond="${outcome eq 'previous'}" target="page2"/>
      <transition event="faces.outcome" cond="${outcome eq 'next'}" target="editExit"/>

    </state>
  </state>
  <state                id="cancel">

  <state id="cancel">

    <onentry>
      <var            name="cancelOutcome"
                      expr="#{profile$edit.cancel}" />

  <onentry>
      <my:var name="cancelOutcome" expr="#{profile$edit.cancel}" />

    </onentry>
    <transition       cond="${cancelOutcome eq 'success'}" target="editExit">
      <var            name="outcome"
                      expr="cancel"/>

    <transition cond="${cancelOutcome eq 'success'}" target="editExit">
      <my:var name="outcome" expr="cancel"/>

    </transition>
  </state> 
  <state                id="finish">

  <state id="finish">

    <onentry>
      <var            name="finishOutcome"
                      expr="#{profile$edit.finish}" />

      <my:var name="finishOutcome" expr="#{profile$edit.finish}" />

    </onentry>
    <transition       cond="${finishOutcome eq 'username'}"
                      target="page1"/>
    <transition       cond="${finishOutcome eq 'password'}"
                      target="page1"/>
    <transition       cond="${finishOutcome eq 'success'}" target="editExit">
      <var            name="outcome"
                      expr="success"/>

    <transition cond="${finishOutcome eq 'username'}" target="page1"/>
    <transition cond="${finishOutcome eq 'password'}" target="page1"/>
    <transition cond="${finishOutcome eq 'success'}" target="editExit">
      <my:var name="outcome" expr="success"/>

    </transition>
  </state>
  <final                id="editExit"/>

  <final id="editExit"/>

</scxml>

F.3 E.3 Examples of Invoke and finalize

The following two SCXML documents demonstrate the use of Invoke and finalize. The first example shows the control flow for a voice portal offering traffic reports.

Example: Traffic Report
<?xml version="1.0"?>
<?access-control allow="*"?>
<scxml initialstate="Intro">

<scxml version="1.0" initial="Intro" profile="ecmascript">

  <state id="Intro">
    <invoke src="dialog.vxml#Intro"/>
    <transition event="success" cond="g_DataModel.sessionChrome.playAds" target="PlayAds"/>
    <transition event="success" cond="!g_DataModel.sessionChrome.playAds &amp;&amp; g_DataModel.ANIQuality" target="ShouldGoBack"/>
    <transition event="success" cond="!g_DataModel.sessionChrome.playAds &amp;&amp; !g_DataModel.ANIQuality" target="StartOver"/>

    <invoke src="dialog.vxml#Intro" targettype="vxml2"/>
    <transition event="success" cond="_data.sessionChrome.playAds" target="PlayAds"/>
    <transition event="success" cond="!_data.sessionChrome.playAds &amp;&amp; _data.ANIQuality" 
                                        target="ShouldGoBack"/>
    <transition event="success" cond="!_data.sessionChrome.playAds &amp;&amp; !_data.ANIQuality" 
                                        target="StartOver"/>

  </state>
  <state id="PlayAds">
    <invoke src="dialog.vxml#PlayAds"/>
    <transition event="success" cond="g_DataModel.ANIQuality" target="ShouldGoBack"/>
    <transition event="success" cond="!g_DataModel.ANIQuality" target="StartOver"/>

    <invoke src="dialog.vxml#PlayAds" targettype="vxml2"/>
    <transition event="success" cond="_data.ANIQuality" target="ShouldGoBack"/>
    <transition event="success" cond="!_data.ANIQuality" target="StartOver"/>

  </state>
  <state id="StartOver">
    <onenter>
      <script>enterStartOver();</script>   

      <script>enterStartOver();</script>

    </onenter>
    <invoke src="dialog.vxml#StartOver">
      <param name="gotItFromANI" expr="g_DataModel.gotItFromANI"/>
      <finalize> 
        <script>finalizeStartOver();</script>   

    <invoke src="dialog.vxml#StartOver" targettype="vxml2">
      <param name="gotItFromANI" expr="_data.gotItFromANI"/>
      <finalize>
        <script>finalizeStartOver();</script>

      </finalize>
    </invoke>
    <transition event="success" target="ShouldGoBack"/>
    <transition event="doOver" target="StartOver"/>
    <transition event="restart" target="Intro"/> <!-- bail out to caller -->
  </state>
  <state id="ShouldGoBack">
    <invoke src="dialog.vxml#ShouldGoBack">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="gotItFromANI" expr="g_DataModel.gotItFromANI"/>
      <finalize> 
        <script>finalizeShouldGoBack();</script>   

    <invoke src="dialog.vxml#ShouldGoBack" targettype="vxml2">
      <param name="cityState" expr="_data.cityState"/>
      <param name="gotItFromANI" expr="_data.gotItFromANI"/>
      <finalize>
        <script>finalizeShouldGoBack();</script>

      </finalize>
    </invoke>
    <transition event="highWay" target="HighwayReport"/>
    <transition event="go_back" target="StartOver"/>
    <transition event="doOver" target="ShouldGoBack"/>
    <transition event="restart" target="Intro"/>
  </state>
  <state id="HighwayReport">
    <invoke src="dialog.vxml#HighwayReport">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="gotItFromANI" expr="g_DataModel.gotItFromANI"/>
      <param name="playHRPrompt" expr="g_DataModel.playHRPrompt"/>
      <param name="metroArea" expr="g_DataModel.metroArea"/>
      <finalize> 
        <script>finalizeHighwayReport();</script>   

    <invoke src="dialog.vxml#HighwayReport" targettype="vxml2">
      <param name="cityState" expr="_data.cityState"/>
      <param name="gotItFromANI" expr="_data.gotItFromANI"/>
      <param name="playHRPrompt" expr="_data.playHRPrompt"/>
      <param name="metroArea" expr="_data.metroArea"/>
      <finalize>
        <script>finalizeHighwayReport();</script>

      </finalize>
    </invoke>
    <transition event="highway" target="PlayHighway"/>
    <transition event="go_back" target="StartOver"/>
    <transition event="doOver" target="HighwayReport"/>
    <transition event="fullreport" target="FullReport"/>
    <transition event="restart" target="Intro"/>
  </state>
  <state id="FullReport">
    <invoke src="dialog.vxml#FullReport">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="metroArea" expr="g_DataModel.metroArea"/>
      <finalize> 
        <script>finalizeFullReport();</script>   

    <invoke src="dialog.vxml#FullReport" targettype="vxml2">
      <param name="cityState" expr="_data.cityState"/>
      <param name="metroArea" expr="_data.metroArea"/>
      <finalize>
        <script>finalizeFullReport();</script>

      </finalize>
    </invoke>
    <transition event="go_back" target="HighwayReport"/>
    <transition event="new_city" target="StartOver"/>
  </state>
  <state id="PlayHighway">
    <invoke src="dialog.vxml#PlayHighway">
      <param name="cityState" expr="g_DataModel.cityState"/>
      <param name="curHighway" expr="g_DataModel.curHighway"/>
      <finalize> 
        <script>finalizePlayHighway();</script>   

    <invoke src="dialog.vxml#PlayHighway" targettype="vxml2">
      <param name="cityState" expr="_data.cityState"/>
      <param name="curHighway" expr="_data.curHighway"/>
      <finalize>
        <script>finalizePlayHighway();</script>

      </finalize>
    </invoke>
    <transition event="go_back" target="HighwayReport"/>
  </state>
</scxml>

The following example shows a the control flow for a blackjack game.

Example: Blackjack
<?xml version="1.0"?>
<?access-control allow="*"?>
<scxml initialstate="master">
<state id="master">

<scxml version="1.0" profile="ecmascript" initial="master"> <state id="master">

    <initial id="init1">
      <transition target="_home"/>
    </initial>
    <transition event="new_dealer" target="NewDealer"/>
    <transition event="mumble" target="_home"/> <!-- bail out to caller -->
    <transition event="silence" target="_home"/> <!-- bail out to caller -->
    <state id="_home">
      <onenter>
        <script>
        g_DataModel = {};

        _data = {};

        </script>
      </onenter>    
      <invoke src="datamodel.v3#InitDataModel">

      </onenter>
      <invoke src="datamodel.v3#InitDataModel" targettype="vxml3">

        <finalize>
          <script>
          var n;
          for (n in g_InvokeResults) {
              g_DataModel[n] = g_InvokeResults[n];

          for (n in event) {
              _data[n] = event[n];

          }
          </script>
        </finalize>
      </invoke>
      <transition event="success" target="Welcome"/>
    </state>
    <state id="Welcome">
      <invoke src="dialog.vxml#Welcome">
        <param name="skinpath" expr="g_DataModel.skinpath"/>

      <invoke src="dialog.vxml#Welcome" targettype="vxml3">
        <param name="skinpath" expr="_data.skinpath"/>

      </invoke>
      <transition event="success" target="Intro2"/>
    </state>
    <state id="Intro2">
      <invoke src="dialog.vxml#Intro2">
        <param name="skinpath" expr="g_DataModel.skinpath"/>

      <invoke src="dialog.vxml#Intro2" targettype="vxml3">
        <param name="skinpath" expr="_data.skinpath"/>

      </invoke>
      <transition event="success" target="EvalDeal"/>
    </state>
    <state id="EvalDeal">
      <onenter>
        <script>enterEvalDeal();</script>
      </onenter>    
      <invoke src="dialog.vxml#EvalDeal">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <param name="playercard1" expr="g_DataModel.playercard1"/>
        <param name="playercard2" expr="g_DataModel.playercard2"/>
        <param name="playertotal" expr="g_DataModel.blackjack.GetTotalOf('caller').toString()"/>
        <param name="dealercardshowing" expr="g_DataModel.dealercardshowing"/>

      </onenter>
      <invoke src="dialog.vxml#EvalDeal" targettype="vxml3">
        <param name="skinpath" expr="_data.skinpath"/>
        <param name="playercard1" expr="_data.playercard1"/>
        <param name="playercard2" expr="_data.playercard2"/>
        <param name="playertotal" expr="_data.blackjack.GetTotalOf('caller').toString()"/>
        <param name="dealercardshowing" expr="_data.dealercardshowing"/>

      </invoke>
      <transition event="success" target="AskHit"/>
    </state>
    <state id="AskHit">
      <invoke src="dialog.vxml#AskHit">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <finalize> 
          <script>finalizeAskHit();</script>   

      <invoke src="dialog.vxml#AskHit" targettype="vxml3">
        <param name="skinpath" expr="_data.skinpath"/>
        <finalize>
          <script>finalizeAskHit();</script>

        </finalize>
      </invoke>
      <transition event="hit" target="PlayNewCard"/>
      <transition event="stand" target="PlayDone"/>
    </state>
    <state id="PlayNewCard">
      <invoke src="dialog.vxml#PlayNewCard">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <param name="playernewcard" expr="g_DataModel.playernewcard"/>
        <param name="playertotal" expr="g_DataModel.blackjack.GetTotalOf('caller').toString()"/>

      <invoke src="dialog.vxml#PlayNewCard" targettype="vxml3">
        <param name="skinpath" expr="_data.skinpath"/>
        <param name="playernewcard" expr="_data.playernewcard"/>
        <param name="playertotal" expr="_data.blackjack.GetTotalOf('caller').toString()"/>

      </invoke>
      <transition event="success" cond="g_DataModel.blackjack.GetTotalOf('caller') &gt;= 21" target="PlayDone"/>      
      <transition event="success" target="AskHit"/> <!-- less than 21 --> 

      <transition event="success" cond="_data.blackjack.GetTotalOf('caller') &gt;= 21" target="PlayDone"/>
      <transition event="success" target="AskHit"/> <!-- less than 21 -->

    </state>
    <state id="PlayDone">
      <onenter>
        <script>enterPlayDone();</script>
      </onenter>    
      <invoke src="dialog.vxml#PlayDone">
        <param name="skinpath" expr="g_DataModel.skinpath"/>
        <param name="gameresult" expr="g_DataModel.blackjack.GetGameResult()"/>
        <param name="dealertotal" expr="g_DataModel.blackjack.GetTotalOf('dealer').toString()"/>

      </onenter>
      <invoke src="dialog.vxml#PlayDone" targettype="vxml3">
        <param name="skinpath" expr="_data.skinpath"/>
        <param name="gameresult" expr="_data.blackjack.GetGameResult()"/>
        <param name="dealertotal" expr="_data.blackjack.GetTotalOf('dealer').toString()"/>

      </invoke>
      <transition event="playagain" target="Intro2"/>
      <transition event="quit" target="_home"/>      

      <transition event="quit" target="_home"/>

    </state>
    <state id="NewDealer">
      <onenter>
       <script>enterNewDealer();</script>
      </onenter>
      <invoke src="dialog.vxml#Dummy"/>
      <transition event="success" target="Welcome"/>    

      <invoke src="dialog.vxml#Dummy" targettype="vxml3"/>
      <transition event="success" target="Welcome"/>

    </state>
  </state>
</scxml>

E.4 Custom Action Elements

Custom Action Elements can be defined in other specifications/namespaces and are responsible for performing actions on behalf of custom components. Logically Custom Action Elements can be thought of as a collection of actions and handlers to perform specific tasks. An example of this is a CCXML <accept> element that is a Custom Action Element:


<transition event="ccxml:connection.alerting">
  <ccxml:accept connectionid="eventdata.connectionid"/>
</transition>

This could be written using a <send> element using the following syntax:


<datamodel>
<data name="connectionid"/>
</datamodel>
<transition event="ccxml:connection.alerting">
  <assign name="connectionid" expr="eventdata.connectionid"/>
  <send targettype="ccxml" event="ccxml:accept" namelist="connectionid"/>
</transition>

A more complicated example might be a CCXML <createcall> where you are both providing variables and getting values back that using only the <send> syntax would be more complex as it would need to be broken over several steps. For example:


<onentry>
  <ccxml:createcall dest="'tel:+18315552020'" connectionid="myConnectionID"/> 
</onentry>

Would need to be modeled in two steps using <send> as you would need to do something like the following:


<datamodel>
  <data name="dest" expr="'tel:+18315552020'"/>
  <data name="connectionid"/>
</datamodel>
<onentry>
  <send targettype="ccxml" event="ccxml:createcall" namelist="dest"/>
</onentry>
<transition event="ccxml:createcall.success">
   <assign name="connectionid" expr="eventdata.connectionid"/>
</transition>

The exact mappings between Custom Action Elements and <send> actions are to be defined in the individual Custom Action Element specifications.

F Conformance

A SCXML 1.0 processor is a user agent that can parse and process Conforming SCXML 1.0 documents.

In a Conforming SCXML 1.0 Processor, the XML parser must be able to parse and process all well-formed XML constructs defined within [XML] and [XMLNames] .It is not required that a Conforming SCXML 1.0 processor use a validating parser.

Conformance in SCXML is defined with respect to profiles. A Conforming SCXML 1.0 Processor that supports a given profile must support the syntax and semantics of all SCXML elements in that profile as described in this document. Consequently, a SCXML 1.0 Processor must not throw an error.unsupported.<element> for any SCXML element in that profile when processing a Conforming SCXML 1.0 Document.

When a Conforming SCXML 1.0 Processor encounters a Conforming SCXML 1.0 Document with non-SCXML elements or attributes which are proprietary, or defined in a non-SCXML namespace, and which cannot be processed, the processor's behavior is defined by the value of the 'exmode' attribute in the root <scxml> element of the document. If 'exmode' is strict, the processor must throw an error.badfetch event. If 'exmode' is 'lax', the processor must ignore the element.

When a Conforming SCXML 1.0 Processor encounters a document with a root element designating a namespace other than SCXML, its behavior is undefined.

When a conforming SCXML 1.0 Processor encounters a document with a root element of <scxml> with a version attribute with a value other than 1.0, its behavior is undefined.

There is, however, no conformance requirement with respect to performance characteristics of the SCXML 1.0 Processor.

G References

CSS2
Cascading Style Sheets, level 2: CSS2 Specification . . B. Bos, et al., Editors. World Wide Web Consortium, 12 May 1998. This version of the CSS2 Recommendation is http://www.w3.org/TR/1998/REC-CSS2-19980512/. The latest version of CSS2 is available at http://www.w3.org/TR/REC-CSS2/. (See http://www.w3.org/TR/1998/REC-CSS2-19980512/.)
OASIS ebXML
ebXML Business Process Specification Schema v2.0 . . (See http://www.oasis-open.org/committees/documents.php?wg_abbrev=ebxml-bp.)
ECMAScript ECMASCRIPT-262
ECMA Script ECMAScript Language Specification Standard ECMA-262, 3rd Edition, December 1999. (See http://www.ecma-international.org/publications/standards/Ecma-262.htm.)
ECMASCRIPT-327
ECMAScript 3rd Edition Compact Profile Standard ECMA-327, July 2001. (See http://www.ecma-international.org/publications/standards/Ecma-327.htm.)
E4X
ECMAScript for XML (E4X) Specification Standard ECMA-357, 2nd Edition, December 2005. (See http://www.ecma-international.org/publications/standards/Ecma-357.htm.)
EL
EL: The JSP 2.0 Expression Language Interpreter (See http://jakarta.apache.org/commons/el/.)
Harel and Politi
Modeling Reactive Systems with Statecharts: The STATEMATE Approach By D. Harel and M. Politi. McGraw-Hill, 1998. (See http://www.wisdom.weizmann.ac.il/~dharel/reactive_systems.html.)
IETF RFC 2119
RFC 2119: Key words for use in RFCs to Indicate Requirement Levels . . Internet Engineering Task Force, 1997. (See http://www.ietf.org/rfc/rfc2119.txt.)
IETF RFC 2396
RFC 2396: Uniform Resource Identifiers . . Internet Engineering Task Force, 1995. (See http://www.ietf.org/rfc/rfc2396.txt.)
W3C CCXML 1.0
Voice Browser Call Control: CCXML Version 1.0 . . W3C, 2005. (See http://www.w3.org/TR/2005/WD-ccxml-20050111/.)
W3C MMI Multimodal Architecture and Interfaces Working Draft . W3C, 2006. (See http://www.w3.org/TR/mmi-arch/.) W3C VoiceXML 2.0 VoiceXML 2.0: Format for Literal IPv6 Addresses in URL's . W3C, 2004. (See http://www.w3.org/TR/VoiceXML20.) UML 2.0 UML Specification Version 2.0 . OMG. (See http://www.omg.org/#UML2.0.) <a id="XMI" name="XMI"