<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gideon.Smdng.nl</title>
	<atom:link href="http://gideon.smdng.nl/feed/" rel="self" type="application/rss+xml" />
	<link>http://gideon.smdng.nl</link>
	<description>Eating vowels for dinner</description>
	<lastBuildDate>Sat, 04 Apr 2009 19:33:57 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>An executable operational semantics for Python</title>
		<link>http://gideon.smdng.nl/2009/01/an-executable-operational-semantics-for-python/</link>
		<comments>http://gideon.smdng.nl/2009/01/an-executable-operational-semantics-for-python/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 17:02:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[latex]]></category>
		<category><![CDATA[lhs2tex]]></category>
		<category><![CDATA[literate]]></category>
		<category><![CDATA[operational]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[semantics]]></category>

		<guid isPermaLink="false">http://gideon.smdng.nl/?p=5</guid>
		<description><![CDATA[This article gives a taste of the operational semantics for Python that I wrote for my master's thesis. The thesis was developed with literate programming: the sources can be compiled to an interpreter or to the document that is my Thesis.]]></description>
			<content:encoded><![CDATA[<p>The following article gives a taste of the work that I&#8217;ve done for my <a href="http://gideon.smdng.nl/wp-content/uploads/thesis.pdf">master&#8217;s thesis</a> at the <a href="http://www.uu.nl">University of Utrecht</a> under the supervision of <a href="http://people.cs.uu.nl/andres/">Andres Löh</a>. If you are interested, feel free to have a look at the <a href='http://gideon.smdng.nl/wp-content/uploads/python-semantics-20090120tar.gz'>source files</a>.</p>
<h2>Introduction</h2>
<p>Programming languages are often specified only in an informal manner; in the available documentation, the language behaviour is described by examples and text. Only the implementation, a compiler or interpreter, describes the exact semantics of constructs.</p>
<p>Python is no different. It is described by an <a href="http://www.python.org/doc/2.5.2/ref/index.html">informal manual</a> and a number of implementations. Notably the original implementation <a href="http://wiki.python.org/moin/CPython">CPython</a> and <a href="http://codespeak.net/pypy/dist/pypy/doc/home.html">PyPy</a>, an implementation of Python in Python. No systematic, formal descriptions of its semantics are available.</p>
<p>We developed a formal semantics for a comprehensive subset of Python called minpy. The semantics are described in literate Haskell, which are compiled to an interpreter as well as a formal specification.</p>
<h2>Rewriting an abstract machine</h2>
<p>The operational semantics are defined by state transitions of an abstract machine. A machine state consist of a heap Θ, an environment stack Γ, a control stack S, and an instruction ι. State transitions are defined by rewrite rules that transform the machine state. These rewrite rules have the following shape.</p>
<p style="text-align: center;"><img class="size-full wp-image-8 aligncenter" title="Shape of a rewrite rule" src="http://gideon.smdng.nl/wp-content/uploads/rewrite-abstract-machine.png" alt="&lt;Θ,Γ,S,ι&gt; ⇒ &lt;Θ',Γ',S',ι'&gt;" width="223" height="28" /></p>
<p>The heap represents the memory of the abstract machine. It is a mapping of addresses to values. Many different kinds of values are stored on the heap, for example integers, strings, lists and objects.</p>
<p>Even the environment is partly stored on the heap. The environment Γ consists of a stack of addresses, which correspond with the scoping blocks that have been entered. The addresses point to mappings on the heap, which in turn map variables to addresses.</p>
<p>The control stack is a stack of continuation frames, i.e., frames that indicate what to do next. One of the traditional functions of a control stack (also known as call stack) is to store the return pointer of a function call that is being executed.</p>
<p>The instruction is the abstract equivalent of a program counter. The instruction can be a piece of a program, such as an expression, statement, or a complete block. But, for example, when an expression has been evaluated it can also hold the resulting address.</p>
<h2>Executing an assignment</h2>
<p>To show what the rewrite rules look like we will have a look at the semantics of variable assignments. Starting with the execution of a variable assignment statement x = e; as instruction, a heap Θ, an environment Γ and a stack S.</p>
<p><img class="size-full wp-image-10 alignnone" title="Executing an assignment statement" src="http://gideon.smdng.nl/wp-content/uploads/rule-execute-assignment.png" alt="&lt;Θ,Γ,S,x = e;&gt; ⇒ &lt;Θ,Γ,S|x = o,e&gt;" width="219" height="55" /></p>
<p>The state is rewritten to a new state that is virtually the same, except that a stack frame x = o is pushed onto the control stack and the expression e is the new instruction. The circle o in the new stack frame indicates that the expression which place it took, will be evaluated.</p>
<p>Once the expression has been evaluated, we end up with a state that has an address instruction a, a stack the assignment frame on top, an environment stack with an address γ₁ on top.</p>
<p><img class="size-full wp-image-13 alignnone" title="Binding a variable" src="http://gideon.smdng.nl/wp-content/uploads/rule-bind-variable.png" alt="&lt;Θ,Γ,S|x = o,e&gt; ⇒ &lt;Θ+[γ₁ → Θ(γ₁) + [x → a]], Γ|γ₁, S, a_None&gt;" width="443" height="56" /></p>
<p>The address γ₁ on top of the environment stack points to the variables bound in the current scope. In the new state, the mapping that contains the bindings is changed to include the new assignment. The environment stack however, remains unchanged. The top stack frame is removed and the result of the assignment statement is None, or rather an address pointing to None.</p>
<p>The changes to the heap are not very intuitive, so let us be more precise: the existing environment mapping bound at γ₁ is overwritten with the old mapping Θ(γ₁) that itself has been extended with the mapping [x → a]. The notation of Θ(γ₁) represents the lookup of γ₁ on the heap Θ. The circled addition operator extends the mapping on its left hand side with the mapping on its right hand side. If the both sides of the circled addition operator have a mapping of the same variable or address, the right hand side takes precedence.</p>
<h2>Literate programming</h2>
<p>The semantics of minpy are described in <a href="http://www.haskell.org/onlinereport/literate.html">literate Haskell</a>, a syntax extension of Haskell that allows us to mix <a href="http://www.haskell.org">Haskell</a> and <a>LaTeX</a> code in the same file. The Haskell compiler <a href="http://www.haskell.org/ghc/">GHC</a> will, when confronted with a literate Haskell file, simply ignore all the Latex code. Latex however, is not natively aware of the literate Haskell code, but can be <a href="http://www.haskell.org/haskellwiki/Literate_programming#Verbatim_package">instructed</a> to include the Haskell code verbatim in the document.</p>
<p>To exploit the advantages of LaTeX typesetting, we preprocessed the literate Haskell sources with <a href="http://people.cs.uu.nl/andres/lhs2tex/">lhs2TeX</a>. This tool transforms Haskell source code into a nicely formatted LaTeX equation. It handles horizontal alignment across multiple lines of code and allows us to customize the transformation through simple macros.</p>
<p>In order to hide all traces of Haskell from the formatted rewrite rules, we have pushed lhs2TeX to its limits. To achieve the current results we introduced an additional preprocessing stage, implemented by a simple Perl script. Furthermore, we had to accept certain restrictions on the Haskell vocabulary and adhere to a number of coding conventions. For example, every state has to be on a single line to get proper alignment. Some rules do not even fit on a 30&#8243; monitor.</p>
<p>The resulting source code is nevertheless quite readable, especially when compared to any equivalent LaTeX code. For instance, the above rule for variable binding is defined by the following code.</p>
<pre><code>rewrite  (State  ( heap                                              )  ( envs :|: env_1 )  ( stack :|: AssFrame x )  ( BwResult a      )) =
         (state  ( heap &lt;+&gt; [env_1 |-&gt; get heap env_1 &lt;+&gt; [x |-&gt; a]] )  ( envs :|: env_1 )  ( stack                )  ( BwResult a_None ))</code></pre>
<p>Note that, while compiling the document requires several steps, GHC can still compile the source code in a single step. This allows us to experiment with the semantics, while ignoring the presentation.</p>
<h2>The interpreter</h2>
<p>The sources of the thesis and some supporting code that implements a parser, pretty printer, and an interactive interpreter, can be compiled by the Haskell compiler GHC to produce an interpreter. Like the interpreter of CPython, this interpreter has both a command-line modus and the ability to interpret files.</p>
<p>The following example shows a session of the interpreter in its command-line modus. First, we declare the factorial function in a single function definition statement. The statement is immediately executed if parsing succeeds. Next, we call the factorial function without an argument, which results in a TypeError exception. Finally we call it with a correct argument and exit the interpreter.</p>
<pre>gideon@gideon-desktop:~$ minpy
&gt;&gt;&gt; def fac(x) :
...     if x &lt;= 0 :
...         return 1
...     else :
...         return fac(x-1) * x
...
&gt;&gt;&gt; fac()
TypeError
&gt;&gt;&gt; fac(4)
24
&gt;&gt;&gt; exiting minpy</pre>
<p>All this will be more than familiar to a Python programmer, except for the rather meager error message. The minpy interpreter can also print a trace of the abstract machine revealing any changes after every rewrite step. This has proven to be very useful when debugging the semantic rules.</p>
<p>The interpreter, and by proxy the semantics, was systematically tested by a test suite written in pure Python, or actually, minpy. Executing the suite with CPython results in only one <a href="http://bugs.python.org/issue3720">failed test</a>, as it is the reference for our semantics. Our interpreter still fails for 13 tests.</p>
<h2>Scope of the semantics</h2>
<p>As mentioned in the introduction, minpy includes a significant number of Python constructs. Functions, generators, objects and classes, operators, exceptions, if, while, for, exec, and import statements are supported, although most only in a simplified form. Class declarations, for instance, must always specify the bases of the class.</p>
<p>Currently, minpy does not have any garbage collection, support for concurrency or foreign functions. It should also be noted that, while minpy does support multiple inheritance, the implementation of metaclasses is still incomplete.</p>
]]></content:encoded>
			<wfw:commentRss>http://gideon.smdng.nl/2009/01/an-executable-operational-semantics-for-python/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
