\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}

\usepackage{titling}
\usepackage{hyperref}

\predate{\par\large\centering}
\postdate{\par}

\title{Gambleswap}
\author{Gambleswap Team}
\date{March 2022}

\begin{document}

\maketitle

\begin{abstract}

Gambleswap is a gambling powered Constant Product Automated Market Making protocol. Liquidity providers will be given \$GMB as a form of passive income and may enter into a gambling game to bet with their \$GMBs. Liquidity providers also can lend their LP tokens to those who do not have enough LP tokens for participating in the gambling game, thus, unlocking leveraging the value locked in liquidity pools even more.
The chance of winning in the game is proportional to the \$GMBs each user has put in the game. Also, it's designed to have the ability to control the total supply and price of \$GMB.

\end{abstract}

\section{Decentralized Exchange}
As a fork of Uniswap, Gambleswap is, in its core, a decentralized liquidity pool based exchange. Liquidity pools contain a huge amounts of two different assets like $aToken$ and $bToken$.
Users can use these pools to swap their $aTokens$ with $bTokens$ or vice versa. The ratio between the amount of token a user deposits and the amount of the token they take out is calculated through an Automated Market Maker (AMM) which will be discussed more later (For more details, see Appendix~\ref{app:amm}).
In Gambleswap, in addition to LP tokens, they also receive \$GMB. These tokens can be used to participate in the gambling and later moderating the Gambleswap ecosystem.

\section{Tokenomics}

Gambleswap has introduced GMB as the main token for particpation to empower its underlying automated market maker.
LP token holders will receive \$GMB as rewards. Later, they can use them to participate in the gambling.

\subsection{Mint GMB}

A fixed number of \$GMB is minted in each block. Each liquidity provider will receive a fraction of these tokens which is proportional to the amount of their LP tokens. In order to get these \$GMBs, the user needs to claim them. When a user $u$ claims that they should receive GMB tokens, the contract calculates the effective number of LP tokens that the user has and then find out their available number of GMB tokens to be minted. Effective LP tokens includes the amount of LP tokens that user holds at the time of calling claim, plus what he already has locked in the gambling game of the last recent 10 rounds, plus what he has lent:

$$
\text{ number of GMB tokens } u \text{ gets in a claim} =
$$
$$
\text{ GMB to mint per LP token }
$$
$$
\times \text{ effective number of LP tokens for the user} u
$$
$$
- \text{ number of all the GMB tokens that } u \text{ minted so far}
$$

