Sunteți pe pagina 1din 155

Masaryk University, Faculty of Informatics

}w!"#$%&123456789@ACDEFGHIPQRS`ye|
Hynek Mlna rk
PhD Thesis

Quantum Programming Language LanQ

Brno, Czech Republic

September 2007

Acknowledgments
This work would not be realized without support of many people who helped me both proessionally and personally. I would like to thank my supervisor, Jozef Gruska, for his guidance, support and advices during my PhD studies. I would like also to express my thanks to Luk Boh, Jan Bouda, Simon Gay, Philippe as ac Jorrand, Rajagopal Nagarajan, Nick Papanikolaou, Simon Perdrix, Igor Peterl Libor Skark, vada, Josef Sprojcar and Tomoyuki Yamakami for their enthusiasm and invaluable comments on LanQ and related discussions. I would like to particularly thank to Rajagopal Nagarajan and Nick Papanikolaou for their hospitality, encouragement and fruitful discussions not only during my visit to the University of Warwick. Finally, I would like to express my deep gratitude to my wife Lucie and to my parents for their endless support and love without which I would never have been able to write this thesis. This work was realized under nancial support of grants MSM0021622419, GACR 201/04/1153 and GACR 201/07/0603.

ii

Contents
I Introduction 1
3 3 4 4 12 12 13 14 16 17 18 19 19 19 20 20 21 21 22 22 22 23 23 24 24 24 25

1 Introduction 1.1 The history of quantum information processing 1.2 Introduction to quantum computing . . . . . . 1.2.1 Basics of quantum mechanics . . . . . . 1.3 Models of quantum computation . . . . . . . . 1.3.1 Models based on classical models . . . . 1.3.2 Measurement-based computation . . . . 1.4 Introduction to programming languages . . . . 1.4.1 Quantum programming languages . . . 1.5 Introduction to process algebras . . . . . . . . . 1.5.1 Quantum process algebras . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

2 Current state of the art 2.1 Functional languages and -calculi . . . . . . . . 2.1.1 Quantum q -calculus van Tonder . . . . 2.1.2 QPL . . . . . . . . . . . . . . . . . . . . . 2.1.3 QML . . . . . . . . . . . . . . . . . . . . . 2.1.4 Quantum -calculus Selinger & Valiron 2.1.5 nQML . . . . . . . . . . . . . . . . . . . . 2.2 Other languages . . . . . . . . . . . . . . . . . . 2.2.1 qGCL . . . . . . . . . . . . . . . . . . . . 2.2.2 QCL . . . . . . . . . . . . . . . . . . . . . 2.2.3 Q language . . . . . . . . . . . . . . . . . 2.2.4 QMC . . . . . . . . . . . . . . . . . . . . 2.3 Quantum process algebras . . . . . . . . . . . . . 2.3.1 CQP . . . . . . . . . . . . . . . . . . . . . 2.3.2 QPAlg . . . . . . . . . . . . . . . . . . . . 2.4 Summary . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

II

LanQ programming language

27
29 29

3 Introduction 3.1 Informal introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

CONTENTS 4 Syntax 4.1 Concrete syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Internal syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 Conguration syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Typing 5.1 Typing rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Basic concepts 6.1 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Reference-related concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Variable-related concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Operational semantics 7.1 Memory model . . . . . . . . . . . . . . . 7.2 Variable properties storage . . . . . . . . 7.3 Conguration . . . . . . . . . . . . . . . . 7.4 Variable properties handling functions . . 7.5 Local memory handling functions . . . . . 7.6 Functions for handling aliasfor constructs 7.7 Internal values . . . . . . . . . . . . . . . 7.8 Transitions . . . . . . . . . . . . . . . . . 7.9 Runtime errors . . . . . . . . . . . . . . . 7.10 Processes and congurations . . . . . . . . 7.10.1 Structural congruence . . . . . . . 7.10.2 Nondeterminism and parallelism . 7.11 Evaluation . . . . . . . . . . . . . . . . . . 7.11.1 Basic rules . . . . . . . . . . . . . 7.11.2 Promotable expressions . . . . . . 7.11.3 Allocation . . . . . . . . . . . . . . 7.11.4 Variable declaration . . . . . . . . 7.11.5 Assignment . . . . . . . . . . . . . 7.11.6 Block . . . . . . . . . . . . . . . . 7.11.7 Conditional statement if . . . . . 7.11.8 Conditional cycle while . . . . . 7.11.9 Method call . . . . . . . . . . . . . 7.11.10 Returning from a method . . . . . 7.11.11 Forking . . . . . . . . . . . . . . . 7.11.12 Measurement . . . . . . . . . . . . 7.11.13 Communication . . . . . . . . . . . 33 33 35 36 39 39 45 45 45 46 49 49 51 54 56 58 60 63 63 64 65 65 66 66 66 67 67 67 68 70 70 70 71 72 73 73 75 77 77 79 80

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

8 Unique resource ownership 8.1 Unique quantum system ownership . . . . . . . . . . . . . . . . . . . . . . . . 8.2 Unique channel end ownership . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 Unique channel ownership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv

CONTENTS 9 Type soundness 9.1 Typing of congurations . . . . . . 9.2 Progress . . . . . . . . . . . . . . . 9.3 Type preservation . . . . . . . . . 9.3.1 Evaluation theorems . . . . 9.3.2 Type preservation lemmata 9.4 Type soundness . . . . . . . . . . . 10 Comparison with related work 10.1 LanQ . . . . . . . . . . . . . 10.2 Omer: QCL . . . . . . . . . . 10.3 Gay, Nagarajan: CQP . . . . 10.4 Jorrand, Lalire: QPAlg . . . . 11 Conclusion References 83 83 84 88 88 97 109 111 111 111 114 116 119 121

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

III

Appendix

131
133 139 139 140 140 141 143 143 144

A Program execution example B Implementation B.1 LanQ simulator . . . . . . . . . B.2 Reference manual . . . . . . . . B.2.1 Statements . . . . . . . B.2.2 Quantum operators . . B.2.3 Variable declarations . . B.2.4 Expressions . . . . . . . B.2.5 Operators and methods

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

CONTENTS

vi

Preface
The original motivation for development of LanQ was the need of an imperative quantum programming language with the syntax similar to some well-known classical language, welldened semantics, and an existing simulator. Moreover, this language was requested to support implementation of multiparty protocols. Such a language can be used by the scientists working in the quantum information processing theory eld to implement and test their ideas of new quantum algorithms and protocols. They would learn the language easily because it is similar to something they already know. The existing semantics enables them to formally verify various program properties. Moreover, the simulator could be connected to existing verication tools thus supporting machineassisted verication. Further, it could benet from existing optimization techniques to help in semi- or fully automatic optimizations of the implemented algorithms and protocols. In the thesis, we dene a typed imperative quantum programming language LanQ that allows programmers to implement any algorithm that is based on either classical or quantum computation or a combination of both. It has well-dened operational semantics, and type soundness of its part lacking communication capabilities is proved. It allows programmers to assign one quantum system to several variables in such a way that all quantum principles, namely no-cloning and no-deleting, are obeyed. The language syntax is similar to that of C language. The developed language has several process algebraic features such as creation a new process (this is done by forking a new process from a running one) and interprocess communication. It therefore supports implementation of multiparty protocols. The quantum resources are proved to be always accessible to at most one process and the channel resources to at most two processes at a time. We prove type soundness for unrestricted language provided the programs are guaranteed to use only a well-formed communication. The rst part of the thesis oers an introduction to the elds used in the thesis in Chapter 1 and provides a list of related work in Chapter 2. The second part presents the developed quantum programming language LanQ. We formally describe the language syntax in Chapter 4, its type system in Chapter 5, denitions of auxiliary functions and structures in Chapter 6, and its memory model and operational semantics in Chapter 7. Further, we prove the unique resource ownership property in Chapter 8, and type soundness in Chapter 9. Detailed comparison with several related formalisms is given in Chapter 10. The appendices form the last part of the thesis. We show an example run of a random number generator implemented in the language in Appendix A, and provide a description of the implementation of LanQ simulator in Appendix B. The simulator is publicly available at http://lanq.sf.net/

vii

Part I

Introduction

Chapter 1

Introduction
1.1 The history of quantum information processing

Quantum information processing is a relatively young branch of computer science and physics. It combines paradigms of classical computer science and methods of information processing with the phenomena exhibited in the quantum world on the basis of the laws of quantum mechanics. The birth of quantum information processing was motivated by several things. It was Feynman in 1982 who observed that there cannot exist any ecient classical algorithm for simulating quantum mechanics [Feynman, 1982]. It was then suggested that building a computer based on the quantum mechanical principles could help in this simulation. It was conjectured that a quantum computer could use less resources and/or solve several types of problems faster than classical computers. Another motivation came from the eld of microelectronics. Current design of processors leads to so small sizes that in only a few decades, according to Moores law [Moore, 1965], circuit elements would reach atomic level where quantum phenomena inevitably appear. Then anyone designing such small circuits would necessarily need to know how to deal with the quantum phenomena. The third big motivation for development of quantum information processing is a better understanding of the quantum world and creation of formalisms and tools that help in handling quantum phenomena. The rst contribution to quantum information processing eld was published in 1984 by Bennett and Brassard a quantum key distribution protocol known nowadays as BB84 protocol [Bennett and Brassard, 1984] which is proved to be unconditionally secure [Mayers, 1996]. This was the rst published work showing the relation of quantum information processing to cryptography. The next contribution to a family of quantum secure key distribution protocols was given by Ekert in 1991 [Ekert, 1991]. Ekerts protocol uses quantum entanglement a specic correlation of several quantum particles not exhibited in the classical world. Bennett, Brassard and Mermin in 1992 created a simplier scheme for quantum key distribution which is also based on entanglement [Bennett, Brassard, and Mermin, 1992]. Teleportation of a quantum bit [Bennett, Brassard, Crpeau, Jozsa, Peres, and Woote ters, 1993] is a protocol which illustrates another feature of the quantum world which is not observed in the classical world. Classically, when we want to move information from one part of a system to another, we must send the physical medium containing the data to the destination. Surprisingly, this is not necessary in the quantum world. Quantum state can be teleported to the destination without physically moving the particle whose state is teleported, 3

1.2. INTRODUCTION TO QUANTUM COMPUTING only two auxiliary classical bits are needed in the protocol. In 1994, Shor invented a famous polynomial-time quantum algorithms for integer factorization and discrete logaritm [Shor, 1994]. This was a big improvement over the classical algorithms which run at best in exponential time. The existence of Shors algorithms gave a great impetus to the development of quantum information processing. They represent a serious threat to currently publicly used cryptography: The security of many algorithms used nowadays (eg. RSA, ElGamal) depends on the computational hardness of factorization of big integers and discrete logaritm computation. If a quantum computer existed and the Shor algorithms were implemented, this would endanger the current secure internet communication which heavily uses these algorithms eg. for securing internet banking and digital signatures. Another algorithm which is an example that quantum algorithms can be exponentially quicker than the classical ones is Deutsch-Jozsa algorithm for discriminating balanced functions from the constant ones [Deutsch and Jozsa, 1992]. Computational complexity of the Deutsch-Jozsa algorithm is constant while complexity of the algorithm solving the same problem using only classical deterministic computation is exponential (in number of bits necessary to encode the function input). Quantum information processing also contributed to other elds of computer science. We should mention mainly the contributions of quantum computer science to both computational and communication complexity theories. The most general proofs of impossibility of unconditional security of coin tossing and bit commitment employ quantum information theoretic results. But quantum information processing is not only a theoretical eld. The results from quantum cryptography are practically used even nowadays. Devices for secure key establishment (on distance of more than 100 km over an optical bre) and truly random number generators (a USB device or a PCI card) are already on the market. There is a running SECOQC project which aims to develop European Quantum Key Distribution network [Alleaume, Bouda, Branciard, Debuisschert, Dianati, Gisin, Godfrey, Grangier, Langer, Leverrier, Lutkenhaus, Painchault, Peev, Poppe, Pornin, Rarity, Renner, Ribordy, Riguidel, Salvail, Shields, Weinfurter, and Zeilinger, 2007]. However, quantum computers are still in experimental phase and can be only found in laboratories. In the following few sections, we give a brief introduction to the elds used in this thesis, namely quantum computing, programming languages and process calculi.

1.2

Introduction to quantum computing

Quantum computing combines results from classical computer science and quantum mechanics. In this section, we give a brief overview of quantum computing basics. For an in-depth overview of the employed sciences we refer the reader to many existing books, eg. [Gruska, 1997, Knuth, 1998, Sipser, 2005] for computer science, [Feynman, 2006, Peres, 1995] for quantum mechanics, and [Gruska, 1999, Nielsen and Chuang, 2000, Preskill, 2000] for quantum computer science.

1.2.1

Basics of quantum mechanics

Although we do not intend to describe quantum mechanics theory in detail, in this section we give a brief overview of quantum mechanics principles used for computation. In the following text, we assume that the reader is familiar with the basic notions from linear algebra. 4

CHAPTER 1. INTRODUCTION Pure states From classical world we are used to the fact that a smallest unit of information a bit can take only value 0 or 1, ie. it is a discrete two-level system. The value of the system is exactly given by either one of those levels. A quantum analogue of a bit is a qubit a quantum bit. Like the classical case, a qubit can be in one of two basis states which we denote |0 and |1 . Contrary to classical bits, a qubit q state can also be in a superposition of these states: q = |0 + |1 where , C and we require that ||2 + ||2 = 1. Informally, a quantum bit can behave as if it was in both states |0 and |1 simultaneously. Let us formalize the previous intuition of a quantum system. We will not restrict ourselves to qubits, ie. two-level systems, but dene the formalism for general nite quantum states. A nite quantum system is represented by a complete nite-dimensional Hilbert space1 : Denition 1.2.1. A metric vector space is called complete if a limit of any Cauchy sequence of vectors is an element of this vector space. Denition 1.2.2. Let H be a complete nite-dimensional complex vector space and | : H H C be an inner product on this space. A nite-dimensional Hilbert space is the complex vector space H together with an inner product | . The inner product denes a vector norm and orthogonality of two vectors: Denition 1.2.3. For a vector , we dene its norm |||| to be: |||| = | .

Two vectors , are said to be orthogonal if | = 0. They are called orthonormal if they are orthogonal and their norms equal to one. A (orthogonal, orthonormal) basis of a vector space H is a set of (orthogonal, orthonormal) linearly independent vectors (so called basis vectors) such that any vector from H can be expressed as a linear combination of the basis vectors. Remark 1.2.4. In the thesis, we work with orthonormal bases only, therefore in the rest of the thesis, by basis we always understand orthonormal basis. A qubit is represented by a two-dimensional Hilbert space, hence its basis consists of exactly two orthonormal vectors. But even in the qubit case, there are uncountably many choices of them. To be able to perform any computation we pick one pair of orthonormal vectors: 1 0 |0 = and |1 = . 0 1 These vectors form an orthonormal basis which we call a standard basis (also called computational basis).
We only consider the nite-dimensional Hilbert spaces as we will not use innite quantum systems in this thesis. For further information regarding innite states see eg. [Peres, 1995].
1

1.2. INTRODUCTION TO QUANTUM COMPUTING In the real world, we assign these two vectors to distinguishable states of some physical two-valued observable quantity of a quantum particle, eg. photon polarization (horizontal: |0 = | , and vertical: |1 = | ) or a spin of an electron (|0 = | , |1 = | ). Besides the standard basis, there is one other very important basis. It is a dual basis (also called diagonal or Hadamard basis) {|+ , | } where: 1 1 |+ = (|0 + |1 ) = 2 2 1 , 1 and 1 1 | = (|0 |1 ) = 2 2 1 . 1

This basis is used eg. in the BB84 protocol [Bennett and Brassard, 1984] (together with the standard basis). After stating how a quantum system is represented, we now formalize its state: Denition 1.2.5. Let H be an n-dimensional Hilbert space and let 0 , . . . , n1 be a basis of H. A (pure) state of a quantum system H is described by a (unit) vector:
n1

=
i=0

i i H

where i C and

n1 2 i=0 |i |

= 1. The numbers i are called probability amplitudes.

Dirac introduced a very useful bra-ket notation. Let be a unit column vector from a Hilbert space H. Then: Bra vector | = where () = ()T is an operation of complex conjugation and transposition. Mathematically, | is a linear functional, it is an element of a dual space of H. It is represented by a row vector, Ket vector | = is the original column vector. Closed quantum system evolution A closed quantum system is a quantum system which does not in any way interact with other systems. Although in the physical reality such a system does not exist (possibly up to the Universe itself), it provides a good approximation for many experiments. Evolution of a closed quantum system from a state | to a state | is represented by a linear operation U acting on states. This operation is required to be unitary. This requirement comes from the requirement on quantum theory consistency: The operation has to map valid quantum states (ie. unit vectors) to valid quantum states (ie. to unit vectors). Denition 1.2.6. We call a complex matrix U unitary i U U = U U = I, where U denotes an operation of complex conjugation and transposition, and I is an identity matrix. The evolution of a closed quantum system from a state | is represented by multiplication of | by a complex-valued unitary matrix U which describes the operation applied onto the system: | = U | . The unitarity of the matrix has an important implication to the quantum system evolution: Any closed quantum system evolution is reversible. This is because the unitary matrices 6

CHAPTER 1. INTRODUCTION represent reversible operations on state vectors. The inverse operation to a unitary matrix U is the operation represented by a (unitary) matrix U . Examples of unitary operations are an identity operator I and Pauli matrices x , y and z . These operations play quite important rle in various areas of both quantum mechanics o and quantum information processing (see eg. [Feynman, 2006]). Among other things, they are necessary components in several quantum computational models (see Subsection 1.3.2). Their matrix representation in the standard basis is the following: I= 1 0 , 0 1 x = 0 1 , 1 0 y = 0 i , i 0 z = 1 0 . 0 1

Another useful operation is so called Hadamard transformation. It is often used in quantum algorithms, for instance in quantum Fourier transform. The transformation is given by the following actions on basis vectors: |0 |+ and |1 | . Its matrix representation is then the following: 1 1 1 . H= 2 1 1 Obtaining classical information about quantum states In the classical case, we can read a bit value as many times as we wish without disturbing the information it carries. Obtaining classical information about quantum state however aects the state in an irreversible way. Classical information about a quantum state is obtained by a measurement of a quantum state.2 A measurement performs stochastic projection of the state vector to some subspace of the state space making the state collapse to the corresponding subspace. Any possible superposition of the measured quantum system state is destroyed. Given a quantum state and a description of a measurement, the probabilities of individual outcomes are predictable. Denition 1.2.7. For a Hilbert space H, a projector is a linear operation P : H H such that P 2 = P and P = P . Quantum projective measurement (also called von Neumann measurement) is given by a set of projectors {Pi }i such that Pi = I,
i

Pi Pj = 0 for i = j.

In the process of a measurement of a state | , one of the projectors Pi is randomly applied to the state. The probability of choosing the projector Pi is given by the third postulate of quantum mechanics and equals to |Pi | |2 . After the measurement, the quantum state collapses to the state: Pi | = . |Pi | |2 Note that if | H is a state then | | is a projector. This allows us to specify a projective measurement by a Hilbert space basis: If {|i }i is an orthonormal basis of a Hilbert space H then i |i i | = I. Therefore the measurement is given by the projectors {|i i |}i .
We will not describe the most general form of the measurement. For information on this account see eg. [Nielsen and Chuang, 2000].
2

1.2. INTRODUCTION TO QUANTUM COMPUTING We usually specify the measurement with respect to physical quantities by observables. A physical observable is a self-adjoint operator. We can decompose an observable O using its eigenvalues i and eigenvectors |i as follows: O=
i

i |i i |.

Note that the |i i | part of the decomposition species a projector Pi . We call this form of the observable O a spectral decomposition of O. Measurement with respect to an observable results into one of its eigenvalues and makes the state collapse to the subspace spanned by the corresponding eigenvectors. Mixed states Imagine a source of photons that produces a vertically polarized photon with probability p and a horizontally polarized one with probability 1 p. When we obtain a photon out of it, we want to describe our a priori knowledge about its state before any measurement. Can we do so? In this case, our knowledge about the photon state is incomplete for we only know the probabilities of individual outcomes. Nevertheless, even such incomplete information can be represented in the quantum formalism: Denition 1.2.8. A mixed state is a probability distribution {pi , |i }i over pure states |i . Therefore we can represent our photon state as: {(p, | ), (1 p, | )}. Mixed states are represented by density matrices: Denition 1.2.9. Let A = (aij ) be a square matrix in a nite complex Hilbert space H. A trace of a matrix A is dened as Tr A = i aii . A square matrix A such that A = A is called hermitian. A matrix A is said to be positive if it is hermitian and |A| 0 for all | H. A density matrix (also called a density operator) is a positive matrix A such that Tr A = 1. To any mixed state {(pi , i )}i we assign a density matrix : =
i

pi |i i |.

Note that a pure state | is represented by a density matrix = | |. Remark 1.2.10. The trace of a density matrix can be thought of as a probability that a quantum system is in the state . In the denition, we require that the state exists with probability 1 (the condition Tr A = 1). However, there is an alternate denition of a density matrix [Selinger, 2004] which allows the trace to be also strictly less than one. In the thesis, we work with density matrices in the sense of Denition 1.2.9. 8

CHAPTER 1. INTRODUCTION One density matrix can represent many dierent mixed states. For example, the mixed states: 1 1 1 1 and = {( , |+ ), ( , | )} = {( , |0 ), ( , |1 )} 2 2 2 2 have the same density matrix: 1 1 0 . 2 0 1 However, as mixed states described by the same density matrix are physically indistinguishable, this correspondence of one density matrix to many mixed states does not cause harm to us. We follow the usual convention and write a state instead of a mixed state represented by a density matrix . A prominent place among the mixed states belongs to the maximally mixed state a 1 mixed state of an n-dimensional quantum system whose eigenvalues are all equal to n . Such a state can be interpretted as follows: For any basis, the system is in any of the basis states 1 with equal probability n . The density matrix of this state is: 1 I n Compound systems In the classical case, we can compose bits to create larger data types, eg. a byte is composed of eight bits. It is now a natural question how we can combine smaller quantum systems to get larger ones. Imagine the situation when we have two particles in states H and H , respectively. We want to describe the state of the system composed of these two particles. In contrast to the classical case, it is not enough to describe the state of the individual subsystems (what suces in the case of bits). The reason is that in the quantum world, the two systems might be quantum-correlated. The overall state of the system is therefore an element of a tensor product of the subsystem spaces: H H . In the case when the states and were prepared separately and did not interact, their overall state is given by the tensor product of the subsystem states: = . Denition 1.2.11. Let us have two matrices A and B: a00 a0m b00 . . , B = . .. . . A= . . . . . am 0 am m bn 0 Their tensor product is dened as: a00 B . AB = . . am 0 B 9 a0m B . . .. . . . am m B where I is an identity operator of order n.

b0n . . .. . . . bn n

1.2. INTRODUCTION TO QUANTUM COMPUTING Note that this way we have also dened the tensor product for vectors because vectors can be regarded as matrices with only one column. We use the following standard notation for qubits: in place of |b0 |b1 |bn for basis vectors |bi , we often write |b0 b1 . . . bn . There exist quantum states of a compound system that cannot be written as a tensor product of states of two separate systems. We call such states entangled. Entanglement is a very specic feature of the quantum world. Due to presence of entanglement, nonlocal phenomena can occur in the quantum world actions performed on one part of the compound system can immediatelly aect the other part of the system. Consider the following important state of two-qubit compound system: 1 = (|00 + |11 ). 2 The state is called EPR state, named after Einstein, Podolsky and Rosen who rst showed the occurence of nonlocal phenomena in quantum mechanics using a very similar state [Einstein, Podolsky, and Rosen, 1935], and the pair of qubits is called EPR pair. This state has a nice property: If one qubit is measured (in the standard basis), we obtain a result b which is either 0 or 1, and the whole state collapses either to |00 or |11 . If we then measure the second qubit in the same basis, we always obtain the same result b. This holds even if the quantum particles are separated by a large distance. The EPR state is used in various quantum protocols, among others in teleportation [Bennett et al., 1993] or several quantum key distribution protocols [Ekert, 1991, Bennett et al., 1992]. Now we know how to represent a state of a quantum compound system. Indeed, an interesting question is: Given a state AB HA HB of a compound system, what is the state of its subsystems? To answer this question, we dene a reduced density operator: Denition 1.2.12. Let AB HA HB be a density operator representing the state of a two-particle quantum system AB. Further, let {i }i be a basis of the system B. The state of system A is represented by a reduced density operator A that is given by partial trace operation: A = TrB AB = i |AB |i .
i

The partial trace operation is a generalization of the trace operation. Next we turn our attention to the operations acting on a compound system H = HA HB . These operations are represented by matrices from H. An operation U which can be written as a tensor product U = UA UB acts on the individual subsystems separately. The operations UA HA , UB HB are then called local operations. Similarly to the quantum states, there are also quantum operations that cannot be written as a tensor product of two local operations. An example of such an operation is a CNOT (Controlled-NOT3 ) operation which operates on two qubits, performing a NOT operation on the second qubit if the rst qubit is in state |1 : |00 |00 1 0 0 0 0 1 0 0 |01 |01 , its matrix representation CN OT : CN OT = 0 0 0 1 . |10 |11 in standard basis is |11 |10 0 0 1 0
Controlled operations are such operations which are executed on a set of target quantum systems only if some other control quantum systems are in a specic state.
3

10

CHAPTER 1. INTRODUCTION Mixed state evolution We now describe the formalism used to describe evolution of a quantum system represented by the density matrix: = pi |i i |.
i

The evolution of a state is described by an operator E : which satises: E is linear: = E() =


i

pi E(|i i |),

If E is applied on a density matrix it yields again a density matrix. Informally this means that if an operation described by E is applied onto a valid system, we obtain again a valid system. We hence require that E maps a positive matrix to a positive matrix, and preserves trace of the matrix as both Tr and Tr are equal to one (by denition of a density matrix), If E is applied to a part A of a compound system AB then the compound system remains in a valid state. In particular, it can be described by a density matrix. This condition is called complete positivity. Now we formalize the previous requirements. Denition 1.2.13. Let HB be a Hilbert space. We call a linear operator F : HB HB : trace-preserving if for for any positive matrix B HB , Tr B = Tr F (B ), positive if for any positive matrix B HB , F (B ) yields a positive matrix, completely positive if F is positive and for any positive matrix B HB , Hilbert space HA and a positive matrix AB HA HB such that TrA AB = B , (I F )AB is a positive matrix. A trace-preserving completely positive operator is called a superoperator. The name superoperator was given because it transforms density operators to density operators. Remark 1.2.14. Like for density matrices, the superoperator can be alternatively dened as a completely positive operator E such that for a density matrix A in the sense of Remark 1.2.10, E is a completely positive operator where Tr E(A) Tr A. The evolution of a closed quantum system is like in the case of pure states represented by an application of a unitary operator on its density matrix. However, as we do not apply the matrix to the vector but to a matrix, there is a dierence: Should such a unitary operation U be applied to a density operator , we represent it as a superoperator EU : = EU () = U U . Superoperators can also represent evolution of open quantum systems, ie. quantum systems which interact with other systems (environment) whose state is unknown. Such an 11

1.3. MODELS OF QUANTUM COMPUTATION evolution is not necessary unitary. Let us have a pure state and let the evolution be represented by a superoperator E. Then the state E() can be mixed. This property is used to represent eg. noisy channels. Consider a channel where a qubit passes without any change with probability p and the qubit value is ipped from 0 to 1 and vice versa with probability 1 p. This channel is called a bit-ip channel. Operation Ebf which represents this channel acting on a state is given as:
Ebf () = pII + (1 p)x x = p

1 0 1 0 0 1 0 1 + (1 p) . 0 1 0 1 1 0 1 0

1.3

Models of quantum computation

In this section, we describe several existing models of quantum computation. We start with models whose predecessors were successful models of classical computation.

1.3.1

Models based on classical models

There have been many successful attempts to adapt classical computational models to the quantum world, for example quantum nite automata [Kondacs and Watrous, 1997], quantum cellular automata [Watrous, 1995], quantum Turing machine [Deutsch, 1985, Bernstein and Vazirani, 1997]. We describe two widely-used models based on classical predecessors which we use later in the thesis, namely quantum circuits and QRAM model, in more detail. Quantum circuits Classical circuits are well known and widely used model for design of variety of electronical devices televisions as well as computer processors. It is a well-readable formal (albeit graphical) specication of the device. Logic circuits realize Boolean-logic functions. Its primitives are wires and gates, eg. gates for realizing NOT, NAND, OR or XOR operations. Quantum circuit model introduced by Deutsch in [Deutsch, 1989] is based on classical logic circuit model. Quantum bits passing through the circuit gates are represented by wires. The gates labelled boxes drawn on these wires represent unitary operations acting on the qubits. Because of the unitarity of the operations, the number of wires cannot change in the circuit. By convention, the operations are applied to the qubits from left to right. Conventionally, the standard basis is used for computation. Quantum circuits cannot contain feedback loops, ie. no wire can return from right to left. Therefore no part of a circuit can be repeatedly used. It also does not support conditional execution of any part of the circuit, ie. we cannot implement any analogue of a classical if statement known eg. from C language. An example of a quantum circuit is shown in Figure 1.1. The circuit operates on two qubits, rst applying the Hadamard transformation to the rst qubit (the H gate) and identity to the second qubit, and next applying Control-NOT operation to both qubits (the CN OT gate). In the algebraic formalism, we start with two qubits in states | and | and assume they are not entangled. Therefore their overall state is | | . Application of the rst gate in the rst step means matrix multiplication of the state | | by the unitary operation H I where I is an identity matrix (for we perform Hadamard transformation on the rst 12

CHAPTER 1. INTRODUCTION qubit | but do nothing on the second qubit | ). It is result by CN OT matrix: 1 0 0 0 1 0 1 0 0 0 CN OT (H I) (| | ) = 0 0 0 1 1 0 0 1 0 0 followed by multiplication of the 0 1 0 1 0 1 (| | ). 0 1 0 1 0 1

This circuit is used to create an EPR pair. If it is given two qubits in the initial state |0 |0 , the state of these qubits gets transformed to the EPR state. QRAM model Quantum Random Access Machine (QRAM) is a classical random access machine in the usual sense able to perform several quantum operations quantum state preparation, unitary operation and measurement on quantum registers [Knill, 1996]. The registers are allocated as needed during a program run. This model supports manipulation of both classical and quantum data, the control of programs is classical. Classical program control enables QRAM to support loops and conditional statements. It makes a QRAM model a universal model that can express any classical and/or quantum algorithm in its pseudocode which is also described in [Knill, 1996]. This model is therefore stronger than quantum circuits. For its features, the QRAM model is much more interesting for quantum algorithm designers than quantum circuits. Although semantics of the language is not specied formally, it suces to standardize algorithm notation what was the original intention of the Knills paper. The LanQ language described in this thesis can be described by this model.

1.3.2

Measurement-based computation

Measurements are used to obtain classical information about a quantum state. The computational models mentioned in previous subsection usually use measurements to obtain the classical information only about the result of the computation. Surprisingly, one can use measurements also to perform computation. One-way quantum computer The one-way quantum computation [Raussendorf and Briegel, 2001] is based on the work with so called cluster states a multipartite quantum state organized into a rectangular lattice in which the particles are entangled in a specic way. The preparation of this state has constant time complexity: initially all qubits up to the input ones are in the |+ state, then | |

Figure 1.1: Example of a quantum circuit. 13

CN OT

1.4. INTRODUCTION TO PROGRAMMING LANGUAGES the Control-Z operation is applied to the qubits neighbouring in the lattice. As the Control-Z operation commutes, it can be applied onto all qubits at the same time. The computation itself consists of one-qubit measurements performed in certain order and basis. Results of individual measurements are uniformly random, introducing an error into the computation. To correct this error, the basis of the next measurement is adapted accordingly. The result qubits also suer from this type of error. However, it was shown in the original a b paper that this error is correctable and always takes the form x z where the x , z are Pauli operators and coecients a and b are either 0 or 1 and are known from the previous measurement outcomes. Teleportation-based quantum computer Another model developed by Nielsen [Nielsen, 2003] and improved by Leung [Leung, 2004] is based on the following observation: The teleportation protocol [Bennett et al., 1993] transfers a state of one qubit from one place to another up to a known and simply correctable error, thus performing an identity operation (up to the error) on the given state. The teleportation employs quantum projective measurement in Bell basis {| + + , | + , | + , | }. Using other bases, we can perform operations other than the identity, again up to a known error. In this model, the connection between the operations and the bases is shown. The original Nielsens formulation uses 4-qubit measurements to simulate any 2-qubit quantum gate what was improved by Leung who showed that 2-qubit measurements are sucient. This model uses four auxiliary qubits for simulation of any n-qubit quantum gate. The original model was further developed by Perdrix [Perdrix, 2005] who used state transfer in place of teleporation as the primitive for computation. This way the number of auxiliary qubits needed for the simulation of any n-qubit gate is reduced only to one qubit, hence reaching the optimum.

1.4

Introduction to programming languages

In this section, we briey introduce the eld of programming languages. For further reading, we refer the reader eg. to [Knuth, 1998, Slonneger and Kurtz, 1995]. A programming language is a medium used for communication between a human and a machine. A programming language must provide rules for an unambiguous notation of programs. For this purpose, we dene syntax and semantics of a programming language. Syntax denes symbols of a language and rules how these symbols can be put together to form phrases. Semantics denes meaning of individual. The semantics of a programming language is usually dened in one of the following ways: Operational semantics the meaning of a phrase is a sequence of abstract machine transitions. To dene operational semantics, one has to rigorously dene a set of states (this can be eg. a -term or a state of some formally specied abstract machine) and a transition function which acts on the states. This type of semantics was pioneered by McCarthy [McCarthy, 1963], Denotational semantics the meaning of a phrase is a phrase (denotation) in other language, usually in a mathematical formalism. For instance, each phrase of the language 14

