<?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>Ahruman’s Webthing</title>
	<atom:link href="http://jens.ayton.se/blag/feed/" rel="self" type="application/rss+xml" />
	<link>http://jens.ayton.se/blag</link>
	<description>Cocoa coding stuff, when I can be bothered.</description>
	<lastBuildDate>Thu, 25 Aug 2011 21:56:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>P och NP nästan utan datorsvammel</title>
		<link>http://jens.ayton.se/blag/p-och-np-nastan-utan-datorsvammel/</link>
		<comments>http://jens.ayton.se/blag/p-och-np-nastan-utan-datorsvammel/#comments</comments>
		<pubDate>Thu, 25 Aug 2011 21:56:35 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[svenska]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=127</guid>
		<description><![CDATA[1928 ställde matematikern David Hilbert sitt Entscheidungs&#173;problem. Frågan var: finns det en algoritm – alltså en ändlig, fast uppställning deterministiska beräkningssteg – som, givet ett formellt språk och ett valfritt matematiskt påstående på det språket, kan avgöra om påståendet är &#8230; <a href="http://jens.ayton.se/blag/p-och-np-nastan-utan-datorsvammel/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>1928 ställde matematikern David Hilbert sitt <i lang="de">Entscheidungs&shy;problem</i>. Frågan var: finns det en algoritm – alltså en ändlig, fast uppställning deterministiska beräkningssteg – som, givet ett formellt språk och ett valfritt matematiskt påstående på det språket, kan avgöra om påståendet är sant eller falskt?</p>
<p>Alonzo Church löste problemet 1936 – svaret är nej. 1937 kom Alan Turing självständigt fram till samma svar med en annorlunda metod, och den lösningen är mest känd. För att formalisera algoritmbegreppet introducerade han en teoretisk “maskin”, <i>Turing&shy;maskinen</i>, som kan manipulera symboler på en remsa enligt en uppsättning regler.</p>
<p>Praktiska datorer är inspirerade av Turing&shy;maskinen, och har stora likheter med den. Bland annat kan de beräkna samma saker, och de har också samma komplexitets&shy;begränsningar: förhållandet mellan storleken på ett problem och den mängd tid och minne det tar att lösa följer samma mönster. (Principiellt gäller samma begränsningar också för människor under optimala förhållanden, det vill säga att de räknar rätt och i fast takt.)</p>
<p>Ett problem anses vara “hanterligt” om det kan lösas inom en tid som beskrivs av ett polynom i problems storlek, eller mindre (t.ex. <i>n</i>² mikrosekunder för att lösa ett beräkning med <i>n</i> poster). Dessa problem sägs tillhöra <i>komplexitets&shy;klassen</i> <b>P</b> (”<span lang="en">polynomial time</span>”).</p>
<p>Turing&shy;maskinen anses kunna beräkna alla funktioner som kan beräknas “effektivt”, vilket dock inte är bevisbart. Ett sätt att försöka motbevisa det är att luckra upp begränsningar i Turing&shy;maskinens definition, där den mest uppenbara är att den är deterministisk, alltså alltid gör samma sak i varje givet tillstånd. Frågan är: om man låter den välja slump&shy;mässigt mellan olika regler, kan den då lösa problem som en deterministisk Turing&shy;maskin (DTM) inte kan? Med andra ord, kan den få fram ett korrekt svar på ändlig tid som en deterministisk aldrig kan nå, om man antar att den vid varje tillfälle väljer “rätt”?</p>
<p style="font-size: 0.8em">(Gammalt datavetar&shy;skämt – man kan sortera en lista i linjär tid enligt följande: välj en ordning slumpmässigt efter en kvant-slumpkälla. Om listan är oordnad, förstör universum. Om flervärlds&shy;tolkningen stämmer har du rätt ordning i de världar som är kvar, annars finns det ingen kvar som kan klaga.)</p>
<p>Svaret på detta är nej; en ickedeterministisk Turing&shy;maskin (NTM) är inte mer generell än en deterministisk, eftersom en NTM kan simuleras av en DTM. Däremot förefaller den vara snabbare: det finns problem som har polynomtids&shy;lösningar på en NTM men ingen känd för DTM. Problem som kan lösas i polynomtid på en NTM tillhör komplexitets&shy;klassen <b>NP</b> (”<span lang="en">nondeterministic polynomial time</span>”).</p>
<p>Alla problem i <b>P</b> tillhör också <b>NP</b>, men man vet inte om motsatsen gäller. Man skulle kunna bevisa att de är lika genom att lösa ett så kallat <i><b>NP</b>-fullständigt</i> problem i polynomtid. Ett problem <i>K</i> är <b>NP</b>-fullständigt om man kan bevisa att alla problem i <b>NP</b> kan omformuleras till <i>K</i>.</p>
<p>Exempel på <b>NP</b>-fullständiga problem:</p>
<ul>
<li><b>Handelsresandeproblemet</b>: givet en uppsättning städer och vägar, hitta den kortaste rutten som besöker varje stad och slutar vid startpunkten. Uppenbara tillämpningar på logistik, men också mycket annat som programmering av industrirobotar.</li>
<li><b>Kappsäcksproblemet</b> (med varianter): givet en uppsättning saker med olika volym och värde, välj ut den värdefullaste kombinationen som kan packas i en viss behållare. Viktigt för handelsresande, men också för schemaläggning och andra typer av planering.</li>
<li><b>Primtalsfaktorisering</b>: givet ett stort tal <i>x</i>, hitta två primtal vars produkt är <i>x</i>. Grunden för de flesta kryptografiska system, eftersom det är väldigt lätt att bekräfta en korrekt lösning.</li>
<li>Diverse problem inom molkylärbiologi, till exempel multipel linjering/inpassning.</li>
</ul>
<p>Den som löser ett <b>NP</b>-fullständigt problem har således en lysande karriär framför sig i speditionsbranschen. Dessutom väntar ett startkapital på en miljon dollar i form av <a href="http://sv.wikipedia.org/wiki/Millennieproblemen">Millenniepriset</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/p-och-np-nastan-utan-datorsvammel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Imitating Greateness: 16-bit Hack ALU Design in Minecraft</title>
		<link>http://jens.ayton.se/blag/imitating-greatness/</link>
		<comments>http://jens.ayton.se/blag/imitating-greatness/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 18:58:11 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Minecraft]]></category>
		<category><![CDATA[logic]]></category>
		<category><![CDATA[minecraft]]></category>
		<category><![CDATA[redstone]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=116</guid>
		<description><![CDATA[In the autumn of 2010, a video of a sixteen-bit ALU in Minecraft by theinternetftw went viral. A month later, I’d bought the game, played around with circuits a bit and published a detailed description of a functionally identical (but &#8230; <a href="http://jens.ayton.se/blag/imitating-greatness/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In the autumn of 2010, a video of <a href="http://www.youtube.com/watch?v=LGkkyKZVzug">a sixteen-bit ALU in Minecraft</a> by theinternetftw went viral. A month later, I’d bought the game, played around with circuits a bit and published a detailed description of a functionally identical (but much smaller) ALU on the Minecraft forum – although not exactly in that order.</p>
<p>Due to changes in the Minecraft forum you can now only read <a href="http://www.minecraftforum.net/topic/63993-imitating-greatness-16-bit-hack-alu-design/">the original thread</a> if you’re logged in, and the formatting is messed up, so I’m reposting it here.</p>
<p>By functionally identical, I mean that my ALU has the same instruction set as theinternetftw’s – the Hack instruction set developed for the book <i><a href="http://www.amazon.com/Elements-Computing-Systems-Building-Principles/dp/026214087X">The Elements of Computing Systems</a></i>. I haven’t read the book, but there’s enough information available online to implement the ALU and most other components.</p>
<p>I didn’t copy any part of theinternetftw’s implementation, but I did use pre-existing XNOR gates and adders as noted in the text.</p>
<p>Minecraft is a moving target, but the ALU still works perfectly (and performs much better). If I built it today, I’d consider using repeaters for the data and control busses, but probably stick with torches because repeaters still aren’t implemented in Redstone Simulator. (Repeaters are simpler, and also give you a signal speed of 18 blocks per cycle if you use them well. Torches can do 17, but only 16 in tightly packed parallel busses.)</p>
<p>Some references:</p>
<ul>
<li> <a href="http://www1.idc.ac.il/tecs/book/preface.pdf">The preface to the book</a></li>
<li> <a href="http://www1.idc.ac.il/tecs/course/talk.pdf">Slides on the Hack architecture</a> (which I found after the initial implementation, but they helped clear some things up).</li>
</ul>
<p>Original posts follow. They’re largely unedited, so they reflect the evolution of the ALU.</p>
<p><span id="more-116"></span><br />
<hr />
<h2>Imitating Greateness: 16-bit Hack ALU Design<br /><span class="post-date" style="font-size: 9pt; color:#888">29 October 2010 – 16:06 (UTC+1)</span></h2>
<p>Like one or two other people, I saw <a href="http://www.youtube.com/watch?v=LGkkyKZVzug">theinternetftw’s ALU</a> video (and <a href="http://www.youtube.com/watch?v=iUjOg6EUgQs">the sequel</a>). I also wondered how it worked, or rather, how one might go around designing such a thing.</p>
<p>A few days later I bought Minecraft and started playing.</p>
<p>Today, I implemented what I believe is a functionally identical ALU in <a href="http://www.minecraftforum.net/topic/16084-baezons-redstone-simulator-v22/">MCRedstoneSim</a>. I shall now proceed to describe it in agonizing detail. Schematic files will be provided.</p>
<p>Some caveats:</p>
<ul>
<li> I haven’t built any part of it in-game.</li>
<li> I haven’t attempted to analyze theinternetftw’s design, and I haven’t read The Elements of Computing Systems. My design is based on the control bits shown in the first video and an understanding of how they’d be used in programming.</li>
<li> I don’t claim to be a redstone wizard. Most of the components are based on designs from the forum and wiki. The original parts can probably be improved.</li>
<li> I haven’t included the data busses, which account for a lot of bulk in theinternetftw’s design.</li>
<li> The “output is zero” flag is not implemented. This is just a NOR of all the output bits, though.</li>
</ul>
<p>The design took about six and a half hours. The result takes up 32&nbsp;×&nbsp;119&nbsp;×&nbsp;9 blocks (sixteen 6&nbsp;+&nbsp;1&nbsp;×&nbsp;27&nbsp;×&nbsp;5 logic elements, control busses and some interface), and uses 2237 wires and 687 torches.</p>
<h3>Specification</h3>
<p>The ALU takes two sixteen-bit inputs (<b>X</b> and <b>Y</b>) and six control bits, and produces a sixteen-bit output (<b>OUT</b>) plus an overflow flag. The control bits are:</p>
<ul>
<li> <b>ZX</b>: if <code>1</code>, treat <b>X</b> as all-zeros.</li>
<li> <b>NX</b>: if <code>1</code>, invert <b>X</b> (that is, flip all bits). Applied after <b>ZX</b>, so if both are set <b>X</b> is treated as all ones. The result of applying <b>ZX</b> and <b>NX</b> to <b>X</b> is referred to as <b>X&#39;</b>.</li>
<li> <b>ZY</b>: like <b>ZX</b>, but for the <b>Y</b> input.</li>
<li> <b>NY</b>: guess.</li>
<li> <b>F</b> (function): if <code>0</code>, the preliminary output <b>O&#39;</b> is the bitwise AND of <b>X&#39;</b> and <b>Y&#39;</b>. If <code>1</code>, <b>O&#39;</b> is the low sixteen bits of the sum of <b>X&#39;</b> and <b>Y&#39;</b>. The seventeenth bit is the overflow flag, <b>FO</b>.</li>
<li> <b>NO</b>: if <code>0</code>, the output <b>OUT</b> is equal to <b>O&#39;</b>. If <code>1</code>, <b>OUT</b> is the bitwise inverse of <b>O&#39;</b>.</li>
</ul>
<p>Currently, <b>FO</b> is not affected by <b>NO</b>, and is meaningless of <b>F</b> is <code>0</code>.</p>
<h3>High-level design</h3>
<p>The design consists of sixteen identical logic elements, which each takes two input bits <b>X<sub>n</sub></b> and <b>Y<sub>n</sub></b>, an input carry bit <b>CI<sub>n</sub></b> for ripple-carry adding, and the six control bits on perpendicular buses. Each element produces an output bit <b>O<sub>n</sub></b> and an output carry bit <b>CO<sub>n</sub></b>. Getting the bits in and out of the ALU is beyond the scope of this project; I’m just using levers and trailing wires.</p>
<h3>Input filters</h3>
<p>The first thing the logic element needs to do is apply the <b>ZX</b>, <b>NX</b>, <b>ZY</b> and <b>NY</b> flags to the input. This requires two functionally identical circuits I call <i>input filters</i>.</p>
<p>The obvious way to implement this would be (<b>X</b>&nbsp;<abbr title="AND">∧</abbr>&nbsp;<abbr title="NOT">¬</abbr><b>ZX</b>) <abbr title="XOR">⊻</abbr> <b>NX</b>. However, an equivalent option with lower latency is (¬<b>X</b>&nbsp;<abbr title="OR">∨</abbr> <b>ZX</b>)&nbsp;=&nbsp;<b>NX</b>.</p>
<div class="digression" style="font-size:smaller; margin:0 2em; background-color:#eee">
<p><i>Digression:</i> To see this, first note that equality (aka XNOR) with one negated term implements inversion: if <b>NX</b> is&nbsp;<code>0</code>, (¬<b>X</b>&nbsp;=&nbsp;<b>NX</b>) is <b>X</b>, while if <b>NX</b> is&nbsp;<code>1</code>, it’s ¬<b>X</b>. (<b>X</b>&nbsp;∧&nbsp;¬<b>ZX</b>) = (¬<b>X</b>&nbsp;∨&nbsp;<b>ZX</b>) by <a href="http://en.wikipedia.org/wiki/De_Morgan%27s_laws">De Morgan’s laws</a>.</p>
</div>
<p>The wiki has <a href="http://www.minecraftwiki.net/wiki/Redstone_circuits#XNOR_Gate_.28.E2.89.A1.29">several XNOR gates</a>. I chose variant C for its compact design, low latency and narrow profile. By running the output across the top of the gate and the <b>X</b> input into an inverter attached to the side, the input filter including its three inputs is three wide and has a three-tick latency.</p>
<div class="digression" style="font-size:smaller; margin:0 2em; background-color:#eee">
<p><i>Digression:</i> If there was an input bus, some of the logic elements would be able to get pre-inverted inputs to save a tick. It would be best to arrange for the low-order logic element to be pre-inverted, because the overall latency of the addition operation depends on the half-add latency of the low-order element and the total carry latency across all elements.</p>
<p>Also, the three-tick latency is only incurred if the <b>X</b> goes low while <b>NX</b> is high. This could be avoided with a good instruction fetcher.</p>
</div>
<p>Here’s a model input filter. <b>X</b> is on the left, and the top two levers are <b>ZX</b> and <b>NX</b> in order.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-input-filter.gif" style="max-width:100%" alt="Model input filter schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-input-filter.schematic">Schematic file</a></p>
<p>I initially placed the two filters directly opposite each other, but I ended up staggering them by two blocks to be able to fit the four control bit inputs between them in a two-block space. The <b>ZX</b> and <b>NX</b> busses will run on bridges and connect to the north filter, while <b>ZY</b> and <b>NY</b> run in tunnels and connect to the south filter. <b>ZY</b> is provided by a torch immediately under the protruding wired block, while the others run on stairs. The buses and their controls are included in the schematic file but left out of the image for clarity.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-two-input-filters.gif" style="max-width:100%" alt="Input filter pair schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-two-input-filters.schematic">Full schematic file</a> (Control bits in order: ZX, NX, ZY, NY)</p>
<h3>Operations</h3>
<p>The input filters produce the values <b>X&#39;</b> and <b>Y&#39;</b>. The next step is to add these and AND them. We’ll select the appropriate value based on the <b>F</b> flag later.</p>
<p>The adder is <a href="http://www.minecraftforum.net/topic/14679-red-stuff-logic-gates/page__view__findpost__p__986131">vandrien’s 5&nbsp;×&nbsp;7&nbsp;×&nbsp;3 design</a> with no modifications. (This is the niftiest part of the entire design – if I had to design my own adder the ALU would be twice as big and significantly slower. Thanks, vandrien!) The <b>Y&#39;</b> line is rerouted slightly. The switch at the top is <b>CI</b>, and the dangling wire at the bottom is <b>CO</b>.</p>
<p class="image"><img src="http://jens.ayton.se/minecraft/alu-with-adder.png" style="max-width:100%" alt="Input filter and adder schematic, floor-level schematic"></p>
<div class="digression" style="font-size:smaller; margin:0 2em; background-color:#eee">
<p><i>Performance:</i> The worst-case latency of the adder is five ticks, but carries are generated, handled and propagated in two ticks. By the time the carry ripple reaches the high-order element, its half-add will be complete, so the carry latency is all that matters for overall time.</p>
</div>
<p>I originally had a separate NAND gate on top of the adder. While decomposing the design from this writeup, I noticed that the <b>X&#39;</b> wire wasn’t connected, but it was working anyway. Turns out I was accidentally extracting an AND from the adder and then NANDing that with <b>Y&#39;</b>. The revised design just uses the AND from the adder directly. The source is either of the two opposing torches on the input side of layer 2 of the adder.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-adder-and.gif" style="max-width:100%" alt="Adder and AND schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-with-adder-and.schematic">Full schematic file</a></p>
<h3>Output muxer</h3>
<p>The next step is to select the appropriate preliminary output, <b>O&#39;</b>. This requires a selector (muxer) circuit which takes three inputs, <b>A</b>, <b>B</b> and <b>S</b>, and outputs <b>A</b> if <b>S</b> is <code>1</code> and <b>B</b> if <b>S</b> is <code>0</code> – that is, (<b>A</b>&nbsp;∧&nbsp;<b>S</b>) ∨ (<b>B</b>&nbsp;∧&nbsp;<b>¬S</b>). Here, <b>S</b> is in the middle to avoid crossing anything. (It will be routed through a tunnel.)</p>
<div class="digression" style="font-size:smaller; margin:0 2em; background-color:#eee">
<p><i>Performance:</i> The latency of the muxer is three when changing <b>S</b> and two for anything else. In a full CPU, it’s reasonable to assume <b>S</b>&nbsp;(<b>F</b>) will be set before the other inputs are ready.</p>
</div>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-output-selector.gif" style="max-width:100%" alt="Output selector schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-output-selector.schematic">Schematic file</a></p>
<p>Plugged in:</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-with-selector.png" style="max-width:100%" alt="ALU channel schematic with output muxer, floor-level schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-with-selector.schematic">Full schematic file</a> (Control bits: ZX, NX, ZY, NY, F)</p>
<h3>Output filter</h3>
<p>The output filter is much like the input filter, but without a zero flag. It consists of an XNOR gate (wiki type C again) which takes <b>O&#39;</b> from the muxer and ¬<b>NO</b> from a tunnelled bus.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-complete-element.png" style="max-width:100%" alt="Complete ALU channel, floor-level schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-with-selector.schematic">Full schematic file</a> (Control bits: ZX, NX, ZY, NY, F, NO)</p>
<p>And there you have it: a one-bit ALU. Here’s a block diagram:</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-block-diagram.png" style="max-width:100%" alt="Output selector schematic"></p>
<p>The complete sixteen-bit version consists of sixteen of these side by side, with their carry flags chained together (low-order bit at the top, high-order bit at the bottom). I’ll spare you the details of working out the control bus wiring and stuff. The final design consists of eight identical two-element modules, with one set of bus repeaters per module, so the bus latency averages one tick per bit. Here it is, calculating its own redstone cost (2237&nbsp;+&nbsp;687 =&nbsp;2924, or 1000&nbsp;1011&nbsp;1101 + 0010&nbsp;1010&nbsp;1111 = 1011&nbsp;0110&nbsp;1100):</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-2237-plus-687.png" style="max-width:100%" alt="Complete revision 1 ALU schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-sixteen-bits.schematic">Full schematic file</a></p>
<div class="digression" style="font-size:smaller; margin:0 2em; background-color:#eee">
<p><i>Operations:</i> It may not be immediately obvious how an ALU with only two operations is enough for useful computation, but the input and output flags let you do quite a lot. Some examples:</p>
<ul>
<li> Move = AND one input with all ones: <b>ZY NY AND</b> &lt;<i>source</i>&gt; &lt;<i>anything</i>&gt;</li>
<li> NOT = move with negate: <b>ZY NY NO AND</b> &lt;<i>source</i>&gt; &lt;<i>anything</i>&gt;</li>
<li> Clear (generate a zero): <b>ZY ZX AND</b> &lt;<i>anything</i>&gt; &lt;<i>anything</i>&gt;</li>
<li> NAND: <b>NO AND</b> &lt;<i>a</i>&gt; &lt;<i>b</i>&gt;</li>
<li> NOR = ¬X ∧ ¬Y: <b>NX NY AND</b> &lt;<i>a</i>&gt; &lt;<i>b</i>&gt;</li>
<li> OR = ¬(¬X ∧ ¬Y): <b>NX NY NO AND</b> &lt;<i>a</i>&gt; &lt;<i>b</i>&gt;</li>
<li> Subtract: <b>NX NO ADD</b> &lt;<i>a</i>&gt; &lt;<i>b</i>&gt;</li>
</ul>
<p>For more, see slide 24 of <a href="http://www1.idc.ac.il/tecs/course/talk.pdf">this presentation</a>.</p>
</div>
<h3>Future directions</h3>
<ul>
<li> The output muxer could probably be made smaller. It’s pretty much the first design that came to mind.</li>
<li> It looks like I could shave off two columns of length, one on each side of the op logic block. The output muxer would need to be flipped over, and the control bit bus negated.</li>
<li> The input filter section is seven wide (including insulation), while the other blocks are six. I think it’s possible to make the input filter section one block narrower by flipping the filters so the control inputs are on the outside, and sharing the inputs between adjacent elements. The input order would then alternate (the first element would have <b>X₀</b> on top and <b>Y₀</b> on the bottom, and the second would have <b>Y₁</b> on top and <b>X₁</b> on the bottom).</li>
<li> Performance profiling. An add should take about 40 ticks, but I haven’t timed it.</li>
<li> Carry look-ahead adder for moar faster. By which I mean “slightly less slow.”</li>
<li> Other computer components: program counter, I/O controller, RAM, ROM. I probably won’t bother with all of them.</li>
</ul>
<h3>FAQ</h3>
<ul>
<li> <i>What’s the point?</i><br />
I don’t understand the question.<br />
Seriously, if you’re going to ask what the <em>point</em> is of doing something for <em>fun</em> in a <em>game</em>, why are you even on this forum?</li>
</ul>
<hr />
<h2>Improved input filter<br /><span class="post-date" style="font-size: 9pt; color:#888">30 October 2010 – 20:26</span></h2>
<p>Improved input filter (and control bus) design, as outlined in first post.</p>
<p>The input filters now have the control inputs outwards, with one space between them, allowing the entire element to be one block narrower. The staggering is also removed, saving two blocks of length, with the control bus zig-zagging instead. Control inputs are torches (for isolation) on top of one torch in the appropriate bus repeater. The busses are negated.</p>
<p>This arrangement increases control bit latency. Wiring the low-order bit’s input differently could eliminate this delay for the add operation.</p>
<p>Since control bits are shared between adjacent input filters in different cells, the input bit order alternates: <b>X₀</b>, <b>Y₀</b>, <b>Y₁</b>, <b>X₁</b>, <b>X₂</b>, <b>Y₂</b>, <b>Y₃</b>, <b>X₃</b>. This will be rather inconvenient to use directly, but can be hidden by appropriate input bus wiring. The control bit order has also changed, to <b>ZX</b>, <b>ZY</b>, <b>NX</b>, <b>NY</b>.</p>
<p>The outputs adder stage will be moved up and back three steps, eliminating the staircase.</p>
<p>I’m not sure what I’m going to do about the output side yet.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-new-input-filter.gif" style="max-width:100%" alt="Four input filter pairs in the new arrangement"><br />
<a href="http://jens.ayton.se/minecraft/alu-new-input-filter.schematic">Schematic file</a></p>
<hr />
<h3>Improved output muxer<br /><span class="post-date" style="font-size: 9pt; color:#888">30 October 2010 – 20:11</span></h3>
<p>Flipping the output muxer over and smashing it into the side of the adder worked out nicely, saving two columns. The select input (circled) is again fed by the <b>NO</b> bus repeater. The bus itself runs at ground level.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-new-adder-and-mux.png" style="max-width:100%" alt="Improved adder and muxer schematic"><br />
<a href="http://jens.ayton.se/minecraft/alu-new-four-bit.schematic">Schematic file</a> (four bits wide)</p>
<p>The output negator XNOR can then be stuck right on the end of that, one step below, with no wiring gap. The control input is tunnelled, and connected to the circled block using two vertical torches. (The extra latency is not a problem, since the data has to go through all the previous blocks first.)</p>
<hr />
<h2>In-game prototype<br /><span class="post-date" style="font-size: 9pt; color:#888">31 October 2010 – 01:56</span></h2>
<p>While waiting for the update server to come back to life, I built a one-bit element in-game.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-one-bit-practical.png" style="max-width:100%" alt="Screen shot of ALU element in game"></p>
<p>Totally legit! Many sheep were seriously annoyed in the making of this device. (Wooden parts are control lines, wool is the structure of the logic element, stone is support structure, access ladders and so forth.)</p>
<p><a href="http://jens.ayton.se/minecraft/alu-new-sixteen-bits.schematic">Here’s the full sixteen-bit schematic</a>, again set to calculate its own component cost (including control interface): 1858 wires (0111&nbsp;0100&nbsp;0010) + 748 torches (0010&nbsp;1110&nbsp;1100) = 2606 redstone (1010&nbsp;0010&nbsp;1110). The 61 extra torches are the vertical-stack control line connections and input inverters, and the 379 fewer wires are space savings and simpler control busses.</p>
<p>The schematic is 26&nbsp;×&nbsp;104&nbsp;×&nbsp;12; 7 columns and 7 rows are interface, and 4 layers are control busses. The logic is 19&nbsp;×&nbsp;(5&nbsp;×&nbsp;16&nbsp;+&nbsp;17 = 97)&nbsp;×&nbsp;8.</p>
<hr />
<h2>Load immediate and control &#038; output busses<br /><span class="post-date" style="font-size: 9pt; color:#888">31 October 2010 – 04:42</span></h2>
<p>In addition to the ALU instructions, the Hack architecture has only one more instruction, the <b>@</b> instruction (or, more traditionally, “load immediate”). This loads a fifteen-bit value into register <i>A</i>. This can be integrated into the ALU by simply whacking another muxer on the end. This muxer takes the ALU output and the corresponding instruction bit (always zero for the high-order bit) as inputs, and the relevant control bit as the selector input.</p>
<p>Rather than add another switch to each element, I added a complete instruction bus. This can take either an <b>@</b> instruction or an ALU instruction. Both use very simple encodings, so the decoder just has to run wires to the right control inputs. The instruction codings are as follows:</p>
<p><b>@ instruction:</b><br />
<code>0DDD DDDD DDDD DDDD</code></p>
<ul>
<li><i>ALU:</i> Copy the instruction word to the output bus.</li>
<li><i>Output controller:</i> write ALU output to register <i>A</i>.</li>
<li><i>Program counter:</i> increment unconditionally.</p>
</li>
</ul>
<p><b>Logic instruction:</b><br />
<code>111A CCCC CCDD DJJJ</code><br />
The bits in each field are numbered from left (high-order) to right, so <b>C₁</b> is adjacent to <b>A</b> and <b>C₆</b> is adjacent to <b>D₁</b>.</p>
<ul>
<li><i>ALU:</i> Set <b>ZX</b> to <b>C₁</b>, <b>NX</b> to <b>C₂</b>, <b>ZY</b> to <b>C₃</b>, <b>NY</b> to <b>C₄</b>, <b>F</b> to <b>C₅</b>, and <b>NO</b> to <b>C₆</b>.</li>
<li><i>Input controller:</i> if <b>A</b> is <code>0</code>, set <b>Y</b> to register <i>A</i>. Otherwise, set <b>Y</b> to the contents of memory at the address specified by register <i>A</i> (referred to as <i>RAM[A]</i> or <i>M</i>). (<b>X</b> is always set to register <i>D</i>).</li>
<li><i>Output controller:</i> if <b>D₁</b>, write to register <i>A</i>. If <b>D₂</b>, write to register <i>D</i>. If <b>D₃</b>, write to <i>RAM[A]</i> (presumably the value of <i>A</i> before updating it). Any combination is valid.</li>
<li><i>Program counter:</i> given condition bits <b>NG</b> (the high bit of the ALU output) and <b>ZR</b> (the NOR of all the output bits), jump to <i>ROM[A]</i> if (<b>J₁</b>&nbsp;∧&nbsp;<b>NG</b>) ∨ (<b>J₂</b>&nbsp;∧&nbsp;<b>ZR</b>) ∨ (<b>J₃</b>&nbsp;∧&nbsp;(<b>NG</b>&nbsp;<abbr title="NOR">⊽</abbr>&nbsp;<b>ZR</b>)), otherwise to the next instruction (dur). All combinations of <b>J</b> bits are valid.</li>
</ul>
<p>(Note: RAM and ROM addresses are word addresses, or to put it differently, both the word size and the byte size is 16 bits.)</p>
<p>Here’s the instruction “<code>DM=D+A</code>” entered into the input bus (top right, levels 6–7):</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-instruction-bus-inputs.png" style="max-width:100%" alt="Control bus unput"></p>
<p>The bits are in reverse order for routing reasons. (If you were standing in front of it facing south, it would be the right way around.) The three bits on the right are the logic instruction prefix (currently only the top bit matters, but the other two could be used for new instructions). The colour-coded ones are the control bits for logic ops; from right to left, <b>ZX</b>, <b>NX</b>, <b>ZY</b>, <b>NY</b>, <b>F</b> and <b>NO</b>. Destination bits <b>D₂</b> and <b>D₃</b> are set, but of course do nothing since there’s no output controller, and the condition bits are clear for no jump.</p>
<p>The logic element outputs are now in the middle of the schematic, so I added an output bus too (ending top right, layers 13-14). Here it is showing the value 5285 (0001&nbsp;0100&nbsp;1010&nbsp;0101), once again backwards.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-output-bus-endpoint.png" style="max-width:100%" alt="Output bus output"></p>
<p><a href="http://jens.ayton.se/minecraft/alu-with-instruction-and-output-busses.schematic">Schematic</a>, set to calculate its own component cost in accordance with ancient tradition: 4232 wires (0001&nbsp;0000&nbsp;1000&nbsp;1000) + 1053 torches (0000&nbsp;0100&nbsp;0001&nbsp;1101) = 5285 redstone (0001&nbsp;0100&nbsp;1010&nbsp;0101).</p>
<p>Design note: seven of the input bits are essentially duplicated in the control bit busses. This could be avoided, but the <b>@</b> instruction would be slower, and it’s not clear that the recovered space could be used for anything since it’s underneath the output bus. I’ll revisit this if/when the other components are designed.</p>
<hr />
<h2>Input busses<br /><span class="post-date" style="font-size: 9pt; color:#888">31 October 2010 – 08:54</span></h2>
<p>…and the logical next step is wiring the input busses. Nothing very interesting about them.</p>
<p><a href="http://jens.ayton.se/minecraft/alu-with-all-busses.schematic">Schematic</a>, set up to calculate 6357 (0001&nbsp;1000&nbsp;1101&nbsp;0101) + 1177 (0000&nbsp;0100&nbsp;1001&nbsp;1001) = 7534 (0001&nbsp;1101&nbsp;0110&nbsp;1110).</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/alu-with-all-busses.gif" style="max-width:100%" alt="Complete ALU schematic with all four busses"></p>
<hr />
<h2>ROM idea<br /><span class="post-date" style="font-size: 9pt; color:#888">7 November 2010 – 19:53</span></h2>
<p>I haven’t done anything interesting (of relevance) this weekend, so here’s something boring instead: ROM. This will store the program, so the more you can fit in the available space the more the computer can do.</p>
<p>This is the cleverest ROM design I’ve been able to come up with, but it might not be the smartest – I suspect a less compressed design may end up taking less space when you consider stacking and control interfaces. I need to build several layers of each type, with output busses, to test this.</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/compact-rom.gif" style="max-width:100%" alt="Single ROM word schematic"><br />
<a href="http://jens.ayton.se/minecraft/compact-rom.schematic">Schematic file</a></p>
<p>Each 1 bit is represented by a torch, and each zero bit (none in the schematic) by the absence of a torch. When the select line is off, the torches are powered and thus zero.</p>
<p>Half the bits feed into a bus above the module, and the other half a bus below the module. Feeding both into a compact bus above the module is possible, but requires more space and introduces delays.</p>
<p>I tried to come up with a way to avoid the parallel select line and space, but failed.</p>
<p>This module can be tiled in two dimensions without any space between copies. Repeater banks are required every three modules in the east/west direction. In the north/south direction, the two output busses are uninterrupted between words, so it’s easy to interpret the ROM as 8-bit or 32-bit elements just by putting a different output bus muxer on the end.</p>
<p>Here’s an eight-word matrix with output bus:</p>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/compact-rom-array.gif" style="max-width:100%" alt="8 word ROM matrix schematic"><br />
<a href="http://jens.ayton.se/minecraft/compact-rom-array.schematic">Schematic file</a></p>
<p>The rows are selected by putting a torch under a negated section of each row bus to force it to zero when not selected. The rows are then fed into the (positive) bus using the same technique. Note that there are currently two levers for each row, one for the low half-bus and one for the high, and these levers are negated while the column select levers are positive.</p>
<hr />
<h2>ALU download and exploded diagram<br /><span class="post-date" style="font-size: 9pt; color:#888">31 October 2010 – 21:31</span></h2>
<p>I present, for your supremely geeky enjoyment, the ALU saved game.</p>
<p class="image" style="font-size:smaller"><a href="http://jens.ayton.se/minecraft/alu-test-2.jpg"><img src="http://jens.ayton.se/minecraft/alu-test-2.jpg" style="max-width:100%" alt="In-game screen shot of complete ALU"></a><br />
<a href="http://jens.ayton.se/minecraft/alu-world.zip">Download</a></p>
<p>(The ALU is not well lit. I strongly recommend setting the game to peaceful before loading.)</p>
<p>In the middle is the ALU, essentially per the schematic above. However, I’ve aded some lights, walkways and signs, and improved the interfaces (except the instruction input, because I got bored). The low-order ALU channel is colour-coded and signposted.</p>
<p>To the right in the picture is a prototype input interface with feedback lights. It’s too bulky to integrate easily, but lifting all the lines off the top of a minimum-width bus was fun.</p>
<p>To the left is an “exploded” ALU channel. It implements the same logic as the ones in the full ALU, but is divided into distinct gates. The individual gates are mostly different from the ones in the real ALU, but they interact in the same way. It’s also colour-coded in the same way as the low-order “real” channel.</p>
<h3>Section 1: input filters</h3>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/exploded-alu-1.png" alt="Exploded diagram: input filters"></p>
<p>The first section consists of the two input filters, the <b>X</b> input filter (right in diagram, diamond on map) and the <b>Y</b> input filter (gold). The main gate in each input filter is an XNOR gate (here <a href="http://www.minecraftwiki.net/wiki/Redstone_circuits#XNOR_Gate_.28.E2.89.A1.29">wiki type A</a>). The <b>X</b> input filter compares the <b>NX</b> control bit – lower right side input in diagram – with (NOT <b>X</b> OR <b>ZX</b>). If both <b>NX</b> and <b>ZX</b> are zero, the output on the <b>X</b> side will be <b>X</b>. If <b>NX</b> is set, it will be ¬<b>X</b>. If <b>ZX</b> is set, it will be <code>0</code>, and if both <b>ZX</b> and <b>NX</b> are set, it will be <code>1</code>.</p>
<p>For simplicity, I’ll refer to the filtered outputs as <b>X</b> and <b>Y</b> below, but this is misleading if any of the <b>NX</b>/<b>NY</b>/<b>ZX</b>/<b>ZY</b> control bits are set.</p>
<p>Logic:<br />
<code>X′ = (¬X ⋁ ZX) ↔ NX<br />
Y′ = (¬Y ⋁ ZY) ↔ NY</code></p>
<h3>Section 2: core functions</h3>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/exploded-alu-2.png" alt="Exploded diagram: core functions"></p>
<p>The second section is a full adder (made out of clay on the map). It consists of two almost identical modules, which are called half-adders. A half-adder takes two input bits, and produces a two-bit output ranging from 0 to 2. The possible combinations are:</p>
<table>
<tr>
<th>X</th>
<th>Y</th>
<th>out</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>00</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>01</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>01</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>10</td>
</tr>
</table>
<p>Note that the low bit of the output is equal to X XOR Y, and the high bit is X AND Y. The half-adder used here, which is identical to the second one in the “real” ALU, is similar to <a href="http://www.minecraftwiki.net/wiki/Redstone_circuits#XOR_Gate_.28.E2.8A.BB.29">wiki XOR gate A</a>, but rearranged so an internal NAND value can be pulled out (and inverted) on either side.</p>
<p>A half-adder is sufficient for a one-bit computer, but to add multiple bits we need to be able to take a carry input and add it to the sum. This is done with a second half-adder which takes the low bit of the first one as one input, and the incoming carry bit from the previous ALU channel as the other input. (This is called ripple-carry adding. There are faster approaches, but they take more space.)</p>
<p>The carry output is the OR of the two half-adders’ carry outputs. This value and the output of the second adder form a two-bit number which is the sum of the three inputs <b>X</b>, <b>Y</b> and <b>CI</b>:</p>
<table>
<tr>
<th>X</th>
<th>Y</th>
<th>CI</th>
<th>out</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
<td>00</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>0</td>
<td>01</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
<td>01</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
<td>10</td>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>01</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
<td>10</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>1</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>11</td>
</tr>
</table>
<p>The ALU has two core functions, ADD and AND. The AND (denoted <b>A</b> below) is acquired by a bridge (brick) from the second AND output of the first half-adder, along the right hand side of the diagram. The ADD value is denoted <b>S</b>, for “sum”.</p>
<p>Logic:<br />
<code>S = X′ ⊻ Y′ ⊻ Ci<br />
CO = (X′ ⋀ Y′) ⋁ ((X′ ⊻ Y′) ⋀ CI)<br />
A = X′ ⋀ Y′</code></p>
<h3>Section 3: function muxer</h3>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/exploded-alu-3.png" alt="Exploded diagram: function muxer"></p>
<p>The third section (obsidian) selects one of the two functions, based on the <b>F</b> control bit. If <b>F</b> is set, the ADD function is selected. Otherwise, the AND function is selected. In logic terms, that’s (<b>F</b> AND <b>S</b>) OR ((NOT <b>F</b>) AND <b>A</b>), here implemented as two <a href="http://www.minecraftwiki.net/wiki/Redstone_circuits#AND_Gate_.28.E2.88.A7.29">basic ANDs</a>, a NOT and a bridge.</p>
<p>Logic:<br />
<code>O′ = (F ⋀ S) ⋁ (¬F ⋀ A)</code></p>
<h3>Section 4: output filter</h3>
<p class="image" style="font-size:smaller"><img src="http://jens.ayton.se/minecraft/exploded-alu-4.png" alt="Exploded diagram: output filter"></p>
<p>The output filter (iron) inverts the output if the <b>NO</b> control bit is set. It’s a single XNOR gate like the ones in the input filter. Since the input isn’t inverted in this case, the <b>NO</b> bit is instead. This is equivalent to using an XOR gate, but is a bit more compact in redstone.</p>
<p>Logic:<br />
<code>O = O′ ↔ ¬NO = O′ ⊻ NO</code></p>
<h3>Section 5: load immediate muxer</h3>
<p>This isn’t included in the exploded channel. On the real ALU, it’s identical to the <b>F</b> mux, but one step down and made out of cossy mobblestone.</p>
<h3>Using the full ALU</h3>
<p>The instruction format is exactly the same as for <a href="http://www.youtube.com/watch?v=ahTv9drZ2GQ">theinternetftw’s CPU</a>. However, mine doesn’t have any registers yet, so you’ll need to copy data from the output to the inputs. Since there’s no I/O, no clock is needed (beyond Minecraft’s update ticks); when the output bank stops changing, it’s finished calculating.</p>
<hr />
<h2>An optimization question<br /><span class="post-date" style="font-size: 9pt; color:#888">11 December 2010 – 16:27</span></h2>
<p>
<blockquote><b>CX gamer <a href="http://www.minecraftforum.net/topic/63993-imitating-greatness-16-bit-hack-alu-design/page__view__findpost__p__1505035">said</a>:</b><br />
Is it possible to apply pipelining to this, so the performance of multiple consecutive calculations can greatly be improved?</p></blockquote>
<p>Probably not within the ALU itself. In a full CPU, you could use instruction prefetching (possibly with prediction of unconditional branches) and start issuing the next instruction slightly before the IO parts of the current one are processed, at least if there’s no memory read in the next instruction. Other obvious optimizations would be a one-word RAM cache, possibly with a second word of write buffer, and tight timing of the various dispatch stages. But in terms of actually being able to <em>do</em> anything, the main focus has to be keeping it small, so you can fit as much RAM as possible.</p>
<p>All high-level CPU optimizations, like pipelining, better algorithms and more powerful high-level instructions (like multiplication) are based on using more CPU die area to do stuff in smarter ways. Since Minecraft space isn’t subject to Moore’s law, we can’t really expect to see much of that sort of improvement in Minecraft computing, although if Notch adds SSI components (like one-block logic gates and latches) things could get interesting.</p>
<p>(Actually, there is one major space saving that can be done now: stacking the ALU and bus channels vertically. Avus, <a href="http://www.minecraftforum.net/topic/63993-imitating-greatness-16-bit-hack-alu-design/page__view__findpost__p__1150559">above</a>, had the right idea, although the size of each channel eats up most of the optimization.) </p>
 <p><a href="http://jens.ayton.se/blag/?flattrss_redirect&amp;id=116&amp;md5=0fea6909da84e0df5af808181796230d" title="Flattr" target="_blank"><img src="http://jens.ayton.se/blag/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/imitating-greatness/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On the Mac App Store</title>
		<link>http://jens.ayton.se/blag/on-the-mac-app-store/</link>
		<comments>http://jens.ayton.se/blag/on-the-mac-app-store/#comments</comments>
		<pubDate>Fri, 22 Oct 2010 10:45:47 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Politics]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=110</guid>
		<description><![CDATA[When the Mac App Store was announced, I said to someone, “‘Convenient’ isn’t the same as ‘good for you’.” This might look slightly odd in a community dedicated to improving people’s workflows, so I’d like to expand on it. (I &#8230; <a href="http://jens.ayton.se/blag/on-the-mac-app-store/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When the Mac App Store was announced, I said to someone, “‘Convenient’ isn’t the same as ‘good for you’.” This might look slightly odd in a community dedicated to improving people’s workflows, so I’d like to expand on it. (I should point out that I myself don’t make any money on software and don’t particularly care how big my audience is, so I’m approaching this as an aware consumer.)</p>
<p>My position on convenience is this:</p>
<ul>
<li>Good user experience is the convenience of not having to use a difficult and dangerous hand crank to start your car.</li>
<li>The Mac App Store is the convenience of having McDonald’s open in your apartment building.</li>
</ul>
<p><span id="more-110"></span>
<p>Of course, everyone is free not to eat at McDonald’s exclusively, or even at all. But this is beside the point. The vast majority will appreciate the convenience, and grow accustomed to it. Soon, the idea of looking elsewhere for food will seem odd. The more adventurous will consider, perhaps, an occasional excursion to the nearby Burger King of Steam or other big brands, but the existence of more obscure alternatives will be little more than a strange piece of trivia. The McDonald’s in your apartment building will have a <i>de facto</i> captive audience.</p>
<p>The captive audience will have little grasp of what the limitations on their diet are, or whether the new baconburger of the week represents the true leading edge of hamburger innovation. They will have no idea whether the prices they are paying are fair, since there will be no market to compare with. If they want organic wholemeal buns with walnuts in, they’re out of luck, because their McDonald’s is doing fine selling the normal kind.</p>
<p>In short, with an effective monopoly on distribution, innovations that reach outside the box of the App Store agreement will not reach users, and there will be no incentive for Apple to cooperate in expanding the box.</p>
<p>I’m not a free market fundamentalist, but I will only approve of a monopoly if there is good reason to believe it will benefit consumers or the population at large in the long term. The App Store doesn’t come close. (Apple’s policy of rejecting apps that are “too similar” to ones already in the store ensure a true free market cannot develop <em>within</em> the store either.)</p>
<p>In the case of the iPad, my requirement as a potential customer has been a side-loading option of some sort, despite the knowledge that it would be very hard to be competitive outside the App Store. It is fundamental that I, as the owner of my hardware, can decide whether I want to install whatever software exists.</p>
<p>But for the Mac, coming at this distasteful compromise situation from the other direction is unacceptable. If the App Store succeeds – and it will, once the stupidity of the distribution agreement is reduced by the smallest possible amount – my next computer will not be a Mac. I will abide inferior, noisy hardware running inferior, noisome software before I abide a cage, be it ever so shiny.</p>
<p><small>For the record: no, I’ve never owned a game console.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/on-the-mac-app-store/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Almost elegant cave man debugging</title>
		<link>http://jens.ayton.se/blag/almost-elegant-cave-man-debugging/</link>
		<comments>http://jens.ayton.se/blag/almost-elegant-cave-man-debugging/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 19:43:20 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[hacks]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=103</guid>
		<description><![CDATA[Recently, the Twitternets pointed me at Vincent Gable’s blog post, The Most Useful Objective-C Code I’ve Ever Written. It is indeed quite useful; given a semi-arbitrary expression, it prints out the value, using @encode() and macros to minimize drudgery. However, &#8230; <a href="http://jens.ayton.se/blag/almost-elegant-cave-man-debugging/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Recently, the Twitternets pointed me at Vincent Gable’s blog post, <a href="http://vgable.com/blog/2010/08/19/the-most-useful-objective-c-code-ive-ever-written/comment-page-1/">The Most Useful Objective-C Code I’ve Ever Written</a>. It is indeed quite useful; given a semi-arbitrary expression, it prints out the value, using <code>@encode()</code> and macros to minimize drudgery.</p>
<p><span id="more-103"></span>
<p>However, it’s limited to a fixed set of types. As Vincent points out, this could be avoided by parsing the <code>@encode()</code> string rather than recognising specific strings. As it happens, I had a partially working parser. It is now wholly working and added a convenience macro similar to Vicent’s, and you can find it <a href="https://github.com/Ahruman/JAValueToString">here</a>. It handles most structs, unions and arrays automatically. It’s still not entirely general, though, in part because of compiler limitations:</p>
<ul>
<li>Bitfields aren’t supported. This is basically because I haven’t bothered. I’m not clear on whether the encoding actually provides enough information to handle these properly, though.</li>
<li>Altivec and SSE vector types aren’t handled, because <code>@encode()</code> completely ignores them – if you have a <code>struct { int a; __m128 v; int b; }</code>, the encoding is <code>{?=ii}</code>, as if the vector wasn’t even there.</li>
<li>Aggregate types with non-standard alignment (<code>#pragma pack</code>) are not supported. Again, the compiler doesn’t encode the necessary information.</li>
</ul>
<p>The latter two cases could easily lead to crashes if left to their own devices. My solution is to first parse the entire type without reading any data, to ensure that the amount of data the parser will consume matches the size according to <code>sizeof()</code>, then reparse if the size matches.</p>
<p>There are probably cases it doesn’t handle. Bug reports would be welcome. Also, it doesn’t handle PPC-64 and ARM, because I don’t have suitable machines to extract alignment information on and I can’t be bothered to read actual documentation.</p>
<p><b>Update (2010-08-22):</b> Added support for <code>_Complex</code> types (encoded as <code>'j'</code>; a <code>complex double</code> is encoded as <code>jd</code> and stored the obvious way, as two doubles in a row).</p>
<p><b>Update (2010-08-23):</b> Fixed alignment calculations for nested structs when alignment is not determined by first member.</p>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/almost-elegant-cave-man-debugging/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Black Tuesday</title>
		<link>http://jens.ayton.se/blag/black-tuesday/</link>
		<comments>http://jens.ayton.se/blag/black-tuesday/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 11:06:27 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Politics]]></category>
		<category><![CDATA[FRA]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=87</guid>
		<description><![CDATA[<span style="color: rgba(0,0,0,0)"><span style="background-color: black">█████</span> <span style="background-color: black">███</span> <span style="background-color: black">██████</span> <span style="background-color: black">███</span></span> FRA <span style="color: rgba(0,0,0,0)"><span style="background-color: black">████</span> <span style="background-color: black">███████</span> <span style="background-color: black">██████</span></span>. <a href="http://jens.ayton.se/blag/black-tuesday/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="censored">
<p><span>███ ██ ███ ████ ██</span>, <span>██████ ███████ ███</span>. <span>██ █ ███ ███</span>. <span>████ ███ ███</span>, <span>█ █████ ███</span>. <span>████ █ ██ █ ███  ███ ██ ██  ██</span>. <span>██ ███ ██ ███ █ █████</span>. <span>███ ████ ███ ██</span>, <span>██ ████ ███ ███</span> FRA <span>████</span>. <span>███ ████ █████ ██</span>, <span>█ ███ ██ ███ █</span>. <span>█████ ███ ██ ██ ███ ███ █ ████ ██ ███</span>. <span>███ █ ██ ███</span>, <span>█ ███ ██</span>. <span>██ ███ ████ ███</span>. <span>███ ██████ ███ ██</span>, <span>██ ███ █ ███ ██</span>.</p>
<p><span>████ █████ ███ ███</span>. <span>██ █ █</span>, <span>███ █ ██ ███ █</span>, <span>███ █ ██</span>. <span>████ ██████ ██ █ ███ ███ ███████</span>. <span>███ █ ██ ██ ██ ████ ███ █ █ ██</span>. <span>████ ██████</span>, <span>██ █████ ███ ████</span>, <span>█ ██ ████ ██</span>, <span>█ ██████ ██ ███ █ ██</span>. <span>██ ████ █████ ██ █ █████</span>. <span>███ ███ ██ █ ██</span>, <span>██████ █████ █</span>. <span>███ ██ ████ ██</span>. <span>██ ████ ███ ███</span>. <span>████ █ ████ ██</span>. <span>█ ███ ████ ███</span>, <span>█ ██ ██████ █ ███ ████</span>. <span>███ █ ██ ██ ██ ███ ████ █ ██ ███</span>. <span>███ ████ ██ ███ ███ ████ ████</span>. <span>██ ██ ██ █ ███ ████ ███</span>.</p>
<p><span>███ █ ███ █</span>. <span>████ ██ ███ █ ███ ███ ███ █ █ ██</span>. <span>██ ████ █████ ████</span>. <span>██ ███ ██ ██ ██ ████ ██ █████ ███ ███</span>. <span>███ ██ ██</span>, <span>███ █ ██ █</span>, <span>█████ ██ ███</span>. <span>██ ███ ██ ████ ███ ████ █ ███ ██ █████</span>. <span>██ █ ██ █ ██ ███ ████</span>. <span>███ ██ ██████ ██</span>, <span>█ ████ ███ ███ ██</span>. <span>█████ ████</span>, <span>██ █ ████ ████</span>, <span>███ ██ █████ ██</span>, <span>█ █████ ███ ███ █ ██</span>. <span>███ ██ ██</span>, <span>███ ████ ████ █</span>, <span>███ ██ ███</span>. <span>█ █ █████ ███</span>. <span>████ ████ █████ ███ ██ ████</span>. <span>█████ ██ ███ ███ █ ████ ██ ███ █ ███ ████ ███ ███</span>; <span>█████ █████</span>, <span>██ ██ ████ █████</span>, <span>███ ██ █████ █</span> FRA <span>█ ██ ████ ███ ██ ██ ███</span>. <span>██ █ ██ ██</span>. <span>██ █ ████ ███</span>. <span>██ ██ █</span>, <span>█████ █ █████ █ ██</span>, <span>████ ██ ███</span>. <span>██ ███</span>. <span>███ █ ██ ███</span>, <span>█ ████ ██</span>.</p>
<p><span>█████ █ ██ ██ ██ ███ █████</span>. <span>██ ████ ███████ ███ █ ████</span>. <span>███ ███ ██ █ ██ █████ ██ ████ ██ ████</span>. <span>██████ ████ ███ ██ ██ ██</span>. <span>██ █ █████ ██</span>. <span>██ █████ ████ ███</span>. <span>███ ████ █████ ██</span>, <span>█ ████ ███ ███ █</span>. <span>██ █████ ████ ██ ██ █████</span>. <span>██ ██████</span>, <span>█ █ █████ ███</span>, <span>██ ██ █████ ██</span>, <span>██ ████ ███ █ █ ██ █</span>. <span>██ ██ ██</span>, <span>████ ██ ███ █ ██</span>, <span>█████ █ ███</span>. <span>██ ████</span>, <span>██ █ ██████ ███</span>, <span>█ ██ ████ ███</span>, <span>█████ ███ ███ ██ █████ ██</span>. <span>██ █ ███ █ ██ ███ ████</span>. <span>██ ███ ███</span>, <span>████ █</span> FRA <span>███ ██</span>, <span>█████ █ ██</span>. <span>███ ████ ████ ██ █ ████</span>. <span>████ ██ ███ ██</span>, <span>██ ████ ██</span>. <span>██████ ████ ███ ██ ██ ████</span>. <span>██ █████ ███ ████</span>.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/black-tuesday/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Proposal: generics (and some other stuff) for Objective-C</title>
		<link>http://jens.ayton.se/blag/generics-for-objective-c/</link>
		<comments>http://jens.ayton.se/blag/generics-for-objective-c/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 20:38:04 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[flamebait]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[notc++]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tl;dr]]></category>
		<category><![CDATA[type system]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=78</guid>
		<description><![CDATA[Some time ago, Greg Parker asked the Twitternets what we’d like to see in a purely hypothetical Objective-C-without-the-C language. Someone — I believe it was Landon Fuller — pointed at an article about the Strongtalk type system for Smalltalk. I &#8230; <a href="http://jens.ayton.se/blag/generics-for-objective-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Some time ago, <a href="http://twitter.com/gparker/">Greg Parker</a> asked the Twitternets what we’d like to see in a purely hypothetical Objective-C-without-the-C language. Someone — I believe it was <a href="http://twitter.com/landonf">Landon Fuller</a> — pointed at an article about <a href="http://bracha.org/nwst.html">the Strongtalk type system for Smalltalk</a>. I quite like the idea of Objective-C-without-the-C (i.e., a language that is native to the Objective-C object system and runtime without the baggage of C), but after reading that article I found myself asking why we couldn’t do something similar in Objective-C.</p>
<p>I don’t think my random musings have much influence on the design of the language, but if I don’t write it down nobody’s going to know how nuts I am, so here’s a semi-concrete proposal for contextual types and generics for Objective-C. Since anyone even mentioning generics in the vicinity of Objective-C will inevitably be flamed for trying to turn it into C++, this is followed by an aside entitled <i>Why This is Not the Baby-eating Spawn of Bjarne Stroustrup</i>. (Nothing personal, Bjarne.)</p>
<p><span id="more-78"></span><br />
<h2 id="types-in-objc">Types in Objective-C</h2>
<p>A fundamental characteristic of Objective-C is that it has two separate type systems: the dynamic type system, which applies to objects, and the static type system, which applies to variables (which may or may not refer to objects).</p>
<p>As far as objects are concerned, the static type system is optional — you can refer to any object with the type <code class="objc code">id</code>, except when calling a method whose type may be ambiguous. The static type system is also advisory — it suggests to programmers, the compiler and other tools such as the <a href="http://developer.apple.com/tools/Xcode/">IDE</a> and <a href="http://clang-analyzer.llvm.org/">analyzer</a> what the class of an object may be at runtime, but doesn’t constrain the object. A variable of type <code>NSString&nbsp;*</code> may actually refer to an <code>NSArray</code> at runtime, and method calls will dynamically go to <code>NSArray</code>’s implementation.</p>
<p>My proposal deals only with the static type system. The idea is to provide information that helps the compiler and analyzer check your logic, and the IDE to provide better suggestions. This is done by replacing <code>id</code> with more specific static types in most of the situations it’s used in. The generated code is not affected in any way. The proposal does not introduce bondage and discipline on the language; the new types can always be cast away.</p>
<h2 id="contextual-types">Contextual Types</h2>
<p>By far the most common use of <code>id</code> is as the return type for methods that may return an instance of “this” class, or of the subclass it’s called on. The obvious examples are <code>+alloc</code> and <code>-init</code>.</p>
<p>The IDE and, I believe, the analyzer already use heuristics to determine the return type of <code>+alloc</code> and <code>-init</code>, but I propose formalizing this in code. It would look something like this:</p>
<pre class="objc code" id="contextual-example">@interface NSObject &lt;NSObject&gt;
{
    Class   isa;
}

+ (void)load;

+ (void) initialize;
- ([:Self]) init;

+ ([:Self]) new;
+ ([:Self]) allocWithZone:(NSZone *)zone;
+ ([:Self]) alloc;

// ...

+ ([:Superclass]) superclass;
+ ([:Class]) class;
- ([:Superclass]) superclass;
- ([:Class]) class;

@end</pre>
<p>When calling a class method, <code>[:Class]</code> resolves to the receiver (or, type-equivalently, a pointer to an instance the receiver’s metaclass), and <code>[:Self]</code> resolves to a pointer to an instance of the receiver. <code>[:Superclass]</code> resolves to the superclass of the receiver. For instances, they resolve as for class methods on the class of the instance.</p>
<p>I’m sure some people will object to the conceptual purity of this design, and possibly the names and syntax. The colon is a bit odd — it’s there to avoid ambiguity with generics (see <a href="#generics">below</a>). All of these are minor quibbles; the syntax would need to be reviewed if actually implementing it.</p>
<p>So what’s the point? Consider the following code:</p>
<pre class="objc code">NSString *s = [[NSArray alloc] init];</pre>
<p>As it stands, this is perfectly valid and doesn’t generate a compiler diagnostic. With the addition of contextual types it would, because:
<ul>
<li> The type of <code>+[NSArray alloc]</code> (inherited from <code>NSObject</code>) is <code>[:Self]</code>, which resolves to <code>NSArray&nbsp;*</code>.</li>
<li> The receiver of the <code>-init</code> is thus known to be an <code>NSArray</code>.</li>
<li> The type of <code>-[NSArray init]</code> (inherited from <code>NSObject</code>) is <code>[:Self]</code>, which again resolves to <code>NSArray&nbsp;*</code>.</li>
<li> Therefore, the right hand side of the assignment is of type <code>NSArray&nbsp;*</code>, and the assignment is invalid.</ul>
<p>If, for some reason, you really wanted to do that, you could use an explicit cast to get rid of the diagnostic.</p>
<h2 id="generics">Generics</h2>
<p>The other major use of <code>id</code> is for polymorphic collections. True polymorphic collections are great! But some of the time, you only want to put one kind of object in your collection, and would appreciate the computer doing the drudge work of checking that you didn’t put the wrong stuff in the wrong place.</p>
<p>From the perspective of the previous section, generics are a simple extension to contextual types. Instead of restricting you to <code>[:Self]</code> and the highly specialized <code>[:Class]</code> and <code>[:Superclass]</code>, you can provide one or more class names as a parameter to a type declaration. Example time again:</p>
<pre class="objc code" id="mythingholder-example">@interface MyThingHolder[ThingType = id] : NSObject
{
    [ThingType]     thing;
}

- ([:Self]) initWithThing:([ThingType])thing;

- (void) setThing:([ThingType])thing;
- ([ThingType]) thing;

// Or, for modernists:
@property (readonly, nonatomic) [ThingType] thing;

@end

// ...
MyThingHolder[NSString] *holder = [[MyThingHolder[NSString] alloc] initWithThing:@"foo"];
holder.thing = [NSNumber numberWithBool:MAYBE];      // Warning: type mismatch
holder.thing = (id)[NSNumber numberWithBool:MAYBE];  // OK. (an issue here would be inconsistent with general Objective-C behaviour.)

// Or, equivalently:
typedef MyThingHolder[NSString] MyStringHolder;
MyStringHolder *holder = [[MyStringHolder alloc] initWithThing:@"foo"];</pre>
<p>Some notes: the type parameter can only be a class, since specialized code is not generated for each type. (See <a href="#bjarnespawn">Why This is Not the Baby-eating Spawn of Bjarne Stroustrup</a> below.) Since the type parameter is always a class, I have made the <code>*</code> implicit. This is cleaner, but could well lead to confusion and is quite likely a bad idea. (If only I had a time machine…)</p>
<p>The type parameter has a default value, previously unheard of in Objective-C, so that you can ignore generics and create a “vanilla” <code>MyThingHolder</code> that works just like in traditional Objective-C. This provides an upgrade path for existing classes:</p>
<pre class="objc code" id="collections-example">@interface NSArray[Item &lt;NSObject&gt; = id &lt;NSObject&gt;] : NSObject &lt;NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration&gt;

- (NSUInteger) count;
- ([Item]) objectAtIndex:(NSUInteger)index;

@end

@interface NSArray[Item] (NSExtendedArray)

- (NSArray[Item] *) arrayByAddingObject:([Item])anObject;
- (NSArray[Item] *) arrayByAddingObjectsFromArray:(NSArray[Item] *)otherArray;
// ...
- (BOOL)containsObject:([Item])anObject;
// ...
<span id="decl-arrayWithObject">+ ([:Self[Item]]) arrayWithObject:([Item])anObject;</span>
// ...
<br/>
@interface NSDictionary[Key &lt;NSCopying, NSObject&gt; = id &lt;NSCopying, NSObject&gt;, Value &lt;NSObject&gt; = id &lt;NSObject&gt;] : NSObject &lt;NSCopying, NSMutableCopying, NSCoding, NSFastEnumeration&gt;

- (NSUInteger) count;
- ([Value]) objectForKey:([Key])aKey;
- (NSEnumerator[Key] *)keyEnumerator;

@end

@interface NSDictionary[Key, Value] (NSExtendedDictionary)

- (NSArray[Key] *) allKeys;
- (NSArray[Key] *) allKeysForObject:([Value])anObject;
- (NSArray[Value] *) allValues;
// ...
- (BOOL) isEqualToDictionary:(NSDictionary[Key, Value] *)otherDictionary;
- (NSEnumerator[Value] *) objectEnumerator;
- (NSArray[Value] *) objectsForKeys:(NSArray[Key] *)keys notFoundMarker:([Value])marker;
// ...
- (void) getObjects:([Value] *)objects andKeys:([Key] *)keys;
// ...</pre>
<p>These examples introduce an additional concept: restrictions on type parameters, in this case protocol requirements. The other obvious type of restriction would be a superclass requirement, such as <code>[Type: NSString = NSString]</code>.</p>
<p>Using these genericized versions in the same manner as the existing versions would require no code changes – as long as you’re using them with objects that fulfil the protocol requirements, which already exist but aren’t explicit in code.</p>
<h2 id="type-conformance">Type Conformance</h2>
<p>A fundamental question for static type systems with inheritance is when implicit casts are allowed. There are subtleties here, some of which I probably haven’t considered, and I have a feeling I’ve considered some and then forgotten about them. The most obvious case is when the base type and each type parameter could be validly cast:</p>
<pre class="objc code" id="basic-implicit-casts-example">NSMutableArray[NSMutableString] *a = whatever;
NSMutableArray *b = a;            // OK, b is NSMutableArray[id &lt;NSObject&gt;]
NSMutableArray[NSString] *c = a;  // OK
a = b;                            // Not OK, implicit cast from NSMutableArray[NSString] to NSMutableArray[NSMutableString]
NSArray[NSMutableString] *d = a;  // OK
NSArray[NSString] *e = a;         // OK
id f = a;                         // OK
</pre>
<p>As indicated <a href="#mythingholder-example">above</a>, passing an <code>id</code> when a parameter type is expected is necessary for consistency with Objective-C in general:</p>
<pre class="objc code" id="id-implicit-cast-example">NSMutableArray[NSString] *a = whatever;
[a addObject:[NSNumber numberWithInt:42]];      // Type mismatch, assuming +numberWithInt: is declared to return [:Self]
[a addObject:(id)[NSNumber numberWithInt:42]];  // OK</pre>
<p>How about the case where a method returns an unadorned type?</p>
<pre class="objc code" id="legacy-example">@interface LegacyThing: NSObject
- (NSArray *) legacyListOfStrings;
@end

LegacyThing *l = whatever;
NSArray[NSString] *list = [l legacyListOfStrings];</pre>
<p>In order to minimize the burden of adopting generic syntax, I’d suggest explicitly permitting this, with an optional warning. (The non-generic equivalent, assigning an <code>id&nbsp;&lt;NSObject&gt;</code> to an <code>NSString&nbsp;*</code>, generates the somewhat unexpected warning <i>“type &#8216;id &lt;NSObject&gt;&#8217; does not conform to the &#8216;NSCopying&#8217; protocol”</i> in GCC and nothing in Clang. Assigning an <code>NSObject&nbsp;*</code> to an <code>NSString&nbsp;*</code> generates warnings in both. My proposal is that assigning a <code>T</code> to a <code>T[P]</code> should work without warning by default, even if the default type parameter is a class rather than <code>id</code> with or without protocols.)</p>
<h2 id="bjarnespawn">Why This is Not the Baby-eating Spawn of Bjarne Stroustrup</h2>
<p>Many Objective-C programmers are refugees from the blasted wasteland of C++, and will reflexively cringe at the similarity with templates:</p>
<pre class="objcpp code" id="cpp-vs-objc-example">std::vector&lt;Duck&gt; ducks;
Chicken chicken;
ducks.push_back(chicken);             // Error
ducks.push_back(*(Duck *)chicken);    // Horrible crash here or some time in the future, maybe.

NSArray[Duck] *ducks = [NSArray new];
Chicken *chicken = [Chicken new];
[ducks addObject:chicken];            // Warning: type mismatch
[ducks addObject:(Duck *)chicken];    // No problem, unless you call -quack on it.
</pre>
<p>While the difference should hopefully be clear by now, I’ll spell it out: in C++, <code>std::vector&lt;Duck&gt;</code> creates an entirely new class (with bits of <code>Duck</code> inlined into it). The Objective-C-with-generics version only provides hints to the compiler, so it can catch mistakes. It doesn’t stop you from putting chickens among your ducks, or make the duck array reject chickens at runtime, or generate a new array-of-chickens class.</p>
<p>In <a href="http://lists.apple.com/archives/objc-language/2003/Dec/msg00084.html">earlier discussions</a> of generics, it has been stated that this type of mistake is rare in practice and should be caught with unit tests. If you feel that way, you’re welcome to stick to your current approach, and the introduction of generics, as described, will not affect you.</p>
<p>To avoid ballooning side effects of generics, I’ve deliberately avoided suggesting generic functions and methods (i.e., ones whose return type is dependent on one or more argument types, independent of their class in the case of methods).</p>
<h2 id="one-last-thing">One Last Thing</h2>
<p>An effect of the above is that I want the language to contain types like <code>NSArray[NSMutableDictionary[NSString, NSSet[NSMutableArray[NSNumber]]]] *</code>. That doesn’t mean I want to spend my time <em>typing</em> <code>NSArray[NSMutableDictionary[NSString, NSSet[NSMutableArray[NSNumber]]]] *</code>, even with autocomplete. Fortunately, there exists a well-known solution to this problem: type inference.</p>
<p>If I access a member of an array of the aforementioned sesquipedalian type, I get an <code>NSMutableDictionary[NSString, NSSet[NSMutableArray[NSNumber]]] *</code>. What’s more, the compiler knows this. The benefit of static typing lies primarily in checking what I do with my dictionary, rather than checking that the item I retrieved is what I thought it was, so I should be able to ask it to type a variable appropriately.</p>
<p>I quite like C++1x’s solution of recycling the <code>auto</code> keyword for this use, but that would conflict with Objective-C’s goal of being a strict superset of C. There are various other choices, such as <code>var</code> or <code>any</code> — or maybe <code>ego</code>. In any case, type inference would lead to code like:</p>
<pre class="objcpp code" id="type-inference-example">typedef NSArray[NSMutableDictionary[NSString, NSSet[NSMutableArray[NSNumber]]]] MyHorribleNestedType;  // TODO: replace with sensible model classes.

MyHorribleNestedType *array = whatever;
var element = [array objectAtIndex:0];              // Type is inferred as NSMutableDictionary[NSString, NSSet[NSMutableArray[NSNumber]]]*
var subEntry = [NSArray arrayWithObject:@"bloop"];  // Type is inferred as NSArray[NSString]
[element setObject:subEntry forKey:@"moop"];        // Type mismatch: expected NSSet[NSMutableArray[NSNumber]], got NSArray[NSString]</pre>
<p>A subtlety here: the return type of <code>[NSArray arrayWithObject:@"bloop"]</code> (declared <a href="#decl-arrayWithObject">previously</a>) is <code>[:Self[Item]]</code>, which is inferred from the receiver (the <code>NSArray</code> class object) and argument to resolve to <code>NSArray[NSString]</code>. Instead of <code>typedef</code>ing <code>MyHorribleNestedType</code>, we could have constructed the type implicitly in the same way. like everything else in the proposal, this is optional; if you used <code>id</code> or explicit, unparameterized types in this example, the type mismatch would not be detected, but the generated code would be identical.</p>
<h2 id="summary">Summary</h2>
<ul>
<li> The <code>id</code> type is very powerful and flexible. However, most of the time you don’t need this flexibility, and type checking is helpful — this is why Objective-C has optional static type checking in the first place, and almost all Objective-C code opts in to it.</li>
<li> The proposal would not impose any new restrictions, or any new guarantees. It would only extend (optional) static type checking to cases which are currently not covered.</li>
<li> It would not involve any implicit code generation, and no runtime overhead.</li>
<li> Combined with type inference, it could catch errors without additional code.</li>
<li> There would be no new collections, and no implementation changes to existing ones other than updated type declarations. (Updated headers would work with the existing implementations.)</li>
<li> If you really don’t want static type checking, you can continue using <code>id</code> everywhere.</li>
<li> I mean it about the “optional”. The proposed change would have no effect unless adopted both by a class and its clients. A parameterized collection pointer can be cast to plain one at any time with no cost.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/generics-for-objective-c/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Multi-type Save Panel Controller</title>
		<link>http://jens.ayton.se/blag/multi-type-save-panel-controller/</link>
		<comments>http://jens.ayton.se/blag/multi-type-save-panel-controller/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 19:35:20 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=68</guid>
		<description><![CDATA[As a change of pace, I thought I’d post some code that doesn’t go out of its way to be bad. JAMultiTypeSavePanelController is a class (abstracted from ImageIO Export for Acorn) to handle the case where you want to offer &#8230; <a href="http://jens.ayton.se/blag/multi-type-save-panel-controller/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As a change of pace, I thought I’d post some code that doesn’t go out of its way to be bad.</p>
<p><code>JAMultiTypeSavePanelController</code> is a class (abstracted from <a href="http://jens.ayton.se/acorn/">ImageIO Export for Acorn</a>) to handle the case where you want to offer the user a choice of formats to save in.</p>
<p><img src="http://jens.ayton.se/blag/wp-content/uploads/2009/08/JAMultiTypeSavePanelController.png" alt="Save panel" border="0" style="max-width: 100%" /><br />
<span id="more-68"></span>
<p>It wraps an <code>NSSavePanel</code> and handles all the UTI and extension details. You can provide a customised <code>NSSavePanel</code> or let the controller create one. The only restriction is that the controller appropriates the accessory view. Usage is similar to <code>NSSavePanel</code> itself:</p>
<pre class="objc-code">NSArray *types =
    [NSArray arrayWithObjects:@"com.apple.rtfd", @"public.rtf", @"public.plain-text", nil];
JAMultiTypeSavePanelController *controller =
    [JAMultiTypeSavePanelController controllerWithSupportedUTIs:types];
controller.autoSaveSelectedUTIKey = @"document format"; // Optional: preferences key for selected type.
controller.sortTypesByName = NO; // Optional: show in specified order instead of alphabetically by display name.
[controller beginSheetForDirectory:nil
                              file:@"untitled 42"
                    modalForWindow:docWindow
                     modalDelegate:self
                    didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:)
                       contextInfo:nil];</pre>
<p><code>-runModalForDirectory:file:</code> is also supported.</p>
<p><a href="https://github.com/Ahruman/JAMultiTypeSavePanelController">Code</a> (MIT/X11 license)</p>
 <p><a href="http://jens.ayton.se/blag/?flattrss_redirect&amp;id=68&amp;md5=b81f9f8b25b2704e0274c544cd4b3172" title="Flattr" target="_blank"><img src="http://jens.ayton.se/blag/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/multi-type-save-panel-controller/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wanted: a Right-Handed Keyboard</title>
		<link>http://jens.ayton.se/blag/right-handed-keyboard/</link>
		<comments>http://jens.ayton.se/blag/right-handed-keyboard/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 23:49:06 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Hardware]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=61</guid>
		<description><![CDATA[My current keyboard looks like this: (Well, roughly. It actually looks like this, but I couldn’t find a decent-resolution Swedish one.) This was a sensible design for the right-handed majority when it was introduced, some time in the stone age. &#8230; <a href="http://jens.ayton.se/blag/right-handed-keyboard/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My current keyboard looks like this:</p>
<p><img src="http://jens.ayton.se/blag/wp-content/uploads/2009/06/left-handed-keyboard.jpg" alt="Left-handed keyboard: keypad on right, empty space on left." border="0" style="max-width: 100%" /></p>
<p>(Well, roughly. It actually looks like <a href="http://jens.ayton.se/blag/wp-content/uploads/2009/06/swedish-keyboard.jpg">this</a>, but I couldn’t find a decent-resolution Swedish one.)</p>
<p>This was a sensible design for the right-handed majority when it was introduced, some time in the stone age. However, since then, something quite important has happened: the keyboard has been joined by another input device, which I suspect is used more than the keypad by most people who are not cursed with an Excel-dominated career.</p>
<p><span id="more-61"></span>
<p>The ergonomics of the extended keyboard + mouse combination is quite, quite horrible. The human arm is not optimized for sitting turned out 30&nbsp;degrees for hours at a time.</p>
<p>Apple has tried at least twice to solve this in one obvious way: remove all or part of the junk on the right. This has been widely, or at least loudly, decried, leading to the Extended ADB Keyboard for high-end Macs in the deep past and to extended keyboards for all in the USB era. There is another solution, though:</p>
<p><img src="http://jens.ayton.se/blag/wp-content/uploads/2009/06/right-handed-keyboard.jpg" alt="Right-handed keyboard: keypad on left, empty space on right." border="0" style="max-width: 100%" /></p>
<p>Unfortunately, day-to-day conservatism means that people, in the aggregate, will loudly complain about having to adopt a superior solution if it involves half an hour of retraining. I’m sure many would point out that this is why we still have rectangular QWERTY keyboards in the first place. Still, if anyone can force change down our throats and make us like it, it’s Apple.</p>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/right-handed-keyboard/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Net Neutrality (EU edition)</title>
		<link>http://jens.ayton.se/blag/net-neutrality/</link>
		<comments>http://jens.ayton.se/blag/net-neutrality/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 23:28:54 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Politics]]></category>
		<category><![CDATA[Net Neutrality]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=54</guid>
		<description><![CDATA[Network neutrality in Europe is under threat. Not in some vague possible future; right now. In one week, on Tuesday the fifth of May, the European Parliament will vote on the second reading of the Telecoms Package and amendments. I &#8230; <a href="http://jens.ayton.se/blag/net-neutrality/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Network neutrality in Europe is under threat. Not in some vague possible future; <em>right now</em>. In one week, on Tuesday the fifth of May, the European Parliament will vote on the second reading of the Telecoms Package and amendments.</p>
<p>I urge all EU citizens to contact an MEP, via e-mail or (preferably) phone, and encourage them to support the Citizens’ Rights Amendments, which reaffirm net neutrality and anti-censorship positions adopted by the European Parliament in the first reading but subsequently removed by the Council of Ministers in their “common position”.</p>
<p>The primary purpose of these amendments is to make it explicit that the European Convention on Human Rights applies to internet and telecoms legislation. This should be obvious, but it is clear from the actions of politicians that it is not; it is all too clear that many see the internet as a frivolous toy, and civil rights obviously do not apply to toys. (It occurs to me that politicians are probably among those in the western world least affected by the digital communications revolution; if they need to communicate, they talk to their secretaries.)</p>
<p>Draft texts of the amendments (not yet numbered) can be found here: <a href="http://www.erikjosefsson.eu/sites/default/files/Citizens_Rights_Amendments_(Part_I).pdf">part I</a>, <a href="http://www.erikjosefsson.eu/sites/default/files/Citizens_Rights_Amendments_(Part_II).pdf">part II</a>, <a href="http://www.erikjosefsson.eu/sites/default/files/Citizens_Rights_Amendments_(Part_III).pdf">part III</a>. There’s a (rather bad) campaign site <a href="http://www.blackouteurope.eu/act/tell-the-parliament-to-vote-yes.html">here</a>, and a less bad editorial – for all that it’s in a pointy-haired e-mag – in Computer World UK <a href="http://www.computerworlduk.com/community/blogs/index.cfm?entryid=2140&#038;blogid=14">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/net-neutrality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Constant objects for fun and non-profit</title>
		<link>http://jens.ayton.se/blag/objc-constant-objects/</link>
		<comments>http://jens.ayton.se/blag/objc-constant-objects/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 02:27:05 +0000</pubDate>
		<dc:creator>Jens Ayton</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[evil]]></category>

		<guid isPermaLink="false">http://jens.ayton.se/blag/?p=45</guid>
		<description><![CDATA[The @&#34;foo&#34; operator for constant NSString objects in Objective-C is extremely convenient. Indeed, if it wasn’t there, programming with Cocoa would be a royal pain. Many of us have at various points wished there was equivalent syntax for NSNumbers, and &#8230; <a href="http://jens.ayton.se/blag/objc-constant-objects/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <code>@&quot;foo&quot;</code> operator for constant <code>NSString</code> objects in Objective-C is extremely convenient. Indeed, if it wasn’t there, programming with Cocoa would be a royal pain. Many of us have at various points wished there was equivalent syntax for <code>NSNumber</code>s, and possibly collections.</p>
<p>As an early Christmas present to fellow lovers of twisted, evil code that should never have seen the light of day under any circumstances whatsoever, I hereby present an implementation of the first half of that wish.</p>
<p><span id="more-45"></span><br />
<h2>Caveat lector</h2>
<p>Now, when I say it’s evil, I really, really mean it. We’re talking about building objects in the data section of your code by packing structs, thus depending on data layout (and as such, depending on the old 32-bit runtime). We’re talking about nested macros with lots of <code>?:</code>s in them. We’re talking about gcc’s built-in parser pseudo-functions. Hearken to the words of Greg Parker, official Objective-C Runtime Wrangler at Apple:</p>
<p style="margin:0 3em">@<a href="https://twitter.com/gparker/status/1051085472">gparker</a>: @ahruman JANumberLiteral would break in several exciting ways in 64-bit. Might almost be safe enough in 32-bit, though.<br />
@<a href="https://twitter.com/ahruman/status/1051088370">ahruman</a>: @gparker Yeah, I know. I’ll be pasting “If you do this in real life, I’ll have to track you down and shoot you” warnings all over it. :-)<br />
@<a href="https://twitter.com/gparker/status/1052054292">gparker</a>: @ahruman Don&apos;t shoot &apos;em, just maim &apos;em a bit. I want my turn after you&apos;re done.<br />
@<a href="https://twitter.com/ahruman/status/1052079228">ahruman</a>: @gparker That’s what kneecaps were invented for.</p>
<p>Be told.</o></p>
<h2>Overview</h2>
<p>So, all that aside… what we’re looking at here is a macro <code>$N(n)</code> which takes a number and returns an <code>NSNumber</code>. (The convention of using dollar signs for macros implementing desired language features was introduced by <a href="http://mooseyard.com/Jens/">the other Jens A</a>.) If passed a compile-time constant, it will produce a constant object, i.e. a single, immortal instance based in the data section with no instantiation overhead, just like a string object constant. If passed a non-constant, it will give you a normal autoreleased <code>NSNumber</code> instead.</p>
<p>Constant <code>NSString</code>s work by creating a struct with the following layout: <code>{&nbsp;&amp;__CFConstantStringClassReference, 1992, &quot;foo&quot;, 3&nbsp;}</code>, where 1992 is a flag field and 3 is the length of the string. (Note that this is not the <code>NSConstantString</code> from the bottom of NSString.h. I believe this change was made in the OS X 10.2 SDK.) <code>__CFConstantStringClassReference</code> is a symbol exported from CoreFoundation.framework and implicitly declared in all Objective-C or Objective-C++ files by the compiler.<small><sup><a href="#objc-constant-objects-footnote-1" name="objc-constant-objects-footnote-ref-1">1</a></sup></small> My task, once I chose to accept it, was to do something similar for <code>NSNumber</code>.</p>
<p>Trying to build actual <code>NSCFNumber</code>s would be an unnecessary extra evil. Instead, I subclassed the abstract <code>NSNumber</code> twice, once for <code>long&nbsp;long</code>s and once for <code>double</code>s, giving me a known layout to target. The subclasses also override <code>-retain</code>, <code>-release</code> and <code>-autorelease</code> to do nothing, in the manner of a singleton. Then, building an instance is conceptually simple:</p>
<pre class="objc-code">const static struct { Class isa; double value; } fakeObj =
{ [JAFloatNumber class], 42.0 };
NSNumber *number = (NSNumber *)&fakeObj;</pre>
<p>The structure needs to be declared <code>static</code> so that it doesn’t evaporate at the end of the containing scope. This presents a dilemma, however: static initializers must be constant expressions, and a method call doesn’t qualify. Besides, we want the object to be constant data.</p>
<p>Luckily for us, classes are represented by global symbols like any other. Well, almost like any other. Unlike symbols based on C identifiers, their linker symbols don’t start with an underscore but with a dot, meaning you can’t reference them the usual way. Fortunately, gcc provides us with a solution in the form of <a href="http://gcc.gnu.org/onlinedocs/gcc-4.2.0/gcc/Asm-Labels.html">asm labels</a>:</p>
<pre class="objc-code">extern const struct objc_class JAFloatLiteralClassObject
        __asm__(&quot;.objc_class_name_JAFloatNumber&quot;);</pre>
<p>The basic implementation then becomes:</p>
<pre>#define JANUMBERLITERAL_CONSTANT_FLOAT(n) \
        ({ static const struct { const struct objc_class *isa; double value; } \
        object = { &#038;JAFloatLiteralClassObject, (n) }; \
        (NSNumber *)&object; })</pre>
<p>A problem here is that, despite all those <code>const</code>s, a non-const value can be used in Objective-C++. (In plain Objective-C, you get a moderately helpful warning about non-const initializers.) If you write a function that returns <code> JANUMBERLITERAL_CONSTANT_FLOAT(random());</code>, each instance will return the same object but its value will change, which is rather bad. The fix is to wrap this up in a macro that uses <code><a href="http://gcc.gnu.org/onlinedocs/gcc-4.2.0/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fconstant_005fp-2458">__builtin_constant_p()</a></code> to ensure constant objects are only created with constant values. For non-constant values, normal autoreleased <code>NSNumber</code>s are created instead.</p>
<h2>Results</h2>
<p>The above pieces, along with a bunch of extra preprocessor stuff to handle the distinctions between Objective-C and Objective-C++ and between integer and floating point values gives us a <code>$N(n)</code> macro which works as advertised: if given an integer constant it returns a <code>JAIntegerNumber</code>, for a floating point constant it returns a <code>JAFloatNumber</code>, and for a non-constant it returns an autoreleased <code>NSCFNumber</code>. But is it really working as intended? The following code:</p>
<pre class="objc-code">static NSNumber *GetNumber(void)
{
    return $N(42.0);
}</pre>
<p>disassembles to:</p>
<pre class="asm-code">    .const_data
    .align 2
_object.67163:
    .long   .objc_class_name_JAFloatNumber  // isa
    .long   0           // low bytes of 42.0
    .long   1078263808  // high bytes of 42.0</pre>
<p>…with the actual use of the object inlined (in an optimized build) to <code>movl $_object.67163, (%esp)</code>. The values 0 and 1078263808 correspond to the little-endian hex value of 42.0: <code>00000000 00004540</code>. In other words, this really is an object as constant data. For comparison, the <code>NSString</code> literal used in the sample code disassembles to:</p>
<pre class="asm-code">    .cstring
LC0:
    .ascii &quot;Hello, World! %@ = %li (%@)\0&quot;
    .section __DATA, __cfstring
    .align 2
LC1:
    .long   ___CFConstantStringClassReference // isa
    .long   1992  // flags
    .long   LC0   // bytes pointer
    .long   27    // length</pre>
<h2>Conclusion</h2>
<p>So there you have it: fully-functional, constant <code>NSNumber</code> objects, as long as you don’t use the 64-bit runtime. Now don’t go actually using it, or I’ll have to shoot your kneecaps off and leave you to Greg.</p>
<p>Oh yeah, the code is <a href="http://code.google.com/p/ahruman/source/browse/#svn/trunk/Stupid/NumberLiteral">on Google Code</a>. For a much simpler macro that just gives you an <code>NSNumber</code>, automatically choosing between integer and floating-point representations, try <a href="http://www.extinguishedscholar.com/wpglob/?p=346">natevw’s</a>.</p>
<hr />
<p><small><sup><a href="#objc-constant-objects-footnote-ref-1" name="objc-constant-objects-footnote-1">^1</a></sup></small> Its value, on my system, is 0xa00034a0. Traditionally (pre Leopard), a value above 0xFFF would mean it’s a real Objective-C class rather than a CF type tag, but that test is no longer in the <a href="http://www.opensource.apple.com/darwinsource/10.5.5/CF-476.15/">CFLite source</a> in Leopard, so it may have changed.</p>
<p>If you declare <code>extern const Class __CFConstantStringClassReference;</code> in an Objective-C++ file, you’ll get the error “&apos;__CFConstantStringClassReference&apos; has a previous declaration as &apos;int __CFConstantStringClassReference []&apos;”. In Objective-C, you won’t be told a type, just that it was “previously declared here”, referring to the location “&lt;built-in>:0”.</p>
]]></content:encoded>
			<wfw:commentRss>http://jens.ayton.se/blag/objc-constant-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