% $$\times (\frac{\text{number of } u \text{'s LP tokens}}{\text{total LP tokens}})
% $$

To make it easier for the users to receive their \$GMB, the pool contract automatically claims these tokens for them whenever they update their LP token value, i.e. when they deposit liquidity to or withdraw liquidity from the pool.

\subsection{Burn GMB}
To be able to control the supply of \$GMB, the gambling game designed to burns some of the minted tokens on a regularly basis. We will discuss it in more details in the following sections.

\section{Gambling Game}
The gambling game is the powerful core of the enhancements added to Gambleswap's AMM logic. The rules of the game can be basically listed as follows:
\begin{itemize}
    \item Participants send their GMB tokens into the gambling contract. These tokens are accumulated to form our jackpot. They also send their bet values, which is a number they have guessed within a particular interval.
    \item Participants need to either own some LP tokens of the certain set of liquidity pools (called authorised pools) or borrow them from the LP lending pool to be able to play the game. Their LP tokens are locked during the game, and afterward, they can unlock them regardless of whether they win or lose. This rule intends to motivate users to provide liquidity in our pools.
    \item A random number is generated using some properties of the block like block number, block difficulty, and block timestamp.
    \item If the number a user has bet on falls inside a certain distance from the randomly generated number, that user is one of the winners of the game. This distance gets larger depending on the amount of GMB tokens they have deposited into the jackpot.
    \item 25\% of the jackpot of each round, and all the accumulated GMBs after every fourth game will be burnt. This is done in order to control the GMB total supply.
    \item If a game doesn't have any winners, the jackpot's contents remain in the jackpot and will be used in the next round. This motivates users to participate in the game if they see there is a non-empty jackpot before they start the game. Therefore, the number of participants can grow substantially.
    \item The maximum chance of winning is 50\%. It means if a player owns all the \$GMBs in the jackpot, they have a maximum 50\% chance of winning.
\end{itemize}

\subsection{Determining winners}
We introduce a variable as $coveragePerGMB$. This value demonstrates the length of the interval that each GMB token covers. Participants can increase their coverage by having more GMBs in the game. User's coverage shows the maximum distance the user's bet value can have with the correct random number for the user to win. The greater this value, the more chance the user has for winning. This value is calculated as follows.

\begin{align*}
    \text{user's coverage} &= min( \frac{1}{4} \times \text{maximum random number}, \\
    &coveragePerGMB \times \text{user's GMB tokens})
\end{align*}

the $\frac{1}{4} \times \text{maximum random number}$ is there to bound the maximum chance of winning to 50 percent.

Users have more chance to win by putting more GMB in the jackpot; each user wins if their bet value falls inside this interval:
$$
(\text{correct random number} - \text{user's coverage},$$
$$
\text{correct random number} + \text{user's coverage})
$$

The $coveragePerGMB$ value in each round is calculated based on the value of the jackpot in the previous game. For the first game, we assume the coveragePerGMB value is 10, and for games after that, we have:
$$
coveragePerGMB = \frac{\text{maximum random number}}{\text{4}
\times \text{total jackpot of the previous game}}
$$

In the other words the coveragePerGMB is a dynamic value depending on the previous game. In each game, this value is the same for all users.
If the number of participants in one game is small, the chance of winning in the next game goes higher; Consequently, more users are encouraged to participate in the next round. Figure \ref{fig:coverage} illustrates the process of determining the winners.

\begin{figure}
    \centering
    \includegraphics[width=\textwidth]{coverage.png}
    \caption{The blue interval shows the entire interval the random number can fall into. If the random number falls into the user's coverage, user will be one of the winners.}
    \label{fig:coverage}
\end{figure}

\subsection{LP Lending}
Gambleswap introduces users a LP lending protocol to participate in gambling game without the need to provide liquidity. There are two user's types in this lending protocol:
\begin{itemize}
    \item Lenders: Users who have LPs can lend their tokens from different pools; In return, after each round of the game, they will be given interest per borrow in form of GMB tokens.
    \item Borrowers: Users who do not have any LP tokens and can participate in each round of the game by borrowing lenders LP tokens. In return, they have to pay the interest to the lenders.
\end{itemize}

Each round of the game has its own capacity on the lending contract, and after each round, the capacity will be released for the upcoming round of the game. Every authorised liquidity pool has a separate lending pool and interest per borrow. Whenever a user attempts to borrow LP token, the lending contract finds the cheapest available pool which has enough capacity, and lends the needed amount of LP token to the user.
Lenders share the accumulated interest of their corresponding pool proportional to their share of the lending pool.

\subsection{Overflow/Underflow in the interval}
The generated interval for each user may exceed the $Maximum Random Number$ or may become less than $zero$. There are three scenarios for an interval:
\begin{itemize}
    \item Overflow: It happens when
    $$CorrectRandomNumber + UserCoverage > MaximumRandomNumber$$ In this scenario, the remaining  amount of the user's coverage will be considered from 0 to the OverflowValue.

    \begin{align*}
        \text{OverflowValue} &= \text{UserCoverage} \\ &+ \text{CorrectRandomNumber} \\ &-  \text{MaxRandomNumber}
    \end{align*}

    Users  will win when the below condition holds:
    $$(\text{betValue} > (\text{correctRandomNumber} - \text{UserCoverage})$$
    $$\lor$$
    $$
     \text{betValue} < \text{overflowValue}
    $$

    \item Underflow: This happens when
    $$UnderflowValue = UserInterval - CorrectRandomNumber$$
    Users  will win when the below condition holds:
    $$
    (\text{betValue} > (\text{maxRandomNumber} - \text{UnderflowValue}))
    $$
    $$\lor$$
    $$
     (\text{betValue} < (\text{CorrectRandomNumber} + \text{UserCoverage}))
    $$

    Figure \ref{fig:overflow} shows the coverage of the user in cases of underflow and overflow.

    \item Normal: In this scenario users will win when their $betValue$ is in the below interval:
    $$
    {CorrectRandomNumber \pm{UserInterval}}
    $$
\end{itemize}

\begin{figure}
    \centering
    \includegraphics[width=\textwidth]{coverage2.png}
    \caption{User's coverage in underflow and overflow cases.}
    \label{fig:overflow}
\end{figure}

\subsection{Expected value of net profit}

Let's assume user $u_i$ deposits $a_i$ GBM tokens in the gambling contract. The random number can be between zero and the maximum. Let's assume the maximum is $M$ and the number of participants is $n$ and number of winners is $W$. Also, $\frac{1}{4}$ of the tokens are burnt.
Therefore, the probability of $u_i$ being one of the winners is:
\begin{equation*}
    p_i = a_i \times \frac{1}{4\times (\sum_{i = 0}^{n} a_i)_{lastRound}}
\end{equation*}
Hence, the expected value of $u_i$'s profit in one round of gambling is:
\begin{align*}
    E[profit(u_i)] &= p_i \times \frac{3\sum_{i=0}^{n}a_i}{4W} \\
    &=
    a_i \times \frac{1}{4\times (\sum_{i = 0}^{n} a_i)_{lastRound}} \times
    \frac{3\sum_{i=0}^{n}a_i}{4W} \\
    &=
    \frac{a_i}{16 W} \times \frac{3\sum_{i=0}^{n} a_i}{(\sum_{i=0}^{n} a_i)_{lastRound}}
\end{align*}

As we see, when the number of players increases in one round in respect to the last round, the probability of winning increases. If we assume the
$\frac{\sum_{i=0}^{n} a_i}{(\sum_{i=0}^{n} a_i)_{lastRound}}$ factor to be close to one, we can see that

$$
E[profit(u_i)] \approx \frac{3a_i}{16W}
$$
So, the expected net profit of the the $u_i$ is approximately
$
\frac{3a_i}{16W} - a_i
$.

\section{Conclusion}
Gambleswap seeks to unlock the hundreds of millions of dollars in value locked in a decentralized exchange. Up until now, the community has shown great enthusiasm toward gambling and lottery games. The economic dynamics behind Gambleswap's gambling game also incentivizes people to provide even more liquidity.

\pagebreak
\appendix
\label{app:amm}
\section{Automated Market Maker}
As mentioned before there are two tokens in each liquidity pool in an AMM-based exchange. The ratio between the amount of one token a user takes out and the amount of the other token the user endows, are calculated using a constant product equation.
Assume the amounts of the tokens are $R_a$ and $R_b$ before the swap. A user can deposit $x$ tokens of $R_a$ in the pool and take $y$ tokens of $R_b$ out.
A small portion of $x$ is taken as a fee. This fee is divided between all liquidity providers proportional to their share in the pool. The fee ratio is shown by $\mu$. Now, because the product of the two tokens amounts should remain equal to $k$, we can calculate $y$ like this:

\begin{align*}
    R_a R_b &= (R_a + (1 - \mu)x)(R_b - y) \\
    \to (1 - \mu)xR_b &= (1 - \mu)xy + yR_1 \\
    \to y &= R_b - \frac{R_aR_b}{R_a + (1 - \mu)x}
\end{align*}

\end{document}


%!TEX root = ../../common/main.tex

\chapter[
  head={Supplementary material to the measurement of \sintwobetait},
  tocentry={Supplementary material to the measurement of \sintwobetabfsfHyperref}
]
{Supplementary material to the measurement of \sintwobetabfsf}
\label{ch:app:measurement_of_sin2beta}

% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Decay time resolution and acceptance}
\label{sec:app:measurement_of_sin2beta:resolution_and_acceptance}

% ------------------------------------------------------------------------------
\subsection{Resolution}
\label{sec:app:measurement_of_sin2beta:resolution_and_acceptance:resolution}

For the \catDD candidates
\cref{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:dd}
shows the fit results of the $\chisq$-fit of the decay time error estimate
calibration parameters for a linear function and a parabolic function with
offset parameter, while
\cref{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:ll}
includes fit results for the \catLL subsample where a linear function and a
parabolic function without offset parameter are fitted.
%
\begin{table}[h]
\centering
\caption{Fit parameters of the decay time resolution calibration functions for the \catDD subsample.}
\label{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:dd}
  \begin{tabular}{lllr@{$\,\pm\,$}lr@{$\,\pm\,$}l}
    \toprule
    Model                       & \multicolumn{2}{c}{Parameter}               &   \multicolumn{2}{c}{narrow width ($i = 1$)}  & \multicolumn{2}{c}{wider width ($i = 2$)}\\
    \midrule
    \multirow{2}{*}{linear}     &   $b_{i}$       &                           &   0.89    &   0.10                  &   1.34        &   0.29    \\
                                &   $c_{i}$       &  (\si{\pico\second})      &   0.008   &   0.004                 &   0.018       &   0.011   \\
    \midrule
    \multirow{3}{*}{parabolic}  &   $a_{i}$      &  (\si{\per\pico\second})  &   -3      &   6                     &   -1          &   17      \\
                                &   $b_{i}$      &                           &    1.2     &   0.5                   &   1.4         &   1.4     \\
                                &   $c_{i}$      &  (\si{\pico\second})      &   0.003   &   0.010                 &   0.016       &   0.028   \\
    \bottomrule
  \end{tabular}
\end{table}
%
\begin{table}[h]
\centering
\caption{Fit parameters of the decay time resolution calibration functions for the \catLL subsample.}
\label{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:ll}
  \begin{tabular}{lllr@{$\,\pm\,$}lr@{$\,\pm\,$}l}
    \toprule
    Model                       & \multicolumn{2}{c}{Parameter}     &  \multicolumn{2}{c}{narrow width ($i = 1$)} &  \multicolumn{2}{c}{wider width ($i = 2$)}\\
    \midrule
    \multirow{2}{*}{linear}     & $b_{i}$  &                          &   1.10        &   0.07            &   1.81        &   0.26    \\
                                & $c_{i}$  & (\si{\pico\second})      &   0.0034      &   0.0019          &   0.009       &   0.008   \\
    \midrule
    \multirow{2}{*}{parabolic}  & $a_{i}$  & (\si{\per\pico\second})  &   -4.7        &   2.1             &   -6          &   8       \\
                                & $b_{i}$  &                          &   1.36        &   0.07            &   2.27        &   0.26    \\
    \bottomrule
  \end{tabular}
\end{table}

\newpage
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section[
  head={Measurement of \CP violation},
  tocentry={Measurement of \CPHyperref violation}
]
{Measurement of \CPbfsf violation}
\label{sec:app:measurement_of_sin2beta:cpv_measurement}

% ------------------------------------------------------------------------------
\subsection{Tables of fixed parameters}
\label{sec:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters}

\begin{table}[h]
\caption{Fixed mass parameters.}
\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:mass}
\centering
\begin{tabular}{lr@{$\,\pm\,$}l}
  \toprule
  Parameter                     & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $\alpha_{1,m}^\text{\catDD}$      & \multicolumn{2}{c}{$2.28$}\\
  $\alpha_{1,m}^\text{\catLL}$      & \multicolumn{2}{c}{$2.1$}\\
  $\alpha_{2,m}^\text{\catDD}$      & \multicolumn{2}{c}{$2.08$}\\
  $\alpha_{2,m}^\text{\catLL}$      & \multicolumn{2}{c}{$2.43$}\\
  $\lambda_m^\text{\catDD}$         & \multicolumn{2}{c}{$-2.8$}\\
  $\lambda_m^\text{\catLL}$         & \multicolumn{2}{c}{$-3.6$}\\
  $\zeta_m^\text{\catDD}$           & \multicolumn{2}{c}{$0.0$}\\
  $\zeta_m^\text{\catLL}$           & \multicolumn{2}{c}{$0.0$}\\
  $n_1^\text{\catDD}$               & \multicolumn{2}{c}{$3.18$}\\
  $n_1^\text{\catLL}$               & \multicolumn{2}{c}{$3.2$}\\
  $n_2^\text{\catDD}$               & \multicolumn{2}{c}{$6.8$}\\
  $n_2^\text{\catLL}$               & \multicolumn{2}{c}{$4.1$}\\
  \bottomrule
\end{tabular}
\end{table}
%
\begin{table}[h]
\caption{Fixed decay time error parameters of the (left) signal and (right)
background parametrisation.}
\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:decay_time_error}
\centering
\begin{tabular}[t]{llr@{$\,\pm\,$}l}
  \toprule
  \multicolumn{2}{c}{Parameter}              & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $f_{\sigma_t}^\text{\catDD,\catOS,\catAU}$ &                       & \multicolumn{2}{c}{$0.069461$}\\
  $f_{\sigma_t}^\text{\catDD,\catOS,\catEB}$ &                       & \multicolumn{2}{c}{$0.09431$}\\
  $f_{\sigma_t}^\text{\catDD,\catSS}$        &                       & \multicolumn{2}{c}{$0.088404$}\\
  $f_{\sigma_t}^\text{\catLL,\catOS}$        &                       & \multicolumn{2}{c}{$0.55165$}\\
  $M_1^\text{\catDD,\catOS,\catAU}$          & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.037506$}\\
  $M_1^\text{\catDD,\catOS,\catEB}$          & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.034481$}\\
  $M_1^\text{\catDD,\catSS}$                 & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.032577$}\\
  $M_2^\text{\catDD,\catOS,\catAU}$          & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.077666$}\\
  $M_2^\text{\catDD,\catOS,\catEB}$          & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.072158$}\\
  $M_2^\text{\catDD,\catSS}$                 & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.059685$}\\
  $M^\text{\catLL,\catOS}$                   & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.033253$}\\
  $M^\text{\catLL,\catSS}$                   & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.029475$}\\
  $k_1^\text{\catDD,\catOS,\catAU}$          &                       & \multicolumn{2}{c}{$0.721$}\\
  $k_1^\text{\catDD,\catOS,\catEB}$          &                       & \multicolumn{2}{c}{$0.73243$}\\
  $k_1^\text{\catDD,\catSS}$                 &                       & \multicolumn{2}{c}{$0.72851$}\\
  $k_1^\text{\catLL,\catOS}$                 &                       & \multicolumn{2}{c}{$0.80445$}\\
  $k_2^\text{\catDD,\catOS,\catAU}$          &                       & \multicolumn{2}{c}{$0.73407$}\\
  $k_2^\text{\catDD,\catOS,\catEB}$          &                       & \multicolumn{2}{c}{$0.65444$}\\
  $k_2^\text{\catDD,\catSS}$                 &                       & \multicolumn{2}{c}{$0.70283$}\\
  $k_2^\text{\catLL,\catOS}$                 &                       & \multicolumn{2}{c}{$0.70335$}\\
  $k^\text{\catLL,\catSS}$                   &                       & \multicolumn{2}{c}{$0.75457$}\\
  \bottomrule
