\documentclass[10pt]{scrartcl}

\usepackage[paper=a4paper,margin=1.2cm]{geometry}
\usepackage[colorlinks=true,linkcolor=black]{hyperref}
\usepackage{fancyvrb}

%---------------------------------------------------------------------------%
% \comment{} provides a mechanism for people to make comments about this
% document.  For comments that have been resolved, but we want to keep a
% record of the reasoning behind the decision, we have \resolvedcomment{}.
%
% Set these macros to 'true' or 'false' to control whether (a) unresolved
% comments are shown, and (b) resolved-but-kept comments are shown.
%
\newcommand{\pjs}[1]{\textcolor{blue}{PJS:#1}}
\newcommand{\gt}[1]{\textcolor{green}{GT:#1}}
\newcommand{\showcomments}{true}
\newcommand{\showresolvedcomments}{false}
%\newcommand{\showcomments}{false}
%\newcommand{\showcomments}{true}
\newcommand{\ignore}[1]{}
%---------------------------------------------------------------------------%

\input{common-spec.tex}
\input{version.tex}

%-----------------------------------------------------------------------------%
\newcommand{\underscore}{\texttt{\n{}}}

%-----------------------------------------------------------------------------%

\newcommand{\TyThing}[1]{\vspace{1.2mm}\noindent\emph{#1} }
\newcommand{\TyOverview}{\TyThing{Overview.}}
\newcommand{\TyInsts}{\TyThing{Allowed Insts.}}
\newcommand{\TySyntax}{\TyThing{Syntax.}}
\newcommand{\TyFiniteType}{\TyThing{Finite?}}
\newcommand{\TyVarifiable}{\TyThing{Varifiable?}}
\newcommand{\TyOrdering}{\TyThing{Ordering.}}
\newcommand{\TyInit}{\TyThing{Initialisation.}}
\newcommand{\TyCoercions}{\TyThing{Coercions.}}

\newcommand{\coerce}[2]{#1 $\stackrel{c}{\rightarrow}$ #2}
\newcommand{\varify}[2]{#1 $\stackrel{v}{\rightarrow}$ #2}


\newcommand{\vblabel}[1]	{\large\textbf{#1}}
\newcommand{\vbcmd}		{>}
\newcommand{\vbout}		{\slshape}

\DefineVerbatimEnvironment{Zinc}{Verbatim}
    {samepage,frame=single,framesep=0.25em,xleftmargin=0.15em,xrightmargin=0.15em}
\DefineVerbatimEnvironment{Shell}{Verbatim}
    {xleftmargin=0.15em,commandchars=\\\{\}}

\title{\textbf{Specification of MiniZinc}}

\author{The MiniZinc Team\\[2ex]
Data61/CSIRO\\
Monash University\\
The University of Melbourne\\
Melbourne, Australia}

% Original authors:
% Nicholas Nethercote, Kim Marriott, Reza Rafeh, Mark Wallace
% and Maria Garcia de la Banda

\date{November 2016\\
{\small (MiniZinc version \mznversion)}}

\sloppy

\pagestyle{plain}


\begin{document}

\maketitle
\thispagestyle{empty}

%---------------------------------------------------------------------------%
% The grammar
%---------------------------------------------------------------------------%
% We define the productions here so they can appear twice in the text --
% once in the appropriate section, and again when the whole grammar is
% presented in the appendix.  They're listed here in the same order as in
% the appendix.

%---------------------------------------------------------------------------%
% Items
%---------------------------------------------------------------------------%
\newcommand{\RuleModel}{
\production{model}
    \maybe{\semicolons{\nt{item}}}
}
\newcommand{\RuleItem}{
\production{item}
%    \nt{type-inst-syn-item}
%\alt\nt{enum-item}
%\alt
\nt{include-item}
\alt\nt{var-decl-item}
\alt\nt{assign-item}
\alt\nt{constraint-item}
\alt\nt{solve-item}
\alt\nt{output-item}
\alt\nt{predicate-item}
\alt\nt{test-item}
\alt\nt{function-item}
\alt\nt{annotation-item}
}

\newcommand{\RuleTypeInstSynItem}{
\production{type-inst-syn-item}
    \term{type} \nt{ident} \nt{annotations} \term{=} \nt{ti-expr}
    % Undefined types are currently not implemented.
    % \term{type} \nt{ident} \maybe{\term{=} \nt{ti-expr}}
}

\newcommand{\RuleEnumItem}{
\production{enum-item}
    \term{enum} \nt{ident} \nt{annotations} \maybe{\term{=} \nt{enum-cases}}
}
\newcommand{\RuleEnumCases}{
\production{enum-cases}
    \curlies{\commas{\nt{ident}}}
}

\newcommand{\RuleIncludeItem}{
\production{include-item}
    \term{include} \nt{string-literal}
}

\newcommand{\RuleVarDeclItem}{
\production{var-decl-item}
    \nt{ti-expr-and-id} \nt{annotations}
        \maybe{\term{=} \nt{expr}}
}

\newcommand{\RuleAssignItem}{
\production{assign-item}
    \nt{ident} \term{=} \nt{expr}
}

\newcommand{\RuleConstraintItem}{
\production{constraint-item}
    \term{constraint} \nt{expr}
}

\newcommand{\RuleSolveItem}{
\production{solve-item}
    \term{solve} \nt{annotations} \term{satisfy}
\alt\term{solve} \nt{annotations} \term{minimize} \nt{expr}
\alt\term{solve} \nt{annotations} \term{maximize} \nt{expr}
}

\newcommand{\RuleOutputItem}{
\production{output-item}
    \term{output} \nt{expr}
}

\newcommand{\RuleAnnotationItem}{
\production{annotation-item}
    \term{annotation} \nt{ident} \nt{params}
}

\newcommand{\RulePredicateItem}{
\production{predicate-item}
    \term{predicate} \nt{operation-item-tail}
}
\newcommand{\RuleTestItem}{
\production{test-item}
    \term{test} \nt{operation-item-tail}
}
\newcommand{\RuleFunctionItem}{
\production{function-item}
    \term{function} \nt{ti-expr} \term{:} \nt{operation-item-tail}
}
\newcommand{\RuleOperationItemTail}{
\production{operation-item-tail}
    \nt{ident} \nt{params} \nt{annotations} \maybe{\term{=} \nt{expr}}
}
\newcommand{\RuleParams}{
\production{params}
    \maybe{\parens{\commas{\nt{ti-expr-and-id}}}}
}
\newcommand{\RuleTIExprAndId}{
\production{ti-expr-and-id}
    \nt{ti-expr} \term{:} \nt{ident}
}

%---------------------------------------------------------------------------%
% Type-insts
%---------------------------------------------------------------------------%
\newcommand{\RuleTIExpr}{
\production{ti-expr}
%    \parens{\nt{ti-expr} \term{:} \nt{ident} \term{where} \nt{expr}}
%\alt
\nt{base-ti-expr}
}
\newcommand{\RuleVarPar}{
\production{var-par}
    \term{var} \altB \term{par} \altB \ensuremath{\epsilon}
}
\newcommand{\RuleBaseTIExpr}{
\production{base-ti-expr}
    \nt{var-par} \nt{base-ti-expr-tail}
}
\newcommand{\RuleBaseTIExprTail}{
\production{base-ti-expr-tail}
    \nt{ident}
\alt\term{bool}
\alt\term{int}
\alt\term{float}
\alt\term{string}
\alt\nt{set-ti-expr-tail}
\alt\nt{array-ti-expr-tail}
%\alt\nt{tuple-ti-expr-tail}
%\alt\nt{record-ti-expr-tail}
%\alt\nt{ti-variable-expr-tail}
\alt\term{ann}
\alt\term{opt} \nt{base-ti-expr-tail}
%\alt\nt{op-ti-expr-tail}
\alt\curlies{\commas{\nt{expr}}}
\alt\dotdotXX{\nt{num-expr}}
}

\newcommand{\RuleTIVariableExprTail}{
\production{ti-variable-expr-tail}
    %\maybe{\term{any}} 
    \regexp{\$[A-Za-z][A-Za-z0-9\n{}]*}
}

\newcommand{\RuleSetTIExprTail}{
\production{set-ti-expr-tail}
    \term{set} \term{of} \nt{base-type}
}

\newcommand{\RuleArrayTIExprTail}{
\production{array-ti-expr-tail}
    \term{array} \squares{\commas{\nt{ti-expr}}} \term{of} \nt{ti-expr}
\alt\term{list} \term{of} \nt{ti-expr}
}

\newcommand{\RuleTupleTIExprTail}{
\production{tuple-ti-expr-tail}
    \term{tuple} \parens{\commas{\nt{ti-expr}}}
}

\newcommand{\RuleRecordTIExprTail}{
\production{record-ti-expr-tail}
    \term{record} \parens{\commas{\nt{ti-expr-and-id}}}
}

\newcommand{\RuleOpTIExprTail}{
\production{op-ti-expr-tail}
    \term{op} \parens{\nt{ti-expr} \term{:}
                      \parens{\commas{\nt{ti-expr}}}}
}

%---------------------------------------------------------------------------%
% Expressions
%---------------------------------------------------------------------------%
\newcommand{\RuleExpr}{
\production{expr}
    \nt{expr-atom} \nt{expr-binop-tail}
}
\newcommand{\RuleNumExpr}{
\production{num-expr}
    \nt{num-expr-atom} \nt{num-expr-binop-tail}
}
\newcommand{\RuleExprAtom}{
\production{expr-atom}
    \nt{expr-atom-head} \nt{expr-atom-tail} \nt{annotations}
}
\newcommand{\RuleNumExprAtom}{
\production{num-expr-atom}
    \nt{num-expr-atom-head} \nt{expr-atom-tail} \nt{annotations}
}
\newcommand{\RuleExprBinopTail}{
\production{expr-binop-tail}
    \maybe{\nt{bin-op} \nt{expr}}
}
\newcommand{\RuleNumExprBinopTail}{
\production{num-expr-binop-tail}
    \maybe{\nt{num-bin-op} \nt{num-expr}}
}
\newcommand{\RuleExprAtomHead}{
\production{expr-atom-head}
    \nt{builtin-un-op} \nt{expr-atom}
\alt\parens{\nt{expr}}
\alt\nt{ident-or-quoted-op}
\alt\term{\underscore}
\alt\nt{bool-literal}
\alt\nt{int-literal}
\alt\nt{float-literal}
\alt\nt{string-literal}
\alt\nt{set-literal}
\alt\nt{set-comp}
\alt\nt{simple-array-literal}
\alt\nt{simple-array-literal-2d}
\alt\nt{indexed-array-literal}
\alt\nt{simple-array-comp}
\alt\nt{indexed-array-comp}
%\alt\nt{tuple-literal}
%\alt\nt{record-literal}
%\alt\nt{enum-literal}
\alt\nt{ann-literal}
\alt\nt{if-then-else-expr}
%\alt\nt{case-expr}
\alt\nt{let-expr}
\alt\nt{call-expr}
\alt\nt{gen-call-expr}
}
\newcommand{\RuleNumExprAtomHead}{
\production{num-expr-atom-head}
    \nt{builtin-num-un-op} \nt{num-expr-atom}
\alt\parens{\nt{num-expr}}
\alt\nt{ident-or-quoted-op}
\alt\nt{int-literal}
\alt\nt{float-literal}
\alt\nt{if-then-else-expr}
\alt\nt{case-expr}
\alt\nt{let-expr}
\alt\nt{call-expr}
\alt\nt{gen-call-expr}
}
\newcommand{\RuleExprAtomTail}{
\production{expr-atom-tail}
    \ensuremath{\epsilon}
\alt\nt{array-access-tail}  \nt{expr-atom-tail}
%\alt\nt{tuple-access-tail}  \nt{expr-atom-tail}
%\alt\nt{record-access-tail} \nt{expr-atom-tail}
}

\newcommand{\RuleBuiltinOp}{
\production{builtin-op}
    \nt{builtin-bin-op}
\alt\nt{builtin-un-op}
}
\newcommand{\RuleBinOp}{
\production{bin-op}
    \nt{builtin-bin-op}
\alt\term{`}\nt{ident}\term{`}
}
\newcommand{\RuleNumBinOp}{
\production{num-bin-op}
    \nt{builtin-num-bin-op}
\alt\term{`}\nt{ident}\term{`}
}

\newcommand{\RuleBuiltinBinOp}{
\production{builtin-bin-op}
    \term{<->}   \altB\term{->}            \altB\term{<-}        \altB
    \term{\backsl{}/}    \altB\term{xor}   \altB\term{/\backsl{}}
\alt\term{<}     \altB \term{>}            \altB \term{<=}       \altB
    \term{>=}    \altB \term{==}           \altB \term{=}        \altB
    \term{!=}
\alt\term{in}    \altB \term{subset}       \altB \term{superset} \altB
    \term{union} \altB \term{diff}         \altB \term{symdiff}
\alt\term{..}    \altB                           \term{intersect}\altB
    \term{++}    \altB \nt{builtin-num-bin-op}
}
\newcommand{\RuleBuiltinNumBinOp}{
\production{builtin-num-bin-op}
    \term{+}     \altB \term{-}     \altB \term{*}        \altB
    \term{/}     \altB \term{div}   \altB \term{mod}
}

\newcommand{\RuleBuiltinUnOp}{
\production{builtin-un-op}
    \term{not} \altB \nt{builtin-num-un-op}
}
\newcommand{\RuleBuiltinNumUnOp}{
\production{builtin-num-un-op}
    \term{+} \altB \term{-}
}

\newcommand{\RuleBoolLiteral}{
\production{bool-literal}
    \term{false} \altB \term{true}
}

\newcommand{\RuleIntLiteral}{
\production{int-literal}
    \regexp{[0-9]+}
\alt\regexp{0x[0-9A-Fa-f]+}
\alt\regexp{0o[0-7]+}
}

\newcommand{\RuleFloatLiteral}{
\production{float-literal}
    \regexp{[0-9]+.[0-9]+}
\alt\regexp{[0-9]+.[0-9]+[Ee][-+]?[0-9]+}
\alt\regexp{[0-9]+[Ee][-+]?[0-9]+}
}

\newcommand{\RuleStringLiteral}{
\production{string-contents}
  \regexp{([\carat{}"\backsl{}n\term{\backsl{}}] | \term{\backsl{}}[\carat{}\backsl{}n\term{(}])*}\\\\
\production{string-literal}
    \regexp{"}\nt{string-contents}\regexp{"}
\alt\regexp{"}\nt{string-contents}\regexp{\term{\backsl{}}\term{(}} \nt{string-interpolate-tail}\\\\
\production{string-interpolate-tail}
    \nt{expr} \regexp{\term{)}}\nt{string-contents}\regexp{"}
\alt\nt{expr} \regexp{\term{)}}\nt{string-contents}\regexp{\term{\backsl{}}\term{(}} \nt{string-interpolate-tail}
}

\newcommand{\RuleSetLiteral}{
\production{set-literal}
    \curlies{\maybe{\commas{\nt{expr}}}}
}

\newcommand{\RuleSetComp}{
\production{set-comp}
    \curlies{\nt{expr} \term{\bar} \nt{comp-tail}}
}
\newcommand{\RuleCompTail}{
\production{comp-tail}
    \commas{\nt{generator}} \maybe{\term{where} \nt{expr}}
}
\newcommand{\RuleGenerator}{
\production{generator}
    \commas{\nt{ident}} \term{in} \nt{expr}
}

\newcommand{\RuleSimpleArrayLiteral}{
\production{array-literal}
    \squares{\maybe{\commas{\nt{expr}}}}
}

\newcommand{\RuleSimpleArrayLiteralTwoD}{
\production{array-literal-2d}
    \squaresPipes{\maybe{\pipes{(\commas{\nt{expr}})}}}
}

\newcommand{\RuleSimpleArrayComp}{
\production{array-comp}
    \squares{\nt{expr} \term{\bar} \nt{comp-tail}}
}

\newcommand{\RuleIndexedArrayLiteral}{
\production{indexed-array-literal}
    \squares{\maybe{\commas{\nt{index-expr}}}}
}
\newcommand{\RuleIndexExpr}{
\production{index-expr}
    \nt{expr} \term{:} \nt{expr}
}

\newcommand{\RuleIndexedArrayComp}{
\production{indexed-array-comp}
    \squares{\nt{index-expr} \term{\bar} \nt{comp-tail}}
}

\newcommand{\RuleArrayAccessTail}{
\production{array-access-tail}
    \squares{\commas{\nt{expr}}}
}

\newcommand{\RuleTupleLiteral}{
\production{tuple-literal}
    \parens{\commas{\nt{expr}}}
}

\newcommand{\RuleTupleAccessTail}{
\production{tuple-access-tail}
    \term{.} \nt{int-literal}
}

\newcommand{\RuleRecordLiteral}{
\production{record-literal}
    \parens{\commas{\nt{named-expr}}}
}
\newcommand{\RuleNamedExpr}{
\production{named-expr}
    \nt{ident} \term{:} \nt{expr}
}

\newcommand{\RuleRecordAccessTail}{
\production{record-access-tail}
    \term{.} \nt{ident}
}

\newcommand{\RuleEnumLiteral}{
\production{enum-literal}
    \nt{ident} \parens{\commas{\nt{named-expr}}}
\alt\nt{ident} \parens{\commas{\nt{expr}}}
\alt\nt{ident}
}

\newcommand{\RuleAnnLiteral}{
\production{ann-literal}
    \nt{ident} \maybe{\parens{\commas{\nt{expr}}}}
}

\newcommand{\RuleIfThenElseExpr}{
\production{if-then-else-expr}
    \term{if} \nt{expr} \term{then} \nt{expr} \spl
    \zeroOrMore{\term{elseif} \nt{expr} \term{then} \nt{expr}} \spl
    \term{else} \nt{expr} \term{endif}
}

\newcommand{\RuleCaseExpr}{
\production{case-expr}
    \term{case} \nt{expr} \curlies{\commas{\nt{case-expr-case}}}
}
\newcommand{\RuleCaseExprCase}{
\production{case-expr-case}
    \nt{ident} \term{-->} \nt{expr}
}

\newcommand{\RuleCallExpr}{
\production{call-expr}
    \nt{ident-or-quoted-op} \maybe{\parens{\commas{\nt{expr}}}}
}

\newcommand{\RuleLetExpr}{
\production{let-expr}
    \term{let} \curlies{\semicolons{\nt{let-item}}} \term{in} \nt{expr}
}

\newcommand{\RuleLetItem}{
\production{let-item}
    \nt{var-decl-item}
\alt\nt{constraint-item}
}

\newcommand{\RuleGenCallExpr}{
\production{gen-call-expr}
    \nt{ident-or-quoted-op} \parens{\nt{comp-tail}} \parens{\nt{expr}}
}

%---------------------------------------------------------------------------%
% Repeated elements
%---------------------------------------------------------------------------%
\newcommand{\RuleIdent}{
\production{ident}
    \regexp{[A-Za-z][A-Za-z0-9\n{}]*}  \quad\% excluding keywords
\alt\term{'}\regexp{[\textasciicircum '\textbackslash xa\textbackslash xd\textbackslash x0]*}\term{'}
}

\newcommand{\RuleIdentOrQuotedOp}{
\production{ident-or-quoted-op}
    \nt{ident}
\alt\term{'}\nt{builtin-op}\term{'}
}

\newcommand{\RuleAnnotations}{
\production{annotations}
    \zeroOrMore{\term{::} \nt{annotation}}
}
\newcommand{\RuleAnnotation}{
\production{annotation}
    \nt{expr-atom-head} \nt{expr-atom-tail}
}

%---------------------------------------------------------------------------%
% Output format
%---------------------------------------------------------------------------%
\newcommand{\RuleOutput}{
\production{output}
    \nt{no-solutions}  \maybe{\nt{warnings}} \nt{free-text}
\alt
    \zeroOrMore{\nt{solution}} \maybe{\nt{complete}}
    \maybe{\nt{warnings}} \nt{free-text}
}

%\newcommand{\RuleOutcome}{
%\production{outcome}
%    \nt{no-solutions} \alt
%    \nt{no-more-solutions} \alt
%    \nt{no-better-solutions}
%}

%\newcommand{\RuleCompleteness}{
%\production{completeness}
%    \nt{complete} \altB \nt{incomplete}
%}

\newcommand{\RuleSolution}{
\production{solution}
    \nt{solution-text}  \maybe{\nl}
    \term{----------} ~\nl
}

\newcommand{\RuleOutcomeStrings}{
\production{no-solutions}
    ~\texttt{=====UNSATISFIABLE=====} ~\nl
}

\newcommand{\RuleComplete}{
\production{complete}
    \texttt{==========} ~\nl
}

%\newcommand{\RuleIncomplete}{
%\production{incomplete}
%    \texttt{Search incomplete:} ~\nl~ \oneOrMore{\nt{message}}
%}

\newcommand{\RuleWarnings}{
\production{warnings}
    \oneOrMore{\nt{message}}
}

\newcommand{\RuleMessage}{
\production{message}
    \oneOrMore{\nt{line}} \\

\production{line}
    \texttt{\%} 
    \regexp{[\carat{}\backsl{}n]*} ~\nl
}

\setcounter{tocdepth}{2}

\pagebreak
\tableofcontents
\pagebreak

%===========================================================================%
\section{Introduction}
%===========================================================================%
This document defines MiniZinc, a language for modelling constraint
satisfaction and optimisation problems.

MiniZinc is a high-level, typed, mostly first-order, functional, modelling
language.  It provides:
\begin{itemize}
\item mathematical notation-like syntax (automatic coercions, overloading,
      iteration, sets, arrays);
\item expressive constraints (finite domain, set, linear arithmetic, integer);
\item support for different kinds of problems (satisfaction, explicit
      optimisation);
\item separation of data from model;
\item high-level data structures and data encapsulation (sets,
      arrays, enumerated types, constrained type-insts);
\item extensibility (user-defined functions and predicates);
\item reliability (type checking, instantiation checking, assertions);
\item solver-independent modelling;
\item simple, declarative semantics.
\end{itemize}
MiniZinc is similar to 
OPL and moves closer to CLP languages such as ECLiPSe.

This document has the following structure.
Section~\ref{Syntax Notation} introduces the syntax notation
used throughout the specification.
Section~\ref{Overview} provides a high-level overview of MiniZinc models.
Section~\ref{Syntax Overview} covers syntax basics.
Section~\ref{High-level Model Structure} covers high-level structure: items,
multi-file models, namespaces, and scopes.
Section~\ref{Types} introduces types and type-insts.
Section~\ref{Expressions} covers expressions.
Section~\ref{Items} describes the top-level items in detail.
Section~\ref{Annotations} describes annotations.
Section~\ref{Partiality} describes how partiality is handled in various
cases.
Appendix~\ref{builtins} describes the language built-ins.
% The following two appendices are commented out.
%Appendix~\ref{Libraries} describes some language libraries.
%Appendix~\ref{Standard Annotations} describes the standard language annotations.
Appendix~\ref{Grammar} gives the MiniZinc grammar.
%Appendix~\ref{MiniZinc} gives the definition of MiniZinc.
Appendix~\ref{Content-types} defines content-types used in this specification.

This document also provides some explanation of why certain design decisions
were made.  Such explanations are marked by the word ``Rationale'' and
written in italics, and do not constitute part of the specification as such.
\Rationale{These explanations are present because they are useful to both
the designers and the users of MiniZinc.}

\paragraph{Original authors.}

The original version of this document was prepared by
Nicholas Nethercote, Kim Marriott, Reza Rafeh, Mark Wallace
and Mar\'{\i}a Garc\'{\i}a de la Banda.
MiniZinc is evolving, however, and so is this document.

For a formally published paper on the MiniZinc language
and the superset Zinc language
, please see: \

N.~Nethercote, P.J. Stuckey, R.~Becket, S.~Brand, G.J. Duck, and G.~Tack.
Minizinc: Towards a standard {CP} modelling language.
In C.~Bessiere, editor, {\em Proceedings of the 13th International
  Conference on Principles and Practice of Constraint Programming}, volume 4741
  of {\em LNCS}, pages 529--543. Springer-Verlag, 2007.


K.~Marriott, N.~Nethercote, R.~Rafeh, P.J.~Stuckey,
M.~Garc\'{\i}a de la Banda, and M.~Wallace.
The Design of the Zinc Modelling Language.
\emph{Constraints}, 13(3):229-267, 2008.


%===========================================================================%
\section{Notation}
  \label{Syntax Notation}
%===========================================================================%
The basics of the EBNF used in this specification are as follows.
\CommonEBNFBasics{sep/term}

MiniZinc's grammar is presented piece-by-piece throughout this document.  It is
also available as a whole in Appendix~\ref{Grammar}.
The output grammar also includes some details of the use of whitespace.
The following conventions are used:

\begin{itemize}
\item A newline character or CRLF sequence is written \nl.
\item A sequence of space characters of length $n$ is written \spc{$n$},
e.g., \spc{2}.
\end{itemize}


%===========================================================================%
\section{Overview of a Model}
  \label{Overview}
%===========================================================================%
%---------------------------------------------------------------------------%
%---------------------------------------------------------------------------%
\CommonTwoConceptualParts{MiniZinc}
                         {The model and data may be separated, or the data
                          may be ``hard-wired'' into the model.}

There are two broad classes of problems: satisfaction and optimisation.
In satisfaction problems all solutions are considered equally good,
whereas in optimisation problems the solutions are
ordered according to an objective and
the aim is to find a solution whose objective is optimal.
Section~\ref{Solve Items} specifies how the class of problem is chosen.

%---------------------------------------------------------------------------%
\subsection{Evaluation Phases}
%---------------------------------------------------------------------------%

%\pjs{Remove the 3 evaluation phases, make it two!}
A MiniZinc model instance is evaluated in two distinct phases.
\begin{enumerate}
\item Instance-time: static checking of the model instance.
\item Run-time: evaluation of the instance (i.e.~constraint solving).
\end{enumerate}
%

The model instance may not compile due to a problem with the model and/or data,
detected at instance-time.
This could be caused by a syntax error, a type-inst error,
the use of an unsupported feature or operation, etc.
In this case the outcome of evaluation is a static error;
this must be reported prior to run-time.
The form of output for static errors is implementation-dependent,
although such output should be easily recognisable as a static error.

An implementation may produce warnings during all evaluation phases.
For example, an implementation may be able to determine that
unsatisfiable constraints exist prior to run-time,
and the resulting warning given to the user may be more helpful than
if the unsatisfiability is detected at run-time.

An implementation must produce a warning
if the objective for an optimisation problem is unbounded.


%---------------------------------------------------------------------------%
\subsection{Run-time Outcomes}
    \label{Run-time Outcomes}
%---------------------------------------------------------------------------%
Assuming there are no static errors,
the output from the run-time phase has the following abstract form:

\begin{productions}
\RuleOutput 
\end{productions}

If a solution occurs in the output
then it must be feasible.
For optimisation problems,
each solution must be strictly better than any preceding solution.

If there are no solutions in the output,
the outcome must indicate that there are no solutions.

If the search is complete the output may state this after the solutions.
The absence of the completness message indicates that the search is incomplete.

Any warnings produced during run-time must be summarised
after the statement of completeness.
In particular, if there were any warnings at all during run-time
then the summary must indicate this fact.

The implementation may produce text in any format after the warnings.
For example, it may print
a summary of benchmarking statistics or resources used.

%---------------------------------------------------------------------------%
\subsection{Output}
  \label{Output}
%---------------------------------------------------------------------------%
% \pjs{Needs a total reworking for MiniZinc!}
Implementations must be capable of producing output of content type
`application/x-zinc-output',
which is described below and also in Appendix~\ref{Content-types}.
Implementations may also produce output in alternative formats.
Any output should conform to
the abstract format from the previous section
and must have the semantics described there.

Content type `application/x-zinc-output' extends
the syntax from the previous section as follows:

\begin{productions}
\RuleSolution
\end{productions}

\noindent

The solution text for each solution must be
as described in Section~\ref{Output Items}.
A newline must be appended if the solution text does not end with a newline.
\Rationale{This allows solutions to be extracted from output
without necessarily knowing how the solutions are formatted.}
Solutions end with a sequence of ten dashes followed by a newline.

\begin{productions}
\RuleOutcomeStrings
\end{productions}

\noindent
The completness result is printed on a separate line.
\Rationale{The strings are designed to clearly indicate
the end of the solutions.}

\begin{productions}
\RuleComplete
\end{productions}

\noindent
If the search is complete, a statement corresponding to the outcome is printed.
For an outcome of no solutions
the statement is that the model instance is unsatisfiable,
for an outcome of no more solutions
the statement is that the solution set is complete,
and for an outcome of no better solutions
the statement is that the last solution is optimal.
\Rationale{These are the logical implications of a search being complete.}

\begin{productions}
\RuleWarnings \\
\\
\RuleMessage
\end{productions}

\noindent
If the search is incomplete,
one or more messages describing reasons for incompleteness may be printed.
Likewise, if any warnings occurred during search
they are repeated after the completeness message.
Both kinds of message should have lines that start with \texttt{\%}
so they are recognized as comments by post-processing.
\Rationale{This allows individual messages to be easily recognised.}

For example, the following may be output for an optimisation problem:

\begin{verbatim}
    =====UNSATISFIABLE=====
    % trentin.fzn:4: warning: model inconsistency detected before search.
\end{verbatim}

\noindent
Note that, as in this case,
an unbounded objective is not regarded as a source of incompleteness.


%===========================================================================%
\section{Syntax Overview}
  \label{Syntax Overview}
%===========================================================================%
\CommonCharacterSetAndComments{MiniZinc}

%---------------------------------------------------------------------------%
\subsection{Identifiers}
     \label{Identifiers}
%---------------------------------------------------------------------------%
Identifiers have the following syntax:
\begin{productions}
    \RuleIdent
\end{productions}
For example:
\begin{verbatim}
    my_name_2
    MyName2
    'An arbitrary identifier'
\end{verbatim}
A number of keywords are reserved and cannot be used as identifiers.  The
keywords are:
\reservedKeywords{}

A number of identifiers are used for built-ins;  see Section~\ref{builtins}
for details.


%===========================================================================%
\section{High-level Model Structure}
  \label{High-level Model Structure}
%===========================================================================%
%---------------------------------------------------------------------------%
\subsection{Items}
%---------------------------------------------------------------------------%
A MiniZinc model consists of multiple \emph{items}:
\begin{productions}
    \RuleModel
\end{productions}

Items can occur in any order;  identifiers need not be declared before they
are used.

Items have the following top-level syntax:
\begin{productions}
    \RuleItem
\end{productions}

%Type-inst synonym items and enumerated type items define new types.

Include items provide a way of combining multiple files into a single
instance.  This allows a model to be split into multiple files
(Section~\ref{Include Items}).

Variable declaration items introduce new global variables and possibly
bind them to a value (Section~\ref{Declarations}).

Assignment items bind values to global variables
(Section~\ref{Assignments}).

Constraint items describe model constraints (Section~\ref{Constraint
Items}).

Solve items are the ``starting point'' of a model, and specify exactly
what kind of solution is being looked for:  plain satisfaction, or the
minimization/maximization of an expression.  Each model must have exactly
one solve item (Section~\ref{Solve Items}).

Output items are used for nicely presenting the result of a model
execution (Section~\ref{Output Items}).
%\emph{Note:} models to be converted to FlatZinc should use the built-in
%{\tt is\_output} annotation on variables rather than an output item.
%If an output item is provided, then the corresponding FlatZinc model
%should have output annotations placed on the variables appearing in the
%original output item.

Predicate items, test items (which are just a special type of predicate)
and function items introduce new user-defined predicates and
functions which can be called in expressions (Section~\ref{preds and fns}).
Predicates, functions, and built-in operators are described collectively as
\emph{operations}.

Annotation items augment the \texttt{ann} type, values of which can specify
non-declarative and/or solver-specific information in a model.

%---------------------------------------------------------------------------%
\subsection{Model Instance Files}
     \label{Model Instance Files}
%---------------------------------------------------------------------------%
MiniZinc models can be constructed from multiple files using
include items (see Section~\ref{Include Items}).  MiniZinc has no
module system as such;  all the included files are simply concatenated and
processed as a whole, exactly as if they had all been part of a single file.
\Rationale{We have not found much need for one so far.  If bigger models
become common and the single global namespace becomes a problem, this should
be reconsidered.}

Each model may be paired with one or more data files.  Data files are more
restricted than model files.  They may only contain variable assignments (see
Section~\ref{Assignments}).

Data files may not include calls to user-defined operations.

Models do not contain the names of data files; doing so would fix the data
file used by the model and defeat the purpose of allowing separate data
files.  Instead, an implementation must allow one or more data files to be
combined with a model for evaluation via a mechanism such as the
command-line.

%An implementation should allow a model to be checked with and without its
%instance data.  When checking a model without data, all global variables
%with fixed type-insts need not be assigned.  
When checking a model with
data, all global variables with fixed type-insts must be assigned, unless
they are not used (in which case they can be removed from the model without
effect).

A data file can only be checked for static errors in conjunction with a
model, since the model contains the declarations that include the types of
the variables assigned in the data file.

A single data file may be shared between multiple models, so long as the
definitions are compatible with all the models.

%---------------------------------------------------------------------------%
\subsection{Namespaces}
     \label{Namespaces}
%---------------------------------------------------------------------------%
All names declared at the top-level belong to a single namespace.
It includes the following names.
\begin{enumerate}
\item All global variable names.
\item All function and predicate names, both built-in and user-defined.
%\item All user-defined type and type-inst names (type-inst synonyms and
%      enumerated types).
\item All enumerated type names and enum case names.
\item All annotation names.
\end{enumerate}

Because multi-file MiniZinc models are composed via
concatenation (Section~\ref{Model Instance Files}), all files share
this top-level namespace.  Therefore a variable \texttt{v} declared in one
model file could not be declared with a different type in a different file,
for example.

MiniZinc supports overloading of built-in and user-defined operations.

%MiniZinc has two kinds of local namespace:  each record and (non-flat) enum
%has its own local namespace for field names.  This means distinct
%records and (non-flat) enums can use the same field names.  All names
%in these local namespaces co-exist without conflict with identical names in
%the top-level namespace---in any situation, which namespace applies can
%always be determined from context.

%---------------------------------------------------------------------------%
\subsection{Scopes}
     \label{Scopes}
%---------------------------------------------------------------------------%
Within the top-level namespace, there are several kinds of local scope that
introduce local names:
\begin{itemize}
\item Comprehension expressions (Section~\ref{Set Comprehensions}).
\item Let expressions (Section~\ref{Let Expressions}).
\item Function and predicate argument lists and bodies (Section~\ref{preds
      and fns}).
%\item Type-inst constraints (Section~\ref{Arbitrarily Constrained
%     Type-insts}).
\end{itemize}
The listed sections specify these scopes in more detail.  In each case, any
names declared in the local scope overshadow identical global names.

%===========================================================================%
\section{Types and Type-insts}
  \label{Types}
%===========================================================================%
MiniZinc provides four scalar built-in types:  Booleans, integers, floats, and
strings; enumerated types; two compound built-in types:  sets and multi-dimensional arrays;
%with arbitrary index types, tuples, and records;  and three kinds of
%user-defined annotation types: type-inst synonyms, enumerated types, and \texttt{ann},
%a user-extensible type that represents annotations.  
and the user extensible annotation type \texttt{ann}.
%Zinc also allows
%type-inst variables in certain places, and has some very limited
%higher-order types.

\CommonInstantiationTypeInstDescription{}

%Zinc also supports \emph{constrained type-insts}, which are type-insts
%with an additional expression that constrains their possible values.

We begin by discussing some properties that apply to every type.  We then
introduce instantiations in more detail.  We then cover each type
individually, giving:  an overview of the type and its possible
instantiations, the syntax for its type-insts, whether it is a finite
type (and if so, its domain), whether it is varifiable, the ordering and
equality operations, whether its variables must be initialised at
instance-time, and whether it can be involved in automatic coercions.  
%We conclude by describing Zinc's constrained type-insts.

%-----------------------------------------------------------------------------%
\subsection{Properties of Types}
%-----------------------------------------------------------------------------%
The following list introduces some general properties of MiniZinc types.
\begin{itemize}
\item Currently all types are monotypes.
%      Recursive types are not allowed.

      In the future we may allow types which are polymorphic
      in other types and also the associated constraints.

\item We distinguish types which are \emph{finite types}.

      In MiniZinc, finite types include Booleans, %flat enums, 
      types defined
      via set expression type-insts such as range types (see
      Section~\ref{Set Expression Type-insts}), as well as sets and arrays,
      %tuples, records and non-flat enums 
      composed of finite types.  Types
      that are not finite types are unconstrained integers, unconstrained
      floats, unconstrained strings, and \texttt{ann}.  Finite types are
      relevant to sets (Section~\ref{Sets}) and array indices
      (Section~\ref{Arrays}).

      Every finite type has a \emph{domain}, which is a set value that holds
      all the possible values represented by the type.

\item Every first-order type (this excludes \texttt{ann}) has a built-in
      total order and a built-in equality; \texttt{>}, \texttt{<},
      \texttt{==}/\texttt{=}, \texttt{!=}, \texttt{<=} and \texttt{>=}
      comparison operators can be applied to any
      pair of values of the same type.  
      \Rationale{This facilitates
      the specification of symmetry breaking and of polymorphic predicates
      and functions.}
      Note that, as in most languages, using equality on floats or types
      that contain floats is generally not reliable due to their inexact
      representation.  An implementation may choose to warn about the use of
      equality with floats or types that contain floats.

%\item Higher-order types are used in very limited ways.  They
%      can only be used with the built-in functions \texttt{foldl} and
%      \texttt{foldr}, which both take a function as their first argument.
\end{itemize}


%---------------------------------------------------------------------------%
\subsection{Instantiations}
     \label{Instantiations}
%---------------------------------------------------------------------------%
\CommonInstantiationsDescription{MiniZinc}
%%
%There are also intermediate instantiations for some compound types---they
%can have a fixed size but may contain unfixed elements.

In MiniZinc decision variables can have the following types: Booleans,
integers, floats, and sets of integers. %, and flat enums.  
%Tuples, arrays, records, non-flat
%enums 
Arrays and \texttt{ann} can contain decision variables.

%---------------------------------------------------------------------------%
\subsection{Type-insts}
     \label{Type-insts}
%---------------------------------------------------------------------------%
\CommonTypeInstDescription{}
MiniZinc allows coercions between some types as well.

Some type-insts can be \emph{varified}, i.e.~made unfixed at the top-level.
For example, \texttt{par int} is varified to \texttt{var int}.  We write this
\varify{\texttt{par int}}{\texttt{var int}}.

Type-insts that are varifiable include the type-insts of the types that can
be decision variables (Booleans, integers, floats, sets, enumerated types).
%, enumerated types), and also tuples and records, 
%if their constituent elements can be varified.
Varification is relevant to %type-inst synonyms and 
array accesses.

%---------------------------------------------------------------------------%
\subsection{Type-inst Expressions Overview}
     \label{Type-inst Expressions Overview}
%---------------------------------------------------------------------------%
This section partly describes how to write type-insts in MiniZinc models.
Further details are given for each type as they are described in the
following sections.

A type-inst expression specifies a type-inst.
\resolvedcomment{zs}{
I think the debacle with declaration syntax in C has shown
that putting non-type things in type expressions is a bad idea.
}{
Since they're now type-inst declarations, hopefully that will avoid the
problems seen with C.
}

Type-inst expressions may include type-inst constraints.

Type-inst expressions appear in variable declarations
(Section~\ref{Declarations}), user-defined operation items
(Section~\ref{preds and fns}).%, and type-inst synonyms
%(Section~\ref{Type-inst Synonym Items}).

Type-inst expressions have this syntax:
\begin{productions}
    \RuleTIExpr \\
    \RuleBaseTIExpr \\
    \RuleVarPar \\
    \RuleBaseTIExprTail
\end{productions}
%The first alternative is for arbitrarily constrained type-insts, which are
%described in Section~\ref{Arbitrarily Constrained Type-insts}.

% Base type-inst expressions have the
% following syntax:
% \begin{productions}
%     \RuleBaseTIExpr \\
%     \RuleVarPar \\
%     \RuleBaseTIExprTail
% \end{productions}

(The final alternative, for range types, uses the numeric-specific
\nt{num-expr} non-terminal, defined in Section~\ref{Expressions Overview},
rather than the \nt{expr} non-terminal.  If this were not the case, the rule
would never match because the `\texttt{..}' operator would always be matched
by the first \nt{expr}.)

This fully covers the type-inst expressions for scalar types.  The compound
type-inst expression syntax is covered in more detail in
Section~\ref{Built-in Compound Types}.  
%Type-inst variable syntax is
%described in more detail in Section~\ref{Type-inst Variables}.

%The constrained type-inst expressions are covered in more
%detail in Section~\ref{Constrained Type-insts}.

The \texttt{par} and \texttt{var} keywords (or lack of them) determine the
instantiation.  The \texttt{par} annotation can be omitted;  the following
two type-inst expressions are equivalent:
\begin{verbatim}
    par int
    int
\end{verbatim}

\Rationale{The use of the explicit \texttt{var} keyword allows an
implementation to check that all parameters are initialised in the model or
the instance.  It also clearly documents which variables are parameters, and
allows more precise type-inst checking.}

A type-inst is fixed if it does not contain \texttt{var} or \texttt{any},
with the exception of \texttt{ann}.

Note that several type-inst expressions that are syntactically expressible
represent illegal type-insts.  For example, although the grammar allows
\texttt{var} in front of all these base type-inst expression tails, it is a
type-inst error to have \texttt{var} in the front of a string or array
%, tuple, record, or type-inst variable type-inst 
expression.

%-----------------------------------------------------------------------------%
\subsection{Built-in Scalar Types and Type-insts}
     \label{Built-in Scalar Types}
%-----------------------------------------------------------------------------%
%---------------------------------------------------------------------------%
\subsubsection{Booleans}
%---------------------------------------------------------------------------%
\TyOverview
Booleans represent truthhood or falsity.  \Rationale{Boolean values are
not represented by integers.
Booleans can be explicit converted to
integers with the \texttt{bool2int} function, which makes the user's intent
clear.}

\TyInsts
Booleans can be fixed or unfixed.

\TySyntax
Fixed Booleans are written \texttt{bool} or \texttt{par bool}.  Unfixed
Booleans are written as \texttt{var bool}.

\TyFiniteType
Yes.  The domain of a Boolean is \texttt{\{false, true\}}.

\TyVarifiable
\varify{\texttt{par bool}}{\texttt{var bool}},
\varify{\texttt{var bool}}{\texttt{var bool}}.

\TyOrdering
The value \texttt{false} is considered smaller than \texttt{true}.

\TyInit
A fixed Boolean variable must be initialised at instance-time;  an unfixed
Boolean variable need not be.

\TyCoercions
\coerce{\texttt{par bool}}{\texttt{var bool}}.

Also Booleans can be automatically coerced to integers; see
Section~\ref{Integers}.  

% [this was relevant when operators like '<' were treated as
% left-associative.  Now that they are treated as non-associative, "0 < x < 10"
% is a syntax error]
%Booleans are not automatically coercible to 0-1 integers.
%\begin{RationaleEnv}
%This could be useful, but it is also dangerous.  In particular, a user might
%mean to write this:
%\begin{verbatim}
%    constraint 0 < x /\ x < 10;
%\end{verbatim}
%but instead write this:
%\begin{verbatim}
%    constraint 0 < x < 10;
%\end{verbatim}
%This would be parsed and implicitly coerced like this:
%\begin{verbatim}
%    constraint coerce(bool, int, 0 < x) < 10;
%\end{verbatim}
%which always succeeds.  Given that Zinc is quite high-level and
%mathematical, it would be very easy for a user to assume that they can write
%\texttt{0 < x < 10} and end up with a very subtle defect in their model.
%Furthermore, the \texttt{bool2int} built-in function lets a user explicitly
%coerce Booleans to integers easily.
%\end{RationaleEnv}

%---------------------------------------------------------------------------%
\subsubsection{Integers}
\label{Integers}
%---------------------------------------------------------------------------%
\TyOverview
\CommonIntegersOverview{}

\TyInsts
Integers can be fixed or unfixed.

\TySyntax
Fixed integers are written \texttt{int} or \texttt{par int}.  Unfixed
integers are written as \texttt{var int}.

\TyFiniteType
Not unless constrained by a set expression (see Section~\ref{Set Expression
Type-insts}).

\TyVarifiable
\varify{\texttt{par int}}{\texttt{var int}},
\varify{\texttt{var int}}{\texttt{var int}}.

\TyOrdering
The ordering on integers is the standard one.

\TyInit
A fixed integer variable must be initialised at instance-time;  an unfixed
integer variable need not be.

\TyCoercions
\coerce{\texttt{par int}}{\texttt{var int}},
\coerce{\texttt{par bool}}{\texttt{par int}},
\coerce{\texttt{par bool}}{\texttt{var int}},
\coerce{\texttt{var bool}}{\texttt{var int}}.

Also, integers can be automatically coerced to floats;  see
Section~\ref{Floats}.

%---------------------------------------------------------------------------%
\subsubsection{Floats}
        \label{Floats}
%---------------------------------------------------------------------------%
\TyOverview
\CommonFloatsOverview{}

\TyInsts
Floats can be fixed or unfixed.

\TySyntax
Fixed floats are written \texttt{float} or \texttt{par float}.  Unfixed
floats are written as \texttt{var float}.

\TyFiniteType
Not unless constrained by a set expression (see Section~\ref{Set Expression
Type-insts}).

\TyVarifiable
\varify{\texttt{par float}}{\texttt{var float}},
\varify{\texttt{var float}}{\texttt{var float}}.

\TyOrdering
The ordering on floats is the standard one.

\TyInit
A fixed float variable must be initialised at instance-time;  an unfixed
float variable need not be.

\TyCoercions
\coerce{\texttt{par int}}{\texttt{par float}},
\coerce{\texttt{par int}}{\texttt{var float}},
\coerce{\texttt{var int}}{\texttt{var float}},
\coerce{\texttt{par float}}{\texttt{var float}}.

%---------------------------------------------------------------------------%
\subsubsection{Enumerated Types}
        \label{Enumerated Types}
%---------------------------------------------------------------------------%
\TyOverview
Enumerated types (or \emph{enums} for short) provide a set of named
alternatives. Each alternative is identified by its \emph{case name}.
Enumerated types, like in many other languages, can be used in the place of
integer types to achieve stricter type checking.

\TyInsts
Enums can be fixed or unfixed.

\TySyntax
Variables of an enumerated type named ``X'' are represented by the term
\texttt{X} or \texttt{par X} if fixed, and \texttt{var X}
if unfixed.

\TyFiniteType
Yes.

The domain of an enum is the set containing all of its case names.

\TyVarifiable
\varify{\texttt{par X}}{\texttt{var X}},
\varify{\texttt{var X}}{\texttt{var X}}.

\TyOrdering
When two enum values with different case names are compared, the value with
the case name that is declared first is considered smaller than the value
with the case name that is declared second.

\TyInit
A fixed enum variable must be initialised at instance-time; an unfixed
enum variable need not be.

\TyCoercions
\coerce{\texttt{par X}}{\texttt{par int}}, \coerce{\texttt{var X}}{\texttt{var int}}.

%---------------------------------------------------------------------------%
\subsubsection{Strings}
%---------------------------------------------------------------------------%
\TyOverview
Strings are primitive, i.e.~they are not lists of characters.

String expressions are used in assertions, output items and
annotations, and string literals are used in include items.

\TyInsts
Strings must be fixed.

\TySyntax
Fixed strings are written \texttt{string} or \texttt{par string}.

\TyFiniteType
Not unless constrained by a set expression (see Section~\ref{Set Expression
Type-insts}).

\TyVarifiable
No.

\TyOrdering
Strings are ordered lexicographically using the underlying character codes.

\TyInit
A string variable (which can only be fixed) must be initialised at
instance-time.

\TyCoercions
None automatic.  However, any non-string value can be manually converted to
a string using the built-in \texttt{show} function or using string interpolation (see Section~\ref{String Interpolation Expressions}).

%---------------------------------------------------------------------------%
\subsection{Built-in Compound Types and Type-insts}
     \label{Built-in Compound Types}
%---------------------------------------------------------------------------%
%---------------------------------------------------------------------------%
\subsubsection{Sets}
        \label{Sets}
%---------------------------------------------------------------------------%
\TyOverview
A set is a collection with no duplicates.

\TyInsts
The type-inst of a set's elements must be fixed.  \Rationale{This is because
current solvers are not powerful enough to handle sets containing decision
variables.}
Sets may contain any type, and may be fixed or unfixed.
If a set is unfixed, its elements must be finite, unless it occurs in one
of the following contexts:
\begin{itemize}
\item the argument of a predicate, function or annotation.
\item the declaration of a variable or let local variable with an
      assigned value.
\end{itemize}

\TySyntax
A set base type-inst expression tail has this syntax:
\begin{productions}
    \RuleSetTIExprTail
\end{productions}
Some example set type-inst expressions:
\begin{verbatim}
    set of int
    var set of bool
\end{verbatim}

\TyFiniteType
Yes, if the set elements are finite types.  Otherwise, no.

The domain of a set type that is a finite type is the powerset of the domain
of its element type.  For example, the domain of \texttt{set of 1..2} is
\texttt{powerset(1..2)}, which is \verb+{{}, {1}, {1,2}, {2}}+.

\TyVarifiable
\varify{\texttt{par set of TI}}{\texttt{var set of TI}},
\varify{\texttt{var set of TI}}{\texttt{var set of TI}},

\TyOrdering
%The pre-defined ordering on sets is the lexicographic ordering on the
%corresponding \emph{characteristic arrays}.  For example,
%\begin{verbatim}
%     {}   <   {2}  <  {1,3}
%\end{verbatim}
%since
%\begin{verbatim}
%  [0,0,0] < [0,1,0] < [1,0,1].
%\end{verbatim}
%
%MiniZinc:
% \pjs{Better check that this is what we actually want!}
The pre-defined ordering on sets is a lexicographic ordering of the
\emph{sorted set form}, where \{1,2\} is in sorted set form, for example,
but \{2,1\} is not.
This means, for instance, \verb'{} < {1,3} < {2}'.

%\Rationale{The order based on the characteristic array
%seems easier to propagate well (as it reduces to the array case)
%than the perhaps more natural one based on the sorted set form.}

\TyInit
A fixed set variable must be initialised at instance-time;  an unfixed
set variable need not be.

\TyCoercions
\coerce{\texttt{par set of TI}}{\texttt{par set of UI}} and
\coerce{\texttt{par set of TI}}{\texttt{var set of UI}} and
\coerce{\texttt{var set of TI}}{\texttt{var set of UI}}, if
\coerce{\texttt{TI}}{\texttt{UI}}.

%\pjs{Is this true for MiniZinc?}
%Fixed sets can be automatically coerced to arrays;  see
%section~\ref{Arrays}.  This means that array accesses can be used on fixed
%sets; \texttt{S[1]} is the smallest element in a fixed set \texttt{S} while
%\texttt{S[card(S)]} is the largest.

%---------------------------------------------------------------------------%
\subsubsection{Arrays}
        \label{Arrays}
%---------------------------------------------------------------------------%
\TyOverview
MiniZinc arrays are maps from fixed integers to values.  
Values can be of any type.  
%When used with integer keys, Zinc arrays
%can be used like arrays in languages like Java, but with other types of key
%they act like associative arrays.  Using floats or types containing floats
%as keys can be dangerous because of their imprecise equality comparison, and
%an implementation may give a warning in this case.  
The values can only have base type-insts.  
Arrays-of-arrays are not allowed.
Arrays can be multi-dimensional.

MiniZinc arrays can be declared in two different ways.
\begin{enumerate}
\item
    \emph{Explicitly-indexed} arrays have index types in the declaration
    that are finite types.  For example:
\begin{verbatim}
  array[0..3] of int: a1;
  array[1..5, 1..10] of var float: a5;
\end{verbatim}
    For such arrays, the index type specifies exactly the indices that will
    be in the array---the array's index set is the \emph{domain} of the
    index type---and if the indices of the value assigned do not match then
    it is a run-time error.

    For example, the following assignments cause run-time errors:
\begin{verbatim}
  a1 = [4,6,4,3,2];   % too many elements
  a5 = [];            % too few elements
\end{verbatim}

\item
    \emph{Implicitly-indexed} arrays have index types in the declaration
    that are not finite types.  For example:
\begin{verbatim}
  array[int,int] of int: a6;
\end{verbatim}
    No checking of indices occurs when these variables are assigned.
\end{enumerate}

In MiniZinc all index sets of an array must be contiguous ranges of integers, or enumerated types. The expression used for initialisation of
an array must have matching index sets. An array expression with an enum
index set can be assigned to an array declared with an integer index set,
but not the other way around. The exception are array literals, which can
be assigned to arrays declared with enum index sets.
For example:
\begin{verbatim}
  enum X = {A,B,C};
  enum Y = {D,E,F};
  array[X] of int: x = array1d(X, [5,6,7]); % correct
  array[Y] of int: y = x;                   % index set mismatch: Y != X
  array[int] of int: z = x;                 % correct: assign X index set to int
  array[X] of int: x2 = [10,11,12];         % correct: automatic coercion for array literals
\end{verbatim}

The initialisation of an array can be done in a separate assignment
statement, which may be present in the model or a separate data file.

Arrays can be accessed.  See Section~\ref{Array Access Expressions} for
details.

\TyInsts
An array's size must be fixed.  Its indices must also have
fixed type-insts.  Its elements may be fixed or unfixed.

\TySyntax
An array base type-inst expression tail has this syntax:
\begin{productions}
    \RuleArrayTIExprTail
\end{productions}
Some example array type-inst expressions:
\begin{verbatim}
    array[1..10] of int
    list of var int
\end{verbatim}
Note that \texttt{list of <T>} is just syntactic sugar for
\texttt{array[int] of <T>}.  \Rationale{Integer-indexed arrays of this form
are very common, and so worthy of special support to make things easier for
modellers.  Implementing it using syntactic sugar avoids adding an extra
type to the language, which keeps things simple for implementers.}

Because arrays must be fixed-size it is a type-inst error to precede an
array type-inst expression with \texttt{var}.

% \pjs{Introduce the $index:value$ as a notation to explain arrays?}
% Syntactic sugar exists for declaring tuple-indexed arrays.  For example,
% the second of the following two declarations is syntactic sugar for the
% first.
% \begin{verbatim}
%     array[tuple(1..5, 1..4)] of int: a5;
%     array[1..5, 1..4]        of int: a5;
% \end{verbatim}

\TyFiniteType
Yes, if the index types and element type are all finite types.
Otherwise, no.

The domain of an array type that is a finite array is the set of all
distinct arrays whose index set equals the domain of the index type
and whose elements are of the array element type.
% For example, the domain of
% \texttt{array[5..6] of 1..2} is
% \verb+{[5:1,6:1], [5:1,6:2], [5:2,6:1], [5:2,6:2]}+.

\TyVarifiable
No.

\TyOrdering
Arrays are ordered lexicographically, taking absence of a value for a given key
to be before any value for that key.  For example,
\texttt{[1, 1]} is less than
\texttt{[1, 2]}, which is less than \texttt{[1, 2, 3]} and
\texttt{array1d(2..4,[0, 0, 0])} is less than \texttt{[1, 2, 3]}.

\TyInit
An explicitly-indexed array variable must be initialised at instance-time
only if its elements must be initialised at instance time.
An implicitly-indexed array variable must be initialised at instance-time
so that its length and index set is known.

\TyCoercions
%\coerce{\texttt{set of TI}}{\texttt{array[1..n] of UI}} if
%\coerce{\texttt{TI}}{\texttt{UI}}, where
%\texttt{n} is the number of elements in the set.  The elements of the
%resulting array will be in sorted order.
%This is handy for initialisation but seems a bit dangerous.
%This means that elements of fixed sets can be accessed like array elements,
%using square brackets.
\coerce{\texttt{array[TI0] of TI}}{\texttt{array[UI0] of UI}}
if \coerce{\texttt{TI}}{\texttt{UI}} and \coerce{\texttt{TI0}}{\texttt{UI0}}.

\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Tuples}
%---------------------------------------------------------------------------%
\TyOverview
Tuples are fixed-size, heterogeneous collections.  They must contain at
least two elements;  unary tuples are not allowed.

\TyInsts
Tuples may contain unfixed elements.

\TySyntax
A tuple base type-inst expression tail has this syntax:
\begin{productions}
    \RuleTupleTIExprTail
\end{productions}
An example tuple type-inst expression:
\begin{verbatim}
    tuple(int, var float)
\end{verbatim}
It is a type-inst error to precede a tuple type-inst expression with
\texttt{var}.

\TyFiniteType
Yes, if all its constituent elements are finite types.  Otherwise, no.

The domain of a tuple type that is a finite type is the Cartesian product of
the domains of the element types.  For example, the domain of
\texttt{tuple(1..2, \{3,5\})} is \verb+{(1,3), (1,5), (2,3), (2,5)}+.

\TyVarifiable
Yes, if all its constituent elements are varifiable.  A tuple is varified by
varifying its constituent elements.

\TyOrdering
Tuples are ordered lexicographically.

\TyInit
A tuple variable must be initialised at instance-time if any of its
constituent elements must be initialised at instance-time.

\TyCoercions
\coerce{\texttt{tuple(TI1,...,TIn)}}{\texttt{tuple(UI1,...UIn)}}, if
\coerce{\texttt{TI1}}{\texttt{UI1}},\ldots,\coerce{\texttt{TIn}}{\texttt{UIn}}.
Also, tuples can be automatically coerced to records;  see
Section~\ref{Records} for details.

%---------------------------------------------------------------------------%
\subsubsection{Records}
        \label{Records}
%---------------------------------------------------------------------------%
\TyOverview
Records are fixed-size, heterogeneous collections.  They are similar to
tuples, but have named fields.

Field names in different records can be identical, because each record's
field names belong to a different namespace (Section~\ref{Namespaces}).

Record field order is significant;  the following two record type-insts are
distinct and do not match:
\begin{verbatim}
    record(var int: x, var int: y)
    record(var int: y, var int: x)
\end{verbatim}

\begin{RationaleEnv}
This is necessary to avoid ambiguity when tuples are coerced to records.
If field ordering did not matter, we could have this array:
\begin{small}
\begin{verbatim}
  [(x:3, y:4), (y:2, x:5), (7,8)]
\end{verbatim}
\end{small}
in which the \texttt{(7,8)} must be coerced to a record, but it is unclear
if it should become \texttt{(x:7, y:8)} or \texttt{(y:7, x:8)}.
\end{RationaleEnv}

\TyInsts
Records may contain unfixed elements.

\TySyntax
A record base type-inst expression tail has this syntax:
\begin{productions}
    \RuleRecordTIExprTail \\
    \RuleTIExprAndId
\end{productions}
An example record type-inst expression:
\begin{verbatim}
    record(int: x, int: y)
\end{verbatim}
It is a type-inst error to precede a record type-inst expression with
\texttt{var}.

\TyFiniteType
Yes, if all its constituent elements are finite types.  Otherwise, no.

The domain of a record type that is a finite type is the same as that of a
tuple type, but with the fields included.  For example, the domain of
\texttt{record(1..2:x, \{3,5\}:y)} is
\verb+{(x:1,y:3), (x:1,y:5), (x:2,y:3), (x:2,y:5)}+.

\TyVarifiable
Yes, if all its constituent elements are varifiable.  A record is varified
by varifying its constituent elements.

\TyOrdering
Records are ordered lexicographically according to the values of the fields.
The field names are irrelevant for comparisons because in order for two
records to be compared they must have the same type-inst, in which case the
field names and order must be the same.

\TyInit
A record variable must be initialised at instance-time if any of its
constituent elements must be initialised at instance-time.

\TyCoercions
\coerce{\texttt{tuple(TI1,...,TIn)}}{\texttt{record(UI1:x1,...UIn:xn)}}, if
\coerce{\texttt{TI1}}{\texttt{UI1}},\ldots,\coerce{\texttt{TIn}}{\texttt{UIn}}.
This is useful for record initialisation.  For example, we can initialise a
record of type \emph{Task} (defined in Section~\ref{Arbitrarily
Constrained Type-insts}) using:
\begin{verbatim}
    Task: T = (10,_,_);
\end{verbatim}
which initialises \texttt{duration} field with 10 and the variable
fields \texttt{start} and \texttt{finish} with `\underscore'.

Also,
\coerce{\texttt{record(TI1:x1,...,TIn:xn)}}
       {\texttt{record(UI1:x1,...UIn:xn)}}, if
\coerce{\texttt{TI1}}{\texttt{UI1}},\ldots,\coerce{\texttt{TIn}}{\texttt{UIn}}.

%---------------------------------------------------------------------------%
\subsection{User-defined Types and Type-insts}
     \label{User-defined Types}
%---------------------------------------------------------------------------%
This section introduces the properties of the user-defined types and
type-insts.  The syntax and details of the items that are used to declare
these new types are in Section~\ref{Items}.

Because these user-defined types have names, their type-inst expressions
are simple identifiers.  Syntactically, any identifier may be used as a base
type-inst expression.  However, in a valid model any identifier within a
base type-inst expression must be one of:
\begin{itemize}
%\item the name of a user-defined type or type-inst (type-inst synonym
%      or enumerated type);
\item the name of a fixed set value (Section~\ref{Set Expression Type-insts}).
\end{itemize}


%---------------------------------------------------------------------------%
\subsubsection{Type-inst Synonyms}
        \label{Type-inst Synonyms}
%---------------------------------------------------------------------------%
\TyOverview
A type-inst synonym is an alternative name for a pre-existing type-inst
which can be used interchangeably with the pre-existing type-inst.
For example, if \texttt{MyFixedInt} is a synonym for \texttt{par int} then
\texttt{MyFixedInt} can be used anywhere \texttt{par int} can, and vice versa.

\TyInsts
Preceding a type-inst synonym with \texttt{var} varifies it, unless the
type-inst is not varifiable, in which case it is a type-inst error.
Preceding a type-inst synonym with \texttt{par} has no effect---the
\texttt{par} is ignored.

\TySyntax
A type-inst synonym named ``X'' is represented by the term \texttt{X}.

\TyFiniteType
As for the pre-existing type-inst.

\TyVarifiable
Yes, if the pre-existing type-inst is varifiable.

\TyOrdering
As for the pre-existing type-inst.

\TyInit
As for the pre-existing type-inst.

\TyCoercions
As for the pre-existing type-inst.
}

%---------------------------------------------------------------------------%
\subsubsection{Option Types}
        \label{option types}
%---------------------------------------------------------------------------%
\TyOverview
Option types defined using the \texttt{opt} type constructor, define types
that may or may not be there. They are similar to \texttt{Maybe} types of
Haskell implicity adding a new value \texttt{<>} to the type.


\TyInsts
The argument of an option type must be one of the base types
\texttt{bool}, \texttt{int} or \texttt{float}.

\TySyntax
The option type is written \texttt{opt <T>} where \texttt{<T>} if one of
the three base types, or one of their constrained instances.

\TyFiniteType
Yes if the underlying type is finite, otherwise no.

\TyVarifiable
Yes.

\TyOrdering
\texttt{<>} is always less than any other value in the type.
But beware that overloading of operators like \texttt{<} is different for
option types.

\TyInit
An \texttt{opt} type variable does not need to be initialised at instance-time. An uninitialised \texttt{opt} type variable is automatically
initialised to \texttt{<>}.

\TyCoercions
\coerce{\texttt{TI}}{\texttt{opt UI}} if \coerce{\texttt{TI}}{\texttt{UI}}.

%---------------------------------------------------------------------------%
\subsubsection{The Annotation Type \texttt{ann}}
     \label{the annotation type}
%---------------------------------------------------------------------------%
\TyOverview
The annotation type, \texttt{ann}, can be used to represent arbitrary term
structures.  It is augmented by annotation items (\ref{Annotation Items}).

\TyInsts
\texttt{ann} is always considered unfixed, because it may contain unfixed
elements.  It cannot be preceded by \texttt{var}.

\TySyntax
The annotation type is written \texttt{ann}.

\TyFiniteType
No.

\TyVarifiable
No.

\TyOrdering
N/A.  Annotation types do not have an ordering defined on them.

\TyInit
An \texttt{ann} variable must be initialised at instance-time.

\TyCoercions
None.

\ignore{
%---------------------------------------------------------------------------%
\subsection{Other Types and Type-insts}
     \label{Other Types}
%---------------------------------------------------------------------------%
%---------------------------------------------------------------------------%
\subsubsection{Type-inst Variables}
        \label{Type-inst Variables}
%---------------------------------------------------------------------------%
\TyOverview
Type-inst variables allow parametric polymorphism.  They can appear in MiniZinc
predicate and function arguments and return type-insts, in let
expressions within predicate and function bodies, and in annotation
declarations;  if one is used outside a function or predicate or annotation
declaration it is a type-inst error.

\TyInsts
A type-inst variable expression consists of a type-inst variable and an
optional prefix.
Type-inst variables can be prefixed by \texttt{par}, in which case they
match any fixed type-inst;  the same is true if they lack a prefix.
%Type-inst variables can also be prefixed by \texttt{any}, in which case they
%match any first-order type-inst.

The meanings of the prefixes are discussed in further detail in
Section~\ref{Parametric Polymorphism}.

\TySyntax
A type-inst variable expression tail has this syntax:
\begin{productions}
    \RuleTIVariableExprTail
\end{productions}
Some example type-inst variable expressions:
\begin{verbatim}
    $T
    par $U3
\end{verbatim}

\TyFiniteType
No.  This is because they can be bound to any type-inst, and not all
type-insts are finite.

\TyVarifiable
No.  This is because they can be bound to any type-inst, and not all
type-insts can be varified.

\TyOrdering
Values of equal type-inst variables can be compared.  The comparison used will
be the comparison of the underlying type-insts.  This is possible because
all type-insts have a built-in ordering.

\TyInit
A variable with a type-inst variable as its type-inst (which can only
appear inside predicate and function bodies) must be initialised.

\TyCoercions
None.
%\coerce{\texttt{par \$T}}{\texttt{any \$T}}.
}
\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Higher-order Types}
        \label{Higher-order Types}
%---------------------------------------------------------------------------%
\TyOverview
Operations (e.g.~predicates) have higher-order types.  Operations can be
used as values when passed as the first argument to \texttt{foldl} or
\texttt{foldr}.  They can also be used as arguments to annotations;
annotation declarations are the only place where operation type-inst
expressions are permitted.

\TyInsts
The type-inst of a higher-order type is determined by the type-insts it can
take as its arguments, and its return type-inst.  A higher-order type value
is never considered fixed, and so cannot be used as the element of a set,
for example.

\TySyntax
An operation type-inst expression tail has this syntax:
\begin{productions}
    \RuleOpTIExprTail
\end{productions}
Some example type-inst variable expressions:
\begin{verbatim}
    op(int:(int));
    op(var bool:(float, any $T));
\end{verbatim}
Note that operation type-inst expressions cannot be written for nullary
operations (i.e.~those lacking arguments).
\Rationale{This is because it is difficult to distinguish the name of a
nullary operation from a call to it, and so passing nullary operations is
difficult.  Furthermore, they are little to no use, so they are unlikely to
be missed.}

\TyFiniteType
No.

\TyVarifiable
No.

\TyOrdering
N/A.  Higher-order types cannot be used in comparisons;  it is a run-time
error if they are.

\TyInit
N/A.  Variables cannot have higher-order types.

\TyCoercions
None.
}
%---------------------------------------------------------------------------%
\subsection{Constrained Type-insts}
     \label{Constrained Type-insts}
%---------------------------------------------------------------------------%
One powerful feature of MiniZinc is \emph{constrained type-insts}.  A
constrained type-inst is a restricted version of a \emph{base} type-inst,
i.e.~a type-inst with fewer values in its domain.

%---------------------------------------------------------------------------%
\subsubsection{Set Expression Type-insts}
        \label{Set Expression Type-insts}
%---------------------------------------------------------------------------%
Three kinds of expressions can be used in type-insts.
\begin{enumerate}
\item Integer ranges:  e.g.~\texttt{1..3}.
\item Set literals:  e.g.~\texttt{var \{1,3,5\}}.
\item Identifiers:  the name of a set parameter (which can be global,
      let-local, the argument of a predicate or function, or a generator
      value) can serve as a type-inst.
\end{enumerate}
In each case the base type is that of the set's elements, and the values
within the set serve as the domain.  For example, whereas a variable with
type-inst \texttt{var int} can take any integer value, a variable with
type-inst \texttt{var 1..3} can only take the value 1, 2 or 3.

All set expression type-insts are finite types.  Their domain is equal to
the set itself.

%---------------------------------------------------------------------------%
\subsubsection{Float Range Type-insts}
%---------------------------------------------------------------------------%
Float ranges can be used as type-insts, e.g.~\verb+1.0 .. 3.0+.  These are
treated similarly to integer range type-insts, although \verb+1.0 .. 3.0+ is
not a valid expression whereas \verb+1 .. 3+ is.

Float ranges are not finite types.

\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Arbitrarily Constrained Type-insts}
        \label{Arbitrarily Constrained Type-insts}
%---------------------------------------------------------------------------%
A more general form of constrained type-inst allows an arbitrary Boolean
\emph{type-inst constraint} expression to be applied to a \emph{base}
type-inst.

Here are two examples of arbitrarily constrained type-inst expressions.  The
first is a fixed integer in the range 1--3, and the second is an unfixed
non-negative float.
\begin{verbatim}
    (par int:   i where i in 1..3): dom;
    (var float: f where f >= 0)   : fplus;
\end{verbatim}
The base type-inst appears before the `:'.  The identifiers \texttt{i} and
\texttt{f} are local identifiers used in the Boolean expression after the
\texttt{where} keyword.  The scope of the local identifiers \texttt{i} and
\texttt{f} extends to the end of the Boolean expression after the
\texttt{where}.

An arbitrarily constrained type-inst is finite only if its base type-inst is
finite.  Its domain is that of its base type-inst, minus those elements that
do not satisfy its constraint.

Finiteness is thus the main difference between set expression
type-insts (Section~\ref{Set Expression Type-insts}) and arbitrarily
constrained type-insts.  For example, in the following three lines, the
first type-inst is equivalent to the second, with one exception.
\begin{verbatim}
    par 1..3        (par int: i where i in 1..3)
    var {1,2,3}     (var int: i where i in {1,2,3})
    MySet           (    int: i where i in MySet)
\end{verbatim}
The exception is that the type-insts on the left-hand side are finite,
whereas those on the right are non-finite.

Every float range type-inst has an equivalent arbitrarily constrained
type-inst.  For example, the following two type-insts are equivalent:
\begin{verbatim}
    1.0 .. 3.0      (float: f where 1.0 <= f /\ f <= 3.0)
\end{verbatim}

An unconstrained type-inst can be viewed as an arbitrarily constrained
type-inst with a \textit{true} constraint.  For example, the following two
type-insts are equivalent:
\begin{verbatim}
    par int
    (par int: i where true)
\end{verbatim}

The Boolean expression associated with a variable declared to have an
arbitrarily constrained type-inst is either tested at instance-time if the
variable is a parameter or else generates a constraint if it is a decision
variable.

An arbitrarily constrained type-inst is varified by varifying its base
type-inst.

Records can use type-inst constraints like other type-insts, for example:
\begin{verbatim}
    type Task = (record(int:     duration,
                        var int: start,
                        var int: finish
                       ): t where t.finish = t.start + t.duration);
\end{verbatim}

Non-flat enums can also involve type-inst constraints;  see
Section~\ref{Enum Items} for details.
}

%===========================================================================%
\section{Expressions}
  \label{Expressions}
%===========================================================================%
%---------------------------------------------------------------------------%
\subsection{Expressions Overview}
     \label{Expressions Overview}
%---------------------------------------------------------------------------%
Expressions represent values.  They occur in various kinds of items.  They
have the following syntax:
\resolvedcomment{rafe}{
    I'd like to have an `\texttt{expr where \{...\}}' construct, a la Haskell,
    where the ... could contain definitions and constraints sections.
}{
    Perhaps a good idea, but we won't do it for now because it's extra
    complexity and it's unclear how useful it will be.  Plus we have let
    expressions, which are similar.
}
\begin{productions}
    \RuleExpr \\
    \RuleExprAtom \\
    \RuleExprBinopTail \\
    \RuleExprAtomHead \\
    \RuleExprAtomTail
\end{productions}

Expressions can be composed from sub-expressions combined with operators.
All operators (binary and unary) are described in Section~\ref{Operators},
including the precedences of the binary operators.  All unary operators bind
more tightly than all binary operators.

Expressions can have one or more annotations.  Annotations bind
more tightly than unary and binary operator applications, but less tightly
than access operations and non-operator applications.  In some cases this
binding is non-intuitive.  For example, in the first three of the following
lines, the annotation \texttt{a} binds to the identifier expression
\texttt{x} rather than the operator application.  However, the fourth
line features a non-operator application (due to the single quotes around
the \texttt{not}) and so the annotation binds to the whole application.
\begin{verbatim}
    not x::a;
    not (x)::a;
    not(x)::a;
    'not'(x)::a;
\end{verbatim}
Section~\ref{Annotations} has more on annotations.

Expressions can be contained within parentheses.

The array access operations
all bind more tightly than unary and binary operators and annotations.  
%The
%access operations can be chained and they associate to the left.  For
%example, these two access operations are equivalent:
%\begin{verbatim}
%    x = a[1].field.1;
%    x = ((a[1]).field).1;
%\end{verbatim}
They are described in more detail in Sections~\ref{Array Access
Expressions}.
%, \ref{Tuple Access Expressions}, \ref{Record Access
%Expressions} and \ref{Non-flat Enum Access Expressions}.

The remaining kinds of expression atoms (from \nt{ident} to
\nt{gen-call-expr}) are described in
Sections~\ref{Identifier Expressions and Quoted Operator Expressions}--\ref{Generator Call Expressions}.

We also distinguish syntactically valid numeric expressions.  This allows
range types to be parsed correctly.
\begin{productions}
    \RuleNumExpr \\
    \RuleNumExprAtom \\
    \RuleNumExprBinopTail \\
    \RuleNumExprAtomHead \\
\end{productions}

%---------------------------------------------------------------------------%
\subsection{Operators}
     \label{Operators}
%---------------------------------------------------------------------------%
Operators are functions that are distinguished by their syntax in one or two
ways.  First, some of them contain non-alphanumeric characters that normal
functions do not (e.g.~`\texttt{+}').  Second, their application is written
in a manner different to normal functions.

We distinguish between binary operators, which can be applied in an infix
manner (e.g.~\texttt{3 + 4}), and unary operators, which can be applied in a
prefix manner without parentheses (e.g.~\texttt{not x}).  We also
distinguish between built-in operators and user-defined operators.  The
syntax is the following:
\begin{productions}
    \RuleBuiltinOp \\
    \RuleBinOp \\
    \RuleBuiltinBinOp \\
    \RuleBuiltinUnOp
\end{productions}

Again, we syntactically distinguish numeric operators.
\begin{productions}
    \RuleNumBinOp \\
    \RuleBuiltinNumBinOp \\
    \RuleBuiltinNumUnOp
\end{productions}

% \pjs{Where do we seay something about the unicode versions of these?}
Some operators can be written using their unicode symbols, which are listed in Table~\ref{bin-ops-unicode} (recall that MiniZinc input is UTF-8).

\begin{table}[t]
\centering
\begin{tabular}{lcl}
  \hline
  Operator              & Unicode symbol & UTF-8 code \\
  \hline
  \texttt{<->}          & $\leftrightarrow$ & E2~86~94\\
  \texttt{->}           & $\rightarrow$ & E2~86~92\\
  \texttt{<-}           & $\leftarrow$ & E2~86~90\\
  \texttt{not}          & $\lnot$ & C2~AC\\
  \verb+\/+          & $\lor$ & E2~88~A8\\
  \verb+/\+          & $\land$ & E2~88~A7\\
  \texttt{!=}  & $\neq$ & E2~89~A0\\
  \texttt{<=}  & $\leq$ & E2~89~A4\\
  \texttt{>=}  & $\geq$ & E2~89~A5\\
  \texttt{in}        & $\in$ & E2~88~88\\
  \texttt{subset}    & $\subseteq$ & E2~8A~86\\
  \texttt{superset}  & $\supseteq$ & E2~8A~87\\
  \texttt{union}     & $\cup$ & E2~88~AA\\
  \texttt{intersect} & $\cap$ & E2~88~A9\\
  
\end{tabular}
\caption{Unicode equivalents of binary operators.}
\label{bin-ops-unicode}
\end{table}

The binary operators are listed in Table~\ref{bin-ops}.

%-----------------------------------------------------------------------------%
\begin{table}[t]
\centering
\begin{tabular}{lll}
\hline
Symbol(s)                       & Assoc.& Prec. \\
\hline
\texttt{<->}                    & left  & 1200  \\

\texttt{->}                     & left  & 1100  \\
\texttt{<-}                     & left  & 1100  \\

\verb+\/+                       & left  & 1000  \\
\texttt{xor}                    & left  & 1000  \\

\verb+/\+                       & left  & 900   \\

\texttt{<}                      & none  & 800   \\
\texttt{>}                      & none  & 800   \\
\texttt{<=}                     & none  & 800   \\
\texttt{>=}                     & none  & 800   \\
\texttt{==},
\texttt{=}                      & none  & 800   \\
\texttt{!=}                     & none  & 800   \\

\texttt{in}                     & none  & 700   \\
\texttt{subset}                 & none  & 700   \\
\texttt{superset}               & none  & 700   \\

\texttt{union}                  & left  & 600   \\
\texttt{diff}                   & left  & 600   \\
\texttt{symdiff}                & left  & 600   \\

\texttt{..}                     & none  & 500   \\

\texttt{+}                      & left  & 400   \\
\texttt{-}                      & left  & 400   \\

\texttt{*}                      & left  & 300   \\
\texttt{div}                    & left  & 300   \\
\texttt{mod}                    & left  & 300   \\
\texttt{/}                      & left  & 300   \\
\texttt{intersect}              & left  & 300   \\

\texttt{++}                     & right & 200   \\

\texttt{`}\nt{ident}\texttt{`}  & left  & 100   \\
\hline
\end{tabular}
\caption{Binary infix operators.
A lower precedence number means tighter binding;  for example,
\texttt{1+2*3} is parsed as \texttt{1+(2*3)} because `\texttt{*}' binds
tighter than `\texttt{+}'.  Associativity indicates how chains of operators
with
equal precedences are handled; for example,
\texttt{1+2+3} is parsed as \texttt{(1+2)+3} because `\texttt{+}' is
left-associative, \texttt{a++b++c} is parsed as \texttt{a++(b++c)}
because `\texttt{++}' is right-associative, and \texttt{1<x<2} is a
syntax error because `\texttt{<}' is non-associative.}
\label{bin-ops}
\end{table}
%-----------------------------------------------------------------------------%

A user-defined binary operator is created by backquoting a normal
identifier, for example:
\begin{verbatim}
    A `min2` B
\end{verbatim}
This is a static error if the identifier is not the name of a binary
function or predicate.

The unary operators are: \texttt{+}, \texttt{-} and \texttt{not}.
User-defined unary operators are not possible.

As Section~\ref{Identifiers} explains, any built-in operator can be used as
a normal function identifier by quoting it, e.g:~\texttt{'+'(3, 4)} is
equivalent to \texttt{3 + 4}.

The meaning of each operator is given in Section~\ref{builtins}.


%---------------------------------------------------------------------------%
\subsection{Expression Atoms}
%---------------------------------------------------------------------------%
%---------------------------------------------------------------------------%
\subsubsection{Identifier Expressions and Quoted Operator Expressions}
        \label{Identifier Expressions and Quoted Operator Expressions}
%---------------------------------------------------------------------------%
Identifier expressions and quoted operator expressions have the following
syntax:
\begin{productions}
    \RuleIdentOrQuotedOp
\end{productions}
Examples of identifiers were given in Section~\ref{Identifiers}.  The
following are examples of quoted operators:
\begin{verbatim}
    '+'
    'union'
\end{verbatim}
In quoted operators, whitespace is not permitted between either quote
and the operator.  Section~\ref{Operators} lists MiniZinc's built-in operators.

Syntactically, any identifier or quoted operator can serve as an expression.
However, in a valid model any identifier or quoted operator serving as an
expression must be the name of a variable.
% one of:
% \begin{itemize}
% \item the name of a variable;
% %\item an enum case name (if it has no arguments);
% \item the name of a predicate, function or operator (but only
%       as the first argument to \texttt{foldl} or \texttt{foldr}, or as an
%       argument in an annotation literal;  see Section~\ref{Higher-order Types});
% %\item the name of (or a synonym of) a flat enum;
% \item a synonym of a fixed set type defined using a range
%       expression or a literal set expression.
% \end{itemize}
%Thus some types can serve as set values: enums, synonyms of enums, and
%synonyms of fixed set types defined using a range expression or a literal
%set expression.

%---------------------------------------------------------------------------%
\subsubsection{Anonymous Decision Variables}
        \label{Anonymous Decision Variables}
%---------------------------------------------------------------------------%
There is a special identifier, `\underscore', that represents an unfixed,
anonymous decision variable.  It can take on any type that can be a decision
variable.  It is particularly useful for initialising decision variables
within compound types.  For example, in the following array the first and
third elements are fixed to 1 and 3 respectively and the second and fourth
elements are unfixed:
\begin{verbatim}
    array[1..4] of var int: xs = [1, _, 3, _];
\end{verbatim}

Any expression that does not contain `\underscore' and does not involve
decision variables is fixed.

%---------------------------------------------------------------------------%
\subsubsection{Boolean Literals}
%---------------------------------------------------------------------------%
Boolean literals have this syntax:
\begin{productions}
    \RuleBoolLiteral
\end{productions}

%---------------------------------------------------------------------------%
\subsubsection{Integer and Float Literals}
%---------------------------------------------------------------------------%
There are three forms of integer literals---decimal, hexadecimal, and
octal---with these respective forms:
\begin{productions}
    \RuleIntLiteral
\end{productions}
For example: \texttt{0}, \texttt{005}, \texttt{123}, \texttt{0x1b7},
\texttt{0o777};  but not \texttt{-1}.

Float literals have the following form:
\begin{productions}
    \RuleFloatLiteral
\end{productions}
For example: \texttt{1.05}, \texttt{1.3e-5}, \texttt{1.3+e5};  but not
\texttt{1.}, \texttt{.5}, \texttt{1.e5}, \texttt{.1e5}, \texttt{-1.0},
\texttt{-1E05}.
A `\texttt{-}' symbol preceding an integer or float literal is parsed as a
unary minus (regardless of intervening whitespace), not as part of the
literal.  This is because it is not possible in general to distinguish a
`\texttt{-}' for a negative integer or float literal from a binary minus
when lexing.

%---------------------------------------------------------------------------%
\subsubsection{String Literals}
%---------------------------------------------------------------------------%
\CommonStringLiterals{}
Long string literals can be split across multiple lines using string
concatenation.  For example:
\begin{verbatim}
    string: s = "This is a string literal "
             ++ "split across two lines.";
\end{verbatim}

%---------------------------------------------------------------------------%
\subsubsection{Set Literals}
        \label{Set Literals}
%---------------------------------------------------------------------------%
Set literals have this syntax:
\begin{productions}
    \RuleSetLiteral
\end{productions}
For example:
\begin{verbatim}
    { 1, 3, 5 }
    { }
    { 1, 2.0 }
\end{verbatim}

The type-insts of all elements in a literal set must be the same, or
coercible to the same type-inst (as in the last example above, where the
integer \texttt{1} will be coerced to a \texttt{float}).

%---------------------------------------------------------------------------%
\subsubsection{Set Comprehensions}
        \label{Set Comprehensions}
%---------------------------------------------------------------------------%
Set comprehensions have this syntax:
\begin{productions}
    \RuleSetComp \\
    \RuleCompTail \\
    \RuleGenerator
\end{productions}
For example (with the literal equivalent on the right):
\begin{verbatim}
    { 2*i | i in 1..5 }     % { 2, 4, 6, 8, 10 }
    {  1  | i in 1..5 }     % { 1 }   (no duplicates in sets)
\end{verbatim}
The expression before the `\texttt{|}' is the \emph{head expression}.  The
expression after the \texttt{in} is a \emph{generator expression}.
%
Generators can be restricted by a \emph{where-expression}.  For example:
\begin{verbatim}
    { i | i in 1..10 where (i mod 2 = 0) }     % { 2, 4, 6, 8, 10 }
\end{verbatim}
%
When multiple generators are present, the right-most generator acts as the
inner-most one.  For example:
\begin{verbatim}
    { 3*i+j | i in 0..2, j in {0, 1} }    % { 0, 1, 3, 4, 6, 7 }
\end{verbatim}
%%
The scope of local generator variables is given by the following rules:
\begin{itemize}
\item They are visible within the head expression (before the `\texttt{|}').
\item They are visible within the where-expression.
\item They are visible within generator expressions in any subsequent
      generators.
\end{itemize}
The last of these rules means that the following set comprehension is allowed:
\begin{verbatim}
    { i+j | i in 1..3, j in 1..i }  % { 1+1, 2+1, 2+2, 3+1, 3+2, 3+3 }
\end{verbatim}

A generator expression must be an array or a fixed set.

\Rationale{For set comprehensions, set generators would suffice, but for
array comprehensions, array generators are required for full expressivity
(e.g.~to provide control over the order of the elements in the resulting
array).  Set comprehensions have array generators for consistency with array
comprehensions, which makes implementations simpler.}

The where-expression (if present) must be Boolean.  
It can be var, in which case the type of the comprehension is lifted to an optional type.  Only one
where-expression per comprehension is allowed.

\begin{RationaleEnv}
Allowing one where-expression per generator is another possibility, and one
that could seemingly result in more efficient evaluation in some cases.  For
example, consider the following comprehension:
\begin{verbatim}
    [f(i, j) | i in A1, j in A2 where p(i) /\ q(i,j)]
\end{verbatim}
If multiple where-expressions were allowed, this could be expressed more
efficiently in the following manner, which avoids the fruitless ``inner loop
iterations'' for each ``outer loop iteration'' that does not satisfy
\texttt{p(i)}:
\begin{verbatim}
    [f(i, j) | i in A1 where p(i), j in A2 where q(i,j)]
\end{verbatim}
However, this efficiency can also be achieved with nested comprehensions:
\begin{verbatim}
    [f(i, j) | i in [k | k in A1 where p(k)], j in A2 where q(i,j)]
\end{verbatim}
Therefore, a single where-expression is all that is supported.
\end{RationaleEnv}

%---------------------------------------------------------------------------%
\subsubsection{Array Literals}
        \label{Array Literals}
%---------------------------------------------------------------------------%
Array literals have this syntax:
\begin{productions}
    \RuleSimpleArrayLiteral
\end{productions}
For example:
\begin{verbatim}
    [1, 2, 3, 4]
    []
    [1, _]
\end{verbatim}

In a array literal all elements must have the same type-inst, or
be coercible to the same type-inst (as in the last example above, where the
fixed integer \texttt{1} will be coerced to a \texttt{var int}).

The indices of a array literal are implicitly $1..n$, where $n$ is
the length of the literal.

%---------------------------------------------------------------------------%
\subsubsection{2d Array Literals}
        \label{2d Array Literals}
%---------------------------------------------------------------------------%
Simple 2d array literals have this syntax:
\begin{productions}
    \RuleSimpleArrayLiteralTwoD
\end{productions}
For example:
\begin{verbatim}
    [| 1, 2, 3
     | 4, 5, 6
     | 7, 8, 9 |]       % array[1..3, 1..3]
    [| x, y, z |]       % array[1..1, 1..3]
    [| 1 | _ | _ |]     % array[1..3, 1..1]
\end{verbatim}

In a 2d array literal, every sub-array must have the same length.

In a 2d array literal all elements must have the same type-inst, or
be coercible to the same type-inst (as in the last example above, where the
fixed integer \texttt{1} will be coerced to a \texttt{var int}).

The indices of a 2d array literal are implicitly $(1,1)..(m,n)$,
where $m$ and $n$ are determined by the shape of the literal.

\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Indexed Array Literals}
        \label{Indexed Array Literals}
%---------------------------------------------------------------------------%
Indexed array literals have this syntax:
\begin{productions}
    \RuleIndexedArrayLiteral \\
    \RuleIndexExpr
\end{productions}
For example:
\begin{verbatim}
    [1:1, 2:4, 3:3, 4:10, 5:5]
\end{verbatim}
The expressions before the colon are keys, those after are values.

In an indexed array literal all keys must have the same type-inst or be
coercible to the same type-inst, and all values must have the same
type-inst or be coercible to the same type-inst.

The keys need not be specified in order.
}

%---------------------------------------------------------------------------%
\subsubsection{Array Comprehensions}
        \label{Array Comprehensions}
%---------------------------------------------------------------------------%
Array comprehensions have this syntax:
\begin{productions}
    \RuleSimpleArrayComp
\end{productions}
For example (with the literal equivalents on the right):
\begin{verbatim}
    [2*i | i in 1..5]       % [2, 4, 6, 8, 10]
\end{verbatim}

Array comprehensions have more flexible type and inst requirements than set
comprehensions (see Section~\ref{Set Comprehensions}).

Array comprehensions are allowed over a variable set with finite type, the
result is an array of optional type, with length equal to the 
cardinality of the upper bound of the variable set.
For example:
\begin{verbatim}
    var set of 1..5: x;
    array[int] of var opt int: y = [ i * i | i in x ];
\end{verbatim}
The length of array will be 5. 

Array comprehensions are allowed where the where-expression is a \texttt{var
  bool}. Again the resulting array is of optional type, and of length
equal to that given by the generator expressions.
For example:
\begin{verbatim}
   var int x;
   array[int] of var opt int: y = [ i | i in 1..10 where i != x ];
\end{verbatim}
The length of the array wtill be 10.

The indices of an evaluated simple array comprehension are implicitly
$1..n$, where $n$ is the length of the evaluated comprehension.

\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Indexed Array Comprehensions}
        \label{Indexed Array Comprehensions}
%---------------------------------------------------------------------------%
Indexed array comprehensions have this syntax:
\begin{productions}
    \RuleIndexedArrayComp
\end{productions}
For example (with the literal equivalent on the right):
\begin{verbatim}
    [i:2*i | i in 1..4]             % [1:2, 2:4, 3:6, 4:8]
\end{verbatim}

Simple array comprehensions have the same type and inst requirements as set
comprehensions (see Section~\ref{Set Comprehensions}).

The keys need not be computed in order.
}

%---------------------------------------------------------------------------%
\subsubsection{Array Access Expressions}
        \label{Array Access Expressions}
%---------------------------------------------------------------------------%
% XXX: say that an out-of-bounds array access causes a static(?) error,
% similar to tuples and records.

Array elements are accessed using square brackets after an expression:
\begin{productions}
    \RuleArrayAccessTail
\end{productions}
For example:
\begin{verbatim}
    int: x = a1[1];
\end{verbatim}

If all the indices used in an array access are fixed, the type-inst of the
result is the same as the element type-inst.  However, if any
indices are not fixed, the type-inst of the result is the varified element
type-inst.  For example, if we have:
\begin{verbatim}
   array[1..2] of int: a2 = [1, 2];
   var int: i;
\end{verbatim}
then the type-inst of \texttt{a2[i]} is \texttt{var int}.  If the element type-inst
is not varifiable, such an access causes a static error.

Multi dimensional arrays 
are accessed using comma separated indices.
%Syntactic sugar exists for accessing tuple-indexed arrays.  For example,
%the second of the following two accesses is syntactic sugar for the first.
\begin{verbatim}
    array[1..3,1..3] of int: a3;
    int: y = a3[1, 2];
\end{verbatim}

Indices must match the index set type of the array. For example, an array declared with an enum index set can only be accessed using indices from that
enum.
\begin{verbatim}
    enum X = {A,B,C};
    array[X] of int: a4 = [1,2,3];
    int: y = a4[1];                  % wrong index type
    int: z = a4[B];                  % correct
\end{verbatim}

%Array accesses can be chained to access arrays-of-arrays, and sub-arrays can
%be extracted from arrays-of-arrays, as the following two examples show.
%\begin{verbatim}
%    array[1..2] of array[1..3] of int: a4;
%    int: y = a4[1][2];
%    array[1..3] of int: a5 = a4[1];
%\end{verbatim}

\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Tuple Literals}
%---------------------------------------------------------------------------%
A tuple literal has this syntax:
\begin{productions}
    \RuleTupleLiteral
\end{productions}
For example:
\begin{verbatim}
    (1, 2.0)
\end{verbatim}
Tuple literals must have at least two elements.  A tuple literal with
a single element is not actually a tuple literal, but rather just a
normal expression with parentheses around it.

% [pjs wants tuple pattern matching, at least for generators]

%---------------------------------------------------------------------------%
\subsubsection{Tuple Access Expressions}
        \label{Tuple Access Expressions}
%---------------------------------------------------------------------------%
Tuple fields are accessed by using a `.'\ and the field number after a tuple
expression:
\begin{productions}
    \RuleTupleAccessTail
\end{productions}
For example, this expression:
\begin{verbatim}
    (3, 4.0).1
\end{verbatim}
has the value 3.  Access of a non-existent field number results in a static
error.

%---------------------------------------------------------------------------%
\subsubsection{Record Literals}
        \label{Record Literals}
%---------------------------------------------------------------------------%
A record literal has this syntax:
\begin{productions}
    \RuleRecordLiteral \\
    \RuleNamedExpr
\end{productions}
For example:
\begin{verbatim}
    Task: t = ( duration:10, start:_, finish:_ );
\end{verbatim}

%---------------------------------------------------------------------------%
\subsubsection{Record Access Expressions}
        \label{Record Access Expressions}
%---------------------------------------------------------------------------%
Record fields are accessed by using a `.'\ and the field name after a record
expression:
\begin{productions}
    \RuleRecordAccessTail
\end{productions}
For example:
\begin{verbatim}
    int: d = t.duration;
\end{verbatim}
Access of a non-existent field name results in a static error.


%---------------------------------------------------------------------------%
\subsubsection{Enum Literals}
        \label{Enum Literals}
%---------------------------------------------------------------------------%
An enum literal has one of the following forms:
\begin{productions}
    \RuleEnumLiteral
\end{productions}
Flat enum literals obviously overlap completely with identifier
expressions (see Section~\ref{Identifier Expressions and Quoted Operator
Expressions}).

Here is an example of initialising parameters of non-flat enum types:
\begin{verbatim}
    multi_point: P1 = int_point(ix:2, iy:3);
    multi_point: P2 = float_point(2.3, 5.6);
\end{verbatim}


%---------------------------------------------------------------------------%
\subsubsection{Non-flat Enum Access Expressions}
        \label{Non-flat Enum Access Expressions}
%---------------------------------------------------------------------------%
Enum fields are accessed like record fields, with a `.'.  However, enum
field access expressions are only allowed within case expressions (described
in Section~\ref{Case Expressions}).  This makes it harder to access a field
that does not exist in a particular non-flat enum value.  If such an access
does occur, it is a run-time error.
}

%---------------------------------------------------------------------------%
\subsubsection{Annotation Literals}
%---------------------------------------------------------------------------%
Literals of the \texttt{ann} type have this syntax:
\begin{productions}
    \RuleAnnLiteral
\end{productions}
For example:
\begin{verbatim}
    foo
    cons(1, cons(2, cons(3, nil)))
\end{verbatim}

There is no way to inspect or deconstruct annotation literals in a MiniZinc
model;  they are intended to be inspected only by an implementation, e.g.~to
direct compilation.

%---------------------------------------------------------------------------%
\subsubsection{If-then-else Expressions}
%---------------------------------------------------------------------------%
MiniZinc provides if-then-else expressions, which provide selection from two
alternatives based on a condition.  They have this syntax:
\begin{productions}
    \RuleIfThenElseExpr
\end{productions}
For example:
\begin{verbatim}
    if x <= y then x else y endif
    if x < 0 then -1 elseif x > 0 then 1 else 0 endif
\end{verbatim}
The presence of the \texttt{endif} avoids possible ambiguity when an
if-then-else expression is part of a larger expression.

The type-inst of the ``if'' expression must be \texttt{par bool} or
\texttt{var bool}.
%  In the future we may allow it to also be \texttt{var bool}.  
The ``then'' and
``else'' expressions must have the same type-inst, or be coercible to the
same type-inst, which is also the type-inst of the whole expression.

If the ``if'' expression is \texttt{var bool} then the type-inst of the
``then'' and ``else'' expressions must be varifiable.

If the ``if'' expression is \texttt{par bool} then 
evaluation of if-then-else expressions is lazy---the condition is evaluated,
and then only one of the ``then'' and ``else'' branches are evaluated,
depending on whether the condition succeeded or failed. 
This is not the case if it is \texttt{var bool}.

\ignore{
%---------------------------------------------------------------------------%
\subsubsection{Case Expressions}
        \label{Case Expressions}
%---------------------------------------------------------------------------%
Zinc provides case expressions for handling the different cases in an
enum.

Case expressions have this syntax:
\resolvedcomment{pjs}{
    I THINK WE NEED PROPER CASE EXPRESSIONS!\\
    \indent\texttt{multi\_point: r;}\\
    \indent\texttt{int M: case r \{ intp(a,\_) --> a , floatp(u,v) --> ceil(u+v) \};}}{
    Decided to keep as is for the moment, for simplicity.
}
\begin{productions}
    \RuleCaseExpr \\
    \RuleCaseExprCase
\end{productions}
For example, we can use the \texttt{multi\n{}point} record in
Section~\ref{multipoint} with the following code:
\begin{verbatim}
    multi_point: r;
    int: M = case r {
        int_point   --> r.ix,
        float_point --> 0,
    };
\end{verbatim}
The comma after the final case is optional.

The type-inst of the case selection expression must be a fixed flat enum or
a non-flat enum.

The type-inst of every result expression must be the same, or be coercible
to the same type-inst, which is also the type-inst of the whole expression.

It is a static error if any case name is not covered by the case statement.

Currently MiniZinc does not support pattern matching.  This may be supported in
the future.
}

%---------------------------------------------------------------------------%
\subsubsection{Let Expressions}
        \label{Let Expressions}
%---------------------------------------------------------------------------%
Let expressions provide a way of introducing local names for one or more
expressions and local constraints
that can be used within another expression.  They are
particularly useful in user-defined operations.

Let expressions have this syntax:
\begin{productions}
    \RuleLetExpr \\
    \RuleLetItem
\end{productions}
For example:
\begin{verbatim}
    let { int: x = 3, int: y = 4; } in x + y;
    let { var int: x; 
          constraint x >= y /\ x >= -y /\ (x = y \/ x = -y); } 
    in x 
\end{verbatim}
The scope of a let local variable covers:
\begin{itemize}
\item The type-inst and initialisation expressions of any subsequent variables
      within the let expression (but not the variable's own initialisation
      expression).
\item The expression after the \texttt{in}, which is parsed as greedily as
      possible.
\end{itemize}
A variable can only be declared once in a let expression.

Thus in the following examples the first is acceptable but the rest are not:
\begin{verbatim}
    let { int: x = 3; int: y = x; } in x + y;  % ok
    let { int: y = x; int: x = 3; } in x + y;  % x not visible in y's defn.
    let { int: x = x; } in x;                  % x not visible in x's defn.
    let { int: x = 3; int: x = 4; } in x;      % x declared twice
\end{verbatim}

The type-inst expressions can include type-inst variables if the let is
within a function or predicate body in which the same type-inst variables
were present in the function or predicate signature.

The initialiser for a let local variable can be omitted only if the variable
is a decision variable.  For example:
\begin{verbatim}
    let { var int: x; } in ...;    % ok
    let {     int: x; } in ...;    % illegal
\end{verbatim}

The type-inst of the entire let expression is the type-inst of the expression
after the \texttt{in} keyword.

There is a complication involving let expressions in negative contexts.  A
let expression occurs in a negative context if it occurs in an expression
of the form \texttt{not X}, \texttt{X <-> Y}, or in the sub-expression
\texttt{X} in \texttt{X -> Y} or \texttt{Y <- X}, or in a subexpression 
\texttt{bool2int(X)}.

If a let expression is used in a negative context, then any let-local
decision variables must be defined only in terms of non-local variables and
parameters.  This is because local variables are implicitly existentially
quantified, and if the let expression occurred in a negative context then
the local variables would be effectively universally quantified which is not
supported by MiniZinc.

Constraints in let expressions float to the nearest enclosing Boolean
context.  For example
\begin{verbatim}
     constraint b -> x + let { var 0..2: y; constraint y != -1;} in y >= 4;
\end{verbatim}
is equivalent to
\begin{verbatim}
     var 0..2: y;
     constraint b -> (x + y >= 4 /\ y != 1);
\end{verbatim} 

%---------------------------------------------------------------------------%
\subsubsection{Call Expressions}
%---------------------------------------------------------------------------%
Call expressions are used to call predicates and functions.

Call expressions have this syntax:
\begin{productions}
    \RuleCallExpr
\end{productions}
For example:
\begin{verbatim}
    x = min(3, 5);
\end{verbatim}

The type-insts of the expressions passed as arguments must match the
argument types of the called predicate/function.  The return type of the
predicate/function must also be appropriate for the calling context.

Note that a call to a function or predicate with no arguments is
syntactically indistinguishable from the use of a variable, and so must be
determined during type-inst checking.

Evaluation of the arguments in call expressions is strict---all arguments
are evaluated before the call itself is evaluated.  Note that this includes
Boolean operations such as \verb+/\+, \verb+\/+, \texttt{->} and \texttt{<-}
which could be lazy in one argument.  The one exception is \texttt{assert},
which is lazy in its third argument (Section~\ref{Other Operations}).

\Rationale{Boolean operations are strict because: (a) this minimises
exceptional cases;  (b) in an expression like \texttt{A -> B}, where
\texttt{A} is not fixed and \texttt{B} causes an abort, the appropriate
behaviour is unclear if laziness is present;  and (c) if a user needs
laziness, an if-then-else can be used.}

The order of argument evaluation is not specified.  \Rationale{Because MiniZinc
is declarative, there is no obvious need to specify an evaluation order, and
leaving it unspecified gives implementors some freedom.}

%---------------------------------------------------------------------------%
\subsubsection{Generator Call Expressions}
        \label{Generator Call Expressions}
%---------------------------------------------------------------------------%
MiniZinc has special syntax for certain kinds of call expressions which makes
models much more readable.

Generator call expressions have this syntax:
\begin{productions}
    \RuleGenCallExpr
\end{productions}
%
A generator call expression \texttt{P(Gs)(E)} is equivalent to the call
expression \texttt{P([E | Gs])}.
For example, the expression:
\begin{verbatim}
    forall(i,j in Domain where i<j)
        (noattack(i, j, queens[i], queens[j]));
\end{verbatim}
(in a model specifying the N-queens problem) is equivalent to:
\begin{verbatim}
    forall( [ noattack(i, j, queens[i], queens[j])
            | i,j in Domain where i<j ] );
\end{verbatim}

The parentheses around the latter expression are mandatory;  this avoids
possible confusion when the generator call expression is part of a larger
expression.

The identifier must be the name of a unary predicate or function that takes
an array argument.

The generators and where-expression (if present) have the same requirements
as those in array comprehensions (Section~\ref{Array Comprehensions}).

%---------------------------------------------------------------------------%
\subsubsection{String Interpolation Expressions}
        \label{String Interpolation Expressions}
%---------------------------------------------------------------------------%
A string expression can contain an arbitrary MiniZinc expression, which will be converted to a string similar to the builtin \texttt{show} function and inserted into the string.

String interpolation has the following syntax:
\begin{productions}
  \RuleStringLiteral
\end{productions}

For example:
\begin{verbatim}
  var set of 1..10: q;
  solve satisfy;
  output [show("The value of q is \(q), and it has \(card(q)) elements.")];
\end{verbatim}

%===========================================================================%
\section{Items}
  \label{Items}
%===========================================================================%
This section describes the top-level program items.

\ignore{
%---------------------------------------------------------------------------%
\subsection{Type-inst Synonym Items}
     \label{Type-inst Synonym Items}
%---------------------------------------------------------------------------%
Type-inst synonym items have this syntax:
\begin{productions}
    \RuleTypeInstSynItem
\end{productions}
For example:
\begin{verbatim}
    type MyInt     = int;
    type FloatPlus = (float: x where x >= 0);
    type Domain    = 1..n;
\end{verbatim}

It is a type-inst error if a type-inst synonym is declared and/or defined
more than once in a model.

Type-inst synonym items can be annotated.
Section~\ref{Annotations} has more details on annotations.

All type-inst synonyms must be defined at model-time.
}

%---------------------------------------------------------------------------%
\subsection{Include Items}
     \label{Include Items}
%---------------------------------------------------------------------------%
Include items allow a model to be split across multiple files.  They have
this syntax:
\begin{productions}
    \RuleIncludeItem
\end{productions}
%%
For example:
\begin{verbatim}
    include "foo.zinc";
\end{verbatim}
includes the file \texttt{foo.zinc}.

Include items are particularly useful for accessing libraries or breaking up
large models into small pieces.  They are not, as Section~\ref{Model
Instance Files} explains, used for specifying data files.

If the given name is not a complete path then the file is searched for in an
implementation-defined set of directories.  The search directories must be
able to be altered with a command line option.

%---------------------------------------------------------------------------%
\subsection{Variable Declaration Items}
     \label{Declarations}
%---------------------------------------------------------------------------%
Variable declarations have this syntax:
\begin{productions}
    \RuleVarDeclItem
\end{productions}
For example:
\begin{verbatim}
    int: A = 10;
\end{verbatim}

It is a type-inst error if a variable is declared and/or defined more than
once in a model.

A variable whose declaration does not include an assignment can be
initialised by a separate assignment item (Section~\ref{Assignments}).  For
example, the above item can be separated into the following two items:
\begin{verbatim}
    int: A;
    ...
    A = 10;
\end{verbatim}

All variables that contain a parameter component must be defined at
instance-time.

Variables can have one or more annotations.
Section~\ref{Annotations} has more on annotations.

%---------------------------------------------------------------------------%
\subsection{Enum Items}
     \label{Enum Items}
%---------------------------------------------------------------------------%
Enumerated type items have this syntax:
\begin{productions}
    \RuleEnumItem \\
    \RuleEnumCases
\end{productions}
An example of an enum:
\begin{verbatim}
     enum country = {Australia, Canada, China, England, USA};
\end{verbatim}

Each alternative is called an \emph{enum case}.  The identifier used to name
each case (e.g.~\texttt{Australia}) is
called the \emph{enum case name}.

Because enum case names all reside in the top-level namespace
(Section~\ref{Namespaces}), case names in different enums must be distinct.

An enum can be declared but not defined, in which case it must be defined
elsewhere within the model, or in a data file.
For example, a model file could contain this:
\begin{verbatim}
    enum Workers;
    enum Shifts;
\end{verbatim}
and the data file could contain this:
\begin{verbatim}
    Workers = { welder, driller, stamper };
    Shifts  = { idle, day, night };
\end{verbatim}
Sometimes it is useful to be able to refer to one of the enum case names
within the model.  This can be achieved by using a variable.  The model
would read:
\begin{verbatim}
    enum Shifts;
    Shifts: idle;            % Variable representing the idle constant.
\end{verbatim}
and the data file:
\begin{verbatim}
    enum Shifts = { idle_const, day, night };
    idle = idle_const;      % Assignment to the variable.
\end{verbatim}
Although the constant \texttt{idle\n{}const} cannot be mentioned in the
model, the variable \texttt{idle} can be.

All enums must be defined at instance-time.

Enum items can be annotated.
Section~\ref{Annotations} has more details on annotations.

Each case name can be coerced automatically to the integer corresponding to its index in the type.
\begin{verbatim}
  int: oz = Australia;  % oz = 1
\end{verbatim}

For each enumerated type $T$, the following functions exist:

\begin{verbatim}
  % Return next greater enum value of x in enum type X
  function T: enum_next(set of T: X, T: x);
  function var T: enum_next(set of T: X, var T: x);
  
  % Return next smaller enum value of x in enum type X
  function T: enum_prev(set of T: X, T: x);
  function var T: enum_prev(set of T: X, var T: x);

  % Convert x to enum type X
  function T: to_enum(set of T: X, int: x);
  function var T: to_enum(set of T: X, var int: x);
\end{verbatim}

% For each enumerated type $T$ MiniZinc automatically creates the function
% \begin{verbatim}
%     toInt(T):int
% \end{verbatim}
% which maps elements to their index in $T$.

%---------------------------------------------------------------------------%
\subsection{Assignment Items}
     \label{Assignments}
%---------------------------------------------------------------------------%
Assignments have this syntax:
\begin{productions}
    \RuleAssignItem
\end{productions}
%%
For example:
\begin{verbatim}
    A = 10;
\end{verbatim}

% \pjs{Add something about automatic coercion of index sets?}

%---------------------------------------------------------------------------%
\subsection{Constraint Items}
     \label{Constraint Items}
%---------------------------------------------------------------------------%
Constraint items form the heart of a model.  Any solutions found for a model
will satisfy all of its constraints.

Constraint items have this syntax:
\begin{productions}
    \RuleConstraintItem
\end{productions}
%%
For example:
\begin{verbatim}
    constraint a*x < b;
\end{verbatim}

The expression in a constraint item must have type-inst \texttt{par bool} or
\texttt{var bool}; note however that constraints with fixed expressions are
not very useful.

%---------------------------------------------------------------------------%
\subsection{Solve Items}
     \label{Solve Items}
%---------------------------------------------------------------------------%
\resolvedcomment{njn}
{Nb: the annotation cannot go after the satisfy/maximize/minimize keyword,
because in "solve maximize :: foo(bar)..."  you can't tell if the "(bar)" is
an argument list for the 'foo', or a parenthesised expression.  This screws
up the grammar when expressed with yacc.}{}

Every model must have exactly one solve item.  Solve items have the
following syntax:
\begin{productions}
    \RuleSolveItem
\end{productions}
Example solve items:
\begin{verbatim}
    solve satisfy;
    solve maximize a*x + y - 3*z;
\end{verbatim}

The solve item determines whether the model represents a constraint
satisfaction problem or an optimisation problem.  In the latter case the
given expression is the one to be minimized/maximized.

The expression in a minimize/maximize solve item can have integer or float type.

\Rationale{This is possible because all type-insts have a defined order.}
Note that having an expression with a fixed type-inst in a solve item is not
very useful as it means that the model requires no optimisation.

Solve items can be annotated.  Section~\ref{Annotations} has more details on
annotations.

%---------------------------------------------------------------------------%
\subsection{Output Items}
     \label{Output Items}
%---------------------------------------------------------------------------%
Output items are used to present the solutions of a model instance.
They have the following syntax:
\begin{productions}
    \RuleOutputItem
\end{productions}
For example:
\begin{verbatim}
    output ["The value of x is ", show(x), "!\n"];
\end{verbatim}

The expression must have type-inst \texttt{array[int] of par string}.  It
can be composed using the built-in operator \texttt{++}
and the built-in functions \texttt{show}, \texttt{show\_int}, and
\texttt{show\_float} 
(Appendix~\ref{builtins}).
The output is the concatenation of the elements of the array. If multiple output items exist, the output is the concatenation of all of their outputs,
in the order in which they appear in the model.

If no output item is present,
the implementation should print all the global variables and their values
in a readable format.


%---------------------------------------------------------------------------%
\subsection{Annotation Items}
     \label{Annotation Items}
%---------------------------------------------------------------------------%
Annotation items are used to augment the \texttt{ann} type.  They have the
following syntax:
\begin{productions}
    \RuleAnnotationItem
\end{productions}
For example:
\begin{verbatim}
    annotation solver(int: kind);
\end{verbatim}

It is a type-inst error if an annotation is declared and/or defined more
than once in a model.

The use of annotations is described in Section~\ref{Annotations}.

%---------------------------------------------------------------------------%
\subsection{User-defined Operations}
     \label{preds and fns}
%---------------------------------------------------------------------------%
% XXX: not saying if operations need to be defined.  Implementation
% currently requires functions and tests to be defined if used, but
% predicates can be bodyless even if used.  Should perhaps require functions
% to be defined even if they're not used (like parameters), and make tests
% like predicates?

MiniZinc models can contain user-defined operations.  They have this syntax:
\begin{productions}
    \RulePredicateItem \\
    \RuleTestItem \\
    \RuleFunctionItem \\
    \RuleOperationItemTail \\
    \RuleParams \\
\end{productions}

The type-inst expressions can include type-inst variables in
the function and predicate declaration.

For example, predicate \texttt{even} checks that its argument is an even
number.
\begin{verbatim}
    predicate even(var int: x) =
        x mod 2 = 0;
\end{verbatim}

%Predicate \texttt{serial} constrains the resistor \texttt{z} to be
%equivalent to connecting the two resistors \texttt{x} and \texttt{y} in
%series (the fields \texttt{r} and \texttt{i} represent resistance and
%current respectively).
%\begin{verbatim}
%    type Resistor = record(var int: r, var int: i);
%    predicate serial(Resistor: x, Resistor: y, Resistor: z) =
%        z.r = x.r + y.r /\
%        z.i = x.i       /\
%        z.i = y.i;
%\end{verbatim}

A predicate supported natively by the target solver can be declared as
follows:
\begin{verbatim}
    predicate alldifferent(array [int] of var int: xs);
\end{verbatim}
Predicate declarations that are natively supported 
in MiniZinc are restricted to using FlatZinc
types (for instance, multi-dimensional and non-1-based arrays are
forbidden).
% \pjs{need to fix this if we allow2d arrays in FlatZinc!}

Declarations for user-defined operations can be annotated.
Section~\ref{Annotations} has more details on annotations.

\subsubsection{Basic Properties}
        \label{Basic Properties}
The term ``predicate'' is generally used to refer to both test items and
predicate items.  When the two kinds must be distinguished, the terms ``test
item'' and ``predicate item'' can be used.

The return type-inst of a test item is implicitly \texttt{par bool}.  The
return type-inst of a predicate item is implicitly \texttt{var bool}.

% \pjs{Can predicates and functionsbe recursive now?}
Predicates and functions are allowed to be recursive. Termination of
a recursive function call depends solely on its fixed arguments, i.e., 
recursive functions and predicates cannot be used to define recursively 
constrained variables.
% \Rationale{This ensures that the satisfiability of models is decidable.}

Predicates and functions introduce their own local names, being those of the
formal arguments.  The scope of these names covers the predicate/function
body.  Argument names cannot be repeated within a predicate/function
declaration.

%MiniZinc is mostly a first-order language, so operations cannot, in
%general, be used as values.  The only exception to this is that they may be
%given as the first argument to \texttt{foldl} or \texttt{foldr}, and as
%arguments in annotation literals (see Section~\ref{Higher-order Types}).

\subsubsection{Ad-hoc polymorphism}
MiniZinc supports ad-hoc polymorphism via overloading.  Functions
and predicates (both built-in and user-defined) can be overloaded.  A name
can be overloaded as both a function and a predicate.

It is a type-inst error if a single version of an overloaded operation with
a particular type-inst signature is declared and/or defined more than once
in a model.  For example:
\begin{verbatim}
    predicate p(1..5: x);
    predicate p(1..5: x) = true;        % error:  repeated declaration
\end{verbatim}

The combination of overloading and coercions can cause problems.
Two overloadings of an operation are said to ``overlap'' if they could match
the same arguments.  For example, the following overloadings of \texttt{p}
overlap, as they both match the call \texttt{p(3)}.
\begin{verbatim}
    predicate p(par int: x);
    predicate p(var int: x);
\end{verbatim}
However, the following two predicates do not overlap because they cannot
match the same argument:
\begin{verbatim}
    predicate q(int:        x);
    predicate q(set of int: x);
\end{verbatim}
We avoid two potential overloading problems by placing some restrictions on
overlapping overloadings of operations.

\begin{enumerate}
\item
The first problem is ambiguity.  Different placement of coercions in
operation arguments may allow different choices for the overloaded function.
For instance, if a MiniZinc function \texttt{f} is overloaded like this:
\begin{verbatim}
    function int: f(int: x, float: y) = 0;
    function int: f(float: x, int: y) = 1;
\end{verbatim}
then \texttt{f(3,3)} could be either 0 or 1 depending on
coercion/overloading choices.

To avoid this problem, any overlapping overloadings of an operation must
be semantically equivalent with respect to coercion.  For example, the
two overloadings of the predicate \texttt{p} above must have bodies that are
semantically equivalent with respect to overloading.

Currently, this requirement is not checked and the modeller must satisfy it
manually.  In the future, we may require the sharing of bodies among
different versions of overloaded operations, which would provide automatic
satisfaction of this requirement.


\item
The second problem is that certain combinations of overloadings could
require a MiniZinc implementation to perform combinatorial search in
order to explore different choices of coercions and overloading.  For
example, if function \texttt{g} is overloaded like this:
\begin{verbatim}
    function float: g(int: t1, float: t2) = t2;
    function int  : g(float: t1, int: t2) = t1;
\end{verbatim}
then how the overloading of \texttt{g(3,4)} is resolved depends upon its
context:
\begin{verbatim}
    float: s = g(3,4);
    int: t = g(3,4);
\end{verbatim}
In the definition of \texttt{s} the first overloaded definition must be used
while in the definition of \texttt{t} the second must be used.

To avoid this problem, all overlapping overloadings of an operation must be
closed under intersection of their input type-insts.  That is, if overloaded
versions have input type-inst $(S_1,....,S_n)$ and $(T_1,...,T_n)$ then
there must be another overloaded version with input type-inst
$(R_1,...,R_n)$ where each $R_i$ is the greatest lower bound (\emph{glb}) of
$S_i$ and $T_i$.

Also, all overlapping overloadings of an operation must be monotonic.  That
is, if there are overloaded versions with input type-insts $(S_1,....,S_n)$
and $(T_1,...,T_n)$ and output type-inst $S$ and $T$, respectively, then
$S_i \preceq T_i$ for all $i$, implies $S \preceq T$.  At call sites, the
matching overloading that is lowest on the type-inst lattice is always used.

For \texttt{g} above, the type-inst intersection (or \emph{glb}) of
\texttt{(float,int)}  and \texttt{(float,int)} is
\texttt{(int,int)}.  Thus, the overloaded versions are not closed under
intersection and the user needs to provide another overloading for
\texttt{g} with input type-inst \texttt{(int,int)}.  The natural
definition is:
\begin{verbatim}
    function int: g(int: t1, int: t2) = t1;
\end{verbatim}
Once \texttt{g} has been augmented with the third overloading, it satisfies
the monotonicity requirement because the output type-inst of the third
overloading is \texttt{int} which is less than the output
type-inst of the original overloadings.

Monotonicity and closure under type-inst conjunction ensure that whenever an
overloaded function or predicate is reached during type-inst checking, there
is always a unique and safe ``minimal'' version to choose, and so the
complexity of type-inst checking remains linear.  Thus in our example
\texttt{g(3,4)} is always resolved by choosing the new overloaded
definition.
\end{enumerate}

\ignore{
\subsubsection{Parametric Polymorphism}
        \label{Parametric Polymorphism}

\pjs{Better check what it actually does!}
MiniZinc supports parametric polymorphism of functions and predicates via
type-inst variables.

For example, function \texttt{min\n{}of\n{}two} takes two parameters and
gives their minimum.
\begin{verbatim}
    function $T:min_of_two($T: x, $T: y) =
        if x <= y then x else y endif;
\end{verbatim}
This function is possible because every type has a built-in ordering.

Section~\ref{Type-inst Variables} explained that type-inst variables can
have no prefix (or, equivalently, a \texttt{par} prefix).  
The prefixes are necessary for precise type-inst signatures of some
user-defined operations.  For example, consider the following two
definitions of a function \texttt{between}:
\begin{verbatim}
    par bool: function between(par $T: x, par $T: y, par $T: z) =
        (x <= y /\ y <= z) \/ (z <= y /\ y <= x);
    var bool: function between($T: x, $T: y, $T: z) =
        (x <= y /\ y <= z) \/ (z <= y /\ y <= x);
\end{verbatim}
The first version has a more precise return type-inst.  The \texttt{par} 
prefixes is needed to express the difference between these two
versions.
\pjs{The example above is causes an error "function defined for this type
  already!}


Note that although \texttt{par \$T} (and also \texttt{\$T}) only
\emph{matches} fixed type-insts, it does not mean that the type-inst
variable \texttt{\$T} must be \emph{bound} to a fixed type-inst.  For
example, with these variables and predicate:
\begin{verbatim}
    par int: pi;
    var int: vi;
    predicate p(par $T: x, $T: y);
\end{verbatim}
the first two of the following are acceptable, but the last two are errors:
\begin{verbatim}
    constraint p(pi, pi);     % ok:  $T bound to 'par int'
    constraint p(pi, vi);     % ok:  $T bound to 'var int'
    constraint p(vi, pi);     % error
    constraint p(vi, vi);     % error
\end{verbatim}
}

\subsubsection{Local Variables}

Local variables in operation bodies are introduced using let expressions.
For example, the predicate \texttt{have\n{}common\n{}divisor} takes two
integer values and checks whether they have a common divisor greater than
one:
\begin{verbatim}
    predicate have_common_divisor(int: A, int: B) =
        let {
            var 2..min(A,B): C;
        } in
            A mod C = 0 /\
            B mod C = 0;
\end{verbatim}

However, as Section~\ref{Let Expressions} explained, because \texttt{C} is
not defined, this predicate cannot be called in a negative context.  The
following is a version that could be called in a negative context:
\begin{verbatim}
    predicate have_common_divisor(int: A, int: B) =
        exists(C in 2..min(A,B))
            (A mod C = 0 /\ B mod C = 0);
\end{verbatim}


%===========================================================================%
\section{Annotations}
  \label{Annotations}
%===========================================================================%
Annotations---values of the \texttt{ann} type---allow a modeller to specify
non-declarative and solver-specific information that is beyond the core
language.  Annotations do not change the meaning of a model, however, only
how it is solved.

Annotations can be attached to variables (on their declarations),
expresssions, type-inst synonyms, enum items, solve items and on user
defined operations.
They have the following syntax:
%\comment{pjs}{
%What exactly do they mean?  In:\\
%     \indent\texttt{strength(24.0) :: forall(i in 1..n) x[i] >= 0}\\
%do I get the penalty of 24 if at least one \texttt{x[i] >= 0} is not satisfied,
%do I get a penalty of 24 for each one that is not satisfied?\\
%}
\begin{productions}
    \RuleAnnotations \\
    \RuleAnnotation
\end{productions}
For example:
\begin{verbatim}
    int: x::foo;
    x = (3 + 4)::bar("a", 9)::baz("b");
    solve :: blah(4)
        minimize x;
\end{verbatim}

The types of the argument expressions must match the argument types of the
declared annotation.  Unlike user-defined predicates and functions,
annotations cannot be overloaded.  \Rationale{There is no particular strong
reason for this, it just seemed to make things simpler.}

Annotation signatures can contain type-inst variables.

The order and nesting of annotations do not matter.  For the expression case
it can be helpful to view the annotation connector \texttt{'::'} as an
overloaded operator:
\begin{verbatim}
    ann: '::'(any $T: e, ann: a);       % associative
    ann: '::'(ann:    a, ann: b);       % associative + commutative
\end{verbatim}
Both operators are associative, the second is commutative.  This means that
the following expressions are all equivalent:
\begin{verbatim}
    e :: a :: b
    e :: b :: a
    (e :: a) :: b
    (e :: b) :: a
    e :: (a :: b)
    e :: (b :: a)
\end{verbatim}
This property also applies to annotations on solve items and variable
declaration items.  \Rationale{This property make things simple, as it
allows all nested combinations of annotations to be treated as if they are
flat, thus avoiding the need to determine what is the meaning of an
annotated annotation.  It also makes the MiniZinc abstract syntax tree simpler
by avoiding the need to represent nesting.}

% The Standard Annotations bit is currently commented out.
%Zinc's built-in annotations are listed in Appendix~\ref{Standard
%Annotations}.  Moreover, an implementation is likely to define a number of
%its own annotations for a variety of purposes.

%===========================================================================%
\section{Partiality}
  \label{Partiality}
%===========================================================================%
The presence of constrained type-insts in MiniZinc means that
various operations are potentially \emph{partial}, i.e.~not clearly defined
for all possible inputs.  For example, what happens if a function expecting
a positive argument is passed a negative argument?  What happens if a
variable is assigned a value that does not satisfy its type-inst constraints?
What happens if an array index is out of bounds?  This section describes
what happens in all these cases.

% \pjs{This is not what seems to happen in the current MiniZinc!}
In general, cases involving fixed values that do not satisfy constraints
lead to run-time aborts.
\Rationale{Our experience shows that if a fixed value fails a constraint, it
is almost certainly due to a programming error.  Furthermore, these cases
are easy for an implementation to check.}

But cases involving unfixed values vary, as we will see.
\Rationale{The best thing to do for unfixed values varies from case to case.
Also, it is difficult to check constraints on unfixed values, particularly
because during search a decision variable might become fixed and then
backtracking will cause this value to be reverted, in which case aborting is
a bad idea.}

% XXX PARTIAL: as described, this static matching turned out to be a bad idea --
% it was not smart enough, and so clearly valid models were rejected, and
% making it smarter is a slippery slope -- there are lots of cases, handling
% all of them is difficult, and ones that aren't handled lead to very
% confusing error messages for users.  See additional "XXX PARTIAL" marks
% below also.
%
%%-----------------------------------------------------------------------------%
%\subsection{Static Matching}
%%-----------------------------------------------------------------------------%
%Before describing the cases, we need to define the notion of
%\emph{static matching}.
%
%A type-inst expression \emph{statically matches} another iff one of the
%following is true.
%\begin{itemize}
%\item
%    They are identical identifiers (ignoring \texttt{par} and \texttt{var}
%    prefixes).  For example, if we have these:
%\begin{verbatim}
%  type Pos = (int: x where x > 0);
%  type Pos2 = Pos;
%  set of int: s135 = {1, 3, 5};
%  enum C = {R, G, B};
%\end{verbatim}
%    then we have the following matches and non-matches.
%\begin{verbatim}
%  Pos         Pos                 % match
%  par s135    var s135            % match
%  C           par C               % match
%  Pos         Pos2                % no match: not synt. identical
%\end{verbatim}
%
%\item
%    They are both range type-insts that contain only scalar literals and
%    function calls, and they are syntactically identical (ignoring
%    differences in whitespace, parentheses, annotations, and \texttt{par}
%    and \texttt{var} prefixes).  For example:
%\begin{verbatim}
%  var 1..5    1..5                % match
%  par m..n+1  m..(n + 1)::foo     % match
%  1..5        1..4+1              % no match: not synt. identical
%  1..f([1,2]) 1..f([1,2])         % no match: '[1,2]' is not scalar
%\end{verbatim}
%
%\item
%    They are both set expression type-insts that involve only scalar
%    literals and function calls, and they are syntactically identical
%    (ignoring differences in whitespace, parentheses, annotations, and
%    \texttt{par} and \texttt{var} prefixes).  For example:
%\begin{verbatim}
%  {1,3,5}         par {1,3,5}     % match
%  {1,f(2::a),5}   {1,f(2::a)}     % match
%  {1,3,5}         {5,3,1}         % no match: not synt. identical
%\end{verbatim}
%\end{itemize}
%
%We now extend this notion to cover expressions.  An expression, \texttt{E},
%\emph{statically matches} a type-inst expression, \texttt{TIE}, iff it has an
%\emph{inferred type-inst expression}, \texttt{InfTIE}, and \texttt{InfTIE}
%statically matches \texttt{TIE}.  The following expressions have inferred
%type-inst expressions.
%
%\begin{itemize}
%\item
%    If \texttt{E} is an identifier expression, and the identifier is that of a
%    variable, the inferred type-inst expression is the one from the variable's
%    declaration.  For example, if we have this:
%\begin{verbatim}
%    var Pos: p;
%\end{verbatim}
%    then the inferred type-inst expression of the expression \texttt{p} is
%    \texttt{var Pos}.
%
%\item
%    If \texttt{E} is an array access expression where the array expression has
%    an inferred type-inst expression \texttt{array[IndexTIE] of ElemTIE}, the
%    inferred type-inst expression is \texttt{ElemTIE}.  For example, if we have
%    this:
%\begin{verbatim}
%    array[1..3] of var Pos: a;
%\end{verbatim}
%    then the expression \texttt{a[1]} has the inferred type-inst expression
%    \texttt{var Pos}.
%
%\item
%    If \texttt{E} is a tuple access expression where the tuple expression has
%    an inferred type-inst expression \texttt{tuple(TIE1, TIE2, ...)}, the
%    inferred type-inst expression is \texttt{TIEn} for the selected \texttt{n}.
%    For example, if we have this:
%\begin{verbatim}
%    tuple(Pos, var int): t;
%\end{verbatim}
%    then the expression \texttt{t.1} has the inferred type-inst expression
%    \texttt{Pos}.
%
%\item
%    If \texttt{E} is a record access expression where the record expression has
%    an inferred type-inst expression \texttt{record(TIE1:x1, TIE2:x2, ...)},
%    the inferred type-inst expression is \texttt{TIEn} for the selected
%    \texttt{n}.
%\end{itemize}
%
%Note that all variables are declared using a type-inst expression, with one
%exception: generator variables.  For those, we determine a declaration
%type-inst expression from the generator expression, \texttt{GE}, (ignoring any
%surrounding set-to-array coercion) using the following rules.
%\begin{itemize}
%\item
%    If \texttt{GE} is an identifier of a type-inst expression (e.g.~the name
%    of a flat enum), the inferred type-inst expression is that same
%    identifier.
%\begin{verbatim}
%  type t135 = {1,3,5};
%  { i | i in t135 }         % i's type-inst expression: t135
%  enum C = {R, G, B};
%  { i | i in C    }         % i's type-inst expression: C
%\end{verbatim}
%
%\item
%    If \texttt{GE} is a set identifier, set literal or range expression, the
%    inferred type-inst expression is the corresponding set expression
%    type-inst expression.
%\begin{verbatim}
%  set of int: s135 = {1,3,5};
%  { i | i in s135 }         % i's type-inst expression: s135
%  { i | i in 1..5 }         % i's type-inst expression: 1..5
%  { i | i in {1,3,5::a} }   % i's type-inst expression: {1,3,5::a}
%\end{verbatim}
%
%\item
%    Otherwise, the inferred type-inst expression is the appropriate
%    unconstrained one.  For example:
%\begin{verbatim}
%  { i | i in [1,3,5] }      % i's type-inst expression: int
%\end{verbatim}
%\end{itemize}
%
%An expression that statically matches a type-inst expression is guaranteed
%to satisfy its constraints at run-time.  The following sections will show
%that static matching is used to guarantee that some potentially partial
%cases are actually total.  This guarantee is conservative---there are many
%expressions that do not statically match a type-inst expression, but would
%satisfy its constraint at run-time.
%
%\Rationale{The static matching rules provide a balance between
%ease-of-implementation and ease-of-use.  As described, static matching is
%easy to implement;  in particular, it does not require any compile-time
%expression evaluation, which would be required if sub-ranges had to be
%detected, for example.  But they also cover most cases that occur in
%practice;  we have seen that modellers almost always use type-inst synonyms
%for complex constrained type-insts, and range type-insts are the other
%common case.  For the cases that static matching does not cover, simple
%workarounds usually exist, such as introducing an intermediate variable with
%an appropriate type-inst expression.}
%
%The matching rules may be expanded in the future to make them less
%conservative if they are too restrictive.

%-----------------------------------------------------------------------------%
\subsection{Partial Assignments}
%-----------------------------------------------------------------------------%
The first operation involving partiality is assignment.  There are four
distinct cases for assignments.
\begin{itemize}
\item
    A value assigned to a fixed, constrained global variable is checked at
    run-time;  if the assigned value does not satisfy its constraints, it is
    a run-time error.  In other words, this:
\begin{verbatim}
  1..5: x = 3;
\end{verbatim}
    is equivalent to this:
\begin{verbatim}
  int: x = 3;
  constraint assert(x in 1..5,
                    "assignment to global parameter 'x' failed")
\end{verbatim}

\item
    A value assigned to an unfixed, constrained global variable makes the
    assignment act like a constraint;  if the assigned value does not
    satisfy the variable's constraints, it causes a run-time model failure.
    In other words, this:
\begin{verbatim}
  var 1..5: x = 3;
\end{verbatim}
    is equivalent to this:
\begin{verbatim}
  var int: x = 3;
  constraint x in 1..5;
\end{verbatim}
    \Rationale{This behaviour is easy to understand and easy to implement.}

\item
    A value assigned to a fixed, constrained let-local variable is checked at
    run-time;  if the assigned value does not satisfy its constraints, it is
    a run-time error.  In other words, this:
\begin{verbatim}
  let { 1..5: x = 3; } in x+1
\end{verbatim}
    is equivalent to this:
\begin{verbatim}
  let { int: x = 3; } in
      assert(x in 1..5,
             "assignment to let parameter 'x' failed", x+1)
\end{verbatim}

% XXX PARTIAL: this was specified when syntactic matching looked like a good
% idea.  For the moment, allowing them to fail seems like a better idea.
%
%\item
%    A value assigned to an unfixed, constrained let-local variable is
%    checked at compile-time;  if the assigned value does not statically
%    match the variable's constraint, it is a compile-time error.  In other
%    words, something like this is not allowed:
%\begin{verbatim}
%  let { var 1..5: x = 3 } in x+1
%\end{verbatim}
%    because \texttt{3} does not statically match \texttt{var 1..5}.
%    \Rationale{This is because this case is very uncommon, and implementing
%    ``failure'' sensibly is not easy.  This is also the case that is most
%    likely to cause a modeller problems, as it can be difficult to introduce
%    an intermediate variable with the appropriate type-inst expression,
%    especially if the let is inside a predicate/function.}
\item
    A value assigned to an unfixed, constrained let-local variable makes the
    assignment act like a constraint;  if the assigned value does not
    statically match the variable's constraint at run-time it fails, and the
    failure ``bubbles up'' to the nearest enclosing Boolean scope, where it
    is interpreted as \texttt{false}.

    \Rationale{This behaviour is consistent with assignments to global
    variables.}
\end{itemize}

Note that in cases where a value is partly fixed and partly unfixed, e.g.~some
tuples, the different elements are checked according to the different cases,
and fixed elements are checked before unfixed elements.  For example:
\begin{verbatim}
    u = [ let { var 1..5: x = 6} in x, let { par 1..5: y = 6; } in y) ];
\end{verbatim}
This causes a run-time abort, because the second, fixed element is checked
before the first, unfixed element.  This ordering is true for the cases in the
following sections as well.  \Rationale{This ensures that failures cannot
mask aborts, which seems desirable.}


%-----------------------------------------------------------------------------%
\subsection{Partial Predicate/Function and Annotation Arguments}
%-----------------------------------------------------------------------------%
The second kind of operation involving partiality is calls and annotations.
% The behaviour for these operations is simple:  constraints on arguments are
% ignored.
%
% \Rationale{This is easy to implement and easy to understand.  It is also
% justifiable in the sense that predicate/function/annotation arguments are
% values that are passed in from elsewhere;  if those values are to be
% constrained, that could be done earlier.  (In comparison, when a variable
% with a constrained type-inst is declared, any assigned value must clearly
% respect that constraint.)}

The semantics is similar to assignments:  fixed arguments that fail their constraints
will cause aborts, and unfixed arguments that fail their constraints will
cause failure, which bubbles up to the nearest enclosing Boolean scope.

% XXX PARTIAL: this text is from when syntactic checking seemed like a good
% idea.  Now just ignoring the argument constraints seems better.
%
%There are two distinct cases.
%
%\begin{itemize}
%\item
%    Each actual argument in a predicate/function call or annotation that
%    corresponds to a fixed, constrained formal argument is checked at
%    run-time;  if the actual argument value does not satisfy the formal
%    argument's constraints, it is a run-time error.
%
%    Similarly, the return value of a function with a constrained return
%    type-inst expression is checked at run-time;  if the return value does
%    not satisfy the return constraints, it is a run-time error.
%
%    In other words, this:
%\begin{verbatim}
%    function 2..6: f(1..5: x) = x+1;
%\end{verbatim}
%    is equivalent to this:
%\begin{verbatim}
%    predicate f(int: x) =
%        assert(x in 1..5, "argument 'x' of 'f' failed",
%            assert(x+1 in 2..6, "return value of 'f' failed", x+1));
%\end{verbatim}
%
%\item
%    Each actual argument in a predicate/function call or annotation that
%    corresponds to an unfixed, formal argument is checked at compile-time;
%    if the actual argument value does not statically match the formal
%    argument's type-inst expression, it is a compile-time error.  For
%    example:
%\begin{verbatim}
%    predicate q(var 1..5: x) = x > 0;
%    var 1..5: i = 3;
%    constraint q(3);            % compile-time error
%    constraint q(i);            % ok
%\end{verbatim}
%    \Rationale{This fits with the way modellers tend to use partial
%    arguments, which is in a sub-type style rather than a constraining
%    style.  Furthermore, implementing failure in this case is difficult.}
%\end{itemize}

%-----------------------------------------------------------------------------%
\subsection{Partial Array Accesses}
%-----------------------------------------------------------------------------%
The third kind of operation involving partiality is array access.  There
are two distinct cases.
\begin{itemize}
\item
    A fixed value used as an array index is checked at run-time;  if the
    index value is not in the index set of the array, it is a run-time
    error.
\item
    An unfixed value used as an array index makes the access act like a
    constraint;  if the access fails at run-time, the failure ``bubbles up''
    to the nearest enclosing Boolean scope, where it is interpreted as
    \texttt{false}.  For example:
\begin{verbatim}
    array[1..3] of int: a = [1,2,3];
    var int: i;
    constraint (a[i] + 3) > 10 \/ i = 99;
\end{verbatim}
    Here the array access fails, so the failure bubbles up to the
    disjunction, and \texttt{i} is constrained to be 99.
    \Rationale{Unlike predicate/function calls, modellers in practice
    sometimes do use array accesses that can fail.   In such cases, the
    ``bubbling up'' behaviour is a reasonable one.}
\end{itemize}

\appendix
%=============================================================================%
\clearpage
\section{Built-in Operations}
  \label{builtins}
%=============================================================================%
This appendix lists built-in operators, functions and
predicates.  They may be implemented as true built-ins, or in libraries that
are automatically imported for all models.  Many of them are overloaded.

Operator names are written within single quotes when used in type
signatures, e.g.~\verb+bool: '\/'(bool, bool)+.

We use the syntax \texttt{TI: f(TI1,...,TIn)} to represent an operation
named \texttt{f} that takes arguments with type-insts \texttt{TI,...,TIn}
and returns a value with type-inst \texttt{TI}.  This is slightly more
compact than the usual MiniZinc syntax, in that it omits argument names.

%\newcommand{\builtin}{\hspace{-8mm}$\bullet$}
\newcommand{\builtin}{\noindent}

%---------------------------------------------------------------------------%
\subsection{Comparison Operations}
%---------------------------------------------------------------------------%
\builtin{}
Less than.  Other comparisons are similar:
greater than (\texttt{>}),
less than or equal (\texttt{<=}),
greater than or equal (\texttt{>=}),
equality (\texttt{==}, \texttt{=}),
and disequality (\texttt{!=}).
% \pjs{Check use of any here!}
\begin{verbatim}
      bool: '<'(    $T,     $T)
  var bool: '<'(var $T, var $T)
\end{verbatim}

%---------------------------------------------------------------------------%
\subsection{Arithmetic Operations}
%---------------------------------------------------------------------------%
\builtin{}
Addition.  Other numeric operations are similar:
subtraction (\texttt{-}), and
multiplication (\texttt{*}).
\begin{verbatim}
      int:   '+'(    int,       int)
  var int:   '+'(var int,   var int)
      float: '+'(    float,     float)
  var float: '+'(var float, var float)
\end{verbatim}

\builtin{}
Unary minus.  Unary plus (\texttt{+}) is similar.
\begin{verbatim}
      int:   '-'(    int)
  var int:   '-'(var int)
      float: '-'(    float)
  var float: '-'(var float)
\end{verbatim}

\builtin{}
Integer and floating-point division and modulo.
\begin{verbatim}
      int:   'div'(    int,       int)
  var int:   'div'(var int,   var int)
      int:   'mod'(    int,       int)
  var int:   'mod'(var int,   var int)
      float: '/'  (    float,     float)
  var float: '/'  (var float, var float)
\end{verbatim}
The result of the modulo operation, if non-zero, always has the same sign as
its first operand.  The integer division and modulo operations are connected
by the following identity:
\begin{verbatim}
  x = (x div y) * y + (x mod y)
\end{verbatim}
Some illustrative examples:
\begin{verbatim}
   7 div  4 =  1        7 mod  4 =  3
  -7 div  4 = -1       -7 mod  4 = -3 
   7 div -4 = -1        7 mod -4 = 3
  -7 div -4 =  1       -7 mod -4 = -3
\end{verbatim}

\builtin{}
Sum multiple numbers.
% Unrolled using \texttt{+}.
Product (\texttt{product}) is similar.  Note that the sum of an empty array
is 0, and the product of an empty array is 1.
\begin{verbatim}
      int:   sum(array[$T]  of     int  )
  var int:   sum(array[$T]  of var int  )
      float: sum(array[$T]  of     float)
  var float: sum(array[$T]  of var float)
\end{verbatim}

\builtin{}
Minimum of two values;  maximum (\texttt{max}) is
similar.
\begin{verbatim}
  any $T:    min(any $T,    any $T )
\end{verbatim}

\builtin{}
Minimum of an array of values;  maximum (\texttt{max}) is similar.
Aborts if the array is empty.
\begin{verbatim}
  any $U:    min(array[$T]  of any $U)
\end{verbatim}

\builtin{}
Minimum of a fixed set;  maximum (\texttt{max}) is similar.
Aborts if the set is empty.
\begin{verbatim}
  $T:    min(set of $T)
\end{verbatim}

\builtin{}
Absolute value of a number.
\begin{verbatim}
      int:   abs(    int)
  var int:   abs(var int)
      float: abs(    float)
  var float: abs(var float)
\end{verbatim}

\builtin{}
Square root of a float.  Aborts if argument is negative.
\begin{verbatim}
      float: sqrt(    float)
  var float: sqrt(var float)
\end{verbatim}

\builtin{}
Power operator.  E.g.~\texttt{pow(2, 5)} gives \texttt{32}.
\begin{verbatim}
    int: pow(int,       int)
  float: pow(float,     float)
\end{verbatim}
% We should also have:
%  var float: pow(var float, int)

\builtin{}
Natural exponent.
\begin{verbatim}
      float: exp(float)
  var float: exp(var float)
\end{verbatim}

\builtin{}
Natural logarithm.  Logarithm to base 10 (\texttt{log10}) and logarithm to base
2 (\texttt{log2}) are similar.
\begin{verbatim}
      float: ln(float)
  var float: ln(var float)
\end{verbatim}

\builtin{}
General logarithm;  the first argument is the base.
\begin{verbatim}
  float: log(float, float)
\end{verbatim}

\builtin{}
Sine.  Cosine (\texttt{cos}), tangent (\texttt{tan}), inverse sine
(\texttt{asin}), inverse cosine (\texttt{acos}), inverse tangent
(\texttt{atan}), hyperbolic sine (\texttt{sinh}), hyperbolic cosine
(\texttt{cosh}), hyperbolic tangent (\texttt{tanh}),
inverse hyperbolic sine (\texttt{asinh}), inverse hyperbolic cosine
(\texttt{acosh}) and inverse hyperbolic tangent (\texttt{atanh}) are similar.
\begin{verbatim}
      float: sin(float)
  var float: sin(var float)
\end{verbatim}

%---------------------------------------------------------------------------%
\subsection{Logical Operations}
%---------------------------------------------------------------------------%
\builtin{}
Conjunction.  Other logical operations are similar:
disjunction (\verb+\/+)
reverse implication (\texttt{<-}),
forward implication (\texttt{->}),
bi-implication (\texttt{<->}),
exclusive disjunction (\texttt{xor}),
logical negation (\texttt{not}).

Note that the implication operators are not written
using \texttt{=>}, \texttt{<=} and \texttt{<=>} as is the case in some
languages.  This allows \texttt{<=} to instead represent ``less than or
equal''.
\begin{verbatim}
      bool: '/\'(    bool,     bool)
  var bool: '/\'(var bool, var bool)
\end{verbatim}

\builtin{}
Universal quantification.
Existential quantification (\texttt{exists}) is similar.  Note that, when
applied to an empty list, \texttt{forall} returns \texttt{true}, and
\texttt{exists} returns \texttt{false}.
\begin{verbatim}
      bool: forall(array[$T]  of     bool)
  var bool: forall(array[$T]  of var bool)
\end{verbatim}

\builtin{}
N-ary exclusive disjunction.
N-ary bi-implication (\texttt{iffall}) is similar, with \texttt{true} instead
of \texttt{false}.
\begin{verbatim}
      bool: xorall(array[$T]  of     bool: bs) = foldl('xor', false, bs)
  var bool: xorall(array[$T]  of var bool: bs) = foldl('xor', false, bs)
\end{verbatim}

%---------------------------------------------------------------------------%
\subsection{Set Operations}
%---------------------------------------------------------------------------%
\builtin{}
Set membership.
\begin{verbatim}
      bool: 'in'(     $T,       set of $T )
  var bool: 'in'(var int,   var set of int)
\end{verbatim}

\builtin{}
Non-strict subset.  Non-strict superset (\texttt{superset}) is similar.
\begin{verbatim}
      bool: 'subset'(    set of $T ,     set of $T )
  var bool: 'subset'(var set of int, var set of int)
\end{verbatim}

\builtin{}
Set union.  Other set operations are similar:
intersection (\texttt{intersect}),
difference (\texttt{diff}),
symmetric difference (\texttt{symdiff}).
\begin{verbatim}
      set of  $T: 'union'(    set of  $T,     set of  $T )
  var set of int: 'union'(var set of int, var set of int )
\end{verbatim}

\builtin{}
Set range.  If the first argument is larger than the second
(e.g.~\texttt{1..0}), it returns the empty set.
\begin{verbatim}
  set of int: '..'(int, int)
\end{verbatim}

\builtin{}
Cardinality of a set.
\begin{verbatim}
      int: card(    set of  $T)
  var int: card(var set of int)
\end{verbatim}

\builtin{}
Union of an array of sets.
%Unrolled with \texttt{union}.
Intersection of multiple sets (\texttt{array\n{}intersect}) is similar.
\begin{verbatim}
      set of  $U:    array_union(array[$T]  of     set of  $U)
  var set of int:    array_union(array[$T]  of var set of int)
\end{verbatim}

\ignore{
\builtin{}
Power set.
\begin{verbatim}
  set of set of $T: powerset(set of $T)
\end{verbatim}

\builtin{}
Cartesian product of sets.   This list is only partial, it extends in the
obvious way, for greater numbers of sets.
\begin{verbatim}
  set of tuple($T1, $T2):      cartesian_product(set of $T1, set of $T2)
  set of tuple($T1, $T2, $T3): cartesian_product(set of $T1, set of $T2,
                                                 set of $T3)
  ...
\end{verbatim}
}

%---------------------------------------------------------------------------%
\subsection{Array Operations}
%---------------------------------------------------------------------------%
\builtin{}
Length of an array.
\begin{verbatim}
  int: length(array[$T] of any $U)
\end{verbatim}

\builtin{}
List concatenation.  Returns the list (integer-indexed array) containing
all elements of the first argument followed by all elements of the
second argument, with elements occurring in the same order as
in the arguments.  The resulting indices are in the range \texttt{1..n},
where \texttt{n} is the sum of the lengths of the arguments.
\Rationale{This allows list-like arrays to be concatenated naturally
and avoids problems with overlapping indices.  The resulting indices
are consistent with those of implicitly indexed array literals.}
Note that \texttt{'++'} also performs string concatenation.
\begin{verbatim}
  array[int] of any $T: '++'(array[int] of any $T, array[int] of any $T)
\end{verbatim}

\ignore{
\builtin{}
Array merge.  Does not change any indices.  If any index is repeated
in the result, it is a run-time error.  Note that it may result in an
interleaving of the elements, e.g.~the merge of \texttt{[1:1, 3:3]}
and \texttt{[2:2, 4:4]} is \texttt{[1:1, 2:2, 3:3, 4:4]}.
\begin{verbatim}
  array[$T] of any $U: merge(array[$T] of any $U, array[$T] of any $U)
\end{verbatim}
}

\builtin{}
Index sets of arrays.  If the argument is a literal, returns \texttt{1..n}
where \texttt{n} is the (sub-)array length.  Otherwise, returns the declared
or inferred index set.  This list is only partial, it extends in the obvious
way, for arrays of higher dimensions.
\begin{verbatim}
  set of $T:  index_set     (array[$T]      of any $V)
  set of $T:  index_set_1of2(array[$T, $U]  of any $V)
  set of $U:  index_set_2of2(array[$T, $U]  of any $V)
  ...
\end{verbatim}

\ignore{
\builtin{}
Get the first and last elements of an array, and the tail of an array (i.e.~all
elements except the first).  All of them abort if the array is empty.
\begin{verbatim}
  any $U:              head(array[$T] of any $U)
  any $U:              last(array[$T] of any $U)
  array[$T] of any $U: tail(array[$T] of any $U)
\end{verbatim}
}

\builtin{}
Replace the indices of the array given by the last argument with the
Cartesian product of the sets given by the previous arguments.  Similar
versions exist for arrays up to 6 dimensions.
\begin{verbatim}
  array[$T1] of any $V: array1d(set of $T1, array[$U] of any $V)
  array[$T1,$T2] of any $V:
      array2d(set of $T1, set of $T2, array[$U] of any $V)
  array[$T1,$T2,$T3] of any $V:
      array3d(set of $T1, set of $T2, set of $T3, array[$U] of any $V)
\end{verbatim}

\ignore{
\builtin{}
Merges an array-of-arrays into an array, by folding \texttt{merge} over
the array-of-arrays.  It is a run-time error if any of the indices are
repeated in the result.
\begin{verbatim}
  array[$U] of $V: array_merge(array[$T] of array[$U] of $V)
\end{verbatim}

\builtin{}
Condenses an array-of-arrays into an array, by folding \texttt{++} over
the array-of-arrays.
The resulting indices are in the range \texttt{1..n}, where \texttt{n} is the
sum of the lengths of the arrays in the argument.
\begin{verbatim}
  array[int] of $T: condense(array[$U] of array[int] of $T)
\end{verbatim}
}

%---------------------------------------------------------------------------%
\subsection{Coercion Operations}
%---------------------------------------------------------------------------%
\builtin{}
Round a float towards $+\infty$, $-\infty$, and the nearest integer,
respectively.
\begin{verbatim}
  int: ceil (float)
  int: floor(float)
  int: round(float)
\end{verbatim}

\builtin{}
Explicit casts from one type-inst to another.
\begin{verbatim}
      int:          bool2int(    bool)
  var int:          bool2int(var bool)
      float:        int2float(    int)
  var float:        int2float(var int)
  array[int] of $T: set2array(set of $T)
\end{verbatim}


%---------------------------------------------------------------------------%
\subsection{String Operations}
%---------------------------------------------------------------------------%
\builtin{}
To-string conversion.  Converts any value to a string for output purposes.
The exact form of the resulting string is implementation-dependent.
\begin{verbatim}
  string: show(any $T)
\end{verbatim}

\builtin{}
Formatted to-string conversion for integers.
Converts the integer given by the second argument into a string right justified
by the number of characters given by the first argument, or left justified
if that argument is negative.
If the second argument is not fixed, the form of the string is
implementation-dependent.
\begin{verbatim}
  string: show_int(int, var int);
\end{verbatim}

\builtin{}
Formatted to-string conversion for floats.
Converts the float given by the third argument into a string right
justified by the number of characters given by the first argument, or left
justified if that argument is negative.
The number of digits to appear after the decimal point is given by
the second argument.
It is a run-time error for the second argument to be negative.
If the third argument is not fixed, the form of the string is
implemenation-dependent.
\begin{verbatim}
  string: show_float(int, int, var float)
\end{verbatim}

\builtin{}
String concatenation.  Note that \texttt{'++'} also performs array
concatenation.
\begin{verbatim}
  string: '++'(string, string)
\end{verbatim}

\builtin{}
Concatenate an array of strings.
Equivalent to folding \texttt{'++'} over the array, but may be implemented more
efficiently.
\begin{verbatim}
   string: concat(array[$T] of string)
\end{verbatim}

\builtin{}
Concatenate an array of strings, putting a seperator beween adjacent strings.
Returns the the empty string if the array is empty.
\begin{verbatim}
   string: join(string, array[$T] of string)
\end{verbatim}

%-----------------------------------------------------------------------------%
\subsection{Bound and Domain Operations}
%-----------------------------------------------------------------------------%

\ignore{
\builtin{}
\begin{verbatim}
         $T:       lb(any $T)
         $T:       ub(any $T)
  set of $T:      dom(any $T)
        int: dom_size(any $T)
\end{verbatim}

The bound operations \texttt{lb/ub} return fixed, correct lower/upper bounds
to the expression.
%
For numeric types, they return a lower/upper bound value,
e.g.\ the lowest/highest value the expression can take.
Similarly for Boolean expressions.
%
For set types, they return a subset/superset,
e.g.\ the intersection/union of all possible values of the set expression.
%
%For tuple/record types, they return a tuple/record
%containing the lower/upper bound of each element.
%
For array types, they return an array of corresponding index set
containing the lower/upper bound of each array element.
%
For example, the lower bound of a set variable that could equal
\texttt{\{1,3,5\}} or \texttt{\{1,2,4\}} is \texttt{\{1}\}, and the upper bound
is \texttt{\{1,2,3,4,5\}}.

The bound operations abort on expressions that have no corresponding finite bound.
For example, this would be the case for a variable declared without bounds
in an implementation that does not assign default bounds.
(Set expressions always have a finite lower bound of course,
namely \texttt{\{\}}, the empty set.)


\vspace{2mm}

The domain operation \texttt{dom} returns a fixed superset
of the possible values of the expression.
%
The \texttt{dom} operation aborts on array expressions.

% We could define dom for array values, but it would consume a large
% amount of space for all but trivial arguments.
%
%   For example, for array values, it returns a set of arrays
%   containing the possible values for each element:
%   \begin{verbatim}
%      var 1..2: x;
%      var 5..6: y;
%
%      dom([1:x, 3:y]) = {[1:1, 3:5], [1:1, 3:6], [1:2, 3:5], [1:2, 3:6]};
%   \end{verbatim}

\vspace{2mm}
}




The bound operations \texttt{lb/ub} return fixed, correct lower/upper bounds
to the expression.
%
For numeric types, they return a lower/upper bound value,
e.g.\ the lowest/highest value the expression can take.
%Similarly for Boolean expressions.
%
For set types, they return a subset/superset,
e.g.\ the intersection/union of all possible values of the set expression.

The bound operations abort on expressions that have no corresponding finite bound.
For example, this would be the case for a variable declared without bounds
in an implementation that does not assign default bounds.
(Set expressions always have a finite lower bound of course,
namely \texttt{\{\}}, the empty set.)


\vspace{2mm}



\builtin{}
Numeric lower/upper bound:
\begin{verbatim}
  int:   lb(var int)
  float: lb(var float)
  int:   ub(var int)
  float: ub(var float)
\end{verbatim}

\builtin{}
Set lower/upper bound:
\begin{verbatim}
  set of int: lb(var set of int)
  set of int: ub(var set of int)
\end{verbatim}

\builtin{}
Versions of the bound operations that operate on arrays are also available,
they return a safe lower bound or upper bound for all members of the array
 -- they abort if the array is empty:
\begin{verbatim}
  int:        lb_array(array[$T] of var int)
  float:      lb_array(array[$T] of var float)
  set of int: lb_array(array[$T] of var set of int)
  int:        ub_array(array[$T] of var int)
  float:      ub_array(array[$T] of var float)
  set of int: ub_array(array[$T] of var set of int)
\end{verbatim}

\builtin{}
Integer domain:
\begin{verbatim}
  set of int: dom(var int)
\end{verbatim}
The domain operation \texttt{dom} returns a fixed superset
of the possible values of the expression.

\builtin{}
Integer array domain, returns a superset of all possible values that may
appear in the array -- this aborts if the array is empty:
\begin{verbatim}
  set of int: dom_array(array[$T] of var int)
\end{verbatim}
% \pjs{It could return an empty set?}

\builtin{}
Domain size for integers:
\begin{verbatim}
  int: dom_size(var int)
\end{verbatim}
The domain size operation \texttt{dom\n{}size} is equivalent
to \texttt{card(dom(x))}.

\vspace{2mm}

Note that these operations can produce different results depending on when
they are evaluated and what form the argument takes.  For example, consider
the numeric lower bound operation.
\begin{itemize}
\item
    If the argument is a fixed expression, the result is the argument's
    value.
\item
    If the argument is a decision variable, then the result depends on
    the context.
    \begin{itemize}
    \item
        If the implementation can determine a lower bound for the variable,
        the result is that lower bound.
        The lower bound may be from the variable's declaration,
        or higher than that due to preprocessing,
        or lower than that if an implementation-defined lower bound is applied
        (e.g.~if the variable was declared with no lower bound,
        but the implementation imposes a lowest possible bound).
    \item
        If the implementation cannot determine a lower bound for the variable,
        the operation aborts.
    \end{itemize}
\item
    If the argument is any other kind of unfixed expression, the
    lower bound depends on the bounds of unfixed subexpressions
    and the connecting operators.
\end{itemize}

%-----------------------------------------------------------------------------%
\subsection{Option Type Operations}
     \label{Option Type Operations}
%-----------------------------------------------------------------------------%

\builtin{}
The option type value ($\top$) is written
\begin{verbatim}
  opt $T:  '<>';
\end{verbatim}

One can determine if an option type variable actually occurs on not using
\texttt{occurs} and \texttt{absent}
\begin{verbatim}
  par bool: occurs(par opt $T);
  var bool: occurs(var opt $T);
  par bool: absent(par opt $T);
  var bool: absent(var opt $T);
\end{verbatim}

One can return the non-optional value of an option type variable using the
function \texttt{deopt}
\begin{verbatim}
  par $T: deopt{par opt $T);
  var $T: deopt(var opt $T);
\end{verbatim}
% Note that this is not really a function only a pseudo function placeholder
% used in the translation of option types to non-option types.
% \pjs{Explain better}

%-----------------------------------------------------------------------------%
\subsection{Other Operations}
     \label{Other Operations}
%-----------------------------------------------------------------------------%
\builtin{}
Check a Boolean expression is true, and abort if not, printing the second
argument as the error message.  The first one returns the third argument, and
is particularly useful for sanity-checking arguments to predicates and
functions;  importantly, its third argument is lazy, i.e.~it is only evaluated
if the condition succeeds.  The second one returns \texttt{true} and is useful
for global sanity-checks (e.g.~of instance data) in constraint items.
\begin{verbatim}
  any $T:   assert(bool, string, any $T)
  par bool: assert(bool, string)
\end{verbatim}

\builtin{}
Abort evaluation, printing the given string.
\begin{verbatim}
  any $T: abort(string)
\end{verbatim}

\builtin{}
Return true. As a side-effect, an implementation may print the first argument.
\begin{verbatim}
  bool: trace(string)
\end{verbatim}

\builtin{}
Return the second argument.
As a side-effect, an implementation may print the first argument.
\begin{verbatim}
  any $T: trace(string, any $T)
\end{verbatim}

\builtin{}
Check if the argument's value is fixed at this point in evaluation.  If not,
abort; if so, return its value.  This is most useful in output items when
decision variables should be fixed---it allows them to be used in places
where a fixed value is needed, such as if-then-else conditions.
\begin{verbatim}
  $T: fix(any $T)
\end{verbatim}

\builtin{}
As above, but return \texttt{false} if the argument's value is not fixed.
\begin{verbatim}
  par bool: is_fixed(any $T)
\end{verbatim}

\ignore{
\builtin{}
Fold a binary function over an array in a left-associative manner.  For
example, \texttt{foldl('+', 0, xs)} is \texttt{sum}, and
\texttt{foldl('}\verb+/\+\texttt{', true, xs)} is \texttt{forall}.
\begin{verbatim}
  any $T: foldl(any $T:(any $T,any $U), any $T, array[$V] of any $U)
\end{verbatim}

\builtin{}
Fold a binary function over an array in a right-associative manner.
\begin{verbatim}
  any $T: foldr(any $T:(any $U,any $T), any $T, array[$V] of any $U)
\end{verbatim}
}

%===========================================================================%
\clearpage
\section{MiniZinc Grammar}
  \label{Grammar}
%===========================================================================%

Section~\ref{Syntax Notation} describes the notation used in the following
Zinc grammar.

%---------------------------------------------------------------------------%
\subsection{Items}
%---------------------------------------------------------------------------%
\begin{productions}
    \RuleModel \\
    \\
    \RuleItem \\
    \\
    \RuleTypeInstSynItem \\
    \\
 %   \RuleEnumItem \\
 %   \RuleEnumCases \\
 %   \RuleEnumCase \\
    \RuleTIExprAndId \\
    \\
    \RuleIncludeItem \\
    \\
    \RuleVarDeclItem \\
    \\
    \RuleAssignItem \\
    \\
    \RuleConstraintItem \\
    \\
    \RuleSolveItem \\
    \\
    \RuleOutputItem \\
    \\
    \RuleAnnotationItem \\
    \\
    \RulePredicateItem \\
    \RuleTestItem \\
    \RuleFunctionItem \\
    \RuleOperationItemTail \\
    \RuleParams
\end{productions}

%---------------------------------------------------------------------------%
\subsection{Type-Inst Expressions}
%---------------------------------------------------------------------------%
\begin{productions}
    \RuleTIExpr \\
    \RuleBaseTIExpr \\
    \RuleVarPar \\
    \RuleBaseTIExprTail \\
    \\
    \RuleSetTIExprTail \\
    \\
    \RuleArrayTIExprTail \\
    \\
%    \RuleTupleTIExprTail \\
%    \\
%    \RuleRecordTIExprTail \\
%    \\
    \RuleTIVariableExprTail \\
    \\
    \RuleOpTIExprTail
\end{productions}

%---------------------------------------------------------------------------%
\subsection{Expressions}
%---------------------------------------------------------------------------%
\begin{productions}
    \RuleExpr \\
    \RuleExprAtom \\
    \RuleExprBinopTail \\
    \RuleExprAtomHead \\
    \RuleExprAtomTail \\
    \\
    \RuleNumExpr \\
    \RuleNumExprAtom \\
    \RuleNumExprBinopTail \\
    \RuleNumExprAtomHead \\
    \\
    \RuleBuiltinOp \\
    \RuleBinOp \\
    \RuleBuiltinBinOp \\
    \RuleBuiltinUnOp \\
    \\
    \RuleNumBinOp \\
    \RuleBuiltinNumBinOp \\
    \RuleBuiltinNumUnOp \\
    \\
    \RuleBoolLiteral \\
    \\
    \RuleIntLiteral \\
    \\
    \RuleFloatLiteral \\
    \\
    \RuleStringLiteral \\
    \\
    \RuleSetLiteral \\
    \\
    \RuleSetComp \\
    \RuleCompTail \\
    \RuleGenerator \\
    \\
    \RuleSimpleArrayLiteral \\
    \\
    \RuleSimpleArrayLiteralTwoD \\
    \\
    \RuleSimpleArrayComp \\
    \\
%    \RuleIndexedArrayLiteral \\
%    \RuleIndexExpr \\
%    \\
%    \RuleIndexedArrayComp \\
    \\
    \RuleArrayAccessTail \\
    \\
%    \RuleTupleLiteral \\
%    \\
%    \RuleTupleAccessTail \\
%    \\
%    \RuleRecordLiteral \\
%    \RuleNamedExpr \\
%    \\
%    \RuleRecordAccessTail \\
%    \\
%    \RuleEnumLiteral \\
    \\
    \RuleAnnLiteral \\
    \\
    \RuleIfThenElseExpr \\
    \\
%    \RuleCaseExpr \\
%    \RuleCaseExprCase \\
    \\
    \RuleCallExpr \\
    \\
    \RuleLetExpr \\
    \RuleLetItem \\
    \\
    \RuleGenCallExpr
\end{productions}

%---------------------------------------------------------------------------%
\subsection{Miscellaneous Elements}
%---------------------------------------------------------------------------%
\begin{productions}
    \RuleIdent \\
    \RuleIdentOrQuotedOp \\
    \\
    \RuleAnnotations \\
    \RuleAnnotation
\end{productions}


\ignore{
%=============================================================================%
\clearpage
\section{MiniZinc}
  \label{MiniZinc}
%=============================================================================%
MiniZinc is modelling language that is a subset of Zinc.  It is easier to
implement, and it can be flattened into FlatZinc in a straightforward
manner.  For more details on the goals of MiniZinc and FlatZinc, please read
\CommonMiniZincPaperTitleAndAuthors{}.

This section defines MiniZinc by describing the features from Zinc that it
does not support.  The two languages have identical grammars, although
various syntactically-correct constructs are not valid in MiniZinc
programs, and should be rejected by post-parsing checks.

\Rationale{In the past, the two languages did have distinct grammars, but
combining them makes this document much simpler.  It also makes the
implementation of MiniZinc a little simpler.  It can also allow for better
error messages if a Zinc-only feature is used in a MiniZinc program;  for
example, if an enum item appears in a MiniZinc program, instead of a syntax
error such as ``syntax error at \texttt{enum}'', a more helpful error such
as ``MiniZinc does not allow enum items'' can be emitted.  And it allows
Zinc features to be added to MiniZinc more easily later on, should we
desire.}

%---------------------------------------------------------------------------%
\subsection{Items}
%---------------------------------------------------------------------------%
MiniZinc has the following restrictions on items.
\begin{itemize}
\item Type-inst synonym items are not supported.
\item Enum items are not supported.
\item User-defined function items are not supported.
\item \CommonSolveMinMaxExprTypeInst{}
\end{itemize}

%---------------------------------------------------------------------------%
\subsection{Type-insts and Expressions}
%---------------------------------------------------------------------------%
MiniZinc has the following restrictions on type-insts and expressions.
\begin{itemize}
\item
    Sets can only contain Booleans, integers, and floats.  Sets of integers
    may be fixed or unfixed;  other sets must be fixed.
\item
    Arrays must have indices that are contiguous integer ranges
    (e.g.~\texttt{0..3}, \texttt{10..12}, or the name of a set variable
    assigned in the model with a range value), or a tuple of contiguous
    integer ranges.

    Furthermore, MiniZinc arrays must be declared with index types that are
    explicit ranges, or variables that are assigned a range value.  Because
    these types are finite, only explicitly-indexed array variables can be
    declared in MiniZinc.  The one exception is that implicitly-indexed
    arrays are allowed as arguments to predicates and annotations.
\item
    Arrays can only contain Booleans, integers, floats or sets of integers
    (all fixed or unfixed), or fixed sets of Booleans or floats, or fixed
    strings.  Arrays-of-arrays are not supported.
\item
    Indexed array literals and comprehensions are not supported.
\item
    Tuples can only be used as array indices, and must contain integers, and
    must be fixed.  Furthermore, neither tuple literals nor tuple accesses
    are supported.
\item
    Records are not supported.  Therefore, neither record literals nor
    record accesses are supported.  Furthermore, there are no local
    namespaces for record field names.
\item
    Enums are not supported, including in data files.  Therefore, case
    expressions are not supported.  Furthermore, there are no local
    namespaces for (non-flat) enum field names.
\item
    The language is entirely first-order;  no higher-order types are
    supported, operation type-inst expressions are not supported, and
    operations cannot be used as values.
\item
    Arbitrarily constrained type-insts are not supported.
\item
    Implicit type coercions (e.g.~int-to-float, set-to-array) are not supported,
    with one exception: set-to-array coercions are allowed in comprehension
    generators.  This allows sets to be used as generator expressions, which
    is very convenient.

    However, explicit type coercions are supported
    (e.g.~\texttt{int2float}), as are implicit inst coercions
    (e.g.~par-int-to-var-int).
\item
    Type-inst variables are not supported in user-defined predicates and
    functions.  However, many of the built-in operations,
    e.g.~\texttt{show}, have signatures that feature type-inst variables,
    and they work with all valid matching MiniZinc types.
\end{itemize}

%---------------------------------------------------------------------------%
\subsection{Built-in Operations}
%---------------------------------------------------------------------------%
MiniZinc has restrictions on built-in operations.
\begin{itemize}
\item
    The comparison operators are not supported for arrays. That is,
    only the following signatures of `\texttt{<}' are supported
    (and likewise for the other comparison operators):
\begin{verbatim}
      bool: '<'(    int,              int)
  var bool: '<'(var int,          var int)
      bool: '<'(    float,            float)
  var bool: '<'(var float,        var float)
      bool: '<'(    bool,             bool)
  var bool: '<'(var bool,         var bool)
      bool: '<'(    string,           string)
      bool: '<'(    set of int,       set of int)
      bool: '<'(    set of bool,      set of bool)
      bool: '<'(    set of float,     set of float)
  var bool: '<'(var set of int,   var set of int)
\end{verbatim}

\item
    Only the following signatures of \texttt{min} are supported (and
    likewise for \texttt{max}):
\begin{verbatim}
      int:   min(    int,       int)
  var int:   min(var int,   var int)
      float: min(    float,     float)
  var float: min(var float, var float)
      int:   min(array[int] of     int)
  var int:   min(array[int] of var int)
      float: min(array[int] of     float)
  var float: min(array[int] of var float)
      int:   min(set of int)
      float: min(set of float)
\end{verbatim}
\item
    Only the following signatures of `\texttt{in}' are supported:
\begin{verbatim}
      bool: 'in'(    int,      set of int)
      bool: 'in'(    bool,     set of bool)
      bool: 'in'(    float,    set of float)
  var bool: 'in'(var int,  var set of int)
\end{verbatim}

\item
    For \texttt{array1d}, \texttt{array2d}, etc., the set arguments must be
    contiguous integer sets, otherwise it is a run-time error.

\item
    % XXX: ones that could be in MiniZinc: concat, head/last/tail,
    % foldl/foldr (which would require lifting the "entirely
    % first-order" restriction above).
    The following built-in operations are not supported:    % (and why not?)
    \texttt{powerset},                                      % set-of-set
    \texttt{cartesian\n{}product},                          % tuples
    \texttt{concat},                                        % (no reason)
    \texttt{head}, \texttt{last}, \texttt{tail},            % (no reason)
    \texttt{condense}, \texttt{condense\n{}int\n{}index},   % array-of-arrays
    \texttt{foldl}, \texttt{foldr}.                         % (no reason)
\iffalse
\item
    The following built-in annotations are not supported:
    \texttt{tree\n{}search}.
\fi
\end{itemize}



\iffalse

% [Seb]
% The "globals" library files aren't mentioned anywhere else in this document.
%-----------------------------------------------------------------------------%
\subsection{Other}
%-----------------------------------------------------------------------------%
MiniZinc has the following other restrictions.
\begin{itemize}
\item
    \texttt{globals.mzn} is the equivalent to the Zinc \texttt{globals.zinc}
    library.
\end{itemize}
\fi
}

%=============================================================================%
\clearpage
\section{Content-types}
  \label{Content-types}
%=============================================================================%

%-----------------------------------------------------------------------------%
\subsection{`application/x-zinc-output'}
  \label{x-zinc-output}
%-----------------------------------------------------------------------------%

The content-type `application/x-zinc-output' defines
a text output format for Zinc.
The format extends the abstract syntax and semantics
given in Section~\ref{Run-time Outcomes},
and is discussed in detail in Section~\ref{Output}.

The full syntax is as follows:

\begin{productions}
\RuleOutput \\
\\
\RuleSolution \\
\\
\RuleOutcomeStrings \\
\\
\RuleComplete \\
\\
\RuleWarnings \\
\\
\RuleMessage
\end{productions}

\noindent
The solution text for each solution must be
as described in Section~\ref{Output Items}.
A newline must be appended if the solution text does not end with a newline.

%-----------------------------------------------------------------------------%

%=============================================================================%
\clearpage
\section{JSON support}
  \label{json}
%=============================================================================%

MiniZinc can support reading input parameters and providing output formatted
as JSON objects. A JSON input file needs to have the following structure:

\begin{itemize}
  \item Consist of a single top-level object
  \item The members of the object (the key-value pairs) represent model parameters
  \item Each member key must be a valid MiniZinc identifier (and it supplies the value for the corresponding parameter of the model)
  \item Each member value can be one of the following:
  \begin{itemize}
    \item A string (assigned to a MiniZinc string parameter)
    \item A number (assigned to a MiniZinc int or float parameter)
    \item The values \texttt{true} or \texttt{false} (assigned to a MiniZinc bool parameter)
    \item An array of values. Arrays of arrays are supported only if all inner arrays are of the same length, so that they can be mapped to multi-dimensional MiniZinc arrays.
    \item A set of values encoded as an object with a single member with key \verb|"set"| and a list of values (the elements of the set).
  \end{itemize}
\end{itemize}

This is an example of a JSON parameter file using all of the above features:

\begin{verbatim}
    {
      "n" : 3,
      "distances" : [ [1,2,3],
                      [4,5,6]],
      "patterns"  : [ {"set" : [1,3,5]}, {"set" : [2,4,6]} ]
    }
\end{verbatim}

The first parameter declares a simple integer \texttt{n}. The \texttt{distances} parameter is a two-dimensional array; note that all inner arrays must be of the same size in order to map to a (rectangular) MiniZinc two-dimensional array. The third parameter is an array of sets of integers.

\end{document}