CHAPTER 1. INTRODUCTION is associated a number or a function. The phrases can be combined to form bigger phrases according to the language syntax. The denotation of these bigger phrases is given by composing the denotations of their subphrases, therefore denotational semantics is compositional. This type of semantics was developed by Scott and Strachey [Scott and Strachey, 1971], Categorical semantics the semantics of a phrase is given by a morphism in a category with prescribed properties. Categorical semantics is hence more abstract than the denotational. The actual shape of the category can vary a lot for example Abramsky and Coecke showed that quantum mechanics can be described by a strongly compact closed category with biproducts [Abramsky and Coecke, 2004].4 As the category of nite vector spaces with unitary transformations, category of sets and relations and a plane picture calculus [Coecke, 2005] are such categories, they all can be used to interpret quantum theory. There are also other approaches to semantics, among others: action semantics, algebraic semantics, axiomatic semantics, game semantics. For further reading on semantics of programming languages, we refer the reader to [Slonneger and Kurtz, 1995] and to [Abramsky and McCusker, 1999] specically for game semantics. A paradigm of a programming language determines a way of expressing programs in the language. The main paradigms are the following: Functional a program is an expression written in a declarative form. The program result is given by reduction of the expression, Logical a program is a theory written in a declarative form. The program result is an answer to some question. This answer has to satisfy the given theory, Imperative a program is a description of a way to obtain a result. During a program run, a global variable specifying a program state is updated. An imperative programming language that supports denition of methods (or functions, routines, procedures) is called procedural. Methods are parametrized program fragments. They allow programmers to structure a program into smaller pieces of code. This improves readability of program code and makes it easier to maintain the program code. The program can then invoke the methods from within a caller method. After a method nishes its execution, it eventually returns a return value to its caller. A higher-order programming language allows one to manipulate functions as if they were data. In such languages it is possible to create functions during a program run, functions can return other functions as their return value etc. A language which is not higher-order is called rst-order. A variable in imperative languages is a specication of a memory location where a value is stored. In functional languages, a variable denotes a variable in the usual mathematical meaning. In general, it is possible to create syntactically correct terms that have no meaning. To avoid this unwanted freedom, we add a type system to a language. A type of a variable species a range of the valid values of the variable. Languages where variables are given
4

Similar result was independently obtained by Selinger [Selinger, 2005].

15

1.4. INTRODUCTION TO PROGRAMMING LANGUAGES a type are called typed [Cardelli, 2004]. To give an example of what typing is useful for, consider a type letter of letters of English alphabet. Let c denote a variable of type letter. Then c can stand for a letter g but it cannot represent a number 4. The usage of types allows a compiler to detect such errors at compile-time. Therefore, taking c as in the previous example, assignment of a value 4 to the variable c can be detected at compile-time and this error can be reported to the programmer. Types are particularly useful when developing a programming language that allows the programmer to express combination of both quantum and classical computations. For example, quantum data cannot be in general duplicated (due to no-cloning theorem, [Wootters and Zurek, 1982]), while classical data can. This means that classical and quantum data must be handled dierently what can be achieved eg. by using dierent types for quantum and classical variables. Type soundness A useful propery of typed languages is type soundness. A language with sound type system guarantees that if a term in the language is typable (ie. we can infer a type of the term), then the evaluation of this term never terminates because of a type error5 (weak type soundness) [Milner, 1978]. We can often prove strong type soundness of a language which guarantees that the evaluation of a typable term t either diverges or yields an answer6 of the same type as the term t. Note that what several other authors, eg. [Cardelli, 2004], understand by type soundness is in fact strong type soundness. Type soundness of a language is nowadays most usually proved using a technique by Wright and Feleisen [Wright and Felleisen, 1994]. This technique is based on similar proofs of subject reduction from combinatory logic and on term rewriting as specied by operational semantics.

1.4.1

Quantum programming languages

A quantum programming language is a language that allows a programmer to describe computations in the quantum world and possibly also in the classical world. We can characterize programming languages by quantumness of their control state and manipulated data. Classical programs can be characterized by the slogan classical control, classical data: both control state of a program and data are classical. Quantum programs can be characterized either by slogan quantum control, quantum data or classical control, quantum data. Control state of a program in the former style is quantum meaning that it can be in a superposition of multiple basis states. In this case all the data are quantum. Programs in the latter style support manipulation of both quantum and classical data while employing a classical program control state. Note that this behaviour is exactly modelled by a QRAM. Several existing quantum programming languages are discussed in Chapter 2.
A type error is a language-dependent concept usually meaning an error arising from passing such arguments to a function which do not belong to the function domain, eg. attempt to add a number 7 to a boolean value false. 6 Specication of what the answer looks like is again language-dependent.
5

16

CHAPTER 1. INTRODUCTION

1.5

Introduction to process algebras

In this section, we briey introduce the eld of process algebras. For further reading, we refer the reader to [Fokkink, 2000] and [Bergstra, Ponse, and Smolka, 2001] for an in-depth introduction to this eld, and to [Baeten, 2004] for a historical overview. A process describes behaviour of a system, ie. a sequence of observable actions and events that are performed in the system. A process algebra is the study of behaviour of parallel or distributed systems by algebraic means [Baeten, 2004]. It is a mathematical tool for describing or specifying processes and their interactions and reasoning about them by means of equations. Hence, process algebras are crucial for proving dierent kinds of process equivalences and properties of multiparty protocols. A process description consists of actions and their compositions. The set of actions is dependent on the system settings. An action can be for instance a keypress on a keyboard or an allocation of a resource. These actions can be composed together to form processes by many dierent operators. The most common composition operators are: Sequential composition P1 .P2 of two processes P1 and P2 the process P2 is run after the process P1 is successfully completed, Alternative composition P1 + P2 of two processes P1 and P2 the system nondeterministically executes either process P1 or P2 7 , Parallel composition P1 P2 (or P1 | P2 ) of two processes P1 and P2 the system executes the processes P1 and P2 simultaneously, Probabilistic composition P1 p P2 of two processes P1 and P2 the system executes the processes P1 with probability p or P2 with probability (1 p). The most inuential process algebras are Milners CCS (Calculus of Communicating Systems) [Milner, 1980], CSP (Communicating Sequential Processes) by Hoare [Hoare, 1983] and ACP (Algebra of Communicating Processes) by Bergstra and Klop [Bergstra and Klop, 1984]. For further reading on these algebras, we refer the reader to [Baeten and Weijland, 1990] and [Bergstra et al., 2001]. The work of Milner, Parrow and Walker led to the development of -calculus, a calculus where not only data but also communication channels can be passed over a channel from a process to another process [Milner, Parrow, and Walker, 1992]. This feature is used eg. to model a situation when a person A is travelling with a mobile phone while speaking to person B while travelling, the phone changes its base stations during the call but the communication channel between A and B remains the same. Any process algebra containing both nondeterministic and probabilistic choices has to specify which choice is solved rst. For more information on this account see [Cazorla, Cuartero, Ruiz, Pelayo, and Pardo, 2003]. Communication The interaction between two or more processes is done by communication. Process algebras oer tools for describing communication among processes, usually by means of abstraction of
Note that process algebras are inherently nondeterministic the choice of order in which the concurrent processes evolve is nondeterministic.
7

17

1.5. INTRODUCTION TO PROCESS ALGEBRAS communication links called channels. We distinguish two types of communication: Synchronous (blocking) communication when a sender attempts to send a message, its execution is delayed until there is another process which can receive. Similarly, when a receiver attempts to receive a message, its execution is delayed until there is another process which sends a message over the corresponding channel. This type of communication can indeed lead to a deadlock when there is no sender/receiver to a receiving/sending process, Asynchronous (nonblocking) communication a sent message waits in a channel until there is a receiver which can receive the message, the sender continues its execution without waiting for the receiver. It has been proved that asynchronous communication can be simulated using the synchronous one but synchronous cannot be simulated using the asynchronous [Palamidessi, 1997]. Note that communication can be a source of nondeterminism. Consider the following four processes (we use the notation of -calculus): A(g) = g 3 .0 B(g) = g(x).0 C(g) = g(x).0 System = (g)(A(g)|B(g)|C(g)) The process A sends a number 3 over the communication channel g and terminates. Both processes B and C behave identically: After a successful reception of the number from the channel g the process terminates. The process System allocates a channel g and executes the processes A, B and C in parallel. Now, which of the processes B or C receives the sent value 3, is left to the nondeterminism. This type of nondeterminism was recognized earlier and there were several approaches to handle it. Kobayashi, Pierce and Turner suggest in [Kobayashi, Pierce, and Turner, 1996] using a linear type system over the -calculus. A channel is assigned a polarity (whether it can be used for sending or receiving) and multiplicity (how many times it can be used for communication, either 1 or ). Linear channels are those channels whose multiplicity is 1 regardless of their polarity. Type system then uses polarities to guarantee that linear channels are used by at most two processes at a time, one sender and one receiver. For a solution for a more complex formalism where channel types for structured communication (so called session types) can be specied see eg. [Gay and Hole, 2005, Yoshida and Vasconcelos, 2007]. The solution is also based on channel polarities checked by the type system.

1.5.1

Quantum process algebras

In quantum process algebras, the communication and the manipulated data can be classical or quantum. This has a large impact on quantum resource handling: a process calculus must guarantee unique ownership of quantum systems among processes. Moreover, if a quantum process algebra supports a combination of quantum and classical computations, expression of quantum measurements must be allowed. Because the measurements are probabilistic by nature, it has to deal with probabilistic choice. As mentioned earlier, if the process algebra also supports nondeterministic choice, it must specify which choice the probabilistic or the nondeterministic is solved rst when they occur simultaneously. 18

Chapter 2

Current state of the art


In this chapter, we give a brief characterization of several quantum programming languages and process algebras that have been developed so far. For the currently most complete survey on quantum programming languages we refer the reader to [Gay, 2006] and to [Glendinning, 2005] for an online list of them. Some of the languages will be discussed in more detail in Chapter 10 where they will be also compared with LanQ.

2.1

Functional languages and -calculi

We can view programs as descriptions of functions which transform input values to some output. This is one reason why many of proposed quantum programming languages are functional. Another reason why functional languages are so popular, is that their operational semantics can be straightforwardly dened. -calculus is a mathematical formal system introduced by Church and Kleene in 1930s. It has a very simple and well-known syntax for writing expressions. Operational semantics is straightforwardly given by reduction rules. Nevertheless, it is powerful enough to express any computable function. Any functional language can be viewed as a syntactic variation of the -calculus [Slonneger and Kurtz, 1995]. This justies the decision to put the functional languages and -calculi to the same section.

2.1.1

Quantum q -calculus van Tonder

The rst successful attempt to create a functional quantum programming language was done by Andr van Tonder in 2003 [van Tonder, 2003a]. He created untyped -calculus for quantum e computing. He proved the model of this calculus to be computationally equivalent to quantum Turing machines. This -calculus was later extended to a typed -calculus in [van Tonder, 2003b] where denotational semantics of the latter calculus was also developed. The language supports higher-order computations to be expressed. To deal with quantum resources, techniques from a linear -calculus were employed. The resources are divided into two groups: Linear these resources can be neither copied nor discarded. Quantum states in the q -calculus are considered to be linear resources, 19

2.1. FUNCTIONAL LANGUAGES AND -CALCULI Nonlinear these resources can be both copied and discarded. A disadvantage of the quantum q -calculus is the nonexistence of measurements in the language. This constraint makes it impossible to combine classical and quantum computations. Therefore, this language can be used for describing purely quantum algorithms. The simulator is available from http://www.het.brown.edu/people/andre/qlambda/.

2.1.2

QPL

Selingers QPL [Selinger, 2004] is an important typed functional language. This language can be described by a slogan quantum data, classical control. It can be used to express any algorithm manipulating quantum and classical data or their combination. The syntax of the language has two interchangeable forms. A program can be described by a graphical ow chart. This form is intuitive and has direct connection to the semantics but it is dicult to manipulate and discourages structured programming. For this reason, a structured textual form of the language exists. The linearity of quantum data is enforced by the syntax which ensures that syntactically distinct variables will refer to physically distinct objects. The language is very restrictive in handling variables: eg. it denies to assign an expression or even a value of another variable to a variable. For example, if a and b are of type bit, the only way to set a to the value of b is the following: if b then a := 1 else a := 0. Indeed, this nonconformity can be overcome by using syntactic abbreviations for frequently used statements. QPL is the rst quantum language with well-dened denotational semantics. The semantics is given by assigning any program fragment a generalized superoperator acting on generalized density matrix tuples: A generalized density matrix D is a positive matrix such that Tr D 1. A generalized density matrix tuple (D0 , . . . , Dn ) is a tuple of generalized density matrices Di such that n 1. A generalized superoperator that acts on generalized i=0 density matrix tuples is then dened similarly to the usual denition of superoperator (see [Selinger, 2004]). The generalization of the density matrix formalism is used to represent of nite classical data. The i-th element of a generalized density matrix tuple Di represents the state of quantum world if the overall state of classical memory is represented by the number i. The probability that the classical memory is in overall state i is given by the trace Tr Di . The fact that generalized superoperators form a complete partial order enables semantics of loops and recursion to be dened naturally as a limit of a sequence of superoperators. Selinger also denes a categorical semantics of the language. Later he showed in [Selinger, 2005] the connection between the categorical semantics of [Abramsky and Coecke, 2004] and the semantics of QPL.

2.1.3

QML

QML is a typed language developed by Altenkirch and Grattage [Altenkirch and Grattage, 2004]. It supports both classical and quantum computations to be expressed. Both data and control of the program ow may be quantum. Even though the language is functional, it only supports rst-order computations to be expressed; all data types are nite. It is therefore not possible to treat functions as data. The technique used for developing the language semantics is interesting. First, they look at classical computations and show them to be reversible in a closed system. Then they 20

CHAPTER 2. CURRENT STATE OF THE ART explain irreversible classical computations based on reversible mechanics. To show it they utilize a heap. Heap is an auxiliary space which can be used during computation. Let A, B be two nite sets. Reversible nite computation of a function f : A B is represented by a bijection on nite sets: f : A H B G where G is a set of possible heap states after computation and H is a set of possible heap states before computation. Such two bijections f , g are considered extensionally equivalent if the functions f and g, whose reversible computations they represent, are equal (f = g). Any computable function f on a nite domain can be represented by such a mapping f . The authors justify usage of superoperators for denition of semantics of quantum computation in the following way: A superoperator can be represented by a space expansion, application of a unitary transformation in the larger space and nally tracing out the auxiliary space. This gives a picture similar to that of the previous paragraph. Therefore, any quantum computation should be in general represented by superoperators. The authors put emphasis on the control of decoherence. For this purpose, their language oers two dierent ifthenelse constructs. One of them measures a qubit in the condition, the second one does not. However, the second if-construct can be used only in certain cases. Another tool used to control the decoherence is minimalisation of weakenings (ie. discarding of quantum states). This is achieved by the type system based on strict logic. Minimalisation of weakenings is a dierence to other quantum programming languages which prevent contraction (duplication of a quantum system) to occur. Indeed, the language does not support duplication of quantum data, but two or more variables are allowed to refer to the same quantum system. The language compiler is available from http://sneezy.cs.nott.ac.uk/qml/compiler/.

2.1.4

Quantum -calculus Selinger & Valiron

The calculus developed by Selinger and Valiron in [Selinger and Valiron, 2006] is a typed quantum data, classical control -calculus. Higher-order computations can be expressed in this language. Contrary to van Tonders language, combination of both classical and quantum computations is supported, measurement of a quantum system is a primitive in the language. To support handling of both quantum and classical data, the type system distinguishes between the types whose values are duplicable and whose not. This type system is used to guarantee that no-cloning and no-deleting of quantum data is not violated. Interestingly, this not only holds for the ground data types but also for the higher-order types. It is therefore possible to have a function of type qbit qbit that can be called only once and another that can be invoked multiple times. It is remarkable that the type system does not satisfy principal type property, ie. that every untyped expression has the most general type. Therefore the authors had to develop a type-inference algorithm which can determine whether a given term is typable in the linear type system, and nd its type. The authors dene operational semantics of this language in terms of probabilistic reduction rules. They prove type preservation and progress lemmata for well-typed programs.

2.1.5

nQML

nQML [Lampis, Ginis, and Papaspyrou, 2006] is a language based on the previously described QML language by Grattage and Altenkirch. This language is characterized by the slogan 21

2.2. OTHER LANGUAGES quantum data and control, allowing to perform a measurement at any point during a program run. The language supports variable aliasing hence several quantum variables can point to the same qubit. To prevent a situation when one qubit is used more than once in one quantum operation, the authors employ the type system. The type of quantum expressions contains specication of the place of the qubits in which the expression value is stored. Then it is easy to check the requirement of distinctness of quantum variables without introducing linear type system. Denotational semantics of the language is dened using density matrices in terms of unitary operations (for terms not containing measurements) and general functions from density matrices to density matrices (for those containing measurements). A publicly available implementation exists and is available from ftp://ftp.softlab. ntua.gr/pub/users/nickie/papers/nqml06.code.tar.gz.

2.2
2.2.1

Other languages
qGCL

Quantum Guarded Command Language (qGCL) was developed by Sanders and Zuliani in [Sanders and Zuliani, 2000, Zuliani, 2001]. Both quantum and classical computations and their combination can be expressed. qGCL was developed from the probabilistic language pGCL which, in turn, was created using Dijkstras GCL as a basis. pGCL was chosen as a base of qGCL because of its rigorous semantics. A probabilistic guarded-command language program is a sequence of assignments and statements skip and abort. The program is manipulated by standard constructors of sequential composition with conditionals, loops and probabilistic and nondeterministic choice. A quantum program in qGCL is a pGCL program which uses quantum procedures. These quantum procedures can be of three types: initialisation of a quantum state, evolution and nalisation (a measurement). This language can be used both as a specication language and a programming language. It has well dened operational semantics. The renement calculus associated with qGCL was inherited from pGCL and extended. It allows systematic program derivation and algebraic reasoning about qGCL programs. The renement calculus also allows to simplify programs algebraically. Simplication is seen as a particular program renement which preserves semantics. Even though recursion is available in pGCL, the language qGCL does not support it [Zuliani, 2001, Sec. 2.4]. This was a decision during design of this language because of the compilation technique used.

2.2.2

QCL

Imperative language QCL was designed by Omer in [Omer, 2000, 2003]. It supports both quantum and classical computations to be expressed and freely interleaved. Its syntax is based on that of C language what makes it easy to learn for ordinary programmers. This language is interesting for many reasons. The language oers tools for simple denition of a quantum operator in the language. It supports creation of reversible quantum gates 22

CHAPTER 2. CURRENT STATE OF THE ART from classical-like code (so called quantum functions). This allows programmers with only a rough knowledge of quantum mechanics to create quantum operators. QCL is not a higher-order programming language, but it retains some features of higherorder languages. For example, it is possible to automatically compute an inverse of a quantum operator. The semantics of this language is not dened. Therefore, it is impossible to prove a program written in QCL to satisfy some property. Omer developed a QCL simulator that is publicly available from http://tph.tuwien. ac.at/~oemer/qcl.html. This language is further discussed in Section 10.2.

2.2.3

Q language

Betteli, Calarco and Seranis Q language [Bettelli, Calarco, and Serani, 2001] is not a language written from scratch. It is an extension of the existing C++ language. Like QCL, it supports description of both quantum and classical computations and their combination. Q philosophy is to extend existing standard language instead of creating a new one. This way programmers need not learn a new language, they just learn the extension.1 This approach also allows the developers to use existing compilers for compilation of programs written in Q. No new compilers or simulators need to be developed, it is possible to only extend the existing ones. This language supports combination of quantum and classical computation in the same way as in QRAM model. This means that classical computations are performed on a classical computer; quantum device, that performs quantum computations, is controlled by the classical computer. Unitary operators are represented by objects in the sense of object-oriented programming. This representation allows programmers to create operators during a program run using operator composition, conjugation etc. Created operators can be optimised before they are used at the quantum device. If the quantum device does not support execution of arbitrary quantum operations, this approach allows the control machine to compute a decomposition of an operator to such primitives that the quantum device can perform. The semantics of this language is not dened formally. A publicly available implementation exists and is available from http://sra.itc.it/people/serafini/qlang/.

2.2.4

QMC

Quantum Model Checker by Gay, Nagarajan and Papanikolaou [Gay, Nagarajan, and Papanikolaou, 2007] is a single-process quantum model checker with a formally dened syntax and semantics. It uses a subset of exogenous quantum propositional logic (EQPL) [Baltazar, Mateus, and Sernadas, 2007] to check the properties of the resulting state. The tool scans all possible paths which the execution of the checked program can take due to quantum measurements and checks whether the EQPL formula is satised for all possible program runs. The model-checker uses the stabilizer formalism for quantum system state representation. Note that using this formalism, instead of one state, a set of quantum states satisfying given stabilizer equations is represented. Stabilizer formalism only allows us to use Cliord group
1

This is the same idea that was used for development of the LanQ syntax.

23

2.3. QUANTUM PROCESS ALGEBRAS operations, 1-qubit measurements, and Cliord group operations conditioned on classical bits to be applied onto a quantum state. Although the set of operations is not universal and not all quantum states can be expressed in this formalism, this model is rich enough to express many practically usable algorithms and protocols, eg. teleportation protocol [Bennett et al., 1993] or quantum dense coding [Bennett and Wiesner, 1992]. Moreover, it is known to be eciently simulable on classical computers (Gottesman-Knill Theorem, [Gottesman, 1998]) and an algorithm for its simulation exists [Aaronson and Gottesman, 2004]. Both EQPL and stabilizer formalism limit the dimension of used quantum systems to two, hence only qubits can be used in the programs. Although it is an insuperable obstacle in a work with higher-dimensional quantum systems, this design decision has important impact on speed making the implementation very fast. Currently, the number of qubits manipulated by the program must be specied before the program is run and cannot be changed during the execution. Although this decision of the authors does not usually cause a problem, the algorithms which allocate qubits dynamically in a loop can be limited by this restriction. The model checker implementation is under development.

2.3

Quantum process algebras

There have been developed several quantum process algebras. We describe two of them, QPAlg and CQP.

2.3.1

CQP

Communicating Quantum Processes developed in [Gay and Nagarajan, 2004, 2005, 2006] is another quantum process algebra. It can describe both quantum and classical interactions and evolution of processes. The syntax and semantics of this algebra are based on the -calculus. In this algebra, the channels are dynamically allocated. Therefore, they are only available to the allocating process and its subprocesses. However, the number of subprocesses that can use an allocated channel for communication is not limited. This way three or more processes can use one channel hence introducing nondeterminism as described in Section 1.5. Communication channels are typed. The type of values that can be sent over individual channels is given by the type of the channel. For example, sending a value of type char over channel that can send only values of type bit, is impossible. The algebra guarantees unique quantum system ownership among processes. Contrary to QPAlg, type soundness is proved for the language. A typechecking algorithm exists and is proved to be sound and complete [Gay and Nagarajan, 2006]. This algebra is further discussed in Section 10.3.

2.3.2

QPAlg

The quantum process algebra QPAlg by Lalire and Jorrand [Lalire and Jorrand, 2004, Jorrand and Lalire, 2004] can describe both classical and quantum interaction and evolution of processes. The syntax and operational semantics of this algebra are based on that of CCS and Lotos. Recently [Lalire, 2006a], it was enhanced by a xpoint operator and typed channels. Names of quantum variables are stored together with their state in a context. The state of quantum variables used in any process in the system is represented by a density matrix. 24

CHAPTER 2. CURRENT STATE OF THE ART The context is also used for storing a mapping between classical variables names and their values. The context is formed in a style of a cactus stack what allows one to declare variables shared among several processes. Processes can communicate over named gates. The gates that processes can use for communication are static, ie. they are given before a process run. Hence, they need not be allocated before their usage. This means that any process has access to any channel until the channels are hidden by a special handling construct. The algebra denes a bisimilarity relation on processes (which is an equivalence relation on processes) in the sense of probabilistic branching bisimulation [Lalire, 2006b]. This type of bisimilarity is weaker than strong bisimilarity because it abstracts from silent transitions. This algebra is further discussed in Section 10.4.

2.4

Summary

All the programming languages presented in this chapter can be used for description of quantum algorithms. Some of the languages cannot describe combination of quantum and classical computations (van Tonders q -calculus). But a practically-usable programming language should support such a combination to be expressed. The reason is that in practice, users pass classical input to a program and require classical output to be returned. Therefore, a classical part of the program should process the input and invoke quantum computation. After the quantum computation is nished, it should present its output to the user in a classical form. Functional languages regard programs as mathematical expressions. Functional programs are manipulated according to mathematical rules. Two of the described functional languages support quantum data processing, but the ow control is classical Selinger and Valirons -calculus and Selingers QPL. Both languages require a quantum system to be referred uniquely, ie. at most one variable should refer to one quantum system. This is a very strong constraint. In real programming, it is quite useful when two or more variables can refer to one quantum system. This constraint is overcome in the QML language by Altenkirch and Grattage and nQML by Lampis, Ginis and Papaspyrou. In their languages, it is allowed to have two or more variables referring to a single quantum system. Contrary to functional languages, imperative languages rather reect underlying machine architecture. Even though functional languages have better formal basis, practical programmers prefer imperative programming languages to functional ones. The qGCL language can be used both as a specication language and a programming language. Its well-dened semantics and renement calculus make this program a good base for optimisation tasks. However, this language lacks recursion. QCL is quite a usable language. It allows programmer to encode nearly any algorithm, quantum or classical, in the language. It contains many usable features like scratch-space management. However, the semantics of the language is not fully dened. Therefore formal proving of program properties is impossible. This is also true for the Q language. QMC is an imperative language that supports checking of EQPL formulas over stabilizer states. Its speed makes it a good choice for verication of properties of quantum states even in complex programs if these states and operations over them can be described in terms of stabilizer formalism. A programming language LanQ developed in the dissertation is imperative and has welldened operational semantics. The semantics is an improvement over two of the mentioned 25

2.4. SUMMARY imperative languages (QCL, Q-language). Moreover, it exhibits several features of process algebras, being able to run several processes in parallel and supporting interprocess communication. Its simulator has been implemented and is shortly described in Appendix B

26

Part II

LanQ programming language

27

Chapter 3

Introduction
In this part of the thesis, we formally dene the language LanQ and prove its properties unique resource ownership and type soundness. The presentation of the language is based on rk, the articles [Mlna 2006a,b, 2007]. The part is structured as follows: In this chapter, we show an example of a LanQ program, The syntax is presented in Chapter 4, The typing system is introduced in Chapter 5, The concepts used in the language semantics denition are formalized in Chapter 6, The language operational semantics is dened in Chapter 7, The unique resource ownership property is proved in Chapter 8, Type soundness of LanQ is proved in Chapter 9, We provide a comparison of LanQ to other existing programming languages and process algebras in Chapter 10.

3.1

Informal introduction

We begin our description of LanQ by an example of implementation of a well-known multiparty quantum protocol a teleportation of an unknown quantum state [Bennett et al., 1993]. First, we declare a method prep0 that prepares a new qubit initialized in the |0 state and returns it as its result. This method is shown in Figure 3.1. It returns a qubit what is seen from the type qbit written in front of the method name. On the rst line of the method body, a qubit variable q is declared. We then assign a newly allocated qubit initialized in a maximally mixed state to q. The qubit is then measured in the standard basis. If the measurement result is 1, we know that the qubit q collapsed to the state |1 , so we apply the Pauli operator x onto it to turn it to the |0 state. Otherwise, it collapsed into the required |0 state. Therefore q in both cases denotes a qubit in |0 state. The qubit is returned to the caller by the return statement. 29

3.1. INFORMAL INTRODUCTION


qbit prep0() { qbit q; q = new qbit(); if (measure (StdBasis,q) == 1) { Sigma x(q); } return q; }

Figure 3.1: Method prep0 for a preparation of a qubit in the |0 state. As a next step towards the implementation of teleportation protocol, we need to declare a method that creates an EPR pair. In LanQ, this method named createEPR is declared as shown in Figure 3.2. The method returns two qubits as seen from the type qbit qbit in front of the method name. In the rst part of its body, we declare two qubit variables q1 and q2 , and a variable qEP R which denotes a system composed of the qubits denoted by q1 and q2 . On the next two lines, we prepare two new qubits, both of them in the |0 state. Then we perform a Hadamard transformation on q1 and CNOT operation on both of these qubits to prepare an EPR pair. Finally, we return the two qubits prepared in EPR state to the caller.
qbit qbit createEPR() { qbit q1 ,q2 ; qEP R aliasfor [q1 ,q2 ]; q1 = prep0(); q2 = prep0(); H(q1 ); CNot(q1 , q2 ); return qEP R ; }

Figure 3.2: Method createEPR that creates a new EPR pair. Now we have declared all the necessary auxiliary methods. We can therefore proceed to the implementation of the teleportation protocol. This program is shown in Figure 3.3. We now briey describe the program. Three methods, main, angela and bert, are dened. Method main is the method from which the program is run. It can be only invoked with no parameters. It does not return any value what can be seen from the type void written in front of method name. Method angela has to be invoked with two parameters a channel end of a channel that can be used for transmission of integer values, and one qubit. It also returns no value. Method bert also takes one end of a channel capable of transmitting integers and another qubit as parameters. This method returns a value of type int to its caller. The program makes use of two other methods, doSomething and doSomethingElse. Their declaration is not included in the example because they are only auxiliary and their purpose is dependent on the actual task of the program. Both of these methods take a qubit as an argument and do not return any value. Next, we describe the behaviour of the declared methods. The main method declares 30