\end{tabular}
%
\quad
%
\begin{tabular}[t]{llr@{$\,\pm\,$}l}
  \toprule
  \multicolumn{2}{c}{Parameter}                  & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $f_{\sigma_t}^\text{\catDD,!(\catOS,\catAU)}$  &                       & \multicolumn{2}{c}{$0.11432$}\\
  $f_{\sigma_t}^\text{\catDD,\catOS,\catAU}$     &                       & \multicolumn{2}{c}{$0.29076$}\\
  $f_{\sigma_t}^\text{\catLL,\catAU}$            &                       & \multicolumn{2}{c}{$0.85159$}\\
  $f_{\sigma_t}^\text{\catLL,\catEB}$            &                       & \multicolumn{2}{c}{$0.93631$}\\
  $M_1^\text{\catDD,!(\catOS,\catAU)}$           & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.03674$}\\
  $M_1^\text{\catDD,\catOS,\catAU}$              & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.037739$}\\
  $M_1^\text{\catLL,\catAU}$                     & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.042243$}\\
  $M_1^\text{\catLL,\catEB}$                     & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.047283$}\\
  $M_2^\text{\catDD,!(\catOS,\catAU)}$           & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.072757$}\\
  $M_2^\text{\catDD,\catOS,\catAU}$              & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.064157$}\\
  $M_2^\text{\catLL,\catAU}$                     & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.030178$}\\
  $M_2^\text{\catLL,\catEB}$                     & ($\si{\pico\second}$) & \multicolumn{2}{c}{$0.029563$}\\
  $k_1^\text{\catDD,!(\catOS,\catAU)}$           &                       & \multicolumn{2}{c}{$0.73464$}\\
  $k_1^\text{\catDD,\catOS,\catAU}$              &                       & \multicolumn{2}{c}{$0.72987$}\\
  $k_1^\text{\catLL,\catAU}$                     &                       & \multicolumn{2}{c}{$0.69218$}\\
  $k_1^\text{\catLL,\catEB}$                     &                       & \multicolumn{2}{c}{$0.59111$}\\
  $k_2^\text{\catDD,!(\catOS,\catAU)}$           &                       & \multicolumn{2}{c}{$0.68463$}\\
  $k_2^\text{\catDD,\catOS,\catAU}$              &                       & \multicolumn{2}{c}{$0.67792$}\\
  $k_2^\text{\catLL,\catAU}$                     &                       & \multicolumn{2}{c}{$0.77259$}\\
  $k_2^\text{\catLL,\catEB}$                     &                       & \multicolumn{2}{c}{$0.78276$}\\
  \bottomrule
\end{tabular}
\end{table}
%
\begin{table}[h]
\caption{Fixed \OS mistag spline parameters for the (left) signal and (right)
background parametrisation.}
\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:eta:os}
\centering
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter                & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $u_{S,1}^\text{\catOS}$  & \multicolumn{2}{c}{$0.0$}\\
  $u_{S,2}^\text{\catOS}$  & \multicolumn{2}{c}{$0.50758$}\\
  $u_{S,3}^\text{\catOS}$  & \multicolumn{2}{c}{$3.0879$}\\
  $u_{S,4}^\text{\catOS}$  & \multicolumn{2}{c}{$3.7690$}\\
  $u_{S,5}^\text{\catOS}$  & \multicolumn{2}{c}{$12.776$}\\
  $u_{S,6}^\text{\catOS}$  & \multicolumn{2}{c}{$9.2243$}\\
  $u_{S,7}^\text{\catOS}$  & \multicolumn{2}{c}{$26.375$}\\
  $u_{S,8}^\text{\catOS}$  & \multicolumn{2}{c}{$29.490$}\\
  $u_{S,9}^\text{\catOS}$  & \multicolumn{2}{c}{$39.154$}\\
  $u_{S,10}^\text{\catOS}$ & \multicolumn{2}{c}{$39.090$}\\
  $u_{S,11}^\text{\catOS}$ & \multicolumn{2}{c}{$34.295$}\\
  \bottomrule
\end{tabular}
%
\qquad
%
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter                           & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
    $u_{B,1}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$0.0$}\\
    $u_{B,2}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$0.25646$}\\
    $u_{B,3}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$2.8381$}\\
    $u_{B,4}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$5.0101$}\\
    $u_{B,5}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$19.184$}\\
    $u_{B,6}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$12.047$}\\
    $u_{B,7}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$42.811$}\\
    $u_{B,8}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$53.376$}\\
    $u_{B,9}^\text{\catDD,\catOS}$    & \multicolumn{2}{c}{$59.998$}\\
    $u_{B,10}^\text{\catDD,\catOS}$   & \multicolumn{2}{c}{$67.425$}\\
    $u_{B,11}^\text{\catDD,\catOS}$   & \multicolumn{2}{c}{$64.236$}\\
    $u_{B,1}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$0.0$}\\
    $u_{B,2}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$0.96109$}\\
    $u_{B,3}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$10.005$}\\
    $u_{B,4}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$13.055$}\\
    $u_{B,5}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$65.181$}\\
    $u_{B,6}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$33.077$}\\
    $u_{B,7}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$161.56$}\\
    $u_{B,8}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$163.82$}\\
    $u_{B,9}^\text{\catLL,\catOS}$    & \multicolumn{2}{c}{$244.14$}\\
    $u_{B,10}^\text{\catLL,\catOS}$   & \multicolumn{2}{c}{$238.57$}\\
    $u_{B,11}^\text{\catLL,\catOS}$   & \multicolumn{2}{c}{$259.16$}\\
  \bottomrule
\end{tabular}
\end{table}
%
\begin{table}[h]
\caption{Fixed \SSpi mistag spline parameters for the (left) signal and (right)
background parametrisation.}
\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:eta:ss}
\centering
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter                      & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $u_{S,1}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{S,2}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{S,3}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.0402$}\\
  $u_{S,4}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.2597$}\\
  $u_{S,5}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.4804$}\\
  $u_{S,6}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.6534$}\\
  $u_{S,1}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{S,2}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{S,3}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.013$}\\
  $u_{S,4}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.1183$}\\
  $u_{S,5}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.2695$}\\
  $u_{S,6}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.4455$}\\
  \bottomrule