CHAPTER 3. INTRODUCTION
void main() { qbit A ,B ; EP R aliasfor [A ,B ]; channel[int] c withends [c0 ,c1 ]; EP R = createEPR(); c = new channel[int](); fork bert(c1 , B ); angela(c0 , A ); } void angela(channelEnd[int] ce0 , qbit ats) { int r; qbit ; } = new qbit(); doSomething(); r = measure (BellBasis, , ats); send (ce0 , r); } int bert(channelEnd[int] ce1 , qbit stto) { int i; i = recv (ce1 ); if (i == 1) { Sigma x(stto); } else if (i == 2) { Sigma z(stto); } else if (i == 3) { Sigma x(stto); Sigma z(stto); } doSomethingElse(stto); return 0;

Figure 3.3: Teleportation implemented in LanQ. variables used in the method body in its rst three lines. The type of variables A , B is qbit. Variable EP R is declared to be an alias for a system composed of the qubits denoted by A and B . Channel c capable of sending integer numbers is declared on the next line. Its ends are named c0 and c1 . On the following lines, method main invokes a method createEPR which creates an EPRpair and assigns the reference to the created pair to the variable EP R . After that, a new channel is allocated and assigned to the variable c. This assignment also initializes variables c0 and c1 which are used to access individual ends of the channel. The next command causes the running process to split into two. One of the processes continues its run in the original process and invokes the method angela. The second process is started from the method bert. The angela method receives one channel end named ce0 and one qubit named ats1 as arguments. After declaring variables r and , it assigns a newly allocated qubit to and passes it to a method doSomething. Then it measures the qubits and ats in the Bell basis, assigns the result of the measurement to the variable r, and sends it over the channel end ce0 . The bert method receives one channel end named ce1 and one qubit stto2 as arguments. After declaring variable i, it receives an integer value from the channel end ce1 and assigns it to the variable i. Depending on the received value it applies none, one or both Pauli operators x and z onto the qubit stto. Then it invokes a method doSomethingElse to which it passes the variable stto as an argument. Finally, it returns zero as its result.

1 2

The name ats is an abbreviation of auxiliary teleportation state. The name stto is an abbreviation of state to teleport on.

31

3.1. INFORMAL INTRODUCTION

32

Chapter 4

Syntax
In this chapter, we dene concrete syntax of LanQ programs, internal syntax used for representation of a parsed program, and syntax of congurations that are used for denition of operational semantics of the language.

4.1

Concrete syntax

In this section, we introduce concrete syntax of LanQ programs. This syntax is used to write programs like the one in Figure 3.3 by a programmer. The syntax is shown in Figure 4.1. Reserved words of the language are written in bold and the identier names are in capitals. Grammar is given in nondeterministic extended Backus-Naur form (EBNF). The root of the grammar is the nonterminal program. For the sake of clarity, the concrete grammar nonterminals names are long and descriptive to indicate their meaning in semantics. We describe meaning of the most important nonterminals here: program words derived from this nonterminal represent LanQ programs, code words derived from this nonterminal represent statements, pExpr words derived from this nonterminal represent promotable expressions, ie. those expressions that can act as statements when they are suxed with a semicolon, methodCall words derived from this nonterminal represent method calls, assignment words derived from this nonterminal represent assignments to variables, measurement words derived from this nonterminal represent quantum measurements, expr words derived from this nonterminal represent expressions, indivExpr words derived from this nonterminal represent ground expressions, ie. expressions that do not contain any operators, op words derived from this nonterminal represent mathematical operators, method words derived from this nonterminal represent method declarations, 33

4.1. CONCRETE SYNTAX

Code program code pExpr

::= method+ ::= ; | pExpr; | f ork | send | return | block | if | while ::= assignment | methodCall | recv | measurement | new nonDupT ype() methodCall ::= methodName ( (methodP arams)? ) methodP arams ::= expr (, expr) assignment ::= variableName = expr measurement ::= measure ( basisName (, variableName) + ) expr ::= indivExpr (op expr)? indivExpr ::= const | variableName | ( expr ) | pExpr op ::= + | | | . . . ::= ::= ::= ::= ::= ::= ::= methodHeader block { (bf s)? } varDeclaration (bf s)? | code (bf s)? type methodName ( methodDeclP aramList? ) methodDeclP aram(, methodDeclP aram) nonV oidT ype paramName nonV oidT ype variableName(, variableName) ; | channelT ype variableName withends [ variableName , variableName ] ; | variableName aliasfor [ variableName (, variableName) ] ;

Block structure method block bf s methodHeader methodDeclP aramList methodDeclP aram varDeclaration

Program ow f ork ::= fork methodCall ; return ::= return (expr)? ; Conditionals and loops if ::= if ( expr ) code (else code)? while ::= while ( expr ) code Communication recv ::= recv ( expr ) send ::= send ( expr , expr ) ; Types type nonV oidT ype dupT ype nonDupT ype channelT ype qT ype qBasicT ype ::= ::= ::= ::= ::= ::= ::= void | nonV oidT ype dupT ype | nonDupT ype int | bool | . . . channelEnd[nonV oidT ype] | channelT ype | qT ype channel[nonV oidT ype] qBasicT ype(qT ype)? qbit | qtrit | . . . Figure 4.1: Concrete syntax.

34

CHAPTER 4. SYNTAX block words derived from this nonterminal represent blocks of code that limit scope of variables, bf s words derived from this nonterminal represent block-forming statements, ie. those statements that can be used inside blocks, and varDeclaration words derived from this nonterminal represent variable declarations. The other nonterminals are auxiliary and their meaning should be obvious from their names. Denition 4.1.1. Let m be a method declaration. We call the part of m which was derived from the nonterminal methodHeader a method header, and the part of m which was derived from the nonterminal block a method body. The concepts dened in Denition 4.1.1 are illustrated in the example shown in Figure 4.2 where a method named mN ame is declared. The parts of the method declaration are annotated on the right side.

T mN ame(T1 a1 , . . . ,Tn an ) { ... statements ... }

method header method body

Figure 4.2: Declaration of a method named mN ame.

4.2

Internal syntax

In this section, we dene the internal syntax of LanQ. Using the concrete syntax, a LanQ program is written as a set of method declarations. However, this notation cannot be used for direct execution of the program. To dene the language semantics, we must rst convert notation of methods of the program to an internal representation dened by the internal syntax. This syntax is similar to the concrete one but does not contain method declaration parts of the concrete syntax and is abbreviated. The internal syntax is dened in Figure 4.3. We dene the following basic syntactic entities there: numbers (N ), lists (L), recursive lists (RL), references (R), constants (C), identiers (I), types (T ), and internal values (v). Promotable expressions (P E) are expressions that can act as statements when postxed by semicolon. Expressions (E) can evaluate to an internal value. The syntactic classes of variable declarations (V D) and statements (S) can be used to build a block. Therefore they are together called block-forming elementary statements (Be). A block-forming statement (B) is built from zero or more such block-forming elementary statements. The root of the grammar is the nonterminal B. Remark 4.2.1. For the sake of clarity, we use the following notation in the rule body. We de note by S an abbreviation of BNF rule body (S), and by E an abbreviation of (E (, E))?. 35

4.3. CONFIGURATION SYNTAX N L RL R C I T v PE E VD S Be B ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= 0 | 1 | ... [] | [N ] L | [RL] none | (Classical,N ) | (Quantum,RL) | (Channel,N ) | (ChannelEnd0 ,N ) | (ChannelEnd1 ,N ) | (GQuantum,L) | (GChannel,N ) R | true | false | | . . . x | y | z | ... | + | | ... void | int | qbit | channel[T ] | channelEnd[T ] | T T | . . . R, C T

new T () | I = E | I(E) | measure(E) | recv(E) I | v | (E) | P E T I; | channel[T ] I withends[I,I]; | I aliasfor [I]; ; | P E; | {B} | if (E) S else S | while (E) S | return; | return E; | fork I(E); | send(E,E); ::= V D | S ::= Be Figure 4.3: Internal syntax.

The semantics uses internal representation of the method bodies. Fortunately, the bodies derived using the concrete syntax and those derived by the internal syntax rules dier only in the following: In internal representation, all if statements have else part, ie. a statement if (E) P is rewritten to if (E) P else ;, In internal representation, all constants C are represented by internal values none, C where T is the type of the constant C,
T

In internal representation, all operators are written in the prex notation and seen as method calls, ie. E F is converted to (E,F ). There is obviously an algorithm which rewrites any method body derived using the concrete syntax to the internal representation. The conversion can be performed right in the program parsing phase. An example of a block written using the concrete syntax and its internal representation is shown in Figure 4.4.

4.3

Conguration syntax

Last, we must dene the syntax of congurations that allows us to specify language semantics in terms of their rewritings. The internal syntax is a part of the conguration syntax. The conguration syntax species formal notation of congurations used for the denition of the operational semantics of LanQ. It is shown in Figure 4.5. The root of the conguration syntax is the nonterminal M Conf . Meaning of individual conguration elements is described later in Section 7.3, examples of congurations can be found in Appendix A. 36

CHAPTER 4. SYNTAX { int r; qbit ; = doSomething(); r = measure (BellBasis, , ats); send (c0 , r); if (r == 0) { measure (StdBasis, ); } }
(a) (b)

{ int r; qbit ; = doSomething(); r = measure (BellBasis, , ats); send (c0 , r); if (== (r,0)) { measure (StdBasis, ); } else ; }

Figure 4.4: Block derived using the concrete syntax (a) and the same block converted to the internal syntax (b). The conguration contains terms being evaluated. The notation of the terms is based on the internal syntax. However, we must also support the following case: Whenever a statement or an expression contains a subexpression then this subexpression must be evaluated rst. After this subexpression evaluation is nished, the result is substituted in place of the subexpression. For this reason, we introduce a concept of a hole () which stands for the awaited result of the subexpression evaluation in the original statement or expression. We call a term not containing a hole a closed term. Terms containing a hole are dened by nonterminals Sc and Ec and represent partially evaluated statements and expressions, respectively, whose subexpression is being evaluated. We also dene syntactic entities for runtime errors (RT Err) and term stack elements (StkEl). Ec Sc RT Err StkEl LM S VP LS P GS Conf M Conf ::= I = | I(v, ,E) | measure(v, ,E) | recv( ) ::= ; | if ( ) S else S | fork I(v, ,E); | send( ,E); | return ; ::= UV | OQV | ISQV ::= B | E | Ec | Sc | RT Err | L | M ::= local memory state as described in Section 7.3 ::= variable properties as described in Section 7.3 ::= (LM S,V P ,StkEl) ::= LS | LS P ::= ((DM ,L),[I|== I]) ::= [GS | P ] ::= p Conf | p Conf |= where DM is a density matrix M Conf where p is a real number, 0 p 1

Figure 4.5: Conguration syntax.

37

4.3. CONFIGURATION SYNTAX

38

Chapter 5

Typing
5.1 Typing rules

LanQ is a typed language. This feature enables us to detect errors arising from incorrect usage of methods, variables and constants at compile time. First, we dene the ground types used in LanQ: void a type with only one value: ,1 int a type of integers, bool a type of truth values true and false, qdit a type of references to d-dimensional quantum systems. These types are called quantum types. Types which are often used are given special names: one can write qbit instead of writing q2it, and in place of q3it one can use qtrit, Q1 Q2 if Q1 , Q2 are quantum types referring to d1 , d2 -dimensional systems, respectively, then Q1 Q2 is a type of references to d1 d2 -dimensional quantum systems. These types are also called quantum types, channel[T] if T is a ground type, it is a type of references to a channel capable of transmitting values of type T. These types are called channel types, channelEnd[T] if T is a ground type, it is a type of references to a channel end of a channel capable of transmitting values of type T. The ground type system can be indeed extended when needed. Additionally, we use several internal types which cannot be used by the programmer: Ref a type of references, dened later in Section 7.1, RTErr a type of runtime errors, and MeasurementBasis a type of measurement bases.
This type is a unit type. In several other languages, it is called dierently, eg. unit in OCaml or () in Haskell. We have decided to use the name void as usual in C-based languages because LanQ follows C language also in many other aspects.
1

39

5.1. TYPING RULES Let S1 , ..., Sn , S be ground types for n 0. Then a method type T is dened to be the type S1 , S2 , ..., Sn S. We call the types S1 , . . . , Sn argument types and the type S a return type. Denition 5.1.1. We dene a set T ypes of types of classical values. We denote by val(T) a set of values of type T and dene a set V alues as a set of values of all types: V alues =
TT ypes

val(T).

After parsing a program, the method declarations are stored in a triplet (MT , MH , MB ) of partial functions. We call this triplet a method typing context where: MT (m) which returns the method type for a method m (the method type is straightforwardly determined from the method header), MH (m) returns the method header for a method m, and MB (m) which returns the method body represented in the internal syntax for a method m. We provide typechecking rules in Figures 5.1 (rules for typechecking programs), 5.2 (rules for typechecking variable declarations), 5.3 (rules for typechecking statements), and 5.4 (rules for typechecking expressions). All the typechecking rules use a typing context what is a pair (M ; ) consisting of: M is a method typing context, is a variable typing context a partial mapping : N ames T ypes that assigns a type to a variable name. We write a variable typing context as = a1 : T1 , . . . , an : Tn meaning that the type Ti is assigned to the variable ai . The extension of a context by a variable b of type Tb is written as , b : Tb . It is undened if b dom and (b) = Tb . Otherwise it is dened as: (, b : Tb )(x) = Tb if x = b, (x) otherwise.

The rule T-Program is used to check typing of a program P whose internal representation is stored in a method typing context (MT , MH , MB ). We call this program well-typed if the premise of the rule T-Program is satised for all methods in this method typing context. This check is passed i all the declared methods satisfy the premises of the typing rule TMethod. Typechecking of a method in the rule T-Method is a little more complicated. The reason is that we require any method m whose return type is not void to return a value of appropriate type in all possible control paths which the evaluation of this method can take. This can be checked at compile time. We split this requirement into two: (1) during evaluation, the method m body always reaches a return statement (or invokes a runtime error or diverges or gets stuck due to incorrect send/recv pairing), and 40

CHAPTER 5. TYPING m dom(MT ) : (MT , MH , MB ) T MH (m) : MT (m) (MT , MH , MB ) T = void RetOk(MB (m)), (MT , MH , MB ); a1 : T1 , . . . , an : Tn , @retV al : T T MB (m) : void (MT , MH , MB ) T T m(T1 a1 , . . . ,Tn an ) : T1 , . . . , Tn T Figure 5.1: Typing rules for program and method declaration. T-VarDecl T-VarDeclChE M ; , I0 : T, . . . , In : T T B : T M ; T T I0 , . . . ,In ;B : T where n 0
T

T-Program

T-Method

M ; , I0 : channel[T ], I1 : channelEnd[T ], I2 : channelEnd[T ] M ; T channel[T ] I0 withends [I1 ,I2 ];B : T

B:T

T-VarDeclAlF

i {1, . . . , n} : M ; T Ii : Ti where Ti is a quantum type, n M ; , I0 : i=1 Ti T B :T M ; T I0 aliasfor [I1 , . . . ,In ];B : T where n 1 Figure 5.2: Typing rules for variable declarations.

T-Skip T-PromoExpr T-Block T-BlockHead M;


T

M;

; : void

M; T PE : T M ; T P E; : void M; M;
T T

B : void {B} : void

Be0 : void M ; T Be1 . . . Ben : void M ; T Be0 Be1 . . . Ben : void where Be0 = V D and n 1 M ; T S0 : void M ; T if (E) S0 else S1 : void
T

T-If T-While T-ReturnVoid T-ReturnExpr T-Fork T-Send

M;

E : bool M;

S1 : void

M ; T E : bool M ; T S : void M ; T while (E) S : void M ; , @retV al : void


T

return; : void

M ; , @retV al : T T E : T M ; T return E; : void M;


T

I(E) : T I is a classical method

M ; T fork I(E); : void M ; T E0 : channelEnd[T] M ; T E1 : T M ; T send(E0 , E1 ); : void Figure 5.3: Typing rules for statements. 41

5.1. TYPING RULES T-Var T-Value T-Bracket T-Alloc T-Assign T-MethodCall M ; , I : T M;


T

I:T
T

R, C
T T

:T

M; M;

E:T (E) : T

T is either a quantum type or a channel type M ; T new T() : T M ; , I : T T E : T M; T I = E : T MT (I) = S0 , . . . , Sn T M ; T E0 : S0 . . . M ; T En : Sn M ; T I(E0 , . . . ,En ) : T where M = (MT , MH , MB ) M; T E0 : MeasurementBasis, i {1, . . . , n} : M ; T Ei : Ti where Ti is a quantum type M ; T measure(E0 ,E1 , . . . ,En ) : int M ; T E : channelEnd[T] M ; T recv(E) : T Figure 5.4: Typing rules for expressions.

T-Measurement T-Recv

(2) any value returned by a return statement during evaluation of the method m body is of appropriate type. This is checked by typing rules T-ReturnVoid and T-ReturnExpr in cooperation with T-Method using a pseudovariable @retV al. The type of this pseudovariable is set in the rule T-Method to the return type of the typechecked method. The rules for typechecking return statement check that this pseudovariable type is the same as the type of the expression specifying the return value. For a formal denition of the condition (1), we dene a predicate RetOk. Denition 5.1.2. Let B be a block-forming statement. We dene a predicate RetOk as:

true RetOk(St ) RetOk(Se ) RetOk(B) = RetOk(Bei ) Bei RetOk(B ) false

if B = return E; if B = if (E) St else Se if B = Be0 Be1 . . . Ben if B = { B } otherwise

Later we prove a lemma stating that if the predicate RetOk is satised on B then any control path of evaluation of B reaches a return; or return E; statement, or a runtime error, or diverges, or gets stuck due to incorrect send/recv pairing (see Lemma 9.3.10). In particular, this result holds for method bodies in a well-typed program what is used in the proof of language type soundness in Lemma 9.3.16. 42

CHAPTER 5. TYPING Note that the predicate RetOk is only approximate. For example, it does not handle the case B = while (E) S because evaluation of the condition E is in general undecidable at compile-time. Hence even for the straightforwardly always-terminating case B = while (true) return 1;, RetOk(B) is not satised. Denition 5.1.3. We call a method m well-typed if the premises of rule T-Method are satised for this method. Remark 5.1.4. Note that if a method m is well-typed and its return type is not void then its body contains only return E; statements, ie. no return; statements. The rest of the typing rules is dened as usual: The rules for typechecking variable declarations in Figure 5.2 check that the subsequent block-forming statement can be typechecked with the variable context extended with the newly declared variables. We formally regard all statements to be of type void what can be seen in the rules for typechecking statements in Figure 5.3. These rules are quite usual up to the rule T-Fork. This rule requires that the method, which should be a new process run from, is classical. This is indeed a natural requirement as running a new process, which is by its nature a classical object, from a quantum operator would be a nonsense. The rules for typechecking expressions shown in Figure 5.4 are designed as usual.

43

5.1. TYPING RULES

44

Chapter 6

Basic concepts
Before we continue with formal denition of the semantics, we must dene several useful functions and structures. First we dene notation used in the rest of the thesis.

6.1

Notation

Notation 6.1.1. Let S be a set, S. Then S = S {}. We denote a set of natural / numbers with zero N {0} by N0 . Denition 6.1.2. Let S be a set. An S-list s = [s1 , . . . , sn ] is a list where n N0 and s1 , . . . , sn S. Set of all nite S-lists {s | s is a nite S-list} is denoted by S[] . Denition 6.1.3. Let m, n N0 . Let L = [l1 , . . . , ln ], K = [k1 , . . . , km ] be lists. Then |L| is a length of a list L, |L| = n. Concatenation of lists L and K is dened as L K = [l1 , . . . , ln , k1 , . . . , km ]. Set of list L elements is dened as set(L) = {l1 , . . . , ln }.

6.2

Reference-related concepts

We use the following specially formed lists for storing references to quantum systems. Denition 6.2.1. Let S be a set. We dene a recursive S-list recursively as: Any S-list [s1 , . . . , sk ] is a recursive S-list, A list [e1 , . . . , em ] is a recursive S-list for any m N0 if e1 , . . . , em are recursive S-lists. For example, [[[1, 2, 3], [2, 3]], [1]] and [] are recursive N-lists. Recursive S-lists are used for the representation of quantum system references in the following way: A reference to a quantum system, be it compound or not, is specied by a recursive N-list. Quantum systems are stored in indexed registers in the quantum memory, one quantum system per one register. The (unique) index is assigned to a quantum system when it is allocated. The reference to the system with index n is a recursive N-list [n]. Let us have two quantum systems and whose indices are 1 and 2, respectively. The references to these quantum systems are r = [1] and r = [2], respectively. A reference to a compound system consisting of the two quantum systems and is then a recursive N-list r = [r , r ] = [[1], [2]]. Note that the structure of , ie. that it consists of two systems, corresponds to the structure of the reference r it is built up from two elements. 45

6.3. VARIABLE-RELATED CONCEPTS Notation 6.2.2. The set of all nite recursive S-lists {s | s is a nite recursive S-list} is denoted by S[ ] . Recursive S-lists allow us to nicely capture quantum system structure in the reference. However, when working with referred quantum systems, eg. applying some unitary operator, we do not want to bother with the structure we only need a list of indices of the aected quantum systems. To get such a linearized list out of the structured one, we dene the following function: Denition 6.2.3. For a recursive S-list s S[ ] , we dene a function linearize : S[ which converts a recursive S-list into an S-list: linearize(s) = s if s S[] linearize([e1 , . . . , em ]) = linearize(e1 ) . . . linearize(em ) where e1 , . . . , em S[
def def

S[]

If a reference R contains a special element which denotes a reference to a nonexistent quantum system, we consider the reference R itself to refer to nonexistent quantum system. Hence linearization of such a reference should return : Denition 6.2.4. For a set S , we dene a function linearize : (S )[ linearize (s) =
def

(S )[] {} as:

linearize(s) = [s1 , . . . , sn ]

if si = for all 1 i n otherwise


]

Denition 6.2.5. Let S be a set. We dene a function set[

: S[
def

S for obtaining the

set of recursive list items regardless of the structure as set[ ] (l) = set(linearize(l)). We also dene function | |[ ] : S[ ] N for getting the length of a recursive list regardless of the structure as |l|[
def

= | linearize(l)|.

6.3

Variable-related concepts

We use partial functions to capture variable properties, eg. mapping a variable name to a place in memory where the variable value is stored, or a mapping to the variable type. We dene several useful functions for handling these partial functions describing variables. Adding a new variable to a set of known variables is represented by extending the domain of the appropriate partial function with the new variable name. We call this function an update. Sometimes we only want to update a variable property if the updated variable is already contained in the domain of the updated function, eg. change a memory reference referred by the variable. We call such an operation a replacement. In general, we dene these functions in the following way: Denition 6.3.1. Let f : X Y be a partial function. For x X, y Y , we dene replacement f [x y] : X Y and update f [x y]+ : X Y as: f [x y](z) = y f (z) if x = z and f (x) is dened, otherwise, 46

CHAPTER 6. BASIC CONCEPTS and f [x y]+ (z) = y f (z) if x = z, otherwise.

Note that the f [x y](x) is dened i f (x) is dened while f [x y]+ (x) is dened even if f (x) is not dened.1 We need to store dierent variable properties: variable type, names of channel ends corresponding to a given channel etc. Each property is represented by a separate partial mapping. Hence variable properties are described by a tuple of such partial functions. Denition 6.3.2. A partial function tuple is a tuple f = (f0 , . . . , fn ) where f0 , . . . , fn are partial functions. We will need to capture variable scope during a method evaluation. For this reason, we dene concepts of list of partial function tuples and list of lists of partial function tuples. Their usage is in more detail explained in Section 7.2. We also extend update and replacement functions to lists of partial function tuples and lists of lists of partial function tuples. Denition 6.3.3. We dene list of partial function tuples recursively as: is an (empty) list of partial function tuples,

[K L f ] is a list of partial function tuples if K is a list of partial function tuples and f is a partial function tuple. The symbol L serves as an element separator only.2 Denition 6.3.4. For a list of partial function tuples K, we dene a replacement K[x y]i and an update K[x y]+,i of outermost x in an i-th partial function of a list of partial function tuples K as:

[K1 L (f0 , . . . , fn )][x y]i [x y]i [K1 L (f0 , . . . , fn )][x y]+,i [x y]+,i

def

[K1 L (f0 , . . . , fi [x y], . . . , fn )] [K1 [x y]i L (f0 , . . . , fn )]

if fi (x) is dened otherwise

def

def def

= [K1 L (f0 , . . . , fi [x y]+ , . . . , fn )]

Denition 6.3.5. We dene a list of lists of partial function tuples recursively as: is an (empty) list of lists of partial function tuples,

[L1 G K] is a list of lists of partial function tuples if L1 is a list of lists of partial function tuples and K is a list of partial function tuples. The symbol G serves as an element separator only.3
The + sign in function index means add the mapping from x to y even if it was not dened yet. L in L stands for local. 3 G in G stands for global.
2 1

47

6.3. VARIABLE-RELATED CONCEPTS Denition 6.3.6. For a list of lists of partial function tuples L, a replacement L[x y]i and an update L[x y]+,i of mapping of x in the outermost list of partial function tuples is dened as:

[L1 G K][x y]i [x y]i [L1 G K][x y]+,i [x y]+,i

def def

= [L1 G K[x y]i ] =

def def

= [L1 G K[x y]+,i ] =

Last, we dene a coalesce4 function of two partial functions f, g : A B. Coalesce g f is a partial function which for (g f )(x) results into f (x) if f (x) is dened, otherwise to g(x): Denition 6.3.7. Let f, g : A gf :A B as: B be partial functions. We dene a coalesce of g and f f (x) g(x) if f (x) is dened otherwise.

(g f )(x) =

Denition 6.3.8. We dene N ames to be a set of all identier names.

The name coalesce is given because this function is similar to the COALESCE function dened in SQL-92 standard.

48

Chapter 7

Operational semantics
In this chapter, we dene the operational semantics of the LanQ programming language.

7.1

Memory model

In this subsection, we describe the memory model used in LanQ implementation. Our abstract machine uses a memory to store values. As we work both with duplicable and nonduplicable data, we have two types of memory: local and system. All processes manage their own memory a local process memory where duplicable values are stored. System manages the system memory used for storing nonduplicable resources. Processes cannot access the system memory directly, they work with resources by means of references to the system memory. This is transparent to the programmer. The memory model is depicted in Figure 7.1.

Figure 7.1: Memory model of LanQ. Several processes are currently running, their memories are shown as red boxes. Variable names are shown in a circle, duplicable variables are shown in green, nonduplicable ones in red. The variables v (integer), and (quantum systems), and c (channel) belonging to one process refer to structured references stored in a process local memory. The structured references are shown as yellow containers. They refer to values shown as the labels in the containers a value 3 in the case of variable v container, and references to the system memory in the rest of the cases. 49

7.1. MEMORY MODEL This memory model consists of four layers. From bottom, the rst layer is the system memory layer where the quantum systems and channels are physically stored. The next one is a value layer which stores classical values and references to system memory. One layer up is a structured reference layer which stores references to the value layer. The structured reference layer is particularly used for handling compound quantum systems. To topmost layer is the variable layer which contains variable names. The connection between neighbouring layers is done via three types of partial functions described later in Section 7.3. This memory model allows us to assign a reference to the same nonduplicable resource to many dierent variables. It also allows us to simply dene communication of resources the mapping from a local reference (stored in the structured reference layer) to a global reference to system memory (stored in the value layer) is invalidated in the sending process and created at the receiver. It is however also a possible source of runtime errors. Consider a situation when a process sends away a qubit. Then the appropriate reference to the system memory is removed but the mappings from variables to the local process memory are preserved. If a process then tries to use such a variable, a runtime error signalling uninitialized variable usage occurs.1 A memory reference species a position of a value in the memory. We distinguish two basic types of references: Local references specify places in a local process memory where variable values are stored. The references assigned to variables during evaluation are always local. A special local reference none refers to no place in the memory. We have four kinds of local references: References to local classical value memory: RefCl = {none} ({Classical} N ), References to local quantum system reference memory: RefQ = {none} ({Quantum} (N )[ ] ), References to local channel reference memory: RefCh = {none}({Channel}N), References to local channel end reference memory: RefChE = {none} ({ChannelEnd0 , ChannelEnd1 } N). The set of local references is dened as: RefL = RefCl RefQ RefCh RefChE . Global references refer to resources stored in system memory. References to system channel memory: RefGCh = {} ({GChannel} N ), References to system quantum memory: RefGQ = {} ({GQuantum} N[] ).
Note that the same behaviour would be exhibited if we invalidated the references from variable layer to the structured reference layer. In that case, we would have to deinitialize all the variables referring to the resource. However, an invalidated variable could be used later in the program what would again lead to a runtime error. We decided to unmap the references to the system memory layer because this operation is faster in general the number of mappings from variable layer to structured reference layer is in general greater than the number of mappings from the value layer to the structured reference layer.
1

50

CHAPTER 7. OPERATIONAL SEMANTICS The set of global references is dened as: RefG = RefGCh RefGQ . A set of all references is dened as: Ref = RefG RefL , and a set of references to nonduplicable values is denoted by: Refnd = RefQ RefCh RefChE . Denition 7.1.1. A memory reference is an element from the set Ref . We dene Ref to be the type of memory references. Remark 7.1.2. Note that a memory reference is a classical value, therefore Ref T ypes.

7.2

Variable properties storage

In this section, we informally introduce a structure used for handling variable properties. Variable properties is a structure where properties of variables neccessary for correct handling of the variables are stored while respecting their scope: The actually running method has access only to variables declared in this method, it cannot access any variable from the caller method. Moreover, the validity of a variable is limited to the block in which the variable is declared. The properties of a variable are formally described later in Section 7.3. They are represented by partial functions which, given a variable name, return: A reference to local process memory where the value of the variable is stored, Variable names representing individual ends of the channel (if the given variable represents a channel), List of variable names representing quantum systems which are subsystems of the compound quantum system (if the given variable represents a compound quantum system), A type of the given variable. Therefore we have a quadruple of partial functions that represent variable properties: f = (fvar , fch , fqa , ftype ). Indeed, this quadruple alone is not powerful enough to handle variable scope. Respecting a variable scope is achieved by using lists of partial function tuples and lists of such lists: A variable can be accessed only from within the block where it was declared. This is ensured by using a list of partial function tuples (separated by L ), where a new tuple is appended to the list when a block is started and removed when the block ends, Only variables from the currently running method are accessible to this method. This is ensured by using a list of lists of partial function tuples (separated by G ) where a new list of partial function tuples is appended when a method is invoked, and removed when the method nishes. 51

7.2. VARIABLE PROPERTIES STORAGE We show the manipulation with a variable properties structure on an example. Consider the following method a: int a(int c) { bool b; b = true; if (b) { int i; . . . } return 3 + c; }

1 2 3 4 5

6 7 8

We show the variable properties construction as the individual lines of the method are executed. As the formal notation of the variable properties is not well-readable, we also provide the reader with its graphical representation. The representation uses the following notation:
fvar f A variable properties tuple (fvar , fch , fqa , ftype ) is represented as: ch , fqa ftype

A list of variable properties [K1 L f ] is represented as:

f , K1
K . L1

A list of lists of variable properties [L1 G K] is represented as:

We assume that the original variable properties were vpG right before calling the method a. When the method a is called, a list of variable properties [ L ([c rc ], [], [], [c int, @retV al int])] is appended to vpG : [vpG G [ L ([c rc ], [], [], [c int, @retV al int])]] (see Figure 7.2(a)). In this appended list, method parameters values are passed to the called method; in our case, the method parameter c refers to the memory as set by the reference rc . On line 1, a new block is started, therefore a new empty variable properties tuple ([], [], [], []) (denoted by here) is appended: [vpG G [[ L ([c rc ], [], [], [c int, @retV al int])] L ]] (see Figure 7.2(b)). On the next line, a variable b is declared, hence the head element of the inner list is modied: [vpG G [[ L ([c rc ], [], [], [c int, @retV al int])] L ([b none], [], [], [b bool])]] 52

CHAPTER 7. OPERATIONAL SEMANTICS

c rc

c rc

b none b bool c rc

c int, @retV al int

c int, @retV al int

c int, @retV al int

vpG

vpG

vpG

(a) Before execution of line 1

(b) After execution of line 1

(c) After execution of line 2

b rb b rb

i none i int b rb

b bool c rc

b bool c rc

b bool c rc

c int, @retV al int

c int, @retV al int

c int, @retV al int

vpG

vpG

vpG

(d) After execution of line 3

(e) After execution of line 4

(f) After execution of line 5

b rb

b bool c rc

c int, @retV al int

vpG

vpG

(g) After execution of line 6

(h) After execution of line 7

Figure 7.2: Variable properties stack construction when invoking the method a. 53

7.3. CONFIGURATION (see Figure 7.2(c)). On line 3, b is assigned a value true which is stored in the memory in a place referred by a reference rb . This modies fvar element of the appropriate variable properties tuple: [vpG G [[ L ([c rc ], [], [], [c int, @retV al int])] L ([b rb ], [], [], [b bool])]] (see Figure 7.2(d)). On line 4, a new block is started, therefore again a new empty variable properties tuple is appended: [vpG G [[[ L ([c rc ], [], [], [c int, @retV al int])] L ([b rb ], [], [], [b bool])] L ]] (see Figure 7.2(e)). On line 5, a new integer variable i is declared what is reected in the head variable properties tuple of the inner list: [vpG G [[[ L ([c rc ], [], [], [c int, @retV al int])] L ([b rb ], [], [], [b bool])] L ([i none], [], [], [i int])]] (see Figure 7.2(f)). On line 6, the block ends, hence the appropriate variable properties tuple is discarded: [vpG G [[ L ([c rc ], [], [], [c int, @retV al int])] L ([b rb ], [], [], [b bool])]] (see Figure 7.2(g)). Finally on line 7, the method execution ends, hence all local variable properties tuples are discarded and the original variable properties structure is restored: vpG (see Figure 7.2(h)).

7.3

Conguration

In this subsection, we formally dene abstract machine conguration which is later used for the denition of LanQ operational semantics. A conguration of the abstract machine used for the denition of LanQ operational semantics is composed of two basic parts global and local. The global part of the conguration represents system memory a quantum state of the whole system and a relation between channels and their ends. The local part of the conguration stores information about individual processes the state of their local memory, variables, and terms to be evaluated. A conguration C describing n processes running in parallel is written as: C = [gs | ls1 lsn ]

where gs is the global part of the conguration and lsj represents the local process conguration of j-th process. The parallel composition is associative in LanQ, hence the pairwise bracketing of processes is not necessary. The components of the abstract machine conguration are formally dened as follows: Global part of the conguration which describes the state of a system memory layer is a pair (Q, C) where: 54

CHAPTER 7. OPERATIONAL SEMANTICS Q describes the state of quantum particles and their dimensions. In the present paper, we represent the quantum state of the system by a pair (, L) of a nite density matrix and a nite list L of natural numbers. The list L represents dimensions of individual quantum subsystems. The order of the list elements is given by the order of quantum system allocations, C represents the channel part of the conguration. Channels and their ends are stored as pairs (c0 , c1 ) written as c0 |== c1 where c0 and c1 represent individual ends of one channel. Local part of the conguration: it denes the state of one process, hence we call it a local process conguration. It is a triplet (lms, vp, ts) where: Local memory state lms is a quadruple of partial functions, lms = (lmsCl , lmsQ , lmsCh , lmsChE ) which stores the state of classical memory and references to nonduplicable resources available to the process: lmsCl : RefCl V alues is a partial function which returns a (classical) value stored at the given position in memory. The set of all such partial functions is denoted by LM SCl , lmsQ : RefQ RefGQ returns a global reference to quantum systems given by the local quantum reference. The set of all such partial functions is denoted by LM SQ , lmsCh : RefCh RefGCh returns a global reference to the channel given by the local channel reference. The set of all such partial functions is denoted by LM SCh , lmsChE : RefChE RefGCh returns a global reference to the channel corresponding to the given local channel end reference. The set of all such partial functions is denoted by LM SChE . The local memory state connects the structured reference layer to the value layer. To simplify the notation, we regard lms itself as a partial function. Note that RefGQ V alues and RefGCh V alues. Now we can dene lms = (lmsCl , lmsQ , lmsCh , lmsChE ) : RefL V alues as: lmsCl (r) if r RefCl , lmsQ (r) if r RefQ , lms(r) = lmsCh (r) if r RefCh , lmsChE (r) if r RefChE , if r = none. The set of all such quadruples lms is denoted by LM S. Variable properties vp represent various properties of variables while respecting variable scope. They are stored as a list of lists of partial function tuples f = (fvar , fch , fqa , ftype ) where: fvar : N ames RefL maps a variable name to a local reference. This partial mapping is used to connect the variable layer to the structured reference layer, 55 |=

7.4. VARIABLE PROPERTIES HANDLING FUNCTIONS fch : N ames N ames N ames maps a channel variable name to variable names representing ends of the channel, fqa : N ames N ames[] maps a variable name representing a quantum system to variable names that represent its subsystems, ftype : N ames T ypes maps a variable name to the variable type. We call the quadruple f a variable properties tuple. We dene V arP ropL to be a set of all nite lists of such partial function tuples f . These lists are built to reect the block structure of a method as described in Section 7.2. We dene V arP rop to be a set of all nite lists of lists of such partial function tuples f . These lists are built to reect the method calls as described in Section 7.2. We dene an empty variable properties tuple as a partial function tuple : = (fvar , fch , fqa , ftype ) where dom(fvar ) = dom(fch ) = dom(fqa ) = dom(ftype ) = . Term stack ts: stack of terms to be evaluated. For the sake of readability, we use a notation where individual stack items are underlined. An empty term stack is denoted by . A conguration can evolve to a probabilistic distribution over congurations, so called mixed conguration. A mixed conguration: {pi , [gsi | lsi,1 is written as:
q i=1 pi

lsi,n ]}q i=1


q

[gsi | lsi,1

lsi,n ]

where
i=1

pi = 1.

It represents congurations of q dierent computational branches, each of them running with probability pi . A conguration can be seen as a special case of a mixed conguration where q = 1 and p1 = 1.

7.4

Variable properties handling functions

In this subsection, we dene functions for retrieving information about variables using variable properties. The dened functions are designed so that they only work with variables accessible from the actually running method. We achieve this by inspecting the structure of the variable properties. If the variable properties are represented by a list of lists of partial function tuples L = [L1 G K] then we consider only its second element the list of partial function tuples K. We do not consider the variable properties from L1 as they are inaccessible to the current method (as explained in Section 7.2). We then walk through the obtained list of partial function tuples K = [K1 L f ]. We attempt to get the requested information about requested variable using appropriate partial function from the variable properties tuple. If the requested information about the variable cannot be obtained from the actual tuple f , we repeat this procedure with the list of partial function tuples K1 . This procedure is designed so that it respects block scope of variables (as in more detail explained in Section 7.2). 56

CHAPTER 7. OPERATIONAL SEMANTICS Denition 7.4.1. We dene a partial function varRef : N ames V arP rop RefL for getting a local reference from a variable name and variable properties as: varRef (x, [L1 G K]) = varRefL (x, K) where varRefL : N amesV arP ropL RefL is a partial function for getting a local reference from a variable name and a list of partial function tuples: varRefL (x, [K1 L (fvar , fch , fqa , ftype )]) =
def def

fvar (x) varRefL (x, K1 )

if fvar (x) is dened otherwise

Denition 7.4.2. We dene a partial function chanEnds : N ames V arP rop N ames N ames for getting variable names that represent individual ends of given channel from a name of the channel and variable properties: chanEnds(x, [L1 G K]) = chanEndsL (x, K) where chanEndsL : N ames V arP ropL N ames N ames is a partial function for getting variable names that represent individual ends of given channel from a name of the channel and a list of partial function tuples: chanEndsL (x, [K1 L (fvar , fch , fqa , ftype )]) =
def def

fch (x) chanEndsL (x, K1 )

if fch (x) is dened otherwise

Denition 7.4.3. We dene a partial function aliasSubsyst : N amesV arP rop N ames[] for getting a list of variable names that represent individual parts of a compound system from a name of the compound system and variable properties: aliasSubsyst(x, [L1 G K]) = aliasSubsystL (x, K) where aliasSubsystL : N ames V arP ropL N ames[] is a partial function for getting a list of variable names that represent individual parts of a compound system from a name of the compound system and a list of partial function tuples: aliasSubsystL (x, [K1 L (fvar , fch , fqa , ftype )]) =
def def

fqa (x) if fqa (x) is dened aliasSubsystL (x, K1 ) otherwise T ypes for

Denition 7.4.4. We dene a partial function typeOf : N ames V arP rop getting a variable type from a name of a variable and variable properties: typeOf (x, [L1 G K]) = typeOfL (x, K)
def

where typeOfL : N ames V arP ropL T ypes is a partial function for getting a type from a name of the variable and a list of partial function tuples: typeOfL (x, [K1 L (fvar , fch , fqa , ftype )]) =
def

ftype (x) typeOfL (x, K1 )

if ftype (x) is dened otherwise

57

7.5. LOCAL MEMORY HANDLING FUNCTIONS

7.5

Local memory handling functions

In this section, we dene functions for local memory state handling. LanQ allows the programmer to create multiple processes. These processes can communicate with each other, namely a process can send some resource, ie. a quantum system or a channel, to another process. In that case, the language must assure that the sent resource becomes unavailable to the sending process. For this reason we dene a function unmapnd 2 which invalidates a reference to some resource in given local memory state. By invalidation we mean setting the appropriate local reference to the sent resource to point to in the local memory state. This function can be split into three functions: unmapping a memory reference to a quantum system (this is done by the function unmapQ 3 ), unmapping a memory reference to a channel (unmapCh 4 ), and unmapping a memory reference to a channel end (unmapChE 5 ). The function unmapQ is designed to obey the following rule: When unmapping a reference to a quantum system then any memory reference which refers to any subsystem of is unmapped too. The function unmapCh is designed to obey the following rule: When unmapping a reference to a channel c then any memory reference to its ends is unmapped too. The reason is that when a process sends away a channel, it also loses control over both its ends. The function unmapChE is designed to obey the following rule: When unmapping a reference to a channel end c then we unmap any memory reference to the corresponding channel. The justication is that when a process sends away a part of a channel, it also loses control over the whole channel. Denition 7.5.1. We dene a function unmapnd : RefL LM S LM S for unmapping a reference to a nonduplicable value from the local memory: unmapQ (n, lms) if ref T ype = Quantum, unmap (n, lms) if ref T ype = Channel, def Ch unmapnd ((ref T ype, n), lms) = unmapChE (i, n, lms) if ref T ype = ChannelEndi , lms otherwise. where Function unmapQ : (N )[
]

LM S LM S is dened as:

unmapQ (n, (lmsCl , lmsQ , lmsCh , lmsChE )) = (lmsCl , lmsQ , lmsCh , lmsChE ). where lmsQ is dened as: lmsQ ((Quantum, l)) =
2 def

lmsQ ((Quantum, l))

if set[ ] (n) set[ ] (l) {}, otherwise,

The The 4 The 5 The

name name name name

unmapnd should be read as unmap (a reference to a) nonduplicable (value). unmapQ should be read as unmap (a reference to a) quantum (value). unmapCh should be read as unmap (a reference to a) channel (value). unmapChE should be read as unmap (a reference to a) channel end (value).

58

CHAPTER 7. OPERATIONAL SEMANTICS Function unmapCh : N LM S LM S is dened as: unmapCh (n, (lmsCl , lmsQ , lmsCh , lmsChE )) = (lmsCl , lmsQ , lmsCh , lmsChE ). where lmsCh = lmsCh [(Channel, n) ], def lmsChE = lmsChE [(ChannelEnd0 , n) , (ChannelEnd1 , n) ], Function unmapChE : {0, 1} N LM S LM S is dened as: unmapChE (i, n, (lmsCl , lmsQ , lmsCh , lmsChE )) = (lmsCl , lmsQ , lmsCh , lmsChE ). where lmsCh = lmsCh [(Channel, n) ], def lmsChE = lmsChE [(ChannelEndi , n) ]. We state a straightforward lemma that helps us later in proving unique quantum system ownership. Informally, we prove that if there was a reference pointing from a local process memory to a quantum system stored at index i in a system memory, then this quantum system is no longer referred from the local process memory after an appropriate application of the unmapnd function. Lemma 7.5.2. Let lms = (lmsCl , lmsQ , lmsCh , lmsChE ) LM S be a local memory state, m (N )[ ] , and lms = unmapnd ((Quantum, m), lms). Then for any j set[ ] (m), j = , and any (Quantum, p) dom(lmsQ ), if j set[ ] (p) then lms ((Quantum, p)) = . Proof. By denition, lms = unmapQ (m, lms). The lemma statement then immediately follows from the denition of unmapQ . We prove similar lemmata for channel and channel end references. Lemma 7.5.3. Let lms = (lmsCl , lmsQ , lmsCh , lmsChE ) LM S be a local memory state, n N, and lms = unmapnd ((Channel, n), lms). Then lms ((Channel, n)) = , lms ((ChannelEnd0 , n)) = , and lms ((ChannelEnd1 , n)) = . Proof. By denition, lms = unmapCh (n, lms). The lemma statement then immediately follows from the denition of unmapCh . Lemma 7.5.4. Let lms = (lmsCl , lmsQ , lmsCh , lmsChE ) LM S be a local memory state, n N, i {0, 1}, and lms = unmapnd ((ChannelEndi , n), lms). Then lms ((Channel, n)) = and lms ((ChannelEndi , n)) = . Proof. By denition, lms = unmapChE (n, lms). The lemma statement then immediately follows from the denition of unmapChE . We extend the function unmapnd so that we can also use any set of references as the rst argument. Denition 7.5.5. For any R = {r1 , . . . , rk } RefL we dene: unmapnd (R, lms) = unmapnd (r1 , unmapnd (r2 , . . . unmapnd (rk , lms) . . . )). 59
def def def

7.6. FUNCTIONS FOR HANDLING ALIASFOR CONSTRUCTS Next, we dene a function for updating a local memory state lms. We use the existing concept of partial function update and extend this concept to local memory states. The extended function updates the appropriate element of the quadruple according to memory reference type. Note that this function automatically adjusts the mapping of channel ends to appropriate channel when adding a mapping to a channel: Denition 7.5.6. Let lms = (lmsCl , lmsQ , lmsCh , lmsChE ) be a local memory state. For r RefL and v V alues, we dene local memory state update lms[r v]+ as: lms if r = none (lmsCl [r v]+ , lmsQ , lmsCh , lmsChE ) if r RefCl , (lmsCl , lmsQ [r v]+ , lmsCh , lmsChE ) if r RefQ , def lms[r v]+ = (lmsCl , lmsQ , lmsCh , lmsChE [r v]+ ) if r RefChE , (lmsCl , lmsQ , lmsCh [r v]+ , lmsChE [(ChannelEnd0 , n)]+ [(ChannelEnd1 , n)]+ ) if r = (Channel, n) RefCh .

7.6

Functions for handling aliasfor constructs

Quantum algorithms often use multipartite quantum systems. LanQ supports the denition of a compound quantum systems using aliasfor construct: If q0 , . . . , qn are quantum variables then the declaration: q aliasfor [q0 , . . . ,qn ]; declares a new quantum variable q which species a quantum system composed from subsystems referred by the variables q0 , . . . , qn . In this subsection, we dene functions needed to handle this construct. To simplify the description of the functions in the following text, we rst dene two concepts: We call a quantum variable which was declared using the aliasfor construct an aliased quantum variable. The quantum variables not declared using the aliasfor construct are called proper quantum variables. In the following text, we require that all quantum variables that any aliased quantum variable is composed of are proper quantum variables. This requirement is later imposed by the semantic rule OP-VarDeclAlF. Handling the aliasfor construct is a little complicated. Two cases must be handled when a reference to a quantum system is assigned to a variable q: (1) The variable q is a proper quantum variable. Hence it can be used in several aliased quantum variables. Then the variable q (1a) and all the aliased quantum variables which use this variable as their subsystem (1b) must be updated, (2) The variable q is an aliased quantum variable. Then all its subsystems must be appropriately modied. However, the subsystems can be also used in several other aliased quantum variables as subsystems. Then all those aliased quantum variables must be updated too. We dene several auxiliary functions which help us with handling the assignment to a quantum variable. These functions modify variable properties and a local memory state 60

CHAPTER 7. OPERATIONAL SEMANTICS elements of a local process conguration. Therefore all these auxiliary functions take the original variable properties vp and local memory state lms as arguments and yield the modied ones. Moreover, all these functions take the name name of the quantum variable being assigned and the assigned reference ref as additional arguments. The simplest case is the case (1a). For this case, we dene a function fassignQSystemDirect which performs the following operations: If the assigned reference ref = (Quantum, q) is invalid (this is checked by the condition linearize (q) = ), the reference ref is invalidated in the local process memory. Otherwise the reference ref is set to map from the local process memory to a global reference to the corresponding quantum systems in the system memory, The assigned quantum variable is mapped to the reference ref . Denition 7.6.1. We dene a function fassignQSystemDirect : LM SQ V arP rop N ames RefQ LM SQ V arP rop as: fassignQSystemDirect (lmsQ , vp, name, ref ) = (lmsQ,ret , vpret ) where lmsQ,ret = lmsQ [(Quantum, q) gq], vpret = vp[name ref ]var , given that ref = (Quantum, q), gq = (GQuantum, linearize (q))
def

if linearize (q) = , otherwise.

To update all the aliased quantum variables which use the assigned proper quantum variable as their subsystems (the case (1b)), we dene an auxiliary function fassignQSystemInAlias which updates one subsystem reference in the aliased quantum variable. This function takes one more argument the index index of the updated subsystem in the aliased quantum variable. It then proceeds as follows: It takes the original reference of the aliased quantum variable varRef (name, vp) and modies its index-th element to point to the newly assigned system (specied by the recursive N-list q). Individual elements of the recursive N-list specifying the new reference are denoted by vj , It unmaps the original reference from the local process memory, If any of the systems in the newly assigned reference is invalid (checked by the condition j : lmsQ ((Quantum, vj )) = ), the newly assigned reference is invalidated in the local process memory. Otherwise the reference ref is set to map from the local process memory to a global reference to the corresponding quantum systems in the system memory, The assigned quantum variable is mapped to the new reference (Quantum, [v1 , . . . , vk ]). Denition 7.6.2. We dene a function fassignQSystemInAlias : LM SQ V arP ropN ames RefQ N LM SQ V arP rop as: fassignQSystemInAlias (lmsQ , vp, name, ref, index) = (lmsQ,ret , vpret ) 61
def

7.6. FUNCTIONS FOR HANDLING ALIASFOR CONSTRUCTS where lmsQ,ret = lmsQ [(Quantum, [v1 , . . . , vk ]) ][(Quantum, [v1 , . . . , vk ]) gq] vpret = vp[name (Quantum, [v1 , . . . , vk ])]var q if i = index vi = vi otherwise, given that ref = (Quantum, q) varRef (name, vp) = (Quantum, [v1 , . . . , vk ]) if j : lmsQ ((Quantum, vj )) = gq = (GQuantum, linearize ([v1 , . . . , vk ])) otherwise Before we dene a function that handles the whole case (1), we must dene one more auxiliary function localAliasedV ars that returns all the aliased quantum variables available in the currently running method. Denition 7.6.3. We dene a function localAliasedV ars : V arP rop P(N ames) as: localAliasedV ars([L1 G K]) = localAliasedV arsL (K) localAliasedV ars( ) = where localAliasedV arsL : V arP ropL P(N ames) is a function for getting a set of all names of variables representing compound systems in the local variable properties list from a list of partial function tuples: localAliasedV arsL ([K1 L (fvar , fch , fqa , ftype )]) = dom(fqa ) localAliasedV arsL (K1 ) def localAliasedV arsL ( ) = Now we are ready to dene a function fassignQSystem that performs assignment to one proper quantum variable while correctly adjusting all aliased quantum variables which use the variable being assigned (case (1)). The function operates as follows: It rst uses the function fassignQSystemDirect to perform the assignment to the proper quantum variable, Then it adjusts all the aliased quantum variables which use the variable being assigned (the set of such variables is denoted by AQV ) using the function fassignQSystemInAlias . Denition 7.6.4. We dene a function fassignQSystem : LM SQ V arP rop N ames RefQ LM SQ V arP rop as: fassignQSystem (lmsQ , vp, name, ref ) = (lmsQ,ret , vpret ) where (lmsQ,0 , vp0 ) = fassignQSystemDirect (lmsQ , vp, name, ref ), (lmsQ,i , vpi ) = fassignQSystemInAlias (lmsQ,i1 , vpi1 , qcsi , ref, li )i : 1 i k, lmsQ,ret = lmsQ,k , vpret = vpk , given that AQV = {aqv localAliasedV ars(vp)| name set(aliasSubsyst(aqv, vp))}, AQV is indexed by numbers i N : 1 i k, aqvi AQV, aliasSubsyst(aqvi , vp) = [aqvi,1 , . . . , aqvi,mi ], aqvi,li = name. 62
def def def def

CHAPTER 7. OPERATIONAL SEMANTICS Last, we dene a function fassignQAlias that performs an assignment to an aliased quantum variable (case (2)). This function operates very straightforwardly it takes each of the proper quantum variables which the aliased quantum variable is composed of and applies the function fassignQSystem onto it. We assume that the number of subsystems of the aliased quantum variable corresponds to the structure of the assigned reference (the length of the N-list in the reference). Denition 7.6.5. We dene a function fassignQAlias : LM SQ V arP ropN amesRefQ LM SQ V arP rop as: fassignQAlias (lmsQ , vp, name, ref ) = (lmsQ,ret , vpret ) where lmsQ,0 = lmsQ , vp0 = vp, (lmsQ,i , vpi ) = fassignQSystem (lmsQ,i1 , vpi1 , qi , (Quantum, vi )) for all 1 i k, lmsQ,ret = lmsQ,k , vpret = vpk , given that aliasSubsyst(name, vp) = [q1 , . . . , qk ], ref = (Quantum, [v1 , . . . , vk ]).
def

7.7

Internal values

Expressions evaluate to references and values which in turn are possibly references to global memory. Operational semantics uses both values and references so we dene internal value to be a triplet (ref, val, T) RefL V alues T ypes written as ref, val T .

7.8

Transitions

We dene operational semantics in terms of the following relations: v Transitions of expressions to internal values, e Transitions of expressions to expressions the order of evaluation is encoded here, s Transitions of statements, ret Transitions of return statements, rte Transitions of runtime errors, r Transitions of statements to statements, used to rewrite an abbreviated statement to the unabbreviated form, p Transitions of processes, Probabilistic transitions of processes, 0 p 1 is the probability of the transition. We dene relation as: =v e s ret rte r p . 63
p

7.9. RUNTIME ERRORS The transitions v , e , s , ret , rte , r and dene deterministic and probabilistic single process evolution. Nondeterminism is introduced by parallel evolution of processes a choice which process gets evolved is nondeterministic. However, there is no nondeterminism in the evolution of individual processes even when they are run in parallel with other processes. This feature simplies the implementation and might be useful in future denition of denotational semantics. This is an improvement over existing quantum process algebras [Lalire and Jorrand, 2004, Gay and Nagarajan, 2004]. In these algebras, there is a nondeterminism arising from resource sharing. Although there is no nondeterminism arising from quantum resource control, there is one arising from channel resources: it is possible for three or more processes to share one channel. When these processes use the channel simultaneously, the resulting behaviour is nondeterministic.6 We avoid this type of nondeterminism by using channel ends for communication instead of the channels themselves and imposing a constraint that one channel end is owned by exactly one process at a time. When probabilistic and nondeterministic choice are to be evaluated simultaneously, we must decide which choice is resolved rst [Cazorla et al., 2003]. However, we have taken the same approach as other authors (eg. [Gay and Nagarajan, 2004]) where the choice of transitions type is resolved deterministically: A conguration that is not mixed is evolved by the transition to a mixed conguration. For a mixed conguration, the next transition must be probabilistic because no other transition is dened for it. Many transitions evolve a conguration C0 to a mixed conguration Cp = 1C1 that consists of only one conguration chosen with probability 1. In the subsequent probabilistic transition, Cp is rewritten to C1 . Such transitions are written directly as C0 C1 . When we get to a situation when no rule is applicable to a conguration, the conguration becomes stuck. This is indeed an unwanted behaviour, therefore we aim to minimize its occurence. This is done by employing typing system and showing language type soundness (this is done in Chapter 9), and by employing runtime checks and introducing runtime errors as described in Section 7.9. However, we cannot eliminate the possibility of getting to a stuck conguration entirely in LanQ. This happens in the case of an ill-typed communication when a process tries to send/receive a value from a channel when there is no receiver/sender at the other end of the channel.
p

7.9

Runtime errors

There exist errors that cannot be recognized during compile time and can occur during the run time. For that reason. we dene special symbols representing such runtime errors: UV: an error representing an uninitialized variable usage. An example method invoking this error is in Figure 7.3(a) (U is a unitary operation there). In this example, the variable q is sent away, hence not initialized. The attempt to perform U (q) therefore invokes a runtime error UV. OQV: an error representing overlapping quantum variable usage. An example method invoking this error is shown in Figure 7.3(b) (U is a two-qubit unitary operation there).
Note however that we can take advantage of the nondeterministic behaviour: It can be used eg. to simply catch server environment serving requests from multiple clients where it is used to resolve which request came from which client. It can be also used to model possible eavesdropping of a communication.
6

64

CHAPTER 7. OPERATIONAL SEMANTICS In this example, variables p and q refer to the same quantum system. An attempt to perform U (p, q) therefore invokes a runtime error OQV. ISQV: an error representing an assignment to an incompatibly structured quantum variable. An example method invoking this error is shown in Figure 7.3(c). In this example, variables p and q refer to qubit systems, r refers to a system composed of the two qubits. An attempt to assign one four-dimensional quantum system to r fails as this assignment must also appropriately set the two systems p and q. Hence this assignment invokes a runtime error ISQV. void ex2() { qbit p,q; q = new qbit(); p = q; U (p,q); }
(b)

void ex1(channelEnd[qbit] c) { qbit q; q = new qbit(); send(c,q); U (q); }


(a)

void ex3() { qbit p,q; r aliasfor [p,q]; r = new q4it(); }


(c)

Figure 7.3: Example methods invoking runtime errors.

7.10

Processes and congurations

In this subsection, we dene special congurations, processes and relations between them. We dene a special conguration start (a starting conguration for any LanQ program execution) and a set 0c of silent local process congurations as: start = [(((1), []), []) | (([], [], [], []), , main())] 0c = {(lms, vp, ) | lms LM S, vp V arP rop} The terminal conguration is dened as a conguration C: C = [gs | (lms1 , vp1 , v1 ) (lmsn , vpn , vn )]
def def

where gs is a global part of the conguration, and for all i, lmsi LM S, vpi V arP rop, and vi is either , runtime error RT Err, or an internal value v. If some of vi is a runtime error, then we call this conguration erroneous.

7.10.1

Structural congruence

In this subsection, we dene structurally congruent processes. A process is fully characterized by a local process conguration, therefore the relation is dened on these local process congurations P, Q and R. Any process is structurally congruent to a process running in parallel with a silent process (rule SC-Nil). Order of processes in the conguration does not matter (SC-Comm) as well as grouping of processes within the conguration (SC-Assoc). 65

7.11. EVALUATION

SC-Nil

0P QQ Q) P

for any 0 0c

SC-Comm P SC-Assoc (P

RP

(Q

R)

7.10.2

Nondeterminism and parallelism

In this subsection, we dene behaviour related to nondeterminism and parallelism. The rule NP-PropagProb states that evolution of a process P leaves all other processes running in parallel with P in their original state while propagating the probability distribution on congurations to the top level. We can exchange congruent processes without any impact on the resulting behaviour (rule NP-Cong). A probabilistic conguration consisting of two or more probabilistic alternatives must resolve a probabilistic choice (rule NP-ProbEvol). [gs | P ] i pi [gsi | Pi ] [gs | P Q] i pi [gsi | Pi Q] [gs | P ] i pi [gsi | Pi ] P P Pi Pi for all i [gs | P ] i pi [gsi | Pi ] pi q for q > 1 i=1 pi [gsi | Pi ] [gsi | Pi ]

NP-PropagProb NP-Cong NP-ProbEvol

7.11

Evaluation

In this section, we dene the transition rules of individual processes.

7.11.1

Basic rules

The rst three rules dene conguration change on a skip statement (rule OP-Skip), a variable (OP-Var) and bracketed expression (OP-Bracket). Next rule (OP-BlockHead) is used to evaluate sequence of statements from rst to last. Last two rules (OP-SubstE and OP-SubstS) denes substitution of the result of an evaluated expressions in place of a hole.

OP-Skip OP-Var

[gs | (lms, vp, ; ts)] s

[gs | (lms, vp, ts)]

[gs | (lms, vp, x ts)] v [gs | (lms, vp, ref, lms(ref ) typeOf (x ,vp) ts)] where ref = varRef (x, vp) [gs | (lms, vp, (E) ts)] r [gs | (lms, vp, Be ts)] r [gs | (lms, vp, E ts)] [gs | (lms, vp, head(Be) tail(Be) ts)] where Be = Be0 Be1 . . . Ben for n 1

OP-Bracket OP-BlockHead

66

CHAPTER 7. OPERATIONAL SEMANTICS

OP-SubstE [gs | (lms, vp, v Ec ts)] e [gs | (lms, vp, Ec[v] ts)] OP-SubstS [gs | (lms, vp, v Sc ts)] e [gs | (lms, vp, Sc[v] ts)]

7.11.2

Promotable expressions

Promotable expressions are expressions that can be turned into statements by appending a semicolon. The expression is evaluated (rule OP-PromoExpr) but the resulting value is then forgotten (rule OP-PromoForget).

OP-PromoExpr OP-PromoForget

[gs | (lms, vp, P E; ts)] e [gs | (lms, vp, P E ; ts)] [gs | (lms, vp, v; ts)] s [gs | (lms, vp, ts)]

7.11.3

Allocation

Allocating a resource is performed by an evaluation of expression new T() where T is a type of the resource, ie. a type of a channel or a quantum system. Allocation of a channel resource is handled by rule OP-AllocC. Note that when a mapping to a new channel is added, due to the denition of local memory state update lms[r v]+ , appropriate mapping from channel ends to the channel is also set. Quantum resource allocation is handled by rule OP-AllocQ.

OP-AllocQ

[gs | (lms, vp, new qdit() ts)] v [gs | (lms , vp, (Quantum, [l]), (GQuantum, [l]) qdit ts)] where l = |L| 1 gs = (( ( d Id ), L [d]), C) lms = lms[(Quantum, [l]) (GQuantum, [l])]+ given that gs = ((, L), C)

OP-AllocC [gs | (lms, vp, new channel[T]() ts)] v [gs | (lms , vp, (Channel, l), (GChannel, l) channel[T] ts)] where l = |C| gs = (Q, C [c0|== c1 ]) lms = lms[(Channel, l) (GChannel, l)]+ given that gs = (Q, C) |=

7.11.4

Variable declaration

Variable declaration extends fvar element of variable properties by a mapping from a variable name to the special reference none (rule OP-VarDecl). We consider any variable declaration 67

7.11. EVALUATION of multiple variables of the same type: T a,b,c; to be an abbreviation of T a; T b; T c; (rule OP-VarDeclMulti). Declaration of a channel with named ends is done in the rule OP-VarDeclChE. It declares three variables one channel and two channel end variables in the same way as in the rule OP-VarDecl, moreover it modies the fch element of variable properties to bind the channel end variables to the channel variable. For a declaration of a quantum compound system, a construction q aliasfor [q0 , . . . ,qn ] is used where q0 , . . . , qn are names of quantum variables (rule OP-VarDeclAlF). Note that some of them can again denote compound systems. To deal with this feature, all variables from {q0 , . . . , qn } that represent compound systems are expanded. This can be seen from the following example we expand the quantum variable declarations so that the declarations on the left and right side are equivalent: qbit q0 ,q1 ,p; q aliasfor [q0 ,q1 ]; r aliasfor [p,q]; qbit q0 ,q1 ,p; q aliasfor [q0 ,q1 ]; r aliasfor [p,q0 ,q1 ];

OP-VarDeclMulti

[gs | (lms, vp, T x,I; ts)] r [gs | (lms, vp, T x; T I; ts)] [gs | (lms, [vpG G [vp L vpL ]], T x; ts)] s [gs | (lms, [vpG G [vp L vpL ]], ts)] where vpL = vpL [x none]+,var [x T ]+,type

OP-VarDecl

OP-VarDeclChE [gs | (lms, [vpG G [vp L vpL ]], channel[T] c withends[c0 ,c1 ]; ts)] s [gs | (lms, [vpG G [vp L vpL ]], ts)] where vpL = vpL [c none]+,var [c0 none]+,var [c1 none]+,var [c (c0 , c1 )]+,ch [c channel[T]]+,type [c0 channelEnd[T]]+,type [c1 channelEnd[T]]+,type OP-VarDeclAlF [gs | (lms, [vpG G [vp L vpL ]], q aliasfor [q0 , . . . ,qn ]; ts)] s [gs | (lms, [vpG G [vp L vpL ]], ts)] where vpL = vpL [q (Quantum, [l0 , . . . , ln ])]+,var [q [q0 , . . . , qn ]]+,qa [q n typeOf (qn , vp)]+,type i=0 l if varRef L (qi , [vp L vpL ]) = (Quantum, l) otherwise

given that li = qi =

p0 , . . . , pk if aliasSubsystL (qi , [vp L vpL ]) = [p0 , . . . , pk ] qi otherwise varRef L (qi , [vp L vpL ]) is dened for 0 i n

7.11.5

Assignment

Assignment command x = E has to be divided into several rules: one where expression e is evaluated (OP-AssignExpr) and the others where the result of evaluation of e is 68

CHAPTER 7. OPERATIONAL SEMANTICS bound to variable x and possibly stored into memory (rules OP-AssignNewValue and OPAssignValue). The value is stored into memory if it was not there yet what is indicated by reference part of the internal value equal to none. Assigning a quantum system to a variable can be complicated when the variable was declared using the aliasfor construct. For example, let be a variable that represents a quantum system composed of systems A and B (it was declared as: aliasfor [A , B ]). Assigning a value to must appropriately modify both A and B and can be only performed if the assigned value represents a compound system made of two subsystems (rule OP-AssignQAValue). Similarly, assigning a value to A must also modify (rule OPAssignQValue). If the structure of assigned system is not compatible with the structure of the assigned variable then a runtime error ISQV occurs (rule OP-AssignQAValueBad).

OP-AssignExpr

[gs | (lms, vp, x = E ts)] e

[gs | (lms, vp, E x = ts)]

[gs | (lms , vp , lr , lv T ts)] OP-AssignNewValue [gs | (lms, vp, x = v ts)] v where lr = (Classical, nc) lmsCl = lmsCl [lr lv]+ vp = vp[x lr ]var given that v = lr, lv T nc N0 is such that lms((Classical, nc)) is not dened lms = lms[lr lv]+ lr = none lv = [gs | (lms , vp , v ts)] OP-AssignQValue [gs | (lms, vp, x = v ts)] v where (lmsQ , vp ) = fassignQSystem (lmsQ , vp, x, lr) given that v = lr, lv T lr = (Quantum, q) and aliasSubsyst(x, vp) is not dened lms = (lmsCl , lmsQ , lmsCh , lmsChE ) lms = (lmsCl , lmsQ , lmsCh , lmsChE ) OP-AssignQAValue [gs | (lms, vp, x = v ts)] v [gs | (lms , vp , v ts)] where (lmsQ , vp ) = fassignQAlias (lmsQ , vp, x, lr) given that v = lr, lv T lr = (Quantum, q) and aliasSubsyst(x, vp) is dened lms = (lmsCl , lmsQ , lmsCh , lmsChE ) lms = (lmsCl , lmsQ , lmsCh , lmsChE ) typeOf (q) = n Qi , T = m Tj i=0 j=0 and m = n and i : Qi Ti = [gs | (lms, vp, x = v ts)] rte [gs | (lms, vp, ISQV)] given that typeOf (q) = n Qi , T = m Tj i=0 j=0 and m = n or i : Qi Ti

OP-AssignQAValueBad

69

7.11. EVALUATION

OP-AssignValue [gs | (lms, vp, x = v ts)] v [gs | (lms, vp , v ts)] vp[x lr]var [x0 (ChannelEnd0 , i)]var [x1 (ChannelEnd1 , i)]var where vp = if lr = (Channel, i) and chanEnds(x, vp) = (x0 , x1 ) vp[x lr]var otherwise given that v = lr, lv T (lr = none lv = ) (lr = (Quantum, q))

7.11.6

Block

Block command is used to limit scope of variables and to execute multiple statements:

OP-Block

[gs | (lms, [vpG G vp], {B} ts)] s [gs|(lms, [vpG G [vp L ]], B L ts)]

OP-BlockEnd [gs | (lms, [vpG G [vp L vpL ]], L ts)] s [gs|(lms, [vpG G vp], ts)]

7.11.7

Conditional statement if

Conditional expression if (E) S1 else S2 has to be split into three rules: one where the condition is evaluated (OP-IfExpr), and to the rules for reduction when the condition evaluates to true (OP-IfTrue) or false (OP-IfFalse).

OP-IfExpr

[gs | (lms, vp, if (E) S1 else S2 ts)] e (lms, vp, E if ( ) S1 else S2 ts)] [gs | (lms, vp, if (v) S1 else S2 ts)] s [gs | (lms, vp, S1 ts)] if v = r, true bool [gs | (lms, vp, if (v) S1 else S2 ts)] s [gs | (lms, vp, S2 ts)] if v = r, false bool

OP-IfTrue

OP-IfFalse

7.11.8

Conditional cycle while

While is operationally converted to a corresponding if statement as usual.

OP-While [gs | (lms, vp, while (E) S ts)] r [gs | (lms, vp, if (E) {S while (E) S} else ; ts)]

70

CHAPTER 7. OPERATIONAL SEMANTICS

7.11.9

Method call

Call of a method m whose parameters are expressions is rewritten to a call of method m whose parameters are values (rule OP-MethodCallExpr). The call of the method m with value parameters is evaluated in two dierent ways depending on whether m represents a classical method or a quantum operator. In the case when m represents a classical method, the call of a method m is rewritten to the unwound body of method m translated to the internal syntax by MB taken from the current method typing context (rule OP-DoMethodCallCl). The variable properties are modied to provide parameter values and types. The type of the pseudovariable @retV al is set because it is later used by rules for typing congurations (see Section 9.1). If m represents a quantum operator Em , the operator Em is applied to a quantum subsystem specied by the parameters v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn . Values v1 , . . . , vn are either global references to quantum storage (GQuantum, lr1 ), . . . , (GQuantum, lrn ) or . In the case when is referred, a runtime error UV occurs (OP-MethodCallQUninit). The condition that all manipulated quantum system are physically dierent can be reformulated as: all the indices in lists lr1 , . . . , lrn are mutually dierent, ie. set[ ] (lrj )set[ ] (lrk ) = and |lrj |[ ] = | set[ ] (lrj )| for all 1 j, k n, j = k. If this condition is not satised, runtime error OQV is invoked (OP-MethodCallQOverlap). The list qsi of indices of quantum systems aected by the applied quantum operator is given by a concatenation of individual linearized lists: qsi = lr1 . . . lrn , which determines quantum system qqsi . Dimension dqqsi of the quantum system ql is calculated from the global part ((, L), C) of the conguration as:
|qsi|

dqqsi =
i=1

Lqsii .

We denote d the order of matrix and d the dimension of untouched part of the system, d = d/dqqsi (rule OP-DoMethodCallQ).

OP-MethodCallExpr

[gs | (lms, vp, m(v,E,E) ts) e [gs | (lms, vp, E m(v, ,E) ts)]

OP-DoMethodCallCl [gs | (lms, vpG , m(v1 , . . . ,vn ) ts) e [gs | (lms , [vpG G [ L vp ]], MB (m) M ts)] where vp = ([a1 r1 , . . . , an rn ], [], [], [a1 T1 , . . . , an Tn , @retV al T]) lms = lms[r1 v1 ]+ . . . [rn vn ]+ given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn (Classical, nci ) if ri = none ri = ri otherwise where all nci are mutually dierent natural numbers such that lms((Classical, nci )) is not dened m represents a classical method and T m(T1 a1 , . . . Tn an ) is a header of method m

71

7.11. EVALUATION

OP-MethodCallQUninit

[gs | (lms, vp, m(v1 , . . . ,vn ) ts)] rte [gs | (lms, vp, UV)] given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn i : vi =

OP-MethodCallQOverlap [gs | (lms, vp, m(v1 , . . . ,vn ) ts)] rte [gs | (lms, vp, OQV)] given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn v1 = (GQuantum, lr1 ), . . . , vn = (GQuantum, lrn ) set[ ] (lrj ) set[ ] (lrk ) = for some 1 j, k n, j = k or |lrj |[ ] = | set[ ] (lrj )| for some 1 j n OP-DoMethodCallQ [gs | (lms, vp, m(v1 , . . . ,vn ) ts)] v [gs | (lms, vp, none,

void

ts)]

where gs = (( , L), C) = T (Em Id (T )) given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn gs = ((, L), C) v1 = (GQuantum, lr1 ), . . . , vn = (GQuantum, lrn ) set[ ] (lrj ) set[ ] (lrk ) = for all 1 j, k n, j = k |lrj |[ ] = | set[ ] (lrj )| for all 1 j n is a permutation matrix which places aected quantum systems to the head of in the order given by v1 , . . . , vn m represents a quantum operator Em

7.11.10

Returning from a method

When a method evaluation nishes, the control is passed back to its caller. The place on the term stack where the called method was invoked by the caller is marked by the M symbol (see OP-DoMethodCallCl). If a method returns no value, it can either end without return statement just by evaluating the last statement in the method (handled by OPReturnVoidImpl) or by explicit return; statement. In that case the return; statement pops everything from the term stack until it nds the symbol M (OP-ReturnVoid). When the method returns a value, the return value is evaluated rst (OP-ReturnExpr) and then the return value is then left on top of the stack after popping all symbols up to M from the stack (OP-ReturnValue).

OP-ReturnVoid [gs | (lms, [vpG G vp], return; tsM M ts)] ret [gs | (lms, vpG , none, void ts)] where tsM does not contain M

72

CHAPTER 7. OPERATIONAL SEMANTICS

OP-ReturnVoidImpl

[gs | (lms, [vpG G vp], M ts)] s [gs | (lms, vpG , none, void ts)] [gs | (lms, vp, return E; ts)] e [gs | (lms, vp, E return ; ts) [gs | (lms, [vpG G vp], return v; tsM M ts)] ret [gs | (lms, vpG , v ts)] where tsM does not contain M

OP-ReturnExpr

OP-ReturnValue

7.11.11

Forking

Forking creates a new process which is started from given method. As fork contains a method call construct, the rule OP-ForkExpr for evaluation of arguments is similar to the rule OPMethodCallExpr. In the rule OP-DoFork, a new process is started, values passed as parameters to the forked method are copied to the new process memory. The nonduplicable values passed as parameters to the forked method are invalidated in the original process memory.

OP-ForkExpr

[gs | (lms, vp, fork m(v,E,E); ts)] e [gs | (lms, vp, E fork m(v, ,E); ts)]

OP-DoFork

[gs | (lms, vp, fork m(v1 , . . . ,vn ); ts)] p [gs | (lms1 , vp, ts) (lms2 , , m(v1 , . . . ,vn ))] where lms1 = unmapnd ({r1 , . . . , rn }, lms1 ) lms2 = ([], [], [], [])[r1 v1 ]+ . . . [rn vn ]+ v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn (Classical, nci ) if ri = none ri = ri otherwise where all nci are mutually dierent natural numbers such that lms1 ((Classical, nci )) is not dened

7.11.12

Measurement

Measurement is performed when measure(b, e1 , . . . ,en ) primitive is evaluated. Its rst argument b determines measurement basis, the other arguments determine quantum systems that are to be simultaneously measured. Arguments e1 , . . . , en evaluate to internal values v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn . Values v1 , . . . , vn are either global references to quantum storage (GQuantum, lr1 ), . . . , (GQuantum, lrn ) or . In the case when is referred, a runtime error UV occurs (OP-MeasureUninit). The condition that all the measured systems are physically dierent can be reformulated as: all the indices in lists lr1 , . . . , lrn are mutually dierent, ie. set[ ] (lrj ) set[ ] (lrk ) = and 73

7.11. EVALUATION |lrj |[ ] = | set[ ] (lrj )| for all 1 j, k n, j = k. If this condition is not satised, runtime error OQV is invoked (OP-MeasureOverlap). The list qsi of indices of quantum systems to be measured is given by a concatenation of individual linearized lists: qsi = lr1 . . . lrn , which determines quantum system qqsi . Dimension dqqsi of the quantum system ql is calculated from the global part ((, L), C) of the conguration as:
|qsi|

dqqsi =
i=1

Lqsii .

We denote d the order of matrix and d the dimension of unmeasured part of the system, = d/dq . d qsi In quantum mechanics, the possible results of the measurement are eigenvalues of the observable. We assign to each eigenvalue an index in a list of all eigenvalues. This index is returned as a result of evaluated measure expression. Indeed, it is possible that two or more eigenvalues are the same (they are called degenerate eigenvalues). In this case, the obtained result is the rst index of corresponding eigenvalue in the list. The list is indexed from zero. Now we can formulate the rules for measurement: [gs | (lms, vp, measure(v,E,E) ts] e [gs | (lms, vp, E measure(v, ,E) ts)] [gs | (lms, vp, measure(vb ,v1 , . . . ,vn ) ts)] rte [gs | (lms, vp, UV)] given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn i : vi =

OP-MeasureExpr

OP-MeasureUninit

OP-MeasureOverlap [gs | (lms, vp, measure(vb , v1 , . . . ,vn ) ts)] rte [gs | (lms, vp, OQV)] given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn v1 = (GQuantum, lr1 ), . . . , vn = (GQuantum, lrn ) set[ ] (lrj ) set[ ] (lrk ) = for some 1 j, k n, j = k or |lrj |[ ] = | set[ ] (lrj )| for some 1 j n

74

CHAPTER 7. OPERATIONAL SEMANTICS

OP-DoMeasure [gs | (lms, vp, measure(vb ,v1 , . . . ,vn ) ts)] v i pi [gsi | (lms, vp, none, f di(i) int ts)] where gsi = ((i , L), C) pi = Tr[T (Pi Id )T (Pi Id ) ] T (Pi Id )T (Pi Id ) i = pi f di(i) is the rst index of i-th eigenvalue in the list of observable eigenvalues given that v1 = r1 , v1 T1 , . . . , vn = rn , vn Tn v1 = (GQuantum, lr1 ), . . . , vn = (GQuantum, lrn ) gs = ((, L), C) set[ ] (lrj ) set[ ] (lrk ) = for all 1 j, k n, j = k |lrj |[ ] = | set[ ] (lrj )| for all 1 j n i i Pi is a spectral decomposition of a measurement in the basis given by vb is a permutation matrix which places measured quantum systems to the head of in the order given by v1 , . . . , vn

7.11.13

Communication

Communication is performed when there is one process sending a value over a channel end and another process waiting to receive a value over a channel end provided that both channel ends belong to the same channel. This condition is equivalent to the condition that both channel ends refer to the same channel. First three rules (OP-SendExpr1, OP-SendExpr2 and OPRecvExpr) are used to evaluate statement arguments. The rule OP-SendRecv performs the communication. When either the sending channel end or the sent value is undened, or a receiving process attempts to receive from uninitialized channel end, a runtime error UV occurs (rules OP-SendUninit and OP-RecvUninit). Unique ownership of resources (both quantum and channel) is ensured by unmapping them from the local memory of the sender process using the function unmapnd .

OP-SendExpr1

[gs | (lms, vp, send(E1 ,E2 ); ts)] e [gs | (lms, vp, E1 send( ,E2 ); ts] [gs | (lms, vp, send(vc ,E); ts)] e [gs | (lms, vp, E send(vc , ); ts]

OP-SendExpr2

OP-SendUninit [gs | (lms, vp, send(v1 ,v2 ); ts)] rte [gs | (lms, vp, UV] given that v1 = r1 , v1 T1 and v1 = or v2 = r2 , v2 T2 and v2 = )

75

7.11. EVALUATION

OP-RecvExpr OP-RecvUninit

[gs | (lms, vp, recv(E) ts)] e

[gs | (lms, vp, E recv( ) ts]

[gs | (lms, vp, recv(v) ts)] rte [gs | (lms, vp, UV] given that v = r, v T and v = [gs | (lms1 , vp1 , send(vc1 ,ve ); ts1 ) (lms2 , vp2 , recv(vc2 ) ts2 )] p [gs | (lms1 , vp1 , ts1 ) (lms2 , vp2 , lr2 , lv2 T ts2 )] where lms1 = unmapnd (sentRef, lms1 ) lr1 if sentRef Refnd lr2 = none otherwise lv2 = sentV al lms2 [sentRef sentV al]+ if sentRef Refnd lms2 = lms2 otherwise given that ve = sentRef, sentV al T vc1 = c1 Ref, c1 V al T vc2 = c2 Ref, c2 V al T c1 Ref = none and c2 Ref = none c1 V al = c2 V al (both ends refer to the same channel)

OP-SendRecv

76

Chapter 8

Unique resource ownership


In this chapter, we prove that a resource, ie. a channel, a channel end, or a quantum system, is accessible to at most one process at a time. Unique resource ownership is a natural requirement that must be fullled when we request a deterministic evolution of individual processes running in a system. If two or more processes were allowed to use the same resource at a time, we could get to the situation when they all want to perform an exclusive operation on a resource. Then the order in which the operations would be performed would be nondeterministic and could possibly lead to dierent results. To ensure unique resource ownership, we must solve the issue here which a consequence of the fact that variables referring to resources may refer both to an individual resource and a group of them.1 We must ensure that a resource, be it referred from a variable denoting a group of resources or individual ones, gets inaccessible from a process when the control over the resource is passed from this process to another one. To solve this issue, we use the following idea: A group of resources is accessible from a process only if the process can access all of the resources which are elements of the group. By accessibility of a quantum system to a process we mean that there is a mapping from the structured reference layer to the system memory layer. This mapping is stored in the local memory state element lms in the local process conguration which describes the process state. This concept is formally dened for dierent kinds of resources in the following sections.

8.1

Unique quantum system ownership

In this section, we prove that a quantum system is always accessible by at most one process. Denition 8.1.1. Let C = [gs | ls1 lsn ] be a conguration. Let us have a quantum system Q stored in the system memory at place referred by (GQuantum, [n]) RefG where n N, and let Pi be a process described by the local process conguration lsi = (lms, vp, ts). We say that the quantum system Q is accessible to the process P i there is a local reference l RefQ such that lms(l) = (GQuantum, p) where n set[ ] (p). Next we state what we mean by unique ownership of a quantum system. We formulate it as a property of a conguration.
An example of a variable referring to a group of resources is an aliased quantum variable it refers to several distinct quantum systems. Similarly, a channel variable can be seen as a group of two variables denoting individual channel ends.
1

77

8.1. UNIQUE QUANTUM SYSTEM OWNERSHIP Denition 8.1.2. Let C = [gs | ls1 lsn ] be a conguration. We say that C satises unique quantum system ownership property if for any quantum system Q, there is at most one process P described by the local process conguration lsi = (lms, vp, ts) for some i {1, . . . , n} such that Q is accessible to P . Lemma 8.1.3. The starting conguration start dened in Section 7.10 satises unique quantum system ownership property. Proof. There is no resource stored in the system memory, therefore the lemma holds trivially. Next we show that if a conguration which satises unique quantum system ownership property is evolved by a transition, then the unique quantum system ownership property holds also for the new conguration. Lemma 8.1.4. Let C0 be a conguration and C1 = q pi Ci,1 a mixed conguration such i=1 that C0 C1 . If C0 satises unique quantum system ownership property then also Ci,1 satises unique quantum system ownership property for all i. Proof. This lemma trivially holds for all the transitions that only manipulate one process, ie. all the transition rules that form the relation up to p . They do not change a local memory state of any other process, hence if C0 satises unique quantum system ownership property then also Ci,1 trivially satises unique quantum system ownership property for all i. We must prove this lemma for the individual rules forming p , ie. for the rules OPDoFork and OP-SendRecv: OP-DoFork: By the denition of the rule OP-DoFork and by Lemma 7.5.2 we know that the quantum systems passed to the new process are not accessible to the original process. By the denition of the rule OP-DoFork, the quantum resources are accessible only to the new process. Therefore the conguration C1 satises unique quantum system ownership property, OP-SendRecv: By the denition of the rule OP-SendRecv and by Lemma 7.5.2 we know that the quantum systems passed along the channel to the receiving process are not accessible to the sending process in C1 . By the denition of the rule OP-SendRecv, the quantum resources are accessible only to the receiving process. Therefore the conguration C1 satises unique quantum system ownership property.

Lemma 8.1.5. Let C0 = q pi Ci,0 , q 1 be a mixed conguration and C1 be a congurai=1 pi tion such that C0 C1 . If Ci,0 satises unique quantum system ownership property for all i then also C1 satises unique quantum system ownership property. Proof. Obvious from the denition of the rule NP-ProbEvol. Theorem 8.1.6 (Unique quantum system ownership). For any conguration C such that start C it holds that any quantum system stored in the system memory is accessible to at most one process. Proof. Corollary of the Lemmata 8.1.3, 8.1.4 and 8.1.5. 78

CHAPTER 8. UNIQUE RESOURCE OWNERSHIP

8.2

Unique channel end ownership

In this section, we prove that a channel end is always accessible by at most one process. Denition 8.2.1. Let Cnf = [gs | ls1 lsn ] be a conguration, gs = (Q, C). Let us have a channel D = D0|== D1 set(C) where D0 , D1 denote ends of a channel, and let D be stored in the system memory at place referred by (GChannel, n) RefG where n N. Let Pi be a process described by the local process conguration lsi = (lms, vp, ts). We say that the channel end Di is accessible to the process P , i {0, 1}, i lms(ChannelEndi ) = (GChannel, n). Next we state what we mean by unique ownership of a channel end. We formulate it as a property of a conguration. Denition 8.2.2. Let C = [gs | ls1 lsn ] be a conguration. We say that C satises unique channel end ownership property if for any channel D = D0 |== D1 , there is at most one process P0 described by the local process conguration lsi = (lms, vp, ts) for some i {1, . . . , n} such that D0 is accessible to P0 , and at most one process P1 described by the local process conguration lsj = (lms, vp, ts) for some j {1, . . . , n} such that D1 is accessible to P1 . Lemma 8.2.3. The starting conguration start dened in Section 7.10 satises unique channel end ownership property. Proof. There is no resource stored in the system memory, therefore the lemma holds trivially. Next we show that if a conguration which satises unique channel end ownership property is evolved by some transition, then the unique channel end ownership property also holds in the resulting conguration. Lemma 8.2.4. Let C0 be a conguration and C1 = q pi Ci,1 a mixed conguration such i=1 that C0 C1 . If C0 satises unique channel end ownership property then also Ci,1 satises unique channel end ownership property for all i. Proof. This lemma trivially holds for all the transitions that only manipulate one process, ie. all the transition rules that form the relation up to p . They do not change a local memory state of any other process, hence if C0 satises unique channel end ownership property then also Ci,1 trivially satises unique channel end ownership property for all i. We must prove this lemma for the individual rules forming p , ie. for the rules OPDoFork and OP-SendRecv: OP-DoFork: By the denition of the rule OP-DoFork, namely from the usage of local memory state update function, we see that a channel end can be mapped into the new process local memory in two ways: either a channel end is directly passed from the original process, or indirectly a channel end is passed as a part of its parent channel. In both cases, the channel end is not accessible to the original process, being unmapped by the function unmapnd from the original process memory (see Lemmata 7.5.3 and 7.5.4). The channel end is hence accessible only to the new process, therefore the conguration C1 satises unique channel end ownership property, 79 |= |=

8.3. UNIQUE CHANNEL OWNERSHIP OP-SendRecv: Similarly, by the denition of the rule OP-SendRecv, namely from the usage of local memory state update function, we see that a channel end can be mapped into the receiving process local memory in two ways: either a channel end is directly sent over a channel from the sending process, or a channel end is passed indirectly as a part of its parent channel. Clearly, the proof of this case is straightforward alteration of the case OP-DoFork.

Lemma 8.2.5. Let C0 = q pi Ci,0 , q 1 be a mixed conguration and C1 be a congui=1 pi ration such that C0 C1 . If Ci,0 satises unique channel end ownership property for all i then also C1 satises unique channel end ownership property. Proof. Obvious from the denition of the rule NP-ProbEvol. Theorem 8.2.6 (Unique channel end ownership). For any conguration C such that start C it holds that any channel end of any channel stored in the system memory is accessible to at most one process. Proof. Corollary of the Lemmata 8.2.3, 8.2.4 and 8.2.5.

8.3

Unique channel ownership

In this section, we prove that a channel is always accessible by at most one process. Denition 8.3.1. Let C = [gs | ls1 lsn ] be a conguration. Let us have a channel D, let D be stored in the system memory at place referred by (GChannel, n) RefG where n N, and let Pi be a process described by the local process conguration lsi = (lms, vp, ts). We say that the channel D is accessible to the process P i there is a local reference l RefCh such that lms(l) = (GChannel, n). Next we state what we mean by unique ownership of a channel. We formulate it as a property of a conguration. Denition 8.3.2. Let C = [gs | ls1 lsn ] be a conguration. We say that C satises unique channel ownership property if for any channel D, there is at most one process P described by the local process conguration lsi = (lms, vp, ts) for some i {1, . . . , n} such that D is accessible to P . Lemma 8.3.3. The starting conguration start dened in Section 7.10 satises unique channel ownership property. Proof. There is no resource stored in the system memory, therefore the lemma holds trivially.

Next we show that if a conguration which satises unique channel ownership property is evolved by a transition, then the unique channel ownership property holds also for the resulting conguration. 80

CHAPTER 8. UNIQUE RESOURCE OWNERSHIP Lemma 8.3.4. Let C0 be a conguration and C1 = q pi Ci,1 a mixed conguration such i=1 that C0 C1 . If C0 satises unique channel ownership property then also Ci,1 satises unique channel ownership property for all i. Proof. This lemma trivially holds for all the transitions that only manipulate one process, ie. all the transition rules that form the relation up to p . They do not change a local memory state of any other process, hence if C0 satises unique channel ownership property then also Ci,1 trivially satises unique channel ownership property for all i. We must prove this lemma for the individual rules forming p , ie. for the rules OPDoFork and OP-SendRecv: OP-DoFork: By the denition of the rule OP-DoFork, namely from the usage of local memory state update function, we see that a channel can be mapped into the new process local memory only when a channel is directly passed from the original process. The channel is unmapped from the original process memory by the function unmapnd if it is passed to the new process, but also in the case when one of its ends is passed to the new process (see Lemmata 7.5.3 and 7.5.4). Hence then number of processes to which the channel is accessible can only be decreased. Therefore the conguration C1 satises unique channel ownership property, OP-SendRecv: By the denition of the rule OP-SendRecv, namely from the usage of local memory state update function, we know that a channel can be mapped into the receiving process local memory only when a channel is directly passed along the channel from the sending process. Clearly, the proof of this case is straightforward alteration of the case OP-DoFork.

Lemma 8.3.5. Let C0 = q pi Ci,0 , q 1 be a mixed conguration and C1 be a congui=1 pi ration such that C0 C1 . If Ci,0 satises unique channel ownership property for all i then also C1 satises unique channel ownership property. Proof. Obvious from the denition of the rule NP-ProbEvol. Theorem 8.3.6 (Unique channel ownership). For any conguration C such that start C it holds that any channel stored in the system memory is accessible to at most one process. Proof. Corollary of the Lemmata 8.3.3, 8.3.4 and 8.3.5. Theorem 8.3.7 (Unique resource ownership). For any conguration C such that start C it holds that any resource stored in the system memory is accessible to at most one process. Proof. Corollary of the Theorems 8.1.6, 8.2.6 and 8.3.6.

81

8.3. UNIQUE CHANNEL OWNERSHIP

82

Chapter 9

Type soundness
In this chapter, we prove type soundness (see eg. [Wright and Felleisen, 1994]) for LanQ. To prove type soundness theorem, we rst dene typing on congurations. Then in series of progress lemmata proofs, we prove that any typable conguration can be reduced by some semantic rule. After this proof, we prove series of type preservation lemmata stating that if a conguration gets reduced to another conguration, either a runtime error occurs or the type of the conguration is preserved. These lemmata straightforwardly imply type soundness of the language. However, we cannot prove the type soundness property for the unrestricted language because it is possible that a program gets to a stuck conguration during the evaluation. This can happen because the send and recv constructs are blocking actions. Consider a process which attempts to send a value over a channel where no other process is receiving the values from the other end of the channel. Then no semantic rule can be applied to the sending process. Symmetrically, it is indeed possible to dene a process which attempts to receive a value from a channel where no other process sends a value over this channel. Such a process also cannot evolve, therefore the evaluation can get to a stuck conguration. In other words, we can prove type soundness only for the noncommunicating part of the language. Nevertheless, if to each send statement there is a corresponding recv expression, then it can be proved that the evaluation of a well-typed conguration never gets stuck, hence type soundness could be proved for the unrestricted language.

9.1

Typing of congurations

To prove LanQ type soundness, we follow the approach of [Bierman, Parkinson, and Pitts, 2003]. Before proving type preservation, we dene typing of congurations in this subsection in Figures 9.1 and 9.2. Any conguration C = [gs | ls1 lsn ] is assigned a type T , written as C : T which is a cartesian product of types of local process congurations ls1 , . . . , lsn . If the type of lsi is Ti then T = (T1 , . . . , Tn ) (see the typing rule T-Config). We call a conguration which can be assigned a type a well-typed conguration. The typing rules provide rules for well-formedness of congurations, hence also for local process congurations. This indeed means that structure of variable properties and a term stack are tightly connected: To any block end mark L on the term stack, the variable properties must contain a nonempty list of variable properties [vp L vpL ] V arP ropL (see 83

9.2. PROGRESS rule TC-BlockEnd); to any method call mark M on the term stack, the variable properties must contain a nonempty list of lists of variable properties [vpG G vp] V arP rop (see rules TC-RetHole, TC-RetExpr, TC-RetVoid and TC-RetImpl). Typing of local process congurations as depicted in Figure 9.1 needs a deeper explanation. Contrary to usual typing of congurations known eg. from -calculi where one conguration contains only one expression, we deal with the situation where there are many expressions in one conguration. These expressions are in our case term stack elements and they altogether form a term stack of a local process conguration. The type of a local process conguration is dened as for types , . The type species the type of the hole in the top term stack element, species the type of the result value. When there is no hole in the top term stack element, is void. According to the conguration syntax, the top term stack element T E can contain at most one hole. As the hole type is always known and the variable typing context can be deduced from variable properties, the type of T E is derivable from the typing rules dened in Chapter 5. If T E is the only term stack element in the local process conguration, its type determines the type of the result value . Otherwise, the type is the type of a hole in the term stack element right beneath T E and we can continue with typing the local process conguration where T E is popped from the term stack. To derive variable typing context from local process conguration variable properties, we dene a function vpContext. This function is dened as follows: Denition 9.1.1. We dene a function vpContext : V arP rop (N ames creates a variable typing context from variable properties as: vpContext([L1 G K]) = vpContextL (K) vpContext( ) = [] where vpContextL : V arP ropL (N ames T ypes) is a function for getting a variable typing context from local variable properties dened as: vpContextL ([K1 L (fvar , fch , fqa , ftype )]) = vpContextL (K1 ) ftype vpContextL ( ) = []
def def def def

T ypes) which

9.2

Progress

In this section, we prove series of progress lemmata, ie. assertions claiming that any welltyped conguration which is not terminal can be reduced by some semantic rule. It also follows from the proof that the choice of the semantic rule for a single process is unique, hence the single process evolution is deterministic. Lemma 9.2.1 (Progress Lemma for probabilism). Let C0 = q pi [gsi | lsi,0 ] be a mixed i=1 p conguration such that C0 : . Then there exists a conguration C1 such that C0 C1 . Proof. Such a mixed conguration C0 is reduced by the rule NP-ProbEvol. 84

CHAPTER 9. TYPE SOUNDNESS


M; M;
C

TC-Empty TC-Runtime TC-ExprHole

(lms, , ) :

(lms, vp, RT Err) : RTErr

M ; , vpContext(vp), : T Ec : M ; C (lms, vp, ts) : M ; C (lms, vp, Ec ts) : M ; , vpContext(vp), : M; M; M;


T C

TC-StatHole

Sc : void M ; C (lms, vp, ts) : void (lms, vp, Sc ts) : if Sc = return ;

TC-RetHole

(lms, vpG , ts) : typeOf (@retV al, [vpG G vp]) C (lms, [vpG G vp], return ; . . . M ts) :
T C

TC-ExprClo

M ; , vpContext(vp) M;

E : M ; C (lms, vp, ts) : (lms, vp, E ts) :

TC-StatClo

M ; , vpContext(vp) T S : void M ; C (lms, vp, ts) : void M ; C (lms, vp, S ts) : if S = return E;, S = return; M ; , vpContext([vpG G vp]) T E : typeOf (@retV al, [vpG G vp]), M ; C (lms, vpG , ts) : typeOf (@retV al, [vpG G vp]) M ; C (lms, [vpG G vp], return E; . . . M ts) : M; M;
C

TC-RetExpr

TC-RetVoid

M ; C (lms, vpG , ts) : void (lms, [vpG G vp], return; . . . M ts) :

TC-RetImpl

(lms, vpG , ts) : typeOf (@retV al, [vpG G vp]) M ; C (lms, [vpG G vp], M ts) : for n > 0

TC-BlockHead

M; M;

(lms, vp, Be0 Be1 . . . Ben ts) : void (lms, vp, Be0 Be1 . . . Ben ts) :

TC-BlockEnd

M;

M ; C (lms, [vpG G vp], ts) : void C (lms, [vpG G [vp L vpL ]], L ts) : void for n > 0

TC-VarDeclMulti

M ; C (lms, vp, T I0 ; T I1 , . . . ,In ; ts) : void M ; C (lms, vp, T I0 ,I1 , . . . ,In ; ts) :

TC-VarDeclOne

varRef (I, vp) is undened M ; C (lms, vp , ts) : void M ; C (lms, vp, T I; ts) : where vp = vp[I T]+,type

varRef (Ii , vp) is undened for i = 0, ..2, I0 , I1 , I2 are mutually dierent, M ; C (lms, vp , ts) : void TC-VarDeclChE M ; C (lms, vp, channel[T ] I0 withends[I1 ,I2 ]; ts) : where vp = vp[c channel[T]]+,type [c0 channelEnd[T]]+,type [c1 channelEnd[T]]+,type varRef (I0 , vp) is undened, Ii : Ti Ti is a quantum type for i = 1, ..n, M ; C (lms, vp , ts) : void (lms, vp, I0 aliasfor [I1 , . . . ,In ]; ts) : n where vp = vp[I0 i=1 Ti ]+,type

M; TC-VarDeclAlF M;

Figure 9.1: Typing rules for local process congurations. 85

9.2. PROGRESS i 1, . . . , q : M ; [GSi | LSi,1 LSi,n ] : i q M; LSi,n ] i=1 pi [GSi | LSi,1 i 1, . . . , n : M ; C LSi : void i M ; [GS | LS1 LSn ] : n i i=1 Figure 9.2: Typing rules for congurations. Lemma 9.2.2 (Progress Lemma for local processes). If C0 = [gs0 | (lms0 , vp0 , T E ts0 )] is a conguration which is not terminal, T E = recv(v), T E = send(v1 ,v2 );, and C0 : then there exists a mixed conguration C1 such that C0 C1 . Proof. By case analysis of all possibilities of the top term stack element T E: Case T E = new T(): As C0 is well-typed, we know that T is either qd it or channel[T] (from the rule T-Alloc). If T = qd it, then the conguration C0 is reduced by the rule OPAllocQ. Otherwise T = channel[T] and the conguration C0 is reduced by the rule OP-AllocC. Case T E = I = E: As C0 is well typed, we know that types of I and E match (from the rule T-Assign). If E = v = lr, lv T then one of the following rules is applied: OP-AssignNewValue if lv = and lr = none, OP-AssignQValue if lr = (Quantum, q) and aliasSubsyst(I, vp0 ) is not dened, OP-AssignQAValue if lr = (Quantum, q) and aliasSubsyst(I, vp0 ) is dened, OP-AssignValue otherwise. Otherwise, the conguration C0 is reduced by the rule OP-AssignExpr. Case T E = I(E): As C0 is well typed, we know that I denotes either a quantum operator or a classical method (from the rule T-MethodCall). If E = v then one of the following rules is applied: OP-DoMethodCallCl if I represents a classical method, OP-DoMethodCallQ if I represents a quantum operator. Otherwise the conguration C0 is reduced by the rule OP-MethodCallExpr. Case T E = measure(E): If E = v then the conguration C0 is reduced by the rule OPDoMeasure, otherwise it is reduced by the rule OP-MeasureExpr. Case T E = recv(E): As E cannot be v (from assumptions) the conguration C0 is reduced by the rule OP-RecvExpr. Case T E = I: As C0 is well typed, we know that varRef (I, vp0 ) is dened. Conguration C0 is reduced by the rule OP-Var. Case T E = v: If |ts0 | = 1 then C0 is a terminal conguration. Otherwise let U T be the rst symbol under the top element of the stack. As the conguration is well-typed, we know that U T must be a symbol containing a hole. Now: 86

T-MixedConf

T-Config

CHAPTER 9. TYPE SOUNDNESS Case U T = Ec: Conguration C0 is reduced by the rule OP-SubstE. Case U T = Sc: Conguration C0 is reduced by the rule OP-SubstS. Case T E = (E): Conguration C0 is reduced by the rule OP-Bracket. Case T E = T I;: If T E = T I; then the conguration C0 is reduced by the rule OPVarDecl. Otherwise it is reduced by the rule OP-VarDeclMulti. Case T E = channel[T] I withends[I,I];: Conguration C0 is reduced by the rule OP-VarDeclChE. Case T E = q aliasfor [q0 , . . . ,qn ];: Conguration C0 is reduced by the rule OP-VarDeclAlF. Case T E = ;: Conguration C0 is reduced by the rule OP-Skip. Case T E = P E;: If P E = v then the conguration C0 is reduced by the rule OP-PromoForget, otherwise it is reduced by OP-PromoExpr. Case T E = L : Conguration C0 is reduced by the rule OP-BlockEnd. Case T E = Be: Conguration C0 is reduced by the rule OP-BlockHead. Case T E = {B}: Conguration C0 is reduced by the rule OP-Block. Case T E = if (E) S1 else S2 : If E = v, then the conguration is reduced by the rule OPIfTrue (OP-IfFalse) when v is true (false). Otherwise, the conguration C0 is reduced by the rule OP-IfExpr. Case T E = while (E) S: Conguration C0 is reduced by the rule OP-While. Case T E = M : Conguration C0 is reduced by the rule OP-ReturnVoidImpl. Case T E = return;: Conguration C0 is reduced by the rule OP-ReturnVoid. Case T E = return E;: If E = v then the conguration C0 is reduced by the rule OPReturnValue, otherwise it is reduced by OP-ReturnExpr. Case T E = fork m(E);: If E = v then the conguration C0 is reduced by the rule OPDoFork. Otherwise it is reduced by the rule OP-ForkExpr. Case T E = send(E1 ,E2 );: If E1 = v then the conguration C0 is reduced by the rule OPSendExpr1. If E2 = v, the conguration C0 is reduced by the rule OP-SendExpr2. Case E1 = v1 and E2 = v2 is prohibited by the assumptions.

Lemma 9.2.3 (Progress Lemma for communication). Let C0 = [gs0 | (lms0 , vp0 , recv(v) ts0 ) (lms1 , vp1 , send(v1 ,v2 ); ts1 ) ls2 lsn ] : be a well-typed conguration. Then there exists a conguration C1 such that C0 C1 . Proof. Such a conguration is not terminal because of the elements recv(v) and send(v1 ,v2 ); on tops of the process term stacks. It is reduced by the rule OP-SendRecv. 87

9.3. TYPE PRESERVATION Corollary 9.2.4. It is possible that a process evolves to a stuck conguration. This is the case when one process attempts to send/receive a value over a channel end and there is no matching process receiving/sending over the corresponding channel end.

9.3
9.3.1

Type preservation
Evaluation theorems

In the denition of LanQ semantics, we assumed that an expression always evaluates to a value (or diverges or gets stuck due to incorrect send/recv pairing, or invokes a runtime error). This assumption was used in all rules which manipulate a subexpression Sub of a statement or an expression: The subexpression Sub is pushed onto the top of the term stack and the place of the awaited result in the original statement/expression is marked with a hole (see eg. the rule OP-AssignExpr). We expect that if the evaluation correctly nishes, the subexpression evaluates to an internal value that in a subsequent step replaces the hole. However, we have not yet shown that the subexpression evaluation accomplishes this assertion. We have to prove that the statement/expression awaiting the result of the subexpression evaluation is not modied before the evaluation of the subexpression yields an internal value (unless a runtime error occurs). This will be shown in this subsection. We will use the following semantic predicates on congurations: ExpOk which is dened for congurations where the top term stack element of the rst local process conguration is some expression E, and BF Ok and StkRetOk which is dened for congurations where the top term stack element of the rst local process conguration is some block-forming statement B. Satisability of these predicates is determined by the future evolution of the congurations in question. The dened predicates are then used in the proof of the statement that if the syntactic predicate RetOk dened in Chapter 5.1 is satised for a block-forming statement B then any control path of evaluation of B reaches a return; or return E; statement, or a runtime error, or diverges, or gets stuck due to incorrect send/recv pairing (see Lemma 9.3.10). This proof is later used in proving type preservation lemma for s (see Lemma 9.3.16, proof of the case OP-ReturnVoidImpl). Denition 9.3.1. For an expression E, we dene a predicate ExpOk(E): ExpOk(E) is satised i for any conguration C0 = [gs0 | (lms0 , vp0 , E ts0 )] : , the evaluation of C0 either diverges or gets stuck due to incorrect send/recv pairing, or reaches one of the following congurations: [gsn | (lms0,n , vp0,n , v ts0 ) [gsn | (lms0,n , vp0,n , RT Err) (lmsk,n , vpk,n , tsk,n )], k 0, or (lmsk,n , vpk,n , tsk,n )], k 0.

Denition 9.3.2. For a block-forming statement B, we dene a predicate BF Ok(B): BF Ok(B) is satised i for any conguration C0 = [gs0 | (lms0 , vp0 , B ts0 )] : , the evaluation either diverges or gets stuck due to incorrect send/recv pairing, or reaches one of the following congurations: 88

CHAPTER 9. TYPE SOUNDNESS [gsn | (lms0,n , vp0,n , ts0 ) (lmsk,n , vpk,n , tsk,n )], k 0, or (lmsk,n , vpk,n , tsk,n )], k 0, ts0,n does not (lmsk,n , vpk,n , tsk,n )], k 0, ts0,n does

[gsn | (lms0,n , vp0,n , return; ts0,n ts0 ) contain M , or

[gsn | (lms0,n , vp0,n , return v; ts0,n ts0 ) not contain M , or [gsn | (lms0,n , vp0,n , RT Err)

(lmsk,n , vpk,n , tsk,n )], k 0.

We further dene a predicate StkRetOk(B): StkRetOk(E) is satised i for any welltyped conguration C0 = [gs0 | (lms0 , vp0 , B M ts0 )] : , the evaluation either diverges or gets stuck due to incorrect send/recv pairing, or reaches one of the following congurations: [gsn | (lms0,n , vp0,n , v ts0 ) [gsn | (lms0,n , vp0,n , RT Err) (lmsk,n , vpk,n , tsk,n )], k 0, or (lmsk,n , vpk,n , tsk,n )], k 0.

Lemma 9.3.3. Let B be a block-forming statement such that BF Ok(B). Then StkRetOk(B). Proof. The evaluation starts from the following conguration: [gs0 | (lms0 , vp0 , B M ts0 )] From BF Ok(B) we know that evolution of this conguration: Diverges or gets stuck due to incorrect send/recv pairing, or gets to a conguration: [gsn | (lmsn , vpn , RT Err) therefore the lemma holds. Gets to a conguration: [gsn | (lmsn , vpn , return; tsn M ts0 ) (lmsk,n , vpk,n , tsk,n )] (lmsk,n , vpk,n , tsk,n )]

By application of OP-ReturnVoid, the 0-th process gets to a conguration: [gsn | (lmsn , vpn , none, therefore the lemma holds. Gets to a conguration: [gsn | (lmsn , vpn , return v; tsn M ts0 ) (lmsk,n , vpk,n , tsk,n )]
void

ts0 )

(lmsk,n , vpk,n , tsk,n )]

By application of OP-ReturnValue, the 0-th process gets to a conguration: [gsn | (lmsn , vpn , v ts0 ) therefore the lemma holds. (lmsk,n , vpk,n , tsk,n )]

89

9.3. TYPE PRESERVATION We want to prove that for any expression E, the predicate ExpOk(E) is satised. We do this by dening inductive syntactic predicates ExpOki and BF Oki with respect to the structure of E and B, respectively. The dependency is the following (a b means a is dependent on b): ExpOk0 o BF Ok0 o ExpOk1 o ... o ExpOki o BF Oki o

Denition 9.3.4. Let E be an expression, B be a block-forming statement. We dene predicates ExpOk0 (E) and BF Ok0 (B) : ExpOk0 (E) E does not contain I(E) as its subexpression. BF Ok0 (B) B contains only such subexpressions E which satisfy ExpOk0 (E). For any i N0 , we further dene predicates ExpOki+1 (E) and BF Oki+1 (B) : ExpOki+1 (E) For any subexpression E0 of E, ExpOki (E0 ) is satised or E0 = I(E) and BF Oki (MB (I)) is satised. BF Oki+1 (B) B contains only such subexpressions E which satisfy ExpOki+1 (E). Next we show the connection between the syntactic predicates ExpOki (E) (BF Oki (E)) and their semantic counterparts ExpOk (BF Ok). Lemma 9.3.5. Let E be an expression such that ExpOk0 (E). Then ExpOk(E) is satised. Proof. By induction on the structure of E. Let C0 = [gs0 | (lms0 , vp0 , E ts0 )] : be any conguration. Base case: Case E = v: ExpOk(v) trivially. Case E = I: By application of OP-Var we reach conguration [gs | (lms, vp, v ts0 )], hence ExpOk(E). Case E = new T(): By application of OP-AllocC/OP-AllocQ reaches conguration [gs | (lms, vp, v ts0 )], hence ExpOk(E). Case E = I = v: By application of OP-AssignNewValue/OP-AssignQAValue/ OP-AssignQValue/OP-AssignValue we reach conguration [gs | (lms, vp, v ts0 )], hence ExpOk(E); by application of OP-AssignQAValueBad we reach conguration [gs | (lms, vp, ISQV)], hence ExpOk(E). Case E = recv(v): By application of OP-SendRecv we reach conguration [gs | (lms, vp, v ts0 )], hence ExpOk(E); by application of OP-RecvUninit we reach conguration [gs | (lms, vp, UV)], hence ExpOk(E). If there is no corresponding send statement, the conguration gets stuck due to incorrect send/recv pairing. Case E = measure(v): By subsequent application of rules OP-DoMeasure and NP-ProbEvol we reach conguration [gs | (lms, vp, v ts0 )], hence ExpOk(E); by application of OP-MeasureUninit we reach conguration [gs | (lms, vp, UV)], hence ExpOk(E); by application of OP-MeasureOverlap we reach conguration [gs | (lms, vp, OQV)], hence ExpOk(E). 90

CHAPTER 9. TYPE SOUNDNESS Next we assume that the lemma holds for all subexpressions E0 of E (inductive hypotesis, IH). Then: Case E = (E0 ): By application of OP-Bracket we reach conguration [gs | (lms, vp, E0 ts0 )] for which the theorem holds by the inductive hypothesis. Hence ExpOk(E). Case E = I = E0 : We get the following evolution: [gs0 | (lms0 , vp0 , I = E0 ts0 )] [gs0 | (lms0 , vp0 , E0 I = ts0 )]
OP-SubstE IH OP-AssignExpr

[gsn | (lmsn , vpn , v I = ts0 )] [gsn | (lmsn , vpn , I = v ts0 )]

The last conguration is one of the base cases for which the lemma holds. Hence ExpOk(E). Case E = recv(E0 ): We get the following evolution: [gs0 | (lms0 , vp0 , recv(E0 ) ts0 )] [gs0 | (lms0 , vp0 , E0 recv( ) ts0 )]
OP-SubstE IH OP-RecvExpr

[gsn | (lmsn , vpn , v recv( ) ts0 )] [gsn | (lmsn , vpn , recv(v) ts0 )]

The last conguration is one of the base cases for which the lemma holds. Hence ExpOk(E). Case E = measure(E0 , . . . ,Ee ): We get the following evolution: [gs0 | (lms0 , vp0 , measure(E0 , . . . ,Ee ) ts0 )] [gs0 | (lms0 , vp0 , E0 measure( , . . . ,Ee ) ts0 )] . . .
OP-MeasureExpr OP-SubstE IH OP-MeasureExpr

[gsn | (lmsn , vpn , v0 measure( , . . . ,Ee ) ts0 )] [gsn | (lmsn , vpn , measure(v0 , . . . ,Ee ) ts0 )]

[gsn | (lmsn , vpn , Ee measure(v0 , . . . , ) ts0 )]


OP-SubstE IH

[gsn | (lmsn , vpn , ve measure(v0 , . . . , ) ts0 )] [gsn | (lmsn , vpn , measure(v0 , . . . ,ve ) ts0 )]

The last conguration is one of the base cases for which the lemma holds. Hence ExpOk(E).

Lemma 9.3.6. Let B be a block-forming statement such that BF Ok0 (B). Then BF Ok(B) is satised. Proof. By induction on the structure of B. Let C0 = [gs0 | (lms0 , vp0 , B ts0 )] : be any conguration. Base case: Case B = return v;: BF Ok(return v;) trivially. Case B = return E;: We get the following evolution: 91

9.3. TYPE PRESERVATION [gs0 | (lms0 , vp0 , return E; ts0 )] [gs0 , |, (lms0 , vp0 , E return ; ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , v return ; ts0 )]
OP-SubstS Lemma 9.3.5 OP-ReturnExpr

[gsn | (lmsn , vpn , return v; ts0 )]

In the last step we see that BF Ok(B). Case B = return;: BF Ok(return;) trivially. Case B = ;: By application of OP-Skip we reach conguration [gs0 | (lms0 , vp0 , ts0 )], hence BF Ok(B). Case B = v;: By application of OP-PromoForget [gs0 | (lms0 , vp0 , ts0 )], hence BF Ok(B). Case B = P E;: We get the following evolution: [gs0 | (lms0 , vp0 , P E; ts0 )] [gs0 , |, (lms0 , vp0 , P E ; ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , v ; ts0 )]
OP-SubstS Lemma 9.3.5 OP-PromoExpr

we

reach

conguration

[gsn | (lmsn , vpn , v; ts0 )]

The last conguration is exactly the previous case for which the lemma holds. Case B = L : By application of OP-BlockEnd we reach conguration [gs0 | (lms0 , vpn , ts0 )], hence BF Ok(B). Case B = fork I(v0 , . . . ,ve );: By application of OP-DoFork we reach conguration [gs0 | (lms0,0 , vp0 , ts0 ) (lms1,0 , , I(v0 , . . . ,ve )], hence BF Ok(B). Case B = fork I(E0 , . . . ,Ee );: We get the following evolution: [gs0 | (lms0 , vp0 , fork I(E0 , . . . ,Ee ); ts0 )] [gs0 , |, (lms0 , vp0 , E0 fork I( , . . . ,Ee ); ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , v0 fork I( , . . . ,Ee ); ts0 )] . . .
OP-ForkExpr Lemma 9.3.5 OP-SubstS Lemma 9.3.5 OP-ForkExpr

[gsn | (lmsn , vpn , fork I(v0 , . . . ,Ee ); ts0 )]

[gsn , |, (lmsn , vpn , Ee fork I(v0 , . . . , ); ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , ve fork I(v0 , . . . , ); ts0 )]
OP-SubstS

[gsn | (lmsn , vpn , fork I(v0 , . . . ,ve ); ts0 )]

The last conguration is exactly the previous case for which the lemma holds. Case B = send(vc ,vv );: If there is no corresponding recv statement, the conguration gets stuck due to incorrect send/recv pairing, therefore the lemma holds. Otherwise, by application of OP-SendRecv we reach conguration [gs0 | (lmsn , vp0 , ts0 )], hence 92

CHAPTER 9. TYPE SOUNDNESS BF Ok(B); by application of OP-SendUninit [gs0 | (lms0 , vp0 , UV)], hence BF Ok(B). Case B = send(Ec ,Ev );: We get the following evolution: [gs0 | (lms0 , vp0 , send(Ec ,Ev ); ts0 )] [gsa , |, (lmsa , vpa , Ec send(,Ev ); ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , vc send( ,Ev ); ts0 )]
OP-SendExpr2 Lemma 9.3.5 OP-SubstS Lemma 9.3.5 OP-SendExpr1

we

reach

conguration

[gsn | (lmsn , vpn , send(vc ,Ev ); ts0 )]

[gsn , |, (lmsn , vpn , Ev send(vc , ); ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , vv send(vc , ); ts0 )]
OP-SubstS

[gsn | (lmsn , vpn , send(vc ,vv ); ts0 )]

The last conguration is exactly the previous case for which the lemma holds. Case B = T I;: By possibly multiple application of OP-VarDeclMulti and OP-VarDecl we reach conguration [gs0 | (lms0 , vpn , ts0 )], hence BF Ok(B). Case B = channel[T ] I withends[I,I];: By application of OP-VarDeclChE we reach conguration [gs0 | (lms0 , vpn , ts0 )], hence BF Ok(B). Case B = I aliasfor [I];: By application of OP-VarDeclAlF we reach conguration [gs0 | (lms0 , vpn , ts0 )], hence BF Ok(B). In the second part of the proof, we assume that the lemma holds for all substatements Be0 of B (inductive hypotesis, IH). Then: Case B = Be0 Be1 . . . Bem for m 1: We get the following evolution: [gs0 | (lms0 , vp0 , Be0 Be1 . . . Bem ts0 )] [gs0 | (lms0 , vp0 , Be0 Be1 . . . Bem ts0 )] or or or or
OP-BlockHead IH OP-BlockHead

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds [gsn | (lmsn , vpn , return; Be1 . . . Bem ts0 )] ie. the lemma holds [gsn | (lmsn , vpn , return v; Be1 . . . Bem ts0 )] ie. the lemma holds diverges or gets stuck ie. the lemma holds [gsn | (lmsn , vpn , Be1 . . . Bem ts0 )] . . . [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds [gsn | (lmsn , vpn , return; Bem ts0 )] ie. the lemma holds [gsn | (lmsn , vpn , return v; Bem ts0 )] ie. the lemma holds diverges or gets stuck ie. the lemma holds [gsn | (lmsn , vpn , Bem ts0 )]

[gsn | (lmsn , vpn , Bem1 Bem ts0 )] or or or or


IH IH

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , return; ts0 )] ie. the lemma holds 93

9.3. TYPE PRESERVATION or [gsn | (lmsn , vpn , return v; ts0 )] ie. the lemma holds or diverges or gets stuck ie. the lemma holds or [gsn | (lmsn , vpn , ts0 )] Therefore the lemma holds for this case. Case B = if (v) S1 else S2 : Depending on v, the evolution continues by rule OP-IfTrue to conguration [gs0 | (lms0 , vp0 , S1 ts0 )], or by rule OP-IfFalse to conguration [gs0 | (lms0 , vp0 , S2 ts0 )]. By IH, we assume that the lemma holds for both S1 and S2 , ie. the lemma holds for this case. Case B = if (E) S1 else S2 : We get the following evolution: [gs0 | (lms0 , vp0 , if (E) S1 else S2 ts0 )]
Lemma 9.3.5 OP-SubstS OP-IfExpr

[gs0 | (lms0 , vp0 , E if ( ) S1 else S2 ts0 )]

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or [gsn | (lmsn , vpn , v if ( ) S1 else S2 ts0 )] [gsn | (lmsn , vpn , if (v) S1 else S2 ts0 )]

The last conguration is exactly the previous case for which the lemma holds. Case B = { B }: We get the following evolution: [gs0 | (lms0 , vp0 , { B } ts0 )]
IH OP-Block

[gs0 | (lms0 , vp0 , B L ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds [gsn | (lmsn , vpn , return; tsn L ts0 )] ie. the lemma holds [gsn | (lmsn , vpn , return v; tsn L ts0 )] ie. the lemma holds diverges or gets stuck ie. the lemma holds [gsn | (lmsn , vpn , L ts0 )]

or or or or
OP-BlockEnd

[gsn | (lmsn , vpn , ts0 )] Therefore the lemma holds for this case. Case B = while (E) S: We get the following evolution: [gs0 | (lms0 , vp0 , while (E) S ts0 )]
see if case OP-While

[gs0 | (lms0 , vp0 , if (E) {S while (E) S} else ; ts0 )]

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or diverges or gets stuck ie. the lemma holds or [gsn | (lmsn , vpn , if (v) {S while (E) S} else ; ts0 )]

Depending on v, the evaluation continues either this way: [gsn | (lmsn , vpn , ; ts0 )]
OP-Skip OP-IfFalse

[gsn | (lmsn , vpn , ts0 )]

so the lemma holds for this case; or the evaluation continues as follows: 94

CHAPTER 9. TYPE SOUNDNESS


OP-BlockHead OP-Block OP-IfTrue

[gsn | (lmsn , vpn , {S while (E) S} ts0 )] [gsn | (lmsn , vpn , S while (E) S L ts0 )] [gsn | (lmsn , vpn , RT Err)] ie. the lemma holds [gsn | (lmsn , vpn , return; tsn L ts0 )] ie. the lemma holds [gsn | (lmsn , vpn , return v; tsn L ts0 )] ie. the lemma holds diverges or gets stuck ie. the lemma holds [gsn | (lmsn , vpn , while (E) S L ts0 )]

[gsn | (lmsn , vpn , S while (E) S L ts0 )] or or or or


IH

Therefore it is possible that evaluation of while statement continues forever. This is the statement of the lemma, hence the lemma holds even for this case.

Lemma 9.3.7. Let E be an expression such that ExpOki+1 (E). Then ExpOk(E) is satised. Proof. The proof proceeds similarly to the proof of Lemma 9.3.5. We must only add the following two cases: Case E = I(v): From ExpOki+1 we know that the predicate BF Oki (MB (I)) is satised, hence by Lemmata 9.3.8 for BF Oki and 9.3.3, the predicate StkRetOk(MB (I)) is satised (). We get the following evolution: [gs0 | (lms0 , vp0 , I(v) ts0 ] [gsn | (lmsn , vpn , MB (I) M ts0 )]
() OP-DoMethodCallCl

[gsn | (lms0,n , vp0,n , RT Err) (lmsk,n , vpk,n , tsk,n )] or [gsn | (lms0,n , vp0,n , v ts0 ) (lmsk,n , vpk,n , tsk,n )] or diverges or gets stuck

Therefore the lemma holds, ExpOk(E). Case E = I(E0 , . . . ,Ee ): By induction on the structure of E: Assume that the lemma holds for all E0 , . . . , Ee (inductive hypotesis, IH). We get the following evolution: [gs0 | (lms0 , vp0 , I(E0 , . . . ,Ee ) ts0 )] [gs0 | (lms0 , vp0 , E0 I( , . . . ,Ee ) ts0 )] . . .
OP-MethodCallExpr OP-SubstE IH OP-MethodCallExpr

[gsn | (lmsn , vpn , v0 I(, . . . , Ee ) ts0 )] [gsn | (lmsn , vpn , I(v0 , . . . , Ee ) ts0 )]

[gsn | (lmsn , vpn , Ee I(v0 , . . . , ) ts0 )]


OP-SubstE IH

[gsn | (lmsn , vpn , ve I(v0 , . . . , ) ts0 )] [gsn | (lmsn , vpn , I(v0 , . . . ,ve ) ts0 )]

The last conguration is one of the base cases for which the lemma holds. Hence ExpOk(E).

Lemma 9.3.8. Let B be a block-forming statement such that BF Oki+1 (B). Then BF Ok(B) is satised. 95

9.3. TYPE PRESERVATION Proof. The proof is nearly identical to the proof of Lemma 9.3.6. We only exchange all usages of Lemma 9.3.5 for evaluation of expression E by Lemma 9.3.7 for ExpOki (E). Corollary 9.3.9. For any at most countably derivable expression E, ExpOk(E) is satised. For any at most countably derivable block-forming statement B, BF Ok(B) is satised. Informally, as the programs are always countably derivable, we have proved the following: Unless a runtime error occurs, the evaluation of an expression E never modies term stack elements under the evaluated expression. If the evaluation does not diverge and does not get to a stuck conguration due to incorrect send/recv pairing, the expression E always yields an internal value, Unless a runtime error occurs, the evaluation of a block-forming statement B never modies term stack elements under the evaluated statement if it does not get to a return statement. In that case, it pops all the elements from the term stack up to the rst occurence of the symbol M . Lemma 9.3.10. Let B be a block-forming statement such that RetOk(B). For any conguration C0 = [gs0 | (lms0 , vp0 , B ts0 )] : , the evaluation either diverges or gets stuck due to incorrect send/recv pairing, or reaches one of the following congurations: [gsn | (lms0,n , vp0,n , return; ts0,n ts0 ) contain M , or (lmsk,n , vpk,n , tsk,n )], k 0, ts0,n does not (lmsk,n , vpk,n , tsk,n )], k 0, ts0,n does

[gsn | (lms0,n , vp0,n , return v; ts0,n ts0 ) not contain M , or [gsn | (lms0,n , vp0,n , RT Err)

(lmsk,n , vpk,n , tsk,n )], k 0.

Proof. By induction on the structure of B. Let C0 = [gs0 | (lms0 , vp0 , B ts0 )] : be any conguration. Base case: Case B = return v;: The lemma holds trivially. Case B = return E;: We get the following evolution: [gs0 | (lms0 , vp0 , return E; ts0 )] [gs0 , |, (lms0 , vp0 , E return ; ts0 )]
ExpOk(E) OP-ReturnExpr

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or diverges or gets stuck ie. the lemma holds or [gsn | (lmsn , vpn , v return ; ts0 )] [gsn | (lmsn , vpn , return v; ts0 )]

OP-SubstS

In the last step we see we get requested conguration, hence the lemma holds. Case B = return;: The lemma holds trivially. Next we assume that the lemma holds for all substatements Be of B such that RetOk(Be) (inductive hypotesis, IH). Then: 96

CHAPTER 9. TYPE SOUNDNESS Case B = Be0 Be1 . . . Bem for m 1: We know that there is at least one j such that RetOk(Bej ). Let b be smallest such j. Moreover, BF Ok(Bei ) for 0 i m. We get the following evolution: [gs0 | (lms0 , vp0 , Be0 Be1 . . . Bem tsa )] [gs0 | (lms0 , vp0 , Be0 Be1 . . . Bem ts0 )] or or or or
OP-BlockHead BF Ok(Be0 ) OP-BlockHead

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds [gsn | (lmsn , vpn , return; Be1 . . . Bem ts0 )] ie. the lemma holds [gsn | (lmsn , vpn , return v; Be1 . . . Bem ts0 )] ie. the lemma holds diverges or gets stuck ie. the lemma holds [gsn | (lmsn , vpn , Be1 . . . Bem ts0 )] . . .

[gsn | (lmsn , vpn , Beb ts0,n ts0 )] By IH, the lemma holds for the last conguration, therefore it holds for this case. Case B = if (v) S1 else S2 : Depending on v, the evolution continues by rule OP-IfTrue to conguration [gs0 | (lms0 , vp0 , S1 ts0 )], or by rule OP-IfFalse to conguration [gs0 | (lms0 , vp0 , S2 ts0 )]. By denition of RetOk, both RetOk(S1 ) and RetOk(S2 ) are satised. By IH, the lemma holds for this case. Case B = if (E) S1 else S2 : We get the following evolution: [gs0 | (lms0 , vp0 , if (E) S1 else S2 ts0 )]
ExpOk(E) OP-IfExpr

[gs0 | (lms0 , vp0 , E if ( ) S1 else S2 ts0 )]

[gsn | (lmsn , vpn , RT Err)] ie. the lemma holds or diverges or gets stuck ie. the lemma holds or [gsn | (lmsn , vpn , v if ( ) S1 else S2 ts0 )] [gsn | (lmsn , vpn , if (v) S1 else S2 ts0 )]

OP-SubstS

The last conguration is exactly the previous case for which the lemma holds. Case B = { B }: We get the following evolution: [gs0 | (lms0 , vp0 , { B } ts0 )] [gs0 | (lms0 , vp0 , B L ts0 )] By IH, the lemma holds for the last conguration, therefore it holds for this case.
OP-Block

Informally, for any block-forming statement B such that RetOk(B), we have proved the following: Unless a runtime error occurs, the evaluation of B always leads to a return statement or diverges or gets stuck due to incorrect send/recv pairing.

9.3.2

Type preservation lemmata

In the previous section, we have proved that for any well-typed conguration C0 : , there exists a conguration C1 such that C0 C1 . The next step in proving type soundness is to prove that any such one-step evaluation preserves the type of the conguration. Formally, 97

9.3. TYPE PRESERVATION that the conguration C1 is well-typed, C1 : , and that = in the case of single processevolution or = for some type in the case of the fork statement. In all cases, the type of the original processes is preserved. We prove type preservation of the transition relation by proving it for its components: v (Lemma 9.3.11), e (Lemma 9.3.12), p (Lemmata 9.3.13 and 9.3.14), r (Lemma 9.3.15), s (Lemma 9.3.16), and ret (Lemma 9.3.17). We do not consider the rte transition which performs transitions to runtime errors. Therefore we only prove weak type soundness, ie. that the evolution never gets to a stuck conguration because of a type error. Lemma 9.3.11 (Type preservation for v ). Let C0 = [gs0 | (lms0 , vp0 , T E ts0 )], C1 = q i=1 pi Ci,1 where Ci,1 = [gsi,1 | (lmsi,1 , vpi,1 , T Ei tsi,1 )] be two congurations such that C0 v C1 . If C0 : then Ci,1 : for all i. Proof. From C0 : we know:
(1) (2) T-rule M ; C (lms0 , vp0 , ts0 ) : M ; vpContext(vp0 ) T T E : TC-ExprClo M ; C (lms0 , vp0 , T E ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , T E ts0 )] :

where the T-rule is a typechecking rule used to derive the type of T E. For each i = 1, . . . , n, we want to prove Ci,1 : :
(premises of the T-rulei ) (3) T-rulei M ; vpContext(vpi,1 ) T T Ei : i M ; C (lmsi,1 , vpi,1 , tsi,1 ) : i TC-ExprClo M ; C (lmsi,1 , vpi,1 , T Ei tsi,1 ) : void T-Config M ; [gsi,1 | (lmsi,1 , vpi,1 , T Ei tsi,1 )] :

where the T-rulei is a typechecking rule used to derive the type i of T Ei . As v rules change the top stack element only, ts0 = tsi,1 for all i. Therefore we must only prove that = i . We do this by case examination of the relation v . OP-AllocC: T E : channel[T] from T-Alloc. T Ei = R, v from T-Value. OP-AllocQ: T E : qd it from T-Alloc. T Ei = R, v
qdit , channel[T] ,

thus T Ei : channel[T]

thus T Ei : qd it from T-Value.

OP-AssignNewValue, OP-AssignQAValue, OP-AssignQValue, OP-AssignValue: T E : T from T-Assign. T Ei = R, v T , thus T Ei : T from T-Value. OP-DoMeasure: T E : int from T-Measurement. T Ei = from T-Value. none, vi
int ,

thus T Ei : int

OP-DoMethodCallQ: As all methods representing quantum operators are regarded as method with return type void, T E : void from T-MethodCall. T Ei = none, void , thus T Ei : void from T-Value. OP-Var: T E = x : T from T-Var, hence vpContext(vp0 )(x) = T. T Ei = R, vx typeOf (x ,vpi,1 ) , thus T Ei : typeOf (x, vpi,1 ) from T-Value. We know that vp0 = vpi,1 as rule OP-Var does not modify variable properties. By denition of vpContext, typeOf (x, vpi,1 ) = T vpContext(vpi,1 )(x) = T. 98

CHAPTER 9. TYPE SOUNDNESS

Lemma 9.3.12 (Type preservation for e ). Let C0 = [gs0 | (lms0 , vp0 , T E0 ts0 )], C1 = [gs1 | (lms1 , vp1 , ts1 )] be two congurations such that C0 e C1 . If C0 : then C1 : . Proof. We prove this lemma for each rule of relation e : OP-MethodCallExpr T E0 = m(v,E,E). From C0 : we know:
(5) (lms0 , vp0 , ts0 ) : TC-ExprClo T-Config

(4) M; M;
C

M;

(lms0 , vp0 , m(v,E,E) ts0 ) : void [gs0 | (lms0 , vp0 , m(v,E,E) ts0 )] :

where (4) is:


(7) M ; vpContext(vp0 ) M ; vpContext(vp0 )
T

(6)

E:

(8) T-MethodCall

m(v,E,E) :

We want to prove C1 : :
(9) M ; vpContext(vp0 ) M; M;
C

E:

(10) TC-ExprClo T-Config

(lms0 , vp0 , E m(v, ,E) ts0 ) : void [gs0 | (lms0 , vp0 , E m(v, ,E) ts0 )] :

where (10) is (here we denote vpc = vpContext(vp0 )):


(11) M ; vpc, :
T T

(12) M;
C

M ; vpc, :

m(v, ,E) :
C

(13) (lms0 , vp0 , ts0 ) : TC-ExprHole

M;

(lms0 , vp0 , m(v, ,E) ts0 ) :

Realizing that (9) = (7), (11) = (6), (12) = (8), and (13) = (5) nishes the proof. OP-AssignExpr, OP-IfExpr, OP-MeasureExpr, OP-PromoExpr, OP-RecvExpr, OP-SendExpr1, OP-SendExpr2 The proof is a straightforward alteration of the proof of OP-MethodCallExpr. OP-ForkExpr T E0 = fork m(v,E,E);. From C0 : we know:
(15) (lms0 , vp0 , ts0 ) : void TC-StatClo T-Config

(14) M; M;
C

M;

(lms0 , vp0 , fork m(v,E,E); ts0 ) : void [gs0 | (lms0 , vp0 , fork m(v,E,E); ts0 )] :

where (14) is (here we denote vpc = vpContext(vp0 )): 99

9.3. TYPE PRESERVATION


(17) M ; vpc T E : M ; vpc
T

(16)

(18) T-MethodCall
T

m(v,E,E); : M ; vpc

m is a classical method T-Fork

fork m(v,E,E); : void

We want to prove C1 : :
(19) M ; vpContext(vp0 ) M; M;
C

E:

(20) TC-ExprClo T-Config

(lms0 , vp0 , E fork m(v, ,E); ts0 ) : void [gs0 | (lms0 , vp0 , E fork m(v, ,E); ts0 )] :

where (20) is (here we denote vpc = vpContext(vp0 )):


(21) M ; vpc, :
T T

(22) M; (23) (lms0 , vp0 , ts0 ) : void TC-StatHole

M ; vpc, : M ; vpc, :
T

m(v, ,E); :
C

fork m(v, ,E); : void


C

M;

(lms0 , vp0 , fork m(v, ,E); ts0 ) :

Realizing that (19) = (17), (22) = (18), (21) = (16), and (23) = (15) nishes the proof. OP-ReturnExpr T E0 = return E;. We know that vp0 = vp1 = [vpG G vp], ts0 = . . . M tsr . Denote by = typeOf (@retV al, vp1 ). From C0 : we know:
(24) (25) M ; vpContext(vp0 ) T E : M ; C (lms0 , vpG , tsr ) : TC-RetExpr M ; C (lms0 , vp0 , return E; . . . M tsr ) : void T-Config M ; [gs0 | (lms0 , vp0 , return E; . . . M tsr )] :

We want to prove C1 : :
(26) M ; vpContext(vp0 ) T E : (27) TC-ExprClo M ; C (lms0 , vp0 , E return ; . . . M tsr ) : void T-Config M ; [gs0 | (lms0 , vp0 , E return ; . . . M tsr )] :

where (27) is:


(28) M ; C (lms0 , vpG , tsr ) : TC-RetHole (lms0 , vp0 , return ; . . . M tsr ) : void

M;

Realizing that (26) = (24), and (28) = (25) nishes the proof. OP-DoMethodCallCl T E0 = m(v). From C0 : we know:
(30) (29) M ; C (lms0 , vp0 , ts0 ) : TC-ExprClo M ; C (lms0 , vp0 , m(v0 , . . . ,vn ) ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , m(v0 , . . . ,vn ) ts0 )] :

100

CHAPTER 9. TYPE SOUNDNESS where (29) is inferred by rule T-MethodCall:


M ; vpContext(vp0 )
T

MT (m) = 0 , . . . , n M ; vpContext(vp0 )
T

(31)

(32) M ; vpContext(vp0 ) m(v0 , . . . ,vn ) :

v0 : 0

We want to prove C1 : :
(33) T-Block M ; vpContext([vp0 G [ L vpM ]]) T MB (m) : void (34) TC-StatClo M ; C (lms0 , [vp0 G [ L vpM ]], MB (m) M ts0 ) : void T-Config M ; [gs0 | (lms0 , [vp0 G [ L vpM ]], MB (m) M ts0 )] :

where M = (MT , MH , MB ) and (34) is:


(35) (lms0 , vp0 , ts0 ) : typeOf (@retV al, [vp0 G [ L vpM ]]) C TC-RetImpl M ; C (lms0 , [vp0 G [ L vpM ]], M ts0 ) :

M;

Method body is always a block. This justies usage of rule T-Block. To see that the premises (35) and (30) specify the same proof, we recall the premise (31): the return type of method m is . From the denition of rule OP-DoMethodCallCl we get that typeOf (@retV al, [vp0 G [ L vpM ]]) = . This nishes the proof. OP-SubstE T E0 = v, moreover the symbol under the top element is Ec. From C0 : we know:
T-Value M ; T r, v T : T (36) (37) TC-ExprClo M ; C (lms0 , vp0 , v Ec ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , v Ec ts0 )] :

where (37) is:


(39) (38) M ; vpContext(vp0 ), : T T Ec : M ; C (lms0 , vp0 , ts0 ) : TC-ExprHole M ; C (lms0 , vp0 , Ec ts0 ) : T

We want to prove C1 : :
(41) (40) M ; vpContext(vp0 ) T Ec[v] : M ; C (lms0 , vp0 , ts0 ) : TC-ExprClo M ; C (lms0 , vp0 , Ec[v] ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , Ec[v] ts0 )] :

From the premise (36), we know v : T. The substitution of v in place of is just an -conversion that does not change type ( : T). Indeed, (41) = (39), and (40) = (38) what nishes the proof. OP-SubstS The proof is a straightforward alteration of the proof of OP-SubstE. 101

9.3. TYPE PRESERVATION

Lemma 9.3.13 (Type preservation for OP-DoFork). Let C0 = [gs0 | (lms0 , vp0 , fork m(v); ts0 )], C1 = [gs1 | (lms1,1 , vp1,1 , ts1,1 )
OP-DoFork

(lms1,2 , vp1,2 , ts1,2 )]

be two congurations such that C0 p C1 . If C0 : then C1 : . Proof. From C0 : we know:


(42) T-MethodCall M ; T m(v) : T (43) T-Fork M ; T fork m(v); : void M ; C (lms0 , vp0 , ts0 ) : void TC-StatClo M ; C (lms0 , vp0 , fork m(v); ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , fork m(v); ts0 )] :

We want to prove C1 : :
(44) M ; C (lms1,1 , vp0 , ts0 ) : void (45) T-Config M ; [gs0 | (lms1,1 , vp0 , ts0 ) (lms1,2 , vp1,2 , ts1,2 )] :

where (45) is:


(46) M;
T

m(v ) : T

T-MethodCall
C

M;

(lms1,2 , , ) : T

M;

(lms1,2 , , m(v )) : void

TC-Empty TC-ExprClo

By inspecting the denition of the rule OP-DoFork we see that the transformation from v to v preserves typing of individual internal values. Moreover, the method typing context M used in the premises (46) and (42) is the same. Hence (46) = (42) and = T. Realizing that (44) = (43) nishes the proof. Lemma 9.3.14 (Type preservation for OP-SendRecv). Let C0 = [gs0 | (lms0,1 , vp0,1 , send(vs ,vv ); ts0,1 ) C1 = [gs1 | (lms1,1 , vp1,1 , ts1,1 ) (lms0,2 , vp0,2 , recv(vr ) ts0,2 )],

(lms1,2 , vp1,2 , ts1,2 )]

be two congurations such that C0 p C1 . If C0 : then C1 : . Proof. From C0 : by rule T-Config we know:
(48) (47) M ; C (lms0,1 , vp0,1 , ts0,1 ) : void TC-StatClo M ; C (lms0,1 , vp0,1 , send(vs , vv ); ts0,1 ) : void

OP-SendRecv

where (47) is (here we denote vpc0,1 = vpContext(vp0,1 )):


M ; vpc0,1
T

T-Value vs : channelEnd[v ] M ; vpc0,1 M ; vpc0,1 T send(vs , vv ); : void

vv : v

T-Value T-Send

102

CHAPTER 9. TYPE SOUNDNESS and (here we denote vpc0,2 = vpContext(vp0,2 )):

T-Value M ; vpc0,2 T vr : channelEnd[ ] (49) T-Recv M ; vpc0,2 T recv(vr ) : M ; C (lms0,1 , vp0,2 , ts0,2 ) : TC-ExprClo M ; C (lms0,2 , vp0,2 , recv(vr ) ts0,2 ) : void

We want to prove C1 : :
(50) M ; C (lms1,1 , vp0,1 , ts0,1 ) : void (51) T-Config [gs0 | (lms1,1 , vp0,1 , ts0,1 ) (lms1,2 , vp1,2 , vv ts1,2 )] :

M;

where (51) is (here we denote vpc1,2 = vpContext(vp1,2 )):


(52) M ; C (lms1,2 , vp0,2 , ts0,2 ) : TC-ExprClo (lms1,2 , vp0,2 , vv ts0,2 ) : void

M ; vpc1,2

vv : M;

T-Value
C

By inspecting the denition of rule OP-SendRecv we see that vs and vr are ends of the same channel, hence their types match. Therefore, = v . Indeed, = v . As changes in local memory state do not change type of internal values, (52) = (49). Realizing that (50) = (48) nishes the proof.

Lemma 9.3.15 (Type preservation for r ). Let C0 = [gs0 | (lms0 , vp0 , T E0 ts0 )], C1 = [gs1 | (lms1 , vp1 , ts1 )] be two congurations such that C0 r C1 . If C0 : then C1 : . Proof. We prove this lemma for each rule of relation r : OP-BlockHead T E0 = Be = Be0 Be1 . . . Ben where n 1. From C0 : we know:
(53) (lms0 , vp0 , Be0 Be1 . . . Ben ts0 ) : void
C

M;

M; M;

(lms0 , vp0 , Be ts0 ) : void [gs0 | (lms0 , vp0 , Be ts0 )] :

TC-BlockHead T-Config

We want to prove C1 : :
(54) (lms0 , vp0 , Be0 Be1 . . . Ben ts0 ) : void T-Config [gs0 | (lms0 , vp0 , Be0 Be1 . . . Ben ts0 )] :

M; C M;

Indeed, (53) = (54). 103

9.3. TYPE PRESERVATION OP-Bracket T E0 = (E). From C0 : we know:


(55) M ; vpContext(vp0 ) M ; vpContext(vp0 ) (56) E: T-Bracket M ; C (lms0 , vp0 , ts0 ) : T (E) : TC-ExprClo M ; C (lms0 , vp0 , (E) ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , (E) ts0 )] :
T

We want to prove C1 : :
(57) (58) M ; vpContext(vp0 ) T E : M ; C (lms0 , vp0 , ts0 ) : TC-ExprClo M ; C (lms0 , vp0 , E ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , E ts0 )] :

Indeed, (57) = (55), and (58) = (56). OP-VarDeclMulti T E0 = T I0 ,I1 , . . . ,In ;. From C0 : we know:
(59) M ; C (lms0 , vp0 , T I0 ; T I1 , . . . ,In ; ts0 ) : void TC-VarDeclMulti M ; C (lms0 , vp0 , T I0 ,I1 , . . . , In ; ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , T I0 ,I1 , . . . ,In ; ts0 )] :

We want to prove C1 : :
(60) (lms0 , vp0 , T I0 ; T I1 , . . . ,In ; ts0 ) : void T-Config [gs0 | (lms0 , vp0 , T I0 ; T I1 , . . . ,In ; ts0 )] :

M; C M;

Indeed, (60) = (59). OP-While T E0 = while (E) S. From C0 : we know:


(62) (61) M ; C (lms0 , vp0 , ts0 ) : void TC-StatClo M ; C (lms0 , vp0 , while (E) S ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , while (E) S ts0 )] :

where (61) is (here we denote vpc = vpContext(vp0 )):


(63) (64) M ; vpc T E : bool M ; vpc T S : void T-While M ; vpc T while (E) S : void

We want to prove C1 : : 104

CHAPTER 9. TYPE SOUNDNESS


(66) (65) M ; C (lms0 , vp0 , ts0 ) : TC-StatClo (lms0 , vp0 , if (E) {S while (E) S} else ; ts0 ) : void T-Config [gs0 | (lms0 , vp0 , if (E) {S while (E) S} else ; ts0 )] :

M; C M;

where (65) is (here we denote vpc = vpContext(vp0 )):


(68) (67) E : bool M ; vpc T {S while (E) S} : void M ; vpc T M ; vpc T if (E) {S while (E) S} else ; : void T-Skip T-If

M ; vpc

; : void

where (68) is by T-Block (here we again denote vpc = vpContext(vp0 )):


(70) (71) M ; vpc T E : bool M ; vpc T S : void T-While while (E) S : void T-BlockHead S while (E) S : void

M ; vpc

(69) T S : void M ; vpc

Indeed, (67) = (70) = (63), (69) = (71) = (64), and (66) = (62).

Lemma 9.3.16 (Type preservation for s ). Let C0 = [gs0 | (lms0 , vp0 , T E0 ts0 )], C1 = [gs1 | (lms1 , vp1 , ts1 )] be two congurations such that C0 s C1 . If C0 : then C1 : . Proof. We prove this lemma for each rule of relation s : OP-Block T E0 = {B}. From C0 : we know (here we denote vpc = vpContext([vpG G vp])):
(72) (73) T B : void T-Block {B} : void M ; C (lms0 , [vpG G vp], ts0 ) : void T TC-StatClo M ; C (lms0 , [vpG G vp], {B} ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G vp], {B} ts0 )] :

M ; vpc M ; vpc

We want to prove C1 : :
(74) M ; vpContext([vpG G [vp L ]]) T B : void (75) TC-StatClo M ; C (lms0 , [vpG G [vp L ]], B L ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G [vp L ]], B L ts0 )] :

where (75) is:


(76) M ; C (lms0 , [vpG G vp], ts0 ) : void TC-BlockEnd M ; C (lms0 , [vpG G [vp L ]], L ts0 ) : void

105

9.3. TYPE PRESERVATION Indeed, vpContext([vpG G [vp L ]]) = vpContext([vpG G vp]), hence the premises (74) and (72) are the same. Realizing that (76) = (73) nishes the proof. OP-BlockEnd T E0 = L . From C0 : we know:
(77) M ; C (lms0 , [vpG G vp], ts0 ) : void TC-BlockEnd M ; C (lms0 , [vpG G [vp L vpL ]], L ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G [vp L vpL ]], L ts0 )] :

We want to prove C1 : :
(78) M ; C (lms0 , [vpG G vp], ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G vp], ts0 )] :