\end{tabular}
%
\qquad
%
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter                     & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $u_{B,1}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{B,2}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{B,3}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.1498$}\\
  $u_{B,4}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$0.8688$}\\
  $u_{B,5}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$1.9698$}\\
  $u_{B,6}^\text{\catDD,\catSS}$ & \multicolumn{2}{c}{$5.3155$}\\
  $u_{B,1}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{B,2}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.0$}\\
  $u_{B,3}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.0022$}\\
  $u_{B,4}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.1173$}\\
  $u_{B,5}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$0.4442$}\\
  $u_{B,6}^\text{\catLL,\catSS}$ & \multicolumn{2}{c}{$1.2042$}\\
  \bottomrule
\end{tabular}
\end{table}
%
\begin{table}[h]
\caption{Fixed decay time resolution parameters}
\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:decay_time_resolution}
\centering
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter                                & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
  $c_1^\text{\catDD}$                      & \multicolumn{2}{c}{$0.0077$}\\
  $c_1^\text{\catLL}$                      & \multicolumn{2}{c}{$0.0045$}\\
  $c_2^\text{\catDD}$                      & \multicolumn{2}{c}{$0.019$}\\
  $c_2^\text{\catLL}$                      & \multicolumn{2}{c}{$0.007$}\\
  $g_2^\text{\catDD}$                      & \multicolumn{2}{c}{$0.251$}\\
  $g_2^\text{\catLL}$                      & \multicolumn{2}{c}{$0.24$}\\
  $\mu_t^\text{\catDD}$                    & \multicolumn{2}{c}{$0.0$}\\
  $\mu_t^\text{\catLL}$                    & \multicolumn{2}{c}{$0.0$}\\
  $b_1^\text{\catDD}$                      & \multicolumn{2}{c}{$0.88$}\\
  $b_1^\text{\catLL}$                      & \multicolumn{2}{c}{$1.04$}\\
  $b_2^\text{\catDD}$                      & \multicolumn{2}{c}{$1.33$}\\
  $b_2^\text{\catLL}$                      & \multicolumn{2}{c}{$1.8$}\\
  $\sigma_\text{\acs*{PV}}^\text{\catDD}$  & \multicolumn{2}{c}{$1.6$}\\
  $\sigma_\text{\acs*{PV}}^\text{\catLL}$  & \multicolumn{2}{c}{$1.40$}\\
  $f_\text{\acs*{PV}}^\text{\catDD}$       & \multicolumn{2}{c}{$0.048$}\\
  $f_\text{\acs*{PV}}^\text{\catLL}$       & \multicolumn{2}{c}{$0.0488$}\\
  \bottomrule
\end{tabular}
\end{table}
%
\begin{table}[h]
\caption{Fixed \catAU acceptance spline parameters for (left) \catAU and (right)
\catEB candidates.}
\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:acc}
\centering
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter              & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
    $h_1^\text{\catAU}$  & \multicolumn{2}{c}{$0.93057$}\\
    $h_2^\text{\catAU}$  & \multicolumn{2}{c}{$0.93485$}\\
    $h_3^\text{\catAU}$  & \multicolumn{2}{c}{$0.96383$}\\
    $h_4^\text{\catAU}$  & \multicolumn{2}{c}{$0.96521$}\\
    $h_5^\text{\catAU}$  & \multicolumn{2}{c}{$0.99547$}\\
    $h_6^\text{\catAU}$  & \multicolumn{2}{c}{$0.97126$}\\
    $h_7^\text{\catAU}$  & \multicolumn{2}{c}{$0.96399$}\\
    $h_8^\text{\catAU}$  & \multicolumn{2}{c}{$0.9725$}\\
    $h_9^\text{\catAU}$  & \multicolumn{2}{c}{$0.98045$}\\
    $h_{10}^\text{\catAU}$ & \multicolumn{2}{c}{$0.97533$}\\
    \bottomrule
\end{tabular}
%
\qquad
%
\begin{tabular}[t]{lr@{$\,\pm\,$}l}
  \toprule
  Parameter               & \multicolumn{2}{c}{Fixed Value} \\
  \midrule
    $h_1^\text{\catEB}$   & \multicolumn{2}{c}{$0.1481$}\\
    $h_2^\text{\catEB}$   & \multicolumn{2}{c}{$0.27167$}\\
    $h_3^\text{\catEB}$   & \multicolumn{2}{c}{$0.29418$}\\
    $h_4^\text{\catEB}$   & \multicolumn{2}{c}{$0.35902$}\\
    $h_5^\text{\catEB}$   & \multicolumn{2}{c}{$0.40022$}\\
    $h_6^\text{\catEB}$   & \multicolumn{2}{c}{$0.4262$}\\
    $h_7^\text{\catEB}$   & \multicolumn{2}{c}{$0.44465$}\\
    $h_8^\text{\catEB}$   & \multicolumn{2}{c}{$0.47084$}\\
    $h_9^\text{\catEB}$   & \multicolumn{2}{c}{$0.49859$}\\
    $h_{10}^\text{\catEB}$ & \multicolumn{2}{c}{$0.52957$}\\
    \bottomrule
\end{tabular}
\end{table}

\FloatBarrier
% ------------------------------------------------------------------------------
\subsection{Fit results of subordinate parameters}
\label{sec:app:measurement_of_sin2beta:cpv_measurement:results}