Indeed, (78) = (77). OP-IfFalse T E0 = if ( r, false


bool )

S1 else S2 . From C0 : we know:

M; C M;

(80) (79) M ; C (lms0 , vp0 , ts0 ) : void TC-StatClo (lms0 , vp0 , if ( r, false bool ) S1 else S2 ts0 ) : void T-Config [gs0 | (lms0 , vp0 , if ( r, false bool ) S1 else S2 ts0 )] :

where (79) is (here we denote vpc = vpContext(vp0 )):


(81) (82) (83) r, false bool : bool M ; vpc T S1 : void M ; vpc T S2 : void T-If M ; vpc T if ( r, false bool ) S1 else S2 : void

M ; vpc

We want to prove C1 : :
(84) (85) M ; vpContext(vp0 ) T S2 : void M ; C (lms0 , vp0 , ts0 ) : void TC-StatClo M ; C (lms0 , vp0 , S2 ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , S2 ts0 )] :

Realizing that (84) = (83), and (85) = (80) nishes the proof. OP-IfTrue The proof is a straightforward alteration of the proof of OP-IfFalse. OP-PromoForget T E0 = v;. From C0 : we know:
(86) (87) M ; vpContext(vp0 ) T v; : void M ; C (lms0 , vp0 , ts0 ) : void TC-StatClo M ; C (lms0 , vp0 , v; ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , v; ts0 )] :