\begin{table}[!h]
  \caption{Results for the estimated signal and background candidate numbers
  from the nominal fit.}
  \label{tab:app:measurement_of_sin2beta:cpv_measurement:results:yields}
  \centering
  \footnotesize
  \resizebox{0.49\textwidth}{!}{
  \begin{tabular}{lllllr@{$\,\pm\,$}l}
    \toprule
    \multicolumn{4}{l}{Sample} & Parameter & \multicolumn{2}{c}{Fitted Value}   \\
    \midrule
    \multirow{24}{*}{2011}  & \multirow{12}{*}{\catDD} & \multirow{4}{*}{\catOS}      & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $5134$   &   $103$  \\
                            &                             &                           &                             & $N_{\Bkg}$ & $9352$   &   $122$  \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $856$    &   $39$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $1413$   &   $46$   \\
                            &                             & \multirow{4}{*}{\catSS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $2028$   &   $54$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $1251$   &   $46$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $324$    &   $20$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $153$    &   $16$   \\
                            &                             & \multirow{4}{*}{\catBS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $941$    &   $38$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $913$    &   $38$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $138$    &   $14$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $121$    &   $13$   \\
                            & \multirow{12}{*}{\catLL} & \multirow{4}{*}{\catOS}      & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $2263$   &   $54$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $1504$   &   $47$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $333$    &   $20$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $304$    &   $19$   \\
                            &                             & \multirow{4}{*}{\catSS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $744$    &   $29$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $119$    &   $14$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $89$     &   $9$    \\
                            &                             &                           &                             & $N_{\Bkg}$ & $13$     &   $4$    \\
                            &                             & \multirow{4}{*}{\catBS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $321$    &   $19$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $119$    &   $13$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $46$     &   $7$    \\
                            &                             &                           &                             & $N_{\Bkg}$ & $11$     &   $4$    \\
    \midrule
    \multirow{24}{*}{2012}  & \multirow{12}{*}{\catDD} & \multirow{4}{*}{\catOS}      & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $10378$  &   $156$  \\
                            &                             &                           &                             & $N_{\Bkg}$ & $20569$  &   $185$  \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $2188$   &   $66$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $4724$   &   $83$   \\
                            &                             & \multirow{4}{*}{\catSS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $4246$   &   $80$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $3199$   &   $74$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $979$    &   $35$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $468$    &   $27$   \\
                            &                             & \multirow{4}{*}{\catBS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $1962$   &   $57$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $2251$   &   $59$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $403$    &   $24$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $343$    &   $23$   \\
                            & \multirow{12}{*}{\catLL} & \multirow{4}{*}{\catOS}      & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $4599$   &   $79$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $3245$   &   $70$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $971$    &   $35$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $939$    &   $35$   \\
                            &                             & \multirow{4}{*}{\catSS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $1550$   &   $41$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $298$    &   $22$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $281$    &   $17$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $55$     &   $9$    \\
                            &                             & \multirow{4}{*}{\catBS}   & \multirow{2}{*}{\catAU}     & $N_{\Sig}$ & $658$    &   $27$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $177$    &   $17$   \\
                            &                             &                           & \multirow{2}{*}{\catEB}     & $N_{\Sig}$ & $118$    &   $11$   \\
                            &                             &                           &                             & $N_{\Bkg}$ & $34$     &   $7$    \\
    \bottomrule
\end{tabular}
}
\end{table}
%
\begin{table}
  \caption{Results for the mass parameters in the nominal fit}
  \label{tab:app:measurement_of_sin2beta:cpv_measurement:results:mass}
  \centering
  \begin{tabular}{llr@{$\,\pm\,$}l}
      \toprule
      \multicolumn{2}{c}{Parameter}                                & \multicolumn{2}{c}{Value}  \\
      \midrule
      $m^{DD}_{}$              & ($\si{\MeVcc}$)        & $5281.80$    & $0.28$        \\
      $\sigma^{DD}_{m}$        & ($\si{\MeVcc}$)        & $9.9$        & $0.1$        \\
      $\beta^{DD}_{m}$         &                        & $-0.004$     & $0.004$     \\
      $\alpha^{DD}_{m}$        & ($\si{(\MeVcc)^{-1}}$) & $-0.00091$   & $0.00019$     \\
      \midrule
      $m^{LL}_{}$              & ($\si{\MeVcc}$)        & $5281.20$    & $0.30$        \\
      $\sigma^{LL}_{m}$        & ($\si{\MeVcc}$)        & $8.33$       & $0.09$        \\
      $\beta^{LL}_{m}$         &                        & $-0.009$     & $0.005$     \\
      $\alpha^{LL}_{m}$        & ($\si{(\MeVcc)^{-1}}$) & $-0.0004$    & $0.0004$      \\
      \bottomrule
    \end{tabular}
\end{table}
%
\begin{table}
  \caption{Results for the background decay time parameters in the nominal fit}
  \label{tab:app:measurement_of_sin2beta:cpv_measurement:results:time:bkg}
  \centering
  \begin{tabular}{llr@{$\,\pm\,$}l}
      \toprule
      \multicolumn{2}{c}{Parameter}       & \multicolumn{2}{c}{Value}                  \\
      \midrule
      $f^{\catDD,\catOS}_{2,t}$   &                       & $0.34$    & $0.06$   \\
      $f^{\catDD,\catOS}_{3,t}$   &                       & $0.049$   & $0.018$  \\
      $\tau^{\catDD,\catOS}_{1}$  & ($\si{\pico\second}$) & $0.579$   & $0.028$  \\
      $\tau^{\catDD,\catOS}_{2}$  & ($\si{\pico\second}$) & $1.41$    & $0.17$   \\
      $\tau^{\catDD,\catOS}_{3}$  & ($\si{\pico\second}$) & $4.2$     & $0.7$    \\
      \midrule
      $f^{\catDD,\catSS}_{2,t}$   &                       & $0.15$    & $0.06$   \\
      $\tau^{\catDD,\catSS}_{1}$  & ($\si{\pico\second}$) & $0.703$   & $0.032$   \\
      $\tau^{\catDD,\catSS}_{2}$  & ($\si{\pico\second}$) & $1.72$    & $0.23$   \\
      \midrule
      $f^{\catLL}_{2,t}$          &                       & $0.48$    & $0.21$   \\
      $f^{\catLL}_{3,t}$          &                       & $0.043$   & $0.027$  \\
      $\tau^{\catLL}_{1}$         & ($\si{\pico\second}$) & $0.22$    & $0.04$  \\
      $\tau^{\catLL}_{2}$         & ($\si{\pico\second}$) & $0.40$    & $0.07$   \\
      $\tau^{\catLL}_{3}$         & ($\si{\pico\second}$) & $4.2$     & $0.5$    \\
      \bottomrule
    \end{tabular}
\end{table}

\clearpage
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Studies of systematic effects}
\label{sec:app:measurement_of_sin2beta:systematics}

% ..............................................................................
\subsubsection{Fit model}
\label{sec:app:measurement_of_sin2beta:systematics:systematics:fit_model}

\begin{figure}[h]
\centering
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_s_res.pdf}\\
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of an asymmetry in the background tagging estimates on the measurement
of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:fit_model:bkg_tagging_asymmetry}
\end{figure}

\begin{figure}[h]
\centering
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_s_res.pdf}\\
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of a small mass and decay time correlation on the measurement of the
\CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:fit_model:mass_time_correlations}
\end{figure}

\clearpage
% ..............................................................................
\subsubsection{Flavour Tagging}
\label{sec:app:measurement_of_sin2beta:systematics:systematics:tagging}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_ft_calibration_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_ft_calibration_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_ft_calibration_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_ft_calibration_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of the systematic uncertainties on the flavour tagging calibration
parameters on the measurement of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:tagging}
\end{figure}

\clearpage
% ..............................................................................
\subsubsection{Decay time resolution}
\label{sec:app:measurement_of_sin2beta:systematics:systematics:resolution}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of the decay time resolution calibration model on the measurement of
the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:resolution:calibration}
\end{figure}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_offset_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_offset_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_offset_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_offset_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of neglecting a non-zero offset in the decay time resolution
calibration model on the measurement of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:resolution:offset}
\end{figure}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of the fraction of candidates with a wrong \PV association on the
measurement of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:resolution:wrong_pv}
\end{figure}

\clearpage
% ..............................................................................
\subsubsection{Decay time acceptance}
\label{sec:app:measurement_of_sin2beta:systematics:systematics:acceptance}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_lower_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_lower_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_lower_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_lower_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of the low decay time acceptance model on the measurement of the \CP
parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:acceptance:lower}
\end{figure}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_upper_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_upper_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_upper_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_acc_upper_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of the upper decay time acceptance correction function on the
measurement of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:acceptance:upper}
\end{figure}

\clearpage
% ..............................................................................
\subsubsection[Production asymmetry, $z$-scale, \DMd, and \DGd]{Production asymmetry, $\mathbfsfit{z}$-scale, $\mathbfsfit{\DMd}$, and $\mathbfsfit{\DGd}$}
\label{sec:app:measurement_of_sin2beta:systematics:systematics:further_studies}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_zscale_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_zscale_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_zscale_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_zscale_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of the relative $z$-scale uncertainty on the measurement of the \CP
parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:zscale}
\end{figure}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of an enlarged production asymmetry $A_P^{\catOO}$ on the measurement
of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:production_asymmetry}
\end{figure}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dgd_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dgd_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dgd_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dgd_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of a non-zero decay width difference $\DGd$ on the measurement
of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:decay_width_difference}
\end{figure}

\begin{figure}[h]
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dmd_s_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dmd_s_res.pdf}
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dmd_c_pull.pdf}\hfill
  \includegraphics[width=0.49\textwidth]{private/content/appendices/figs/systematics_fs_dmd_c_res.pdf}
\caption{Shown are (left) pull and (right) residual distributions of the
parameters (top) \SJpsiKS and (bottom) \CJpsiKS from a \ToyMC study of the
influence of an enlarged mass difference $\DMd$ on the measurement
of the \CP parameters.}
\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:mass_difference}
\end{figure}


\section{Overview} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:over}

A \emph{class hierarchy} is a partially ordered set $(H,\subtype)$ where $H$ is a potentially open set
of classes and $\subtype$ is a reflexive, transitive and anti-symmetric
\emph{subtyping relation} on $H$. We use \emph{class} and \emph{type}
interchangeably.
% as the exact distinction is not important for this discussion.
When two classes are in a subtyping relation $D \subtype B$, the class $D$
is said to be a (possibly indirect) \emph{derived class} (or subtype) of $B$;
the class $B$ is called a (possibly indirect) \emph{base class}
(or supertype) of $D$.
 %When the transitive reduction
%$\subtypeD$ of $\subtype$ is a function, $H$ is usually referred to as
%\emph{hierarchy} to indicate single inheritance.

The %\emph{most-derived type of an object} also known as the
\emph{dynamic type of an object} is the type used to create it.
The \emph{static type of an expression} is the type of that expression
as given by the static semantics.%, i.e. the typing rules of expressions.
%  By
% \emph{dynamic type} of an object we call any base class of the most-derived type.

\subsection{Type Switch}

%This section generalizes pattern matching of closed algebraic datatype values
%to case analysis of hierarchical and extensible datatype values.
In general, a \emph{type switch} or \emph{typecase} is a multiway branch statement
that distinguishes values based on their type. In a multi-paradigm programming
language like \Cpp{}, which supports parametric, ad-hoc, and
subtyping polymorphisms, such a broad definition subsumes numerous different
typecase constructs studied in the literature~\cite{Intensional95,Glew99,OpenShutTypecase05}.
In this work, we only look at typecasing scenarios based on the class inheritance
of \Cpp{}, similar to those studied by Glew~\cite{Glew99}.
% It is possible to generalize type switch
% (the notion, not our implementation) to static polymorphism of \Cpp{} (ad-hoc and
% parametric polymorphism enabled by overloading and templates) along the line of
% work introduced by Harper and Morrisett~\cite{Intensional95} and studied in the
% context of closed and extensible solutions by Vytiniotis et
% al~\cite{OpenShutTypecase05}, but we do not address such a generalization here.
We use the term \emph{type switch} instead of a broader \emph{typecase} to
stress the run-time nature of the type analysis similar to how regular
\code{switch}-statement of \Cpp{} performs case analysis of values at run time.

The term \emph{object descriptor} means either a pointer or a reference to
an object.
Given an object descriptor, called \emph{subject}, of static type \code{S}
referred to as the \emph{subject type}, and a list of
\emph{target types} \code{Ti} associated with the branches, a type switch
statement needs to identify a suitable clause $m$ based on
the dynamic type \code{D <: S} of the subject as well as a suitable
conversion that coerces the subject to the target type \code{Tm}.
Due to multiple inheritance, types \code{Ti} may not all directly
derive from the static type \code{S}. However,
%because of the strong static type safety requirement,
the type of the applicable clause \code{Tm} will necessarily have to be a
supertype of the subject's dynamic type \code{D <: Tm}.
A hypothetical type switch
statement, not currently supported by \Cpp{}, may look as following:
%
\begin{lstlisting}[keepspaces]
switch (subject) { case T1: s1; ... case Tn: sn; }
\end{lstlisting}
%
\noindent
There is no need for an explicit \emph{default clause} in our setting because
it is semantically equivalent to a case clause guarded by the
subject type: \code{case S: s}. The only semantic difference such a choice
makes is in the treatment of null pointers.
One may naively think that null pointers should be handled by
the default clause.  However, not distinguishing between
invalid object and valid object of a known static but unknown dynamic type may
lead to nasty run-time errors.

%\noindent
Similar control structures exist in many programming languages, e.g.
\emph{match} in Scala~\cite{Scala2nd}, \emph{case} in Haskell~\cite{Haskell98Book} and
ML~\cite{ML90}, \emph{typecase} in Modula-3~\cite{Modula3TS} and CLOS (as a
macro), \emph{tagcase} in CLU~\cite{CLURefMan}, \emph{union case} in Algol 68,
and date back to at least Simula's \emph{Inspect} statement~\cite{Simula67}.
The statement can, in general, be given numerous plausible semantics:
%
\begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\item \emph{First-fit} semantics will evaluate the first statement $s_i$ such
      that $T_i$ is a base class of $D$.
\item \emph{Best-fit} semantics will evaluate the statement corresponding to the
      most-specialized base class $T_i$ of $D$ if it is unique (subject to
      ambiguity).
\item \emph{Exact-fit} semantics will evaluate statement $s_i$ if $T_i=D$.
\item \emph{All-fit} semantics will evaluate all statements $s_i$ whose guard
      type $T_i$ is a supertype of $D$ (order of execution has to be defined).
\item \emph{Any-fit} semantics might choose non-deterministically one of the
      statements enabled by the all-fit semantics.
\end{itemize}
%
The list is not exhaustive and depending on a language, any of them
is a plausible choice. Functional languages, for example, often prefer
first-fit semantics because it is similar to case analysis in mathematics.
Object-oriented languages are typically inclined to best-fit semantics due
to its similarity to overload resolution and run-time dispatch; however, some
do opt for first-fit semantics to mimic the functional style: e.g. Scala~\cite{Scala2nd}.
Exact-fit semantics can often be seen in languages supporting discriminated
union types (sum types): e.g. \emph{variant records} in Pascal, Ada and Modula-2,
\emph{oneof} and \emph{variant objects} in CLU, \emph{unions} in C and \Cpp{}, etc.
All-fit and any-fit semantics might be seen in languages based on predicate
dispatching~\cite{ErnstKC98} or guarded commands~\cite{EWD:EWD472}, where a
predicate can be seen as a characteristic function of a type, while logical
implication -- as subtyping.

\subsection{The Expression Problem}

Type switching is related to a more general problem manifesting the differences
in functional and object-oriented programming styles.
Conventional algebraic datatypes, as found in most functional languages, allow
for easy addition of new functions on existing data types. However, they fall short
in extending data types themselves (e.g. with new constructors), which requires
modifying the source code. Object-oriented languages make
data type extension trivial through inheritance, but the addition of new
functions operating on these classes typically requires changes to the class
definition. This dilemma is known as the \emph{expression problem}~\cite{Cook90,exprproblem}.

\noindent
Classes differ from algebraic data types in two important ways. Firstly, they
are \emph{extensible}, for new variants can be added later by inheriting from
the base class. Secondly, they are \emph{hierarchical} and thus typically
\emph{non-disjoint} since variants can be inherited from other variants and form
a subtyping relation between themselves~\cite{Glew99}. In contrast, variants in
conventional algebraic data types are \emph{disjoint} and \emph{closed}.
Some functional languages e.g. ML2000~\cite{ML2000} and its predecessor, Moby,
were experimenting with \emph{hierarchical extensible sum types}, which are
closer to object-oriented classes then algebraic data types are, but,
interestingly, they provided no %neither traditional nor efficient
facilities for performing case analysis on them.

Zenger and Odersky refined the expression problem in the context of
independently extensible solutions~\cite{fool12} as a challenge to find an
implementation technique that satisfies the following requirements:
%
\begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\item \emph{Extensibility in both dimensions}: It should be possible to add new
      data variants, while adapting the existing operations accordingly. It
      should also be possible to introduce new functions.
\item \emph{Strong static type safety}: It should be impossible to apply a
      function to a data variant, which it cannot handle.
\item \emph{No modification or duplication}: Existing code should neither be
      modified nor duplicated.
\item \emph{Separate compilation}: Neither datatype extensions nor addition of
      new functions should require re-typechecking the original datatype or
      existing functions. No safety checks should be deferred until link or
      runtime.
\item \emph{Independent extensibility}: It should be possible to combine
      independently developed extensions so that they can be used jointly.
\end{itemize}
%
While these requirements were formulated for extensible data types with
disjoint variants, object-oriented languages primarily deal with
hierarchical data types. We thus found it important to state explicitly an
additional requirement based on the Liskov substitution principle~\cite{Lis87}:
%
\begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\item \emph{Substitutability}: Operations expressed on more general data variants
      should be applicable to ones that are more specific.
      %(the latter being in a subtyping relation with the former).
\end{itemize}

%Depending on the semantics of the language's subtyping relation,
%substitutability requirement may turn pattern matching into an expensive
%operation. OCaml, for example, that uses structural subtyping on its object
%types, does not offer pattern

\noindent
We will refer to a solution that satisfies all of the above requirements as \emph{open}.
Numerous solutions have been proposed to dealing with the expression problem in both
functional~\cite{garrigue-98,LohHinze2006} and object-oriented
camps~\cite{Palsberg98,Krishnamurthi98,Zenger:2001,runabout}, but very few have
made their way into one of the mainstream languages. We refer the reader to Zenger
and Odersky's original manuscript for a discussion of the approaches~\cite{fool12}.
Most of the discussed object-oriented solutions focused on the visitor design pattern and its extensions,
which even today seem to be the most commonly used approach to dealing with the
expression problem in object-oriented languages.

A lot has been written about the visitor design pattern~\cite{DesignPatterns1993,Palsberg98,Zenger:2001,Oliveira08}.
Its advantages include \emph{extensibility of functions}, \emph{speed}, and
\emph{being a library solution}. Nevertheless, the solution is \emph{intrusive},
\emph{specific to hierarchy}, and requires a lot of \emph{boilerplate code} to
be written. It also introduces \emph{control inversion}, but, most importantly,
-- \emph{hinders extensibility} of classes.