106

CHAPTER 9. TYPE SOUNDNESS We want to prove C1 : :


(88) (lms0 , vp0 , ts0 ) : void T-Config [gs0 | (lms0 , vp0 , ts0 )] :

M; C M;

Realizing that (88) = (87) nishes the proof. OP-ReturnVoidImpl T E0 = M . From C0 : we know:
(89) M ; C (lms0 , vpG , ts0 ) : typeOf (@retVal , [vpG G vp]) TC-RetImpl M ; C (lms0 , [vpG G vp], M ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G vp], M ts0 )] :

We want to prove C1 : :
(90) M ; vpContext(vpG ) T none, void : void M ; C (lms0 , vpG , ts0 ) : void TC-ExprClo M ; C (lms0 , vpG , none, void ts0 ) : void T-Config M ; [gs0 | (lms0 , vpG , none, void ts0 )] :

We must prove that typeOf (@retV al, [vpG G vp]) = void. The only way to get M to the stack is by an invocation of a method m using rule OP-DoMethodCallCl which also sets typeOf (@retV al, [vpG G vp]) to the return type T of the method m. Since we only consider well-typed programs, the method m is well-typed. Let T be not void. From the premises of typing rule T-Method, this means that RetOk(MB (m)) is satised. However, by Lemma 9.3.10 we know that there must be a return; or return v; statement evaluated during evaluation of method ms body. This would replace M . But this contradicts our assumption that T E = M . Therefore typeOf (@retV al, [vpG G vp]) = void. The proof of this case is now nished as (90) is equal to (89). OP-Skip T E0 = ;. From C0 : we know:
(91) M ; vpContext(vp0 ) T ; : void M ; C (lms0 , vp0 , ts0 ) : void TC-StatClo M ; C (lms0 , vp0 , ; ts0 ) : void T-Config M ; [gs0 | (lms0 , vp0 , ; ts0 )] : T-Skip