%In this work we are not trying to solve the expression problem in its full
%generality. Instead, we concentrate on deficiencies of the visitor design
%pattern independently of its relation to the expression problem and advocate for
%a solution that suits object-oriented paradigm better than visitors do.

\subsection{An Open Type Switch}

Type switch alone does not solve the expression problem in the context
of an object-oriented language, for the existing code may have to be
modified to consider new variants. Relying on a default clause is not
an acceptable solution in this situation, because often the
only reasonable default behavior is to raise an exception.
Zenger and Odersky observed that defaults transform type errors that should
manifest statically into runtime exceptions~\cite{fool12}.
In our experience, newly added variants were more often extending an existing
variant than creating an entirely disjoint one. In a compiler, for
example, a new kind of type expression will typically extend a
\code{TypeExpression} variant, while a new form of annotation will extend an
\code{Annotation} variant, thus not extending the root \code{ASTNode} directly.
Due to the substitutability requirement, this new variant will be treated as a
variant it extends in all the existing code. The functions that will be affected
by its addition and thus have to be modified will be limited to functions
directly analyzing the variant it extends and not providing a default behavior.

To account for this subtlety of extensible hierarchical data types, we use a
term \emph{open type switch} to refer to a type switch that satisfies all the
requirements of an \emph{open solution to the expression problem} stated above
except for the \emph{no modification or duplication} requirement. We loosen it
to allow modification of functions for which the newly added variant becomes a
disjoint (orthogonal) case not handled by a default clause. We believe that the
loosened requirement allows us to express pragmatically interesting restrictions
that developers are willing to live with. Furthermore,
open type switch overcomes
all the major shortcomings of the visitor design pattern:
%
\begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\item Case analysis with an open type switch is non-intrusive as it
      inspects the hierarchy externally and can be applied retroactively.
\item New variants can be accounted for in the newly written code and will be
      seen as a base class or default in the existing code.
\item The affected functions are limited to those for which the newly added
      variant is a disjoint case.
\item The code avoids the control inversion and the need for boilerplate code
      that visitors introduce, and is thus a more direct expression of the
      intent.
\end{itemize}

\subsection{\Cpp{} Specifics: Subobjects}
\label{sec:specifics}

\Cpp{} supports two kinds of multiple inheritance:
\emph{non-virtual} inheritance and \emph{virtual} inheritance~\cite{CPPARM90}.
The difference between the two only arises in situations where a
class indirectly inherits from the same base class via more than one path
in its class hierarchy.  Rigorous accounts of \Cpp{} multiple inheritance
semantics use the notion of \emph{subobject}~\cite{RF95}.

\begin{figure}[htbp]
  \centering
    \includegraphics[width=0.47\textwidth]{Inheritance.pdf}
  \caption{Multiple Inheritance in \Cpp{}}
  \label{fig:inheritance}
\end{figure}

\noindent
Consider the simple class hierarchy in Figure~\ref{fig:inheritance}(1). Class
\code{D} indirectly inherits from class \code{A} through its \code{B} and
\code{C} base classes. In this case, the user may opt to keep distinct
subobjects of class \code{A} (repeated inheritance) or a shared one (virtual
inheritance) by specifying how \code{B} and \code{C} inherit from
\code{A}. The kind of inheritance is thus not a property of a given class, but a
property of an inheritance relation between classes and it is possible to mix the two.

A class hierarchy gives rise to a \emph{subobject graph}, where a given class
node may be replicated when inherited repeatedly or left shared when inherited
virtually. The edges in such a graph represent \emph{subobject containment} and
indicate whether such containment is shared or exclusive.
Every class $C$ in the class hierarchy will have its own subobject
graph representing the subobjects of an object of dynamic type $C$.
Figure~\ref{fig:inheritance}(2) shows subobject graph for class \code{D}
obtained for the class hierarchy in Figure~\ref{fig:inheritance}(1) under repeated (a) and virtual (b)
inheritance of class \code{A} by classes \code{B} and \code{C}. The shared
containment is indicated with the dashed arrows, while exclusive -- with the solid
ones.

\Cpp{}'s notion of multiple inheritance is fundamentally about
subobjects, not just types.  Virtual inheritance is about
sharing the base-class subobjects, whereas non-virtual inheritance
reflects distinction in base-class subobjects from distinct class inheritance paths~\cite{CPPARM90}.

An object descriptor of static type $A$ referencing an object of the dynamic
type $C$ can be understood as any $C$\code{::*::}$A$-node in the subobject graph of $C$.
Casts can be understood as a change from one subobject to another.
We use the terms \emph{source subobject} and \emph{target
subobject} to refer to the argument and result of the cast, respectively. Their
static types will be referred to as \emph{source type} and \emph{target type}
respectively. \Cpp{} distinguishes three kinds of casts: upcasts, downcasts, and
crosscasts.

An \emph{upcast} is a cast from a derived class to one of its bases. When the
base class is unambiguous, such casts are implicit and require no additional
annotations. When the base class is ambiguous, cast failure is manifested
statically in the form of a compile-time error. For example, this is the case with
casting \code{D} to \code{A} under repeated multiple inheritance of \code{A},
in which case the user needs to explicitly cast the object to \code{B} or
\code{C} first in order to indicate the desired subobject and resolve the ambiguity.
In some cases, however, introduction of such an explicit cast is not possible:
e.g. in implicit conversions generated by the compiler to implement covariant
return types, crosscasts or conversions in generic code. This does not mean
that in such cases we violate the Liskov substitution principle: the
classes are still in a subtyping relation, but an implicit conversion is not
available.

A \emph{downcast} is a cast from a base class to one of its derived classes. The
cast has to determine at run-time whether the source subobject is contained by a
subobject of the target type in the dynamic type's subobject graph. Failure
of such a cast is manifested dynamically at run-time.

A \emph{crosscast} is a cast between classes that are not necessarily related by
inheritance except by sharing a common derived class (subclass).
Accordingly to the \Cpp{} semantics such cast is defined to be a
composition of upcast to target type and downcast to the dynamic type.
While the downcast to the dynamic type is always guaranteed to succeed
regardless of the source subobject, the upcast to the target type may be
ambiguous, in which case the cast will fail at runtime. A cast from \code{Y} to
\code{B} inside an object of dynamic type \code{D} in
Figure~\ref{fig:inheritance}(2a,2b) is an example of a successful crosscast. A
similar cast from \code{Y} to \code{A} inside \code{D} under the repeated
inheritance in Figure~\ref{fig:inheritance}(2a) will fail because of the ambiguous
upcast from \code{D} to \code{A}.

An interesting artifact of these distinctions can be seen in an example of
casting a subobject of type \code{Z} to a subobject of type \code{A} in
Figure~\ref{fig:inheritance}(2a). The subobject \code{D::B::A::Z} will be
successfully cast to \code{D::B::A}, while the \code{D::C::A::Z} will be
successfully cast to \code{D::C::A}. These casts do not involve downcasting to
\code{D} followed by an upcast to \code{A}, which would be ambiguous, but
instead take the dynamic type of a larger subobject (\code{D::B} or \code{D::C})
that the source subobject is contained in into account in order to resolve the
ambiguity. A similar cast from \code{Y} to \code{A} will fail; should
\code{Y} have also been non-virtually derived from \code{Z}, the cast from
\code{D::C::Y::Z} to \code{A} would have failed. This shows that the distinction
between crosscast and downcast is not based solely on the presence of a
subtyping relation between the source and target types, but also on the actual
position of the source subobject in the dynamic type's subobject graph.

The \Cpp{} inheritance model, presented here informally, further complicates the definition and
implementation of a type switch compared to simpler models. We have to define the
type switch so that only unambiguous casting between a source and a target within an object is possible.
That is, the implementation of the cast between source and target subobjects must take into account the
location of the source subobject in the subobject graph, rather than
just the dynamic and target types, which would suffice for a simple subtype testing.
Of course, every use of dynamic casting and every implicit cast are type safe~\cite{WNST06}.

%\section{Problem Description} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\label{sec:probl}

\subsection{Existing Approaches to Type Case Analysis}
\label{sec:prev}

The closed nature of algebraic data types allows for their efficient
implementation. The traditional compilation scheme assigns unique (and often
small and sequential) tags to every variant of the algebraic data type and type
switching is then simply implemented with a multi-way branch~\cite{Spuler94}
(usually a jump table) over all the tags~\cite{Augustsson85}. Dealing with
extensible hierarchical data types makes this %extremely efficient
approach infeasible:

\begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\item \emph{Extensibility} implies that the compiler may not know the exact set
      of all the derived classes until link-time (due to \emph{separate compilation})
      or even run-time (due to \emph{dynamic linking}).
\item \emph{Substitutability} implies that we should be able to
      match tags of derived classes against case labels representing tags of
      base classes.
\item The presence of \emph{multiple inheritance} might require pointer adjustments
      that are not known at compile time (e.g. due to virtual base classes,
      ambiguous base classes or crosscasting).
\end{itemize}

%\noindent
%In some cases the substitutability requirement can be satisfied by obtaining
%the base class' tag from a derived one first and then performing the jump.
%This will work as long as we have only base classes in the case clauses.
%Derived classes that have to be treated separately from the rest of their
%siblings will essentially be indistinguishable from them.
%
%When tags are not chosen arbitrarily but to reflect the subtyping relation of the
%underlying hierarchy (e.g. certain bit set for certain base class), the assumed
%structure of tags is likely to make the set of tags sparse. On one hand this
%decreases the number of representable hierarchies and thus hinders openness,
%while on the other it forces the compiler to use a decision tree instead of a jump
%table to implement the switch. The former was consistently slower than the
%latter one in our experience, even though the opposite was noted on some
%architectures for small number of case clauses~\cite[\textsection 4]{garrigue-98}.

\noindent
There are two main approaches to implementing case analysis on extensible
hierarchical data types discussed in the literature.

The first approach is based on either explicit or implicit sealing of the class
hierarchy on which type switching can be performed. \Cpp{}11, for example, allows
the user to prohibit further derivation by specifying a class to be ``final''~\cite{C++11},
similar to Scala and Java. The compiler then may use the above tag
allocation over all variants to implement type analysis~\cite[\textsection
4.3.2]{EmirThesis}.
In some cases, the sealing may happen implicitly. For example, languages %that allow names
with both internal and external linkage may employ the fact that classes
with internal linkage will not be externally accessible and are thus effectively
sealed. While clearly efficient, the approach is not open as it avoids the
question rather than answers it.

The broader problem with this approach is that techniques that rely on unique or
sequential compile or link-time constants violate independent extensibility
since without a centralized authority there is no guarantee same constant will
not be chosen in a type-unsafe manner by independent extensions. Updating such
constants at load time may be too costly even when possible. %More often than
%not, however such updates may require code regeneration since decision trees,
%lookup tables etc. may have been generated by compiler for given values.

An important practical solution that follows this approach is the visitor design
pattern~\cite{DesignPatterns1993}. The set of \code{visit} methods in a visitor's
interface essentially seals the class hierarchy. Extensions have been proposed
in the literature~\cite{Zenger:2001}, but they have problems of their own,
as discussed in \textsection\ref{sec:rw}.

The second approach employs type inclusion tests combined with decision
trees~\cite{Cardelli84} to avoid unnecessary checks. Its efficiency is then
entirely focused on the efficiency of type inclusion
tests~\cite{Schubert83,Wirth88,Cohen91,Caseau93,Vortex96,Krall97nearoptimal,Vitek97,PQEncoding,FastDynCast,Ducournau08}.

%"A couple of years later, Nikolaus With published an approach based on type
%inclusion. However, that approach does not work well in the presence of multiple
%inheritance and separates the single logical operation of gaining type-safe
%access to an object into two, implying the possibility of a programmer error."

\Cpp{} has handled general dynamic casting since 1987, when multiple inheritance
was added to the language~\cite{Str87}. Wirth later presented a technique that
can be used to implement subtype tests by traversing a linked list of
types~\cite{Wirth88}. His encoding required little space, but ran in time
proportional to the distance between the two types in the class hierarchy.
A trivial constant-time type inclusion test can be implemented with a
\emph{binary matrix}, encoding the subtyping relation on the class
hierarchy~\cite{Vortex96}. While efficient in time, it has quadratic space
requirements, which makes it expensive for use on large class hierarchies. Cohen
proposed the first space-efficient constant-time algorithm, but it can
only deal with single inheritance~\cite{Cohen91}. \emph{Hierarchical encoding}
is another constant-time test that maps subtype queries into subset queries on
bit-vectors~\cite{Caseau93,Krall97nearoptimal}. The approach can handle multiple
inheritance, but the space and time required for a subtype test in this encoding
increases with the size of the class hierarchy; also, Caseau's approach~\cite{Caseau93} is
limited to class hierarchies that are lattices. Schubert's \emph{relative
numbering}~\cite{Schubert83} encodes each type with an interval $[l,r]$,
effectively making type inclusion tests isomorphic to a simple range checking.
The encoding is optimal in space and time, but it is limited to single
inheritance. \emph{PQ-Encoding} of Zibin and Gil employs PQ-trees to improve
further space and time efficiency of the constant-time inclusion
testing~\cite{PQEncoding}. While capable of handling type inclusion queries on
hierarchies with multiple inheritance, the approach makes the closed world assumption and can be costly
for use with dynamic linking because it is not incremental.
The approach of Gibbs and Stroustrup~\cite{FastDynCast} employs divisibility of
numbers to obtain a constant-time type inclusion test. The approach can handle
multiple inheritance and was the first constant-time technique to addresses the
problem of casts between subobjects. Unfortunately, the approach limits the size
of the class hierarchies that can be encoded with this technique.
Ducournau proposed a constant-time inclusion test based on the fact that, in an
open solution, a class has a known number of base classes, and thus perfect hashes
can be used to map them to this-pointer offsets typically used to implement
subobject casts \cite{Ducournau08}. Unfortunately, the approach addresses only
virtual multiple inheritance and (similarly to other approaches) relies on
load-time computations. An excellent introduction to and detailed
analysis of existing constant-time type inclusion tests can be found in
\cite{Vitek97,PQEncoding}.

With the exception of work by Gibbs and Stroustrup~\cite{FastDynCast}, all the
approaches to efficient type-inclusion testing we found in the literature were
based on the assumption that \emph{the outcome of a subtyping test as well as
the subsequent cast depend only on the target type and the dynamic type of
the object}. Although that assumption is sound for subtyping tests and subtype
casts for shared inheritance (including single), it does not reflect the
relationship between subobjects in the general case of multiple inheritance
as found in \Cpp{}.

\subsection{The Source of Inefficiency}

While constant-time type inclusion tests are invaluable in optimizing subtype
tests in programming languages, their use in implementing a type switch is
inferior to some workaround techniques. This may prevent wide adoption of a
language implementation of such a feature due to its inferior performance.
We implemented 3 constant-time type inclusion tests: binary
matrix~\cite{Vitek97}, Cohen's algorithm~\cite{Cohen91}, and fast dynamic
cast~\cite{FastDynCast} and combined them with a decision tree to implement a
type switch on a class hierarchy ideally suited for such scenarios: a perfect binary tree with
classes number $2i$ and $2i+1$ derived from a class number $i$. Our workaround
techniques included the visitor design pattern and a switch on the sealed sequential
set of tags.

\begin{figure}[htbp]
  \centering
    \includegraphics[width=0.47\textwidth]{DCast-vs-Visitors.pdf}
  \caption{Type switch based on constant-time subtype tests}
  \label{fig:DCastVis2}
\end{figure}

The chart in Figure~\ref{fig:DCastVis2} shows the number of cycles (Y-axis) each
technique took to recognize an object of the dynamic type $i$ (X-axis).
Despite known limitations, binary matrix and Cohen's algorithm are some of the
fastest known type inclusion tests for single inheritance~\cite{Vitek97}. It
is nonetheless easy to see that the logarithmic cost associated with the
decision tree very quickly surpasses the constant overhead of double dispatch
(20 cycles) present in the visitor design pattern or the jump-table
implementation of the switch on all tags (11 cycles). We expect the cost of
techniques capable of handling multiple inheritance to be even higher, especially
those addressing casting between subobjects (e.g. fast dynamic cast). The edgy
shape of timing results reflects the shape of the class hierarchy used for this
experiment.
%We show in \textsection{sec:viscmp} that
%our open solution is capable of delivering an amortized constant-time type
%switching wi