We want to prove C1 : :
(92) (lms0 , vp0 , ts0 ) : void T-Config [gs0 | (lms0 , vp0 , ts0 )] :

M; C M;

Realizing that (92) = (91) nishes the proof. 107

9.3. TYPE PRESERVATION OP-VarDecl T E0 = T x;. From C0 : we know:


(93) M ; C (lms0 , [vpG G [vp L vpL ]], ts0 ) : void TC-VarDeclOne M ; C (lms0 , [vpG G [vp L vpL ]], T x; ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G [vp L vpL ]], T x; ts0 )] :

We want to prove C1 : :
(94) M ; C (lms0 , [vpG G [vp L vpL ]], ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G [vp L vpL ]], ts0 )] :

where vpL = vpL [x none]+,var [x T ]+,type . By denition, vpL = (fvar , fch , fqa , ftype ) and vpL = (fvar , fch , fqa , ftype ). By denitions of OP-VarDecl and TC-VarDeclOne, we get ftype = ftype . This is enough to see that (94) is equal to (93) as the other parts of the variable properties tuples (ie. fvar , fch , fqa , fvar , fch , fqa ) are never used in typing. OP-VarDeclAlF, OP-VarDeclChE The proof is a straightforward alteration of the proof of OP-VarDecl.

Lemma 9.3.17 (Type preservation for ret ). Let C0 = [gs0 | (lms0 , [vpG G vp], T E0 . . . M ts0 )], C1 = [gs1 | (lms1 , vpG , ts1 )] be two congurations such that C0 ret C1 . If C0 : then C1 : . Proof. We prove this lemma for each rule of relation ret : OP-ReturnValue T E0 = return v;. From C0 : we know (here we denote vpc = vpContext([vpG G vp]) and = typeOf (@retV al, [vpG G vp])):
(95) T-Value M ; C (lms0 , vpG , ts0 ) : M ; vpc T v : TC-RetExpr M ; C (lms0 , [vpG G vp], return v; . . . M ts0 ) : void T-Config M ; [gs0 | (lms0 , [vpG G vp], return v; . . . M ts0 )] :

We want to prove C1 : :
(96) M ; vpContext(vpG ) T v : M ; C (lms0 , vpG , ts0 ) : TC-ExprClo M ; C (lms0 , vpG , v ts0 ) : void T-Config M ; [gs0 | (lms0 , vpG , v ts0 )] : T-Value

The type of return value v does not depend on the context, therefore it is always . Realizing that (96) = (95) nishes the proof. OP-ReturnVoid T E0 = return;. From C0 : we know: 108

CHAPTER 9. TYPE SOUNDNESS


(97) M ; C (lms0 , vpG , ts0 ) : void TC-RetVoid (lms0 , [vpG G vp], return; . . . M ts0 ) : void T-Config [gs0 | (lms0 , [vpG G vp], return; . . . M ts0 )] :

M; C M;

We want to prove C1 : (here we denote vpc = vpContext(vpG )):


M ; vpc
T

(98) T-Value none, void : void M ; C (lms0 , vpG , ts0 ) : void TC-ExprClo M ; C (lms0 , vpG , none, void ts0 ) : void T-Config M ; [gs0 | (lms0 , vpG , none, void ts0 )] :

Realizing that (98) = (97) nishes the proof.

9.4

Type soundness

Theorem 9.4.1 (Type soundness for single-process programs). For any program which does not contain fork, send and recv constructs, if a conguration C0 : evolves to a terminal conguration Cn , then either Cn is an erroneous conguration, or Cn : . Proof. This is the corollary of the progress (Lemmata 9.2.1 and 9.2.2) and type preservation lemmata (Lemmata 9.3.11, 9.3.12, 9.3.15, 9.3.16 and 9.3.17). Theorem 9.4.2 (Type soundness for noncommunicating part of the language). For any program which does not contain send and recv constructs, if a conguration C0 = [gs0 | ls0,1 ls0,m ] : evolves to a terminal conguration Cn , then either Cn is an erroneous conguration, or Cn : for some type . Proof. This is the corollary of the progress (Lemmata 9.2.1 and 9.2.2) and type preservation lemmata (Lemmata 9.3.11, 9.3.12, 9.3.13, 9.3.15, 9.3.16 and 9.3.17). Theorem 9.4.3 (Type soundness if well-formed communication is guaranteed). For any program which gets never stuck due to incorrect send/recv pairing, if a conguration C0 = [gs0 | ls0,1 ls0,m ] : evolves to a terminal conguration Cn , then either Cn is an erroneous conguration, or Cn : for some type . Proof. This is the corollary of the progress (Lemmata 9.2.1, 9.2.2 and 9.2.3) and type preservation lemmata (Lemmata 9.3.11, 9.3.12, 9.3.13, 9.3.14, 9.3.15, 9.3.16 and 9.3.17).

109

9.4. TYPE SOUNDNESS

110

Chapter 10

Comparison with related work


In this chapter, we compare LanQ features with several other languages and process algebras. This comparison can be used as a simple key when LanQ is appropriate for desired usage and when another language should be better chosen. We rst briey recall the properties of LanQ. The other formalisms will be presented in a similar manner.

10.1

LanQ

Theoretical features: Category of the formalism: imperative language with several process-algebraic features Formal semantics: yes, operational Type soundness: yes Mixed or pure states: mixed Practical features: Simulator implemented: yes, Java LanQ is a complex language. It combines a programming language with several features of process algebras process creation, interprocess communication. The comparison with several other existing formalisms follows.

10.2

Omer: QCL

Theoretical features: Category of the formalism: imperative language Formal semantics: no Type soundness: no Mixed or pure states: pure Practical features: 111

10.2. OMER: QCL


qureg[1] a; U(a);

Figure 10.1: QCL: Example program which creates a 1-qubit register a and performs a unitary transformation U on the qubit refered from the register a.
operator z(quconst c) { qureg q = c; // redeclare c as qureg H(q); // transform into dual basis X(q); // X-rotation in dual basis H(q); // transform back into } // computational basis

Figure 10.2: QCL: Correct (?) implementation of the Z-gate Z = HXH = |0 0| |1 1| (from [Omer, 2003]). Simulator implemented: yes, C++, Unix only Quantum Computation Language (QCL) [Omer, 2000, 2003] is the syntactically closest existing quantum programming language to LanQ. Its syntax is also similar to that of C language. QCL only allows one process to be run at a time, hence it can be used only for implementation of quantum algorithms but not protocols. The language was developed as a practical tool for scientists working in quantum computing. It has an existing interpreter which is being actively developed since 1998. Currently (September 2007), the latest version 0.6.3 is from December 2006. An example of a program written in QCL is shown in Figure 10.1. The language is typed and provides many types found in C language for classical data int, char, etc. In the quantum world, it can work with qubits only. Nevertheless, it distinguishes between four dierent quantum types to restrict the way in which any applied quantum operators may aect the corresponding a n-qubit quantum register: qureg n-qubit register that can be used without restrictions, quvoid n-qubit register that must be initially in the |0
n

state,

quconst n-qubit register that must not be modied by any quantum operator, quscratch auxiliary n-qubit register initially in the |0 n state that must become disentangled from the rest of the registers after nishing the execution of the block in which a quscratch register was declared. The distinction of the quantum types is done to support optimization techniques that can benet from a priori knowledge of the register usage, and to make programs better readable. However, the quconst parameter can be overriden to act as usual qureg register as shown in Figure 10.2. This gure was borrowed from [Omer, 2003, p. 80]. But allowing such redeclarations is dangerous what is also fairly mentioned in the dissertation [Omer, 2003]. It also makes the program code less readable because a programmer cannot be sure that a register which is declared as quconst would not be modied by some called subroutine. The errors arising from such constructions are hard to nd. 112

CHAPTER 10. COMPARISON WITH RELATED WORK LanQ does not yet oer means which would enable the programmer to specify future (quantum) variable usage in the declaration. However, it is planned for LanQ to support it and also to develop an automatic tool that would infer this information instead of requiring its specication from the programmer. This task can be probably done statically using standard data-ow analysis techniques. Declaration of a quantum register in QCL immediately allocates the appropriate number of qubits and assigns them to the register. This is dierent to LanQ where a variable declaration and quantum system allocation are done separately. It is also possible to declare a quantum register which represents a system compound of other quantum registers or their parts in QCL what is similar to the aliasfor construct in LanQ. The quantum part of the language works with qubits in pure state only. This is enough to implement the currently existing quantum algorithms. This representation of quantum state also speeds up the simulation of the application of quantum operators as the state is a vector and not a (density) matrix. However, usage of density matrices in LanQ allows a programmer to work with mixed states and use more general quantum operators. New quantum operators can be declared in a classical-like language. This style is a very nice because it allows programmers to abstract from the underlying physical formalism. In LanQ, declaration of new operators is only allowed using a matrix representation in libraries (see Appendix B). As QCL is a procedural language, it is possible to dene reusable named blocks of code. QCL oers the following types of such blocks: Procedures (the declaration is introduced by the keyword procedure) general subroutines with side-eects on the program state. Procedures can take arguments, use all global variables declared in a program, external input etc. They do not return any value, Functions (no keyword used) general subroutines that return a value. A function behaviour deterministically and exclusively depends on its arguments. Functions cannot read an input or use global variables, therefore they cannot invoke procedures (because procedures are less restricted), Quantum operators (operator) invertible blocks of code representing unitary operators. These subroutines are allowed to take both classical and quantum parameters and provide automatic management of quantum scratch registers, Basis permutations (qufunct) they are similar to quantum operators but do not support usage of quantum scratch registers. An example of a basis permutation declaration is shown in Figure 10.3. In LanQ, we only have single type of named reusable blocks of code methods. They are on the same level as QCL functions. However, it is planned to develop a hierarchy of named blocks similar to QCL to allow dierent levels of optimizations of a program. To sketch the idea: it is relatively straightforward how to decide whether a method uses only quantum resources or whether it also requires some classical. Then we can for example optimize purely quantum methods dierently than the classical ones. Semantics of QCL is not given formally. Therefore no program written in this language can be formally proved to satisfy any property. It would be possible to take the implementation as the formal denition of the semantics, however this semantics would require the existence 113

10.3. GAY, NAGARAJAN: CQP


qufunct flip(qureg q) { // Invert order of qubits int i; for i=0 to #q/2-1 { Swap(q[i],q[#q-i-1]); // swap 2 opposite qubits } }

Figure 10.3: QCL: Example of a basis permutation declaration. of formal semantics of C++ language which is not available. For the same reason, it is not possible to prove the language type soundness.

10.3

Gay, Nagarajan: CQP

Theoretical features: Category of the formalism: process algebra Formal semantics: yes, operational Type soundness: yes Mixed or pure states: pure Practical features: Simulator implemented: no Communicating Quantum Processes (CQP) [Gay and Nagarajan, 2004, 2005, 2006] is a typed process algebra based on -calculus. The original -calculus is enriched over primitives for measurement and transformations of quantum state. It has sound type system which guarantees that one qubit is owned by only one process in the system. The basic build blocks of the process syntax are values (v) variables (x, y, . . . ), literal values of data types (0, 1, . . . ), and unitary transformation names (H,CNot, . . . ). Expressions (e) consist of values (v), functions over expressions (eg. a sum e1 + e2 ), quantum measurements in standard basis (measure e1 , . . . , en ), and applications of unitary transformations (e1 , . . . , en = e). A process (P ) denition is built from the following primitives: a terminal process (0), parallel composition of processes (P1 |P2 ), communication (sending e![e1 , . . . , en ].P and receiving e?[e1 , . . . , en ].P ), actions ({e}.P ), allocation of a new channel ((new x : T )P where T denotes a channel type) and a new qubit allocation ((qbit x)P ). An example of a process denition is shown in Figure 10.4.

P repEP R(s : [Qbit], t : [Qbit]) = (qbit x)(qbit y)({x = H} . {x, y = CNot} . s![x] . t![y] . 0) Figure 10.4: CQP: Example of a process P repEP R which takes as arguments two channels s, t capable of transmitting qubits. The process prepares an EPR pair: it creates two qubits, applies unitary transformations H onto the qubit x and CN ot onto both of them, and sends them over the channels s and t. 114

CHAPTER 10. COMPARISON WITH RELATED WORK The operational semantics of CQP is dened in terms of small-step transitions on congurations: t = (; ; P ) where denotes a (pure) state of the manipulated qubits and their internal names, internal names of allocated channels, and P a process term. The transition function either transforms a conguration t to a probabilistic mixture of congurations ti : t i pi ti where pi denotes the probability of reaching the conguration ti , i pi = 1, or performs a probabilistic pi transition from a probabilistic mixture of congurations to a single conguration: i pi ti 1 t. Transitions of the shape t0 1 t1 t1 are abbreviated to t0 t1 . This is the same idea which was used in the operational semantics of LanQ. Note that the structure of CQP conguration (; ; P ) is similar to the structure of a LanQ conguration. In LanQ, a conguration C = [gs | ls1 lsn ] consists of a global part gs = (Q, C) and state of individual processes ls1 , . . . , lsn . We show the similarity by comparing individual elements of the congurations: In the CQP conguration, is of the shape q0 , . . . , qn = | where qi are qubit names that specify physical qubit positions and the vector | represents the (pure) quantum state. To corresponds the Q element of the LanQ conguration. It is of the shape (, L) where species the (mixed) quantum state and L dimensions of allocated quantum systems. In LanQ, we do not need to keep track of quantum system names as the systems are identied by their index but we must store the system dimensions to be able to compute quantum variable state from its index. In this element, LanQ is more general than CQP because it allows to express mixed states and quantum systems of higher dimensions than two, In the CQP conguration, is a list of allocated channel internal names. It is similar to the C element of the LanQ conguration which stores a list of allocated channels, The P element of the CQP conguration stores the actual state of evaluation of a process term in what it fulls the same function as lsi elements of the LanQ conguration. One dierence between CQP and LanQ is in the way of evaluation. CQP evaluation of a single process is a transformation of one (process) term to another. Contrary to this approach, LanQ stores a stack of terms for a single process. This makes LanQ evaluation more complex but also allows it to simply handle higher-level programming languages features such as variable scope handling or returning a value from a method. Another dierence lies in variable handling. In LanQ, it is possible to have many variables pointing to one resource what is unsupported by CQP. This is a consequence of dierent memory models of LanQ and CQP. In LanQ, we work with a four-layer memory model (see Section 7.1). In contrast, CQP works with a two-layer memory model which consists of a system memory layer and a process memories layer. System memory physically contains the qubits and channels. It is connected to the process memories by the and elements of the CQP conguration. Local memories of the individual processes are directly specied by the process terms. There is no need for the variable layer: The variables in CQP denote places in the local process memory (ie. in the process term) where the references to the system memory (ie. qubit or channel internal names) are substituted after allocation of a qubit or a channel. This two-level memory model benets from easy usage of a linear type system that 115

10.4. JORRAND, LALIRE: QPALG

Figure 10.5: Memory model of CQP. is used to guarantee unique qubit ownership among processes. Further, the type system can statically check that no qubit is used more than once in a multiqubit measurement or unitary operation just by checking mutual distinctness of all used variables and internal qubit names. The memory model is depicted in Figure 10.5 where the following conguration is shown: (q0 = |0 ; c0 , c1 ; R | (qbit y)({q0 = H} . {q0 , y = CNot} . c0 ![q0 ] . c1 ![y] . 0) | Q). The system memory contains an allocated qubit with internal name q0 and two channels with internal names c0 and c1 . LanQ diers to CQP in resource allocation: In LanQ, the declaration of a variable which denotes a resource and the allocation of the resource are done separately. In CQP, these two phases are joined, so a qubit variable x is both declared and the corresponding qubit is allocated when executing the action (qbit x); similarly for channels. This style prevents the newly allocated qubit to be assigned to a variable already pointing to a qubit. The approach chosen in LanQ allows a programmer to use the same variable name for dierent quantum systems during a method execution. This reduces the demand for auxiliary variables. A qubit is always initialized to a |0 state in CQP after allocation. In LanQ, a newly allocated quantum system is initialized to a maximally mixed state. The former style simplies qubit handling because any pure state can be obtained from the |0 state by a simple application of a corresponding unitary operation to the qubit right after the allocation. The approach chosen in LanQ reects the physical model where a quantum particle is obtained in an unknown state (what is represented by allocation) and only after that, it can be adjusted to the required (pure) state by measurement. CQP eliminates the nondeterminism arising from possible concurrent usage of quantum systems. It does not resolve nondeterminism arising from possible concurrent usage of the same channels by three or more processes. In LanQ, the nondeterminism arising from possible concurrent usage of any resources is eliminated.

10.4

Jorrand, Lalire: QPAlg

Theoretical features: Category of the formalism: process algebra Formal semantics: yes, operational Type soundness: no (but type preservation proved) 116

CHAPTER 10. COMPARISON WITH RELATED WORK

PrepZeroMinusOne = [ h : Qubit Qubit ] [ g : Nat Qubit . g!1 . nil [ x : Qubit . g?x . H[x] . h!x . nil ]]

def

Figure 10.6: QPAlg: Example of a process PrepZeroMinusOne which takes a gate h as its argument. It creates a qubit x in |1 state, applies a unitary transformation H onto it, and sends it over the gate h. Mixed or pure states: mixed Practical features: Simulator implemented: no Quantum Process Algebra (QPAlg) [Jorrand and Lalire, 2004, Lalire and Jorrand, 2004, Lalire, 2005, 2006a,b] is a typed process algebra based on CCS and Lotos. The original formulation of this calculus [Lalire and Jorrand, 2004, Lalire, 2005] involved communication in quantum system allocation and measurements. This is no longer true for measurements in [Lalire, 2006a]. We rst describe the process algebra syntax as dened in [Lalire, 2006a]. The smallest syntactical elements are constants (v) and variables (x). Variable scope is limited by a process for which the variables are declared([x1 : T1 , . . . , xn : Tn .P ] where Ti denotes a type and P is a process in which the variables xi can be used). The expressions (e) can be constants, variables or their tensor product, admissible transformations (quantum operations that do not yield a classical result A[e], eg. unitary transformations, and quantum operations that yield a classical result A[x, e], ie. general quantum measurements), and arithmetic and boolean operations on expressions. An action (a) can be a communication (sending the result of an expression evaluation g!e, receiving a value into a variable g?x), an assignment of an expression to a variable, or an expression. A process (P ) is dened in terms of a terminal process (nil), composition of an action and a process (a.P ), parallel composition of processes (P1 P2 ), nondeterministic composition of processes (P1 + P2 ), conditional choice ([c1 P1 , . . . , cn Pn ], probabilistic composition of two processes (P1 pj P2 ), and sequential composition of processes (P1 ; P2 ). Recursive processes can be dened in this calculus (without parameters (fix X.P ) and parametrized ((fix X[x1 : T1 , . . . , xn : Tn ].P )[e1 , . . . , en ]). An example of a process denition is shown in Figure 10.6. The semantics of this algebra is dened operationally on states P/C where P is an evaluated process term and C =< s, q = , f > is a conguration where: s is an environment tree which contains mappings from variables to their types, q is a sequence of quantum variable names and is the state of allocated qubits, f is a partial function assigning values to classical variables. If a process term is about to evaluate a variable declaration, the declared variables are renamed so that their names are unique in the whole system. This justies the usage of just one partial function f for representation of the states of classical variables of all processes, 117

10.4. JORRAND, LALIRE: QPALG

N = [ g : Nat Qubit . g!1 . nil

def

[ x : Qubit . g?x . ( H[x] . nil

x [x] . nil ) . nil]]

Figure 10.7: QPAlg: Example of a process N which creates a qubit x in |1 state, and applies unitary transformations H and x onto it. The order of the application of the unitary operations is resolved nondeterministically. and similarly for the list q. This is dierent to the approach chosen in LanQ where we do not rename variables in the unwound method body the visibility of variables is handled by the structure of variable properties as described in Section 7.2. The environment tree is a binary tree. It is built during the evaluation according to the stucture of parallel compositions of the processes in the evaluated term P . The environment tree is used to track variable scope in the processes. It is handled in such a way that if a variable is available to a process then it is also available to all its subprocesses. It clearly follows that the nondeterminism arises from possible concurrent usage of the same resource by multiple processes as shown in Figure 10.7. The amount of cases when this type of nondeterminism occurs is partially reduced by QPAlg type system, however only for communication of quantum variables to guarantee unique qubit ownership for a subtree of processes. This type of nondeterminism is not present in LanQ. The structure of the environment tree is given by the fact that the parallel composition operator in QPAlg is not associative. This is dierent to both LanQ and CQP where parallelism is associative, hence the processes can be represented by a list. In QPAlg, a quantum variable initialization is done by means of classical-to-quantum communication: A number 0 (or 1) is sent over the channel to initialize the new qubit to the state |0 (or |1 ). This is an analogue of an assignment to a quantum variable, however this action can only be performed on quantum variables that have not been initialized yet. An example of a qubit initialization is a part of the example shown in Figure 10.6. The probabilistic behaviour introduced by using admissible transformations is captured on the level of congurations. A state P/C can hence evolve to a state P/ pi Ci where pi are probabilities that this state evolves in a subsequent step to P/Ci , i pi = 1. Note that QPAlg also supports probabilistic choice on the level of processes: pi Pi /C where pi are probabilities that this state evolves in a subsequent step to Pi /C, i pi = 1. This type of choice is not supported in LanQ. A probabilistic choice in QPAlg is solved prior to the nondeterministic one. QPAlg supports denition of recursive processes using a xpoint operator. There is no such an operator in LanQ, recursion is only supported by means of a recursive invocation of a method. Therefore reasoning about recursive processes is better done in QPAlg than in LanQ. QPAlg contains nondeterminism arising of possible concurrent usage of the same resource (both quantum systems and channels) by multiple processes. This type of nondeterminism is eliminated in LanQ.

118

Chapter 11

Conclusion
We have developed an imperative typed quantum programming language LanQ that also has several features of process algebras. It supports implementation of algorithms and multiparty protocols that use both quantum and classical data. The statements manipulating quantum and classical data can be arbitrarily interleaved. We have dened the language syntax which is similar to the syntax of C language, its operational semantics and its type system. We have proved language type soundness for the restricted part of the language which does not contain send and recv statements, and for the whole language provided the executed programs are guaranteed to use only a wellformed communication. This makes the language very usable for scientists who can use it for verication of properties of quantum algorithms and protocols. We have shown that individual resources are guaranteed to be accesible to at most one process at a time. This way we minimize nondeterminism there is no nondeterminism in evolution of individual processes running in the system. The only nondeterminism arises from the choice of order of simultaneously running processes evolution. This feature signicantly simplies the language implementation. The language has existing simulator available from the address http://lanq.sf.net/. The existence of this implementation brings the language to the stage when it can be practically used for implementation of quantum algorithms and protocols, and makes it a usable tool for a machine-assisted formal verication of the properties of the algorithms and protocols. There are several directions which the future research on LanQ can take, both theoretically and practically. We outline those most remarkable in the following paragraphs. From the theoretical point of view, it would be nice to develop a notion of process equivalence for LanQ. It can be then used to develop optimization techniques for LanQ programs. LanQ does not have denotational semantics yet. Creation of this type of semantics is a hard task. The semantics will be probably rst developed for the single-process part of the language. Then it will be probably developed for the restricted language without communicating capabilities. The latter semantics will surely benet from the fact that the evolution of individual processes is deterministic, the only nondeterminism arises from the possibility of dierent order of evaluation of dierent processes. From practical point of view, there are several improvements that should be done to make LanQ more comfortable for its users. It would be convenient to allow programmers to dene quantum operators in a classical-like language. Simulator speed is currently painful. The main reason is the time complexity of manip119

ulation with density matrix that represents quantum state of allocated quantum systems. This can be solved by using several dierent implementations of quantum memory one using mixed states, other using pure states, other for example stabilizer states, and possibly in the future another one for a real quantum memory. The user could choose which of the implementations he prefers for an execution of his program. This would indeed involve small changes in the semantics, at least for a quantum system allocation because the maximally mixed state is not be expressible in some of these formalisms. The quantum systems that are not used remain in the system memory. Therefore we should (theoretically) elaborate and (practically) implement a kind of garbage collector that frees inaccessible resources from the system memory.

120

References
S. Aaronson and D. Gottesman. Improved simulation of stabilizer circuits. Phys. Rev. A, 70 (5), 2004. S. Abramsky and B. Coecke. A categorical semantics of quantum protocols. ph/0402130, 2004. URL http://www.arxiv.org/abs/quant-ph/0402130. quant-

S. Abramsky and G. McCusker. Game semantics. In H. Schwichtenberg and U. Berger, editors, Computational Logic: Proceedings of the 1997 Marktoberdorf Summer School, pages 156. Springer-Verlag, 1999. R. Alleaume, J. Bouda, C. Branciard, T. Debuisschert, M. Dianati, N. Gisin, M. Godfrey, P. Grangier, T. Langer, A. Leverrier, N. Lutkenhaus, P. Painchault, M. Peev, A. Poppe, T. Pornin, J. Rarity, R. Renner, G. Ribordy, M. Riguidel, L. Salvail, A. Shields, H. Weinfurter, and A. Zeilinger. SECOQC White Paper on Quantum Key Distribution and Cryptography. quant-ph/0701168, 2007. URL http://www.arxiv.org/abs/quant-ph/ 0701168. T. Altenkirch and J. Grattage. A functional quantum programming language. ph/0409065, 2004. URL http://www.arxiv.org/abs/quant-ph/0409065. quant-

J. Baeten. A brief history of process algebra. Technical Report CSR 04-02, Vakgroep Informatica, Technische Universiteit Eindhoven, 2004. URL http://www.win.tue.nl/fm/ 0402history.pdf. J. C. M. Baeten and W. P. Weijland. Process algebra. Cambridge University Press, New York, NY, USA, 1990. ISBN 0-521-40043-0. R. Baltazar, P. amd Chadha, P. Mateus, and A. Sernadas. Towards model-checking quantum security protocols. In Dini, P., editor, Proceedings of the First Workshop on Quantum Security: QSec07. IEEE Press, 2007. C. Bennett and G. Brassard. Quantum Cryptography: Public Key Distribution and Coin Tossing. In Proceedings of IEEE International Conference on Computers Systems and Signal Processing, pages 175179, India, Dec. 1984. Bangalore. C. H. Bennett and S. J. Wiesner. Communication via one- and two-particle operators on einstein-podolsky-rosen states. Phys. Rev. Lett., 69(20):28812884, Nov 1992. doi: 10. 1103/PhysRevLett.69.2881. C. H. Bennett, G. Brassard, and N. D. Mermin. Quantum cryptography without Bells theorem. Phys. Rev. Lett., 68(5):557559, 1992. 121

REFERENCES C. H. Bennett, G. Brassard, C. Crpeau, R. Jozsa, A. Peres, and W. K. Wootters. Teleporting e an unknown quantum state via dual classical and einstein-podolsky-rosen channels. Phys. Rev. Lett., 70(13):18951899, Mar 1993. doi: 10.1103/PhysRevLett.70.1895. J. Bergstra and J. Klop. Process algebra for synchronous communication. Information and Control, 60(1/3):109137, 1984. J. A. Bergstra, A. Ponse, and S. A. Smolka, editors. Handbook of Process Algebra, New York, NY, USA, 2001. Elsevier Science Inc. ISBN 0444828303. E. Bernstein and U. Vazirani. Quantum complexity theory. SIAM J. Comput., 26(5):1411 1473, 1997. URL http://citeseer.ist.psu.edu/bernstein97quantum.html. S. Bettelli, T. Calarco, and L. Serani. Toward an architecture for quantum programming, 2001. URL http://www.arxiv.org/abs/cs.PL/0103009. G. Bierman, M. Parkinson, and A. Pitts. MJ: An imperative core calculus for Java and Java with eects. Technical Report 563, Cambridge University Computer Laboratory, April 2003. URL citeseer.ist.psu.edu/article/bierman03mj.html. L. Cardelli. Type systems. In A. B. Tucker, editor, The Computer Science and Engineering Handbook. CRC Press, 2004. URL http://research.microsoft.com/Users/luca/ Papers/TypeSystems.pdf. D. Cazorla, F. Cuartero, V. V. Ruiz, F. L. Pelayo, and J. J. Pardo. Algebraic theory of probabilistic and nondeterministic processes. J. Log. Algebr. Program., 55(1-2):57103, 2003. B. Coecke. Kindergarten Quantum Mechanics. quant-ph/0510032, 2005. URL http://www. arxiv.org/abs/quant-ph/0510032. D. Deutsch. Quantum computational networks. Proceedings of the Royal Society of London Ser. A, A425(1868):7390, 1989. URL http://citeseer.ist.psu.edu/ deutsch85quantum.html. D. Deutsch. Quantum theory, the Church-Turing principle and the universal quantum computer. Proceedings of the Royal Society of London Ser. A, A400:97117, 1985. URL http://citeseer.ist.psu.edu/deutsch85quantum.html. D. Deutsch and R. Jozsa. Rapid Solution of Problems by Quantum Computation. In Proceedings: Mathematical and Physical Sciences, volume 439, pages 553558, 1992. A. Einstein, B. Podolsky, and N. Rosen. Can quantum-mechanical description of physical reality be considered complete? Phys. Rev., 47(10):777780, May 1935. doi: 10.1103/ PhysRev.47.777. A. K. Ekert. Quantum cryptography based on bells theorem. Phys. Rev. Lett., 67(6):661663, 1991. R. Feynman. The Feynman Lectures on Physics, The Denitive Edition Volume 3. AddisonWesley, 2006. ISBN 0805390499. 122

REFERENCES R. Feynman. Simulating Physics with Computers. International Journal of Theoretical Physics, 21(6&7):467488, 1982. URL http://citeseer.ist.psu.edu/ feynman82simulating.html. W. Fokkink. Introduction to Process Algebra. Springer-Verlag New York, Inc., Secaucus, NJ, USA, 2000. ISBN 354066579X. S. Gay and M. Hole. Subtyping for session types in the pi calculus. Acta Informatica, 42(2): 191225, 2005. S. J. Gay. Quantum programming languages: Survey and bibliography. Mathematical Structures in Computer Science, 16(4), 2006. URL http://www.dcs.gla.ac.uk/~simon/ publications/QPLsurvey.pdf. S. J. Gay and R. Nagarajan. Communicating Quantum Processes. quant-ph/0409052, 2004. URL http://www.arxiv.org/abs/quant-ph/0409052. S. J. Gay and R. Nagarajan. Communicating quantum processes. In POPL 05: Proceedings of the 32nd ACM Symposium on Principles of Programming Languages, pages 145157, 2005. ISBN 1-58113-830-X. S. J. Gay and R. Nagarajan. Types and typechecking for Communicating Quantum Processes. Mathematical. Structures in Comp. Sci., 16:375406, 2006. ISSN 0960-1295. S. J. Gay, R. Nagarajan, and N. Papanikolaou. QMC: A Model Checker for Quantum Systems. quant-ph/0704.3705v2, 2007. URL http://www.arxiv.org/abs/quant-ph/0704.3705v2. I. Glendinning. Quantum programming languages and tools, 2005. URL http://www.vcpc. univie.ac.at/~ian/hotlist/qc/programming.shtml. Online catalogue. D. Gottesman. The heisenberg representation of quantum computers. quant-ph/9807006, 1998. URL http://www.arxiv.org/abs/quant-ph/9807006. J. Gruska. Foundations of Computing. International Thomson Publishing Computer Press, 1997. ISBN 1-85032-243-0. J. Gruska. Quantum Computing. McGraw-Hill, 1999. ISBN 0-07-709503-0. C. A. R. Hoare. Communicating sequential processes. Commun. ACM, 26(1):100106, 1983. ISSN 0001-0782. doi: http://doi.acm.org/10.1145/357980.358021. P. Jorrand and M. Lalire. Toward a quantum process algebra. In CF 04: Proceedings of the 1st conference on Computing frontiers, pages 111119, New York, NY, USA, 2004. ACM Press. ISBN 1-58113-741-9. doi: http://doi.acm.org/10.1145/977091.977108. E. Knill. Conventions for quantum pseudocode. Technical Report LAUR-96-2724, Los Alamos National Laboratory, 1996. URL http://citeseer.ist.psu.edu/knill96conventions. html. D. E. Knuth. The Art of Computer Programming, Volumes 1-3. Addison Wesley Professional, 1998. ISBN 0-201-48541-9. 123

REFERENCES N. Kobayashi, B. C. Pierce, and D. N. Turner. Linearity and the Pi-Calculus. In POPL 96: Proceedings of the 23rd ACM SIGPLAN-SIGACT symposium on Principles of programming languages, pages 358371, New York, NY, USA, 1996. ACM Press. ISBN 0-89791-769-3. doi: http://doi.acm.org/10.1145/237721.237804. A. Kondacs and J. Watrous. On the power of quantum nite state automata. In FOCS 97: Proceedings of the 38th Annual Symposium on Foundations of Computer Science (FOCS 97), page 66, Washington, DC, USA, 1997. IEEE Computer Society. ISBN 0-8186-8197-7. M. Lalire. A Probabilistic Branching Bisimulation for Quantum Processes. quant-ph/0508116, 2005. URL http://www.arxiv.org/abs/quant-ph/0508116. M. Lalire. Dveloppement dune notation alorithmique pour le calcul quantique. PhD thesis, e Grenoble Institute of Technology, 2006a. M. Lalire. Relations among Quantum Processes: Bisimilarity and Congruence. Mathematical. Structures in Comp. Sci., 16(3), 2006b. ISSN 0960-1295. M. Lalire and P. Jorrand. A process-algebraic approach to concurrent and distributed quantum computation: operational semantics. quant-ph/0407005, 2004. URL http: //www.arxiv.org/abs/quant-ph/0407005. M. Lampis, K. G. Ginis, and N. S. Papaspyrou. Quantum data and control made easier. In P. Selinger, editor, Preliminary Proceedings of the 4th International Workshop on Quantum Programming Languages, pages 7386, 2006. The nal version will be published in Electronic Notes in Theoretical Computer Science. D. W. Leung. Quantum computation by measurements. International Journal of Quantum Information, 2(1):3334, 2004. D. Mayers. Quantum key distribution and string oblivious transfer in noisy channels. In CRYPTO 96: Proceedings of the 16th Annual International Cryptology Conference on Advances in Cryptology, pages 343357, London, UK, 1996. Springer-Verlag. ISBN 3-54061512-1. J. McCarthy. A Basis for a Mathematical Theory of Computation. In P. Braort and D. Hirschberg, editors, Computer Programming and Formal Systems, pages 3370. NorthHolland, Amsterdam, 1963. URL http://citeseer.ist.psu.edu/mccarthy63basis. html. R. Milner. A theory of type polymorphism in programming. Journal of Computer and System Sciences, 17:348375, 1978. R. Milner. A calculus of communicating systems, volume 92. Springer Verlag, 1980. ISBN 0-387-10235-3. R. Milner, J. Parrow, and D. Walker. A calculus of mobile processes, i. Inf. Comput., 100(1): 140, 1992. ISSN 0890-5401. doi: http://dx.doi.org/10.1016/0890-5401(92)90008-4. H. Mlna LanQ an Imperative Quantum Programming Language. In MEMICS 2006, rk. 2nd Doctoral Workshop on Mathematical and Engineering Methods in Computer Science, 124

REFERENCES pages 113120. Faculty of Information Technology, Brno University of Technology, 2006, Oct. 2006a. ISBN 80-214-3287-X. H. Mlna Operational Semantics of Quantum Programming Language LanQ. Technical rk. Report FIMU-RS-2006-10, Faculty of Informatics, Masaryk University, 2006, Dec. 2006b. H. Mlna Operational Semantics and Type Soundness of Quantum Programming Language rk. LanQ. quant-ph/0708.0890, 2007. URL http://arxiv.org/abs/0708.0890. G. E. Moore. Cramming more components onto integrated circuits. Electronics, 38(8), April 1965. M. Nielsen and I. Chuang. Quantum computation and quantum information. Cambridge University Press, 2000. M. A. Nielsen. Universal quantum computation using only projective measurement, quantum memory, and preparation of the |0 state. Phys. Lett. A, 308(2-3):96100, 2003. B. Omer. Quantum programming in QCL. Masters thesis, TU Vienna, 2000. B. Omer. Structured Quantum Programming. PhD thesis, TU Vienna, 2003. URL http: //tph.tuwien.ac.at/{~}oemer/doc/structquprog.ps. C. Palamidessi. Comparing the expressive power of the synchronous and the asynchronous -calculus. In POPL 97: Proceedings of the 24th ACM SIGPLAN-SIGACT symposium on Principles of programming languages, pages 256265, New York, NY, USA, 1997. ACM Press. ISBN 0-89791-853-3. doi: http://doi.acm.org/10.1145/263699.263731. S. Perdrix. State transfer instead of teleportation in measurement-based quantum computation. International Journal of Quantum Information, 3(1):219223, 2005. A. Peres. Quantum Theory: Concepts and Methods. Kluwer, 1995. ISBN 978-0-7923-3632-7. J. Preskill. Lecture notes on physics 219/computer science 219 course, quantum computation, 2000. Available at http://www.theory.caltech.edu/people/preskill/ph219/. R. Raussendorf and H. J. Briegel. A one-way quantum computer. Phys. Rev. Lett., 86(22): 51885191, May 2001. doi: 10.1103/PhysRevLett.86.5188. J. W. Sanders and P. Zuliani. Quantum programming. In MPC, volume 1837 of Lecture Notes in Computer Science, pages 8099. Springer, 2000. ISBN 3-540-67727-5. D. Scott and C. Strachey. Towards a mathematical semantics for computer languages. In J. Fox, editor, Proceedings Symposium Computers and Automata, pages 1946. Polytechnic Institute of Brooklyn Press, 1971. URL http://citeseer.ist.psu.edu/ mccarthy63basis.html. P. Selinger. Towards a quantum programming language. Mathematical. Structures in Comp. Sci., 14(4):527586, 2004. ISSN 0960-1295. doi: http://dx.doi.org/10.1017/ S0960129504004256. 125

REFERENCES P. Selinger. Dagger compact closed categories and completely positive maps. In P. Selinger, editor, Preliminary Proceedings of the 3rd International Workshop on Quantum Programming Languages, pages 127148, 2005. The nal version will be published in Electronic Notes in Theoretical Computer Science. P. Selinger and B. Valiron. A lambda calculus for quantum computation with classical control. Mathematical. Structures in Comp. Sci., 16(3):527552, 2006. ISSN 0960-1295. doi: http: //dx.doi.org/10.1017/S0960129506005238. P. W. Shor. Algorithms for quantum computation: Discrete logarithms and factoring. In Proceedings of the 35th Annual Symposium on Foundations of Computer Science. IEEE Computer Society Press, 1994. M. Sipser. Introduction to the Theory of Computation, Second Edition. Course Technology, 2005. ISBN 978-0534950972. K. Slonneger and B. L. Kurtz. Formal syntax and semantics of programming languages: a laboratory based approach. Addison-Wesley, 1995. ISBN 0-201-65697-3. A. van Tonder. A Lambda Calculus for Quantum Computation. quant-ph/0307150, 2003a. URL http://www.arxiv.org/abs/quant-ph/0307150. A. van Tonder. Quantum computation, categorical semantics and linear logic. ph/0312174, 2003b. URL http://www.arxiv.org/abs/quant-ph/0312174. quant-

J. Watrous. On One-Dimensional Quantum Cellular Automata. In IEEE Symposium on Foundations of Computer Science, pages 528537, 1995. URL http://citeseer.ist. psu.edu/watrous95onedimensional.html. W. Wootters and W. Zurek. A single quantum cannot be cloned. Nature, 299:802803, 1982. A. K. Wright and M. Felleisen. A syntactic approach to type soundness. Information and Computation, 115(1):3894, 1994. URL http://citeseer.ist.psu.edu/wright92syntactic. html. N. Yoshida and V. T. Vasconcelos. Language primitives and type discipline for structured communication-based programming revisited: Two systems for higher-order session communication. Electron. Notes Theor. Comput. Sci., 171(4):7393, 2007. ISSN 1571-0661. doi: http://dx.doi.org/10.1016/j.entcs.2007.02.056. P. Zuliani. Quantum Programming. PhD thesis, University of Oxford, 2001. URL http: //web.comlab.ox.ac.uk/oucl/work/paolo.zuliani/pzthesis.ps.gz.

126

Index
S-list, 45 accessible resource channel, 80 channel end, 79 quantum, 77 aliased quantum variable, 60 aliasSubsyst, 57 aliasSubsystL , 57 argument types, 40 basis, 5 computational, 5 diagonal, 6 Hadamard, 6 standard, 5 basis vectors, 5 BF Ok, 88 BF Ok0 , 90 BF Oki , 90 blacksquare, 47 block-forming statements, 35 blocks, 35 bra-ket notation, 6 categorical semantics, 15 chanEnds, 57 chanEndsL , 57 channel type, 39 closed expression, 37 closed statement, 37 closed term, 37 CNOT, 10 coalesce of g and f , 48 communication asynchronous, 18 synchronous, 18 conguration, 54 conguration syntax, 36 127 denotational semantics, 14 density matrix, 8 density operator, 8 reduced, 10 dual basis, 6 empty variable properties tuple, 56 entanglement, 10 EPR pair, 10 EPR state, 10 erroneous conguration, 65 ExpOk, 88 ExpOk0 , 90 ExpOki , 90 fassignQAlias , 63 fassignQSystemDirect , 61 fassignQSystemInAlias , 61 fassignQSystem , 62 nite-dimensional Hilbert space, 5 rst-order, 15 function lms, 55 g f , 48 global reference, 50 ground type, 39 Hadamard transformation, 7 hermitian matrix, 8 higher-order, 15 Hilbert space, 5 hole, 37 internal value, 63 layer structured reference, 50 system memory, 50 value, 50 variable, 50

INDEX linearize, 46 linearizeb ot, 46 list length, 45 list of lists of partial function tuples, 47 list of partial function tuples, 47 LM S, 55 LM SQ , 55 lmsQ , 55 LM SChE , 55 lmsChE , 55 LM SCh , 55 lmsCh , 55 LM SCl , 55 lmsCl , 55 local, 49 local memory state, 55 local memory state update, 60 local operations, 10 local process conguration, 55 local process memory, 49 local reference, 50 localAliasedV ars, 62 matrix density, 8 hermitian, 8 positive, 8 trace, 8 maximally mixed state, 9 measurement projective, 7 von Neumann, 7 memory reference, 51 method, 33 method body, 35 method declaration, 33 method header, 35 method type, 40 method typing context, 40 mixed conguration, 56 mixed state, 8 N ames, 48 observable, 8 operational semantics, 14 operator completely positive, 11 128 positive, 11 trace-preserving, 11 paradigm functional, 15 imperative, 15 logical, 15 partial function tuple, 47 partial trace, 10 Pauli matrices, 7 positive matrix, 8 probability amplitudes, 6 procedural language, 15 program, 33 projective measurement, 7 projector, 7 proper quantum variable, 60 pure state, 6 quantum type, 39 qubit, 5 recursive S-list, 45 reduced density operator, 10 Ref , 51 RefG , 51 RefL , 50 RefQ , 50 RefChE , 50 RefCh , 50 RefCl , 50 RefGCh , 50 RefGQ , 50 Refnd , 51 replacement, 46 list of partial function tuples, 47 RetOk, 42 return type, 40 RT Err, 37 rule NP-Cong, 66 NP-ProbEvol, 66 NP-PropagProb, 66 OP-AllocC, 67 OP-AllocQ, 67 OP-AssignExpr, 69 OP-AssignNewValue, 69 OP-AssignQAValueBad, 69

INDEX OP-AssignQAValue, 69 OP-AssignQValue, 69 OP-AssignValue, 70 OP-BlockEnd, 70 OP-BlockHead, 66 OP-Block, 70 OP-Bracket, 66 OP-DoFork, 73 OP-DoMeasure, 75 OP-DoMethodCallCl, 71 OP-DoMethodCallQ, 72 OP-ForkExpr, 73 OP-IfExpr, 70 OP-IfFalse, 70 OP-IfTrue, 70 OP-MeasureExpr, 74 OP-MeasureOverlap, 74 OP-MeasureUninit, 74 OP-MethodCallExpr, 71 OP-MethodCallQOverlap, 72 OP-MethodCallQUninit, 72 OP-PromoExpr, 67 OP-PromoForget, 67 OP-RecvExpr, 76 OP-RecvUninit, 76 OP-ReturnExpr, 73 OP-ReturnValue, 73 OP-ReturnVoidImpl, 73 OP-ReturnVoid, 72 OP-SendExpr1, 75 OP-SendExpr2, 75 OP-SendUninit, 75 OP-Skip, 66 OP-SubstE, 67 OP-SubstS, 67 OP-VarDeclAlF, 68 OP-VarDeclMulti, 68 OP-VarDecl, 68 OP-Var, 66 OP-While, 70 SC-Assoc, 65 SC-Comm, 65 SC-Nil, 65 runtime error, 64 ISQV, 65 OQV, 64 UV, 64 129 semantics, 14 categorical, 15 denotational, 14 operational, 14 spectral decomposition, 8 square, 47 starting conguration, 65 StkEl, 37 StkRetOk, 89 strong type soundness, 16 stuck, 64 superoperator, 11 syntax, 14 block-forming elementary statement, 35 block-forming statement, 35 constant, 35 expression, 35 identier, 35 lists, 35 number, 35 promotable expression, 35 recursive list, 35 reference, 35 runtime error, 37 statement, 35 term stack element, 37 type, 35 value, 35 variable declaration, 35 system memory, 49 tensor product, 9 term stack, 56 terminal conguration, 65 trace, 8 type bool, 39 channel, 39 channel end, 39 compound system, 39 int, 39 MeasurementBasis, 39 qdit, 39 qbit, 39 qtrit, 39 Ref, 51 RTErr, 39

INDEX void, 39 typeOf , 57 T ypes, 40 typing context, 40 unique channel end ownership property, 79 unique channel ownership property, 80 unique quantum system ownership property, 78 unitary, 6 unmapQ , 58 unmapChE , 59 unmapCh , 59 unmapnd , 58 update, 46 list of partial function tuples, 47 V alues, 40 variable declarations, 35 variable properties, 55 variable properties tuple, 56 variable typing context, 40 V arP rop, 56 V arP ropL , 56 varRef , 57 varRefL , 57 vector bra, 6 ket, 6 orthogonal, 5 orthonormal, 5 vector space basis, 5 complete, 5 von Neumann measurement, 7 vpContext, 84 weak type soundness, 16 well-typed conguration, 83 well-typed method, 43 well-typed program, 40

130

Part III

Appendix

131

Appendix A

Program execution example


The probabilistic nature of a measurement of quantum particles allows us to create generator of truly random numbers: Let us have a quantum particle in the state | = 1 (|0 + |1 ). 2 Now we apply a measurement of this particle in the basis {|0 , |1 } (so called standard basis). The result of the measurement is 0 or 1 with equal probability. The random number generator can be implemented as shown in Figure A.1. int main() { qbit q; q = new qbit(); return measure (StdBasis,q); }

Figure A.1: Program example: Random number generator. Before the execution, we must specify the method typing context M = (MT , MH , MB ). We have a program containing only a method main, hence the domain of the functions in the M is {main}. M is specied as: MT (main) = void int MH (main) = int main() MB (main) = { qbit q; q = new qbit(); return measure ( none, StdBasis
MeasurementBasis ,q);

The execution of the program is shown in Figure A.2. For typographical reasons we have simplied variable properties tuple we do not show states of fch , fqa and ftype as only the fvar element of the tuple is needed in the example.

133

start = [(((1), []), []) | (([], [], [], []), , main())] e OP-DoMethodCallCl
MeasurementBasis , q);

[(((1), []), []) | (([], [], [], []), [ G [ L ]], { qbit q; q = new qbit(); return measure ( none, StdBasis s OP-Block

} M )]

[(((1), []), []) | (([], [], [], []), [ G [[ L ] L ]], qbit q; q = new qbit(); return measure ( none, StdBasis r OP-BlockHead

MeasurementBasis , q);

L M )]

[(((1), []), []) | (([], [], [], []), [ G [[ L ] L ]], qbit q; q = new qbit(); return measure ( none, StdBasis s OP-VarDecl

MeasurementBasis , q);

L M )]

134 r OP-BlockHead e OP-PromoExpr e OP-AssignExpr

[(((1), []), []) | (([], [], [], []), [ G [[ L ]L [q none]]], q = new qbit(); return measure ( none, StdBasis

MeasurementBasis , q);

L M )]

[(((1), []), []) | (([], [], [], []), [ G [[ L ]L [q none]]], q = new qbit(); return measure ( none, StdBasis

MeasurementBasis , q);

L M )]

[(((1), []), []) | (([], [], [], []), [ G [[ L ] L [q none]]], q = new qbit() ; return measure ( none, StdBasis

MeasurementBasis , q);

L M )]

Figure A.2: Program example: Random number generator execution (part 1/4).

e OP-AssignExpr [(((1), []), []) | (([], [], [], []), [ G [[ L ] L [q


MeasurementBasis , q);

none]]], new qbit() q = ; return measure ( none, StdBasis v OP-AllocQ

L M )]

[(( 1 2 e OP-SubstE

1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q none]]], 0 1 (Quantum, [1]), (GQuantum, [1]) Q2 q = ; return measure ( none, StdBasis MeasurementBasis , q); L M )]

[(( 1 2

1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q none]]], 0 1 q = (Quantum, [1]), (GQuantum, [1]) Q2 ; return measure ( none, StdBasis MeasurementBasis , q); L M )]

APPENDIX A. PROGRAM EXECUTION EXAMPLE

135 e OP-SubstS s OP-PromoForget

[(( 1 2

v OP-AssignQValue 1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 (Quantum, [1]), (GQuantum, [1]) Q2 ; return measure ( none, StdBasis MeasurementBasis , q); L M )]

[(( 1 2

1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 (Quantum, [1]), (GQuantum, [1]) Q2 ; return measure ( none, StdBasis MeasurementBasis , q); L M )]

Figure A.2: Program example: Random number generator execution (part 2/4).

s OP-PromoForget

[(( 1 2

1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 return measure ( none, StdBasis MeasurementBasis , q); L M )]

[(( 1 2

e OP-ReturnExpr 1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 measure( none, StdBasis MeasurementBasis , q) return ; L M )]

[(( 1 2 v OP-Var

e OP-MeasureExpr 1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 q measure( none, StdBasis MeasurementBasis , ) return ; L M )]

136 v OP-DoMeasure

[(( 1 2

1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 (Quantum, [1]), (GQuantum, [1]) Q2 measure( none, StdBasis MeasurementBasis , ) return ; L M )]

[(( 1 2

e OP-SubstE 1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 1 measure( none, StdBasis MeasurementBasis , (Quantum, [1]), (GQuantum, [1]) Q2 ) return ; L M )]

Figure A.2: Program example: Random number generator execution (part 3/4).

v OP-DoMeasure

0.5 [((

1 0 0 0.5 [(( 0
0.5

0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 none, 0 int return ; L M )] 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 1 none, 1 int return ; L M )] NP-ProbEvol
0.5

Evolution of measurement branch 0

Evolution of measurement branch 1

We continue showing the program evolution of the branch where the measurement returned the value 0 only. The other measurement branch evolves obviously the same way, the only dierence is in the measured value and the global quantum state.

APPENDIX A. PROGRAM EXECUTION EXAMPLE

137 0.5 NP-ProbEvol

[((

1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], 0 0 none, 0 int return ; L M )] e OP-SubstS 1 0 , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), [ G [[ L ] L [q (Quantum, [1])]]], [(( 0 0 return none, 0 int ; L M )] v OP-ReturnValue 1 0 [(( , [2]), []) | (([], [(Quantum, [1]) (GQuantum, [1])], [], []), , none, 0 int )] 0 0

Figure A.2: Program example: Random number generator execution (part 4/4).

138

Appendix B

Implementation
B.1 LanQ simulator

LanQ simulator has been implemented in Java language. It is therefore a multiplatform implementation which runs on any platform supported by Java 5. The simulator is publicly available from the address http://lanq.sourceforge.net/. Its source code without libraries has in total nearly 12,500 lines of code (more than 31,000 lines of code with comments and blank lines used to logically structure the code). The simulator can output the sequence of congurations and transitions of a program run to support quantum program and protocol verication. Currently, only text and LaTeX outputs are supported, XML output is planned. XML is a machine-readable format. Therefore after adding support for XML to LanQ, it can be used by other tools which can be for example: User-friendly debugger a (graphical) application which supports a step-by-step evaluation of a program and a visualisation of its conguration to allow programmers eectively nd any bugs in their code, Model checker this tool would check formulas expressing properties of given congurations and/or sequences of transitions. These tools are not available yet. However, they would help LanQ to become a more usable tool. User-dened operators and methods which are dened in libraries are supported by the existing implementation. An example of a library (partly taken from the LanQ standard library) is shown in Figure B.1. The operators and methods can be compiled to a Java class and then used. Hermitian operators and unitary matrices can be specied in matrix form. Note that the decision whether the given Hermitian operator represents a valid quantum operation or not is left on the user. The simulator is run by a command: java -jar lanq.jar executed in the same directory where the le lanq.jar is stored. In this form, it displays help on command-line parameters and exists. A LanQ program is run by the command: java -jar lanq.jar [options] le.lanq 139

B.2. REFERENCE MANUAL /********************************************* * Classical methods * *********************************************/ native lanq.library.methods.Dump_q; native lanq.library.methods.Print; /********************************************* * Pauli X operator * *********************************************/ unitary Sigma_x = [ [ 0, 1 ], [ 1, 0 ] ]; /********************************************* * A Hermitian operator * *********************************************/ hermitian ProjTo0 = [ [sqrt(2), 0], [0, 0]];

Figure B.1: Example of a LanQ library. where le.lanq is the le containing LanQ program to be run. Optional options specify additional options of the simulator as described in the following table: Option Meaning -v Be verbose display the stages of program manipulation -ct Display congurations and transitions in text mode A Display congurations and transitions in L TEX mode -cl -ci Display also internal transitions (eg. when waiting for communication) -o le Redirect system messages (ie. congurations, transitions, termination messages) to the given le

B.2
B.2.1

Reference manual
Statements

Block statement Syntax: { block-forming statements } Description: Groups given block-forming statements. 140

APPENDIX B. IMPLEMENTATION Fork statement Syntax: fork methodName([p0 [, p1 [, ...]]]); Description: Starts a new process. The process execution is started from given method methodName. Any nonduplicable resources passed as arguments to the newly started process become unavailable in the original process. If statement Syntax: if (expr ) statement1 [else statement2 ] Description: If given expr evaluates to true, executes the statement1, else executes the statement2. Return statement Syntax: return; return expr ; Description: Finishes execution of a current method and eventually returns given expr as a return value of the method. Send statement Syntax: send(channelEndName, value); Description: Sends given value value over a channel whose one end is available to the process as channelEndName. Any nonduplicable resource passed as the sent value becomes unavailable in the sending process. This is a blocking operation. Skip statement Syntax: ; Description: Performs no operation. While cycle Syntax: while (expr ) statement Description: While expr evaluates to true, executes given statement.

B.2.2
CNot

Quantum operators

Syntax: CNot(p0 ,p1 ); CNot(p2 ); 141

B.2. REFERENCE MANUAL Arguments:

Name p0 p1 p2

Type qbit qbit q4it

Description First qubit Second qubit Qu-4-it to apply the CNot operation on.

Description: Applies a CNOT operator to given qubits. Qubit p0 acts as a control qubit, qubit p1 acts as a target qubit. If the second variant is used, it applies CNOT operation onto the given 4-dimensional quantum system p2. Had Syntax: Had(p0 ); Arguments: Name p0 Type qbit Description Qubit to apply the operator on

Description: Applies Hadamard operator to the given qubit. Sigma x Syntax: Sigma x(p0 ); Arguments: Name p0 Type qbit Description Qubit to apply the operator on

Description: Applies Pauli x operator to the given qubit. Sigma y Syntax: Sigma y(p0 ); Arguments: Name p0 Type qbit Description Qubit to apply the operator on

Description: Applies Pauli y operator to the given qubit. Sigma z Syntax: Sigma z(p0 ); Arguments: Name p0 Type qbit Description Qubit to apply the operator on

Description: Applies Pauli z operator to the given qubit. 142

APPENDIX B. IMPLEMENTATION

B.2.3

Variable declarations

Variable declaration Syntax: T id0 [, id1 [, ...]]; Description: Declares new variables id0, id1, ... of type T. Compound system declaration Syntax: id0 aliasfor [id1 [, id2 [, ...]]]; Description: Declares a new quantum variable id0 which acts as a compound quantum system whose components are quantum systems id1, id2, ... Channel with ends declaration Syntax: channel[T] id0 withends [id1, id2 ]; Description: Declares a new channel variable id0 of type channel[T] and variables id1 and id2 of type channelEnd[T] which denote individual ends of the channel.

B.2.4

Expressions

Allocation expression Syntax: new T() Description: Allocates new quantum system (if T is a quantum type) or a new channel (if T is a channel type). Return value: The newly allocated resource. Assignment expression Syntax: x = expr Description: Assigns the result of evaluation of given expr to variable x. Return value: The result of evaluation of given expr. Bracket expression Syntax: (expr ) Description: Evaluates to the value of the expression expr. Return value: The value of the expression expr. Constant expression Syntax: c Description: Evaluates to the value of the constant c. Return value: The value of the constant c. 143

B.2. REFERENCE MANUAL Measurement expression Syntax: measure(basis, q0 [, q1 [, ...]]) Description: Measures given quantum systems q0, q1, ... in given measurement basis basis. Possible bases are StdBasis, DualBasis and BellBasis. Return value: The index of the measured eigenvalue. Method call expression Syntax: methodName([p0 [, p1 [, ...]]]) Description: Invokes the method methodName with given arguments. Return value: The return value of the called method. Recv expression Syntax: T recv(channelEndName) Description: Receives a value from given channel end. This is a blocking operation. Return value: The received value.

B.2.5

Operators and methods

Nonequality test operator Syntax: p0 ! = p1 Arguments: Name p0 p1 Type int int Description First number Second number

Description: Returns true i the numbers are nonequal. Plus operator Syntax: p0 + p1 Arguments: Name p0 p1 Type int int Description First number Second number

Description: Adds two numbers and returns result. 144

APPENDIX B. IMPLEMENTATION Minus operator Syntax: p0 p1 Arguments: Name p0 p1 Type int int Description First number Second number

Description: Subtracts second number from the rst and returns result. Equality test operator Syntax: p0 == p1 Arguments: Name p0 p1 Type int int Description First number Second number

Description: Returns true i the numbers are equal. dump q method Syntax: dump q(p0 ) Arguments: Name p0 Type qdit Description Quantum system of any dimension

Description: Displays the state (the density matrix) of the given quantum system. print method Syntax: print(p0 ) Arguments: Name p0 Type int Description integer to print

Description: Prints given integer to standard output.

145

S-ar putea să vă placă și