<?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>Cappuccino Blog &#187; Code</title>
	<atom:link href="http://cappuccino.org/discuss/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://cappuccino.org/discuss</link>
	<description>Home of Cappuccino and Objective-J</description>
	<lastBuildDate>Thu, 19 Aug 2010 01:56:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Solving the JavaScript Memory Management Problem</title>
		<link>http://cappuccino.org/discuss/2010/04/01/solving-the-javascript-memory-management-problem/</link>
		<comments>http://cappuccino.org/discuss/2010/04/01/solving-the-javascript-memory-management-problem/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 00:01:58 +0000</pubDate>
		<dc:creator>ross</dc:creator>
				<category><![CDATA[Cappuccino]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Objective-J]]></category>

		<guid isPermaLink="false">http://cappuccino.org/discuss/?p=606</guid>
		<description><![CDATA[JavaScript has some real problems. Anyone who has programmed for the web can attest to that. And anyone familiar with what we&#8217;re doing with Cappuccino will recognize that we&#8217;re not afraid to tackle those problems head on. When we created Objective-J we set out to create a set of true enhancements to the JavaScript language [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript has some real problems. Anyone who has programmed for the web can attest to that. And anyone familiar with what we&#8217;re doing with Cappuccino will recognize that we&#8217;re not afraid to tackle those problems head on. When we created Objective-J we set out to create a set of true enhancements to the JavaScript language that would add powerful new dynamic features to the language, like advanced automatic dependency resolution, truly dynamic message passing, and familiar classical inheritance. By all accounts it has been a tremendous success.</p>
<p>Lately, though, we&#8217;re beginning to realize that we didn&#8217;t quite go far enough. Memory issues have long plagued JavaScript developers. Because the garbage collector is opaque to the developer, and nothing like &#8220;finalize&#8221; is provided by the language, programmers often find themselves in situations where they are forced to hold on to an object reference for too long (or forever) creating a memory leak.</p>
<p>Just as we&#8217;ve done before, when we tackled this problem we decided to look at what has worked in the past. Finding inspiration in the elegant simplicity of C, we knew we&#8217;d found the right solution. And so, we&#8217;re pleased to announce the immediate availability of a manual memory management system in Cappuccino.</p>
<p>A lot of Cocoa developers disparaged garbage collection when it came to Objective-C, and we&#8217;ve come to realize they were absolutely right! Why rely on machines to solve problems for us when we can do it by hand. So, we&#8217;ve taken the Cocoa reference counting system and implemented it in JavaScript. We&#8217;ve replaced the existing no-op -retain, -release, and -autorelease methods with fully working implementations. When an object&#8217;s release count reaches 0, the object&#8217;s dealloc method will be called, and the memory will be able to be reclaimed. Now you have a clear way to clean up unwanted references when an object is no longer being used. Just make sure you do your reference counting correctly!</p>
<p>To do this right, we&#8217;ve created a global object table. These objects aren&#8217;t going anywhere on their own! If you don&#8217;t release an object, it will stick around forever, ensuring you&#8217;ll always have it when you need it. This global table acts as a lookup table for any object, allowing us to finally implement pointers in JavaScript. Since $ has become the coolest way to do completely non-standard lookups in an almost indecipherable way, we thought we&#8217;d jump on the bandwagon. Pass any pointer to $ and you&#8217;ll get the associated object! How do you get a pointer you ask? $$ of course! For example:</p>
<pre><code>
var o = [CPobject new]; // +new returns with a retain count of 1!
var p = $$(o); // returns a pointer to o

o === $(p); // we dereference the pointer and get the right object!</code></pre>
<p>Zombies come standard, too! Just set OBJJ_ZOMBIE_DETECTION to true and objj_msgSend will throw an exception if you ever message an object that&#8217;s been dealloc&#8217;d. </p>
<p>We&#8217;ve even take the time to properly -autorelease all objects returned from class methods in Foundation, but we&#8217;ve made absolutely no effort to properly retain those objects in Cappuccino code that uses them yet. So we need your help. Every line must be scrutinized (but we shouldn&#8217;t to automate this process, as it would surely be too error prone). Rather than focus on developing new features or fixing bugs in the issue tracker, we hope that all Cappuccino contributors will spend their time writing memory management code so that we can fully realize this web development revolution!</p>
<p>We&#8217;ll be including these exciting new features in a future release, so you should get started adding manual memory management code to every single line of Cappuccino you&#8217;ve ever written! In the meantime, check out the <a href="http://github.com/280north/cappuccino/commit/6678bba94f7778b245d8219292b3a6ac85d31678">working code on Github</a>.</p>
<p><em>Please note this is an April Fools joke!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://cappuccino.org/discuss/2010/04/01/solving-the-javascript-memory-management-problem/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Internet Explorer: Global Variables, and Stack Overflows</title>
		<link>http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/</link>
		<comments>http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 00:07:48 +0000</pubDate>
		<dc:creator>ross</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://cappuccino.org/discuss/?p=560</guid>
		<description><![CDATA[Every once in a while, you stumble upon a particularly strange bug. A bug that seems to defy the rules of space-time. A bug that makes you pull your hair out for days. A bug that almost certainly includes Internet Explorer. This was one of those bugs for me, and since I haven&#8217;t found a [...]]]></description>
			<content:encoded><![CDATA[<p><center><img style = "border:1px solid black;" src="http://rossboucher.com/wp-content/uploads/2010/03/StackOverflow.jpg" alt="Stack overflow at line: 0" title="Stack overflow at line: 0" width="282" height="197" /></center></p>
<p>Every once in a while, you stumble upon a particularly strange bug. A bug that seems to defy the rules of space-time. A bug that makes you pull your hair out for days. A bug that almost certainly includes Internet Explorer. This was one of those bugs for me, and since I haven&#8217;t found a lot of information out there even now that I know what the problem was, I wanted to write it up for posterity.</p>
<p>It starts with what looks like a relatively benign function, that we&#8217;ll call recurse:</p>
<pre><code style="border:1px solid rgb(255, 100, 100);">
window.recurse = function(times)
{
    if (times !== 0)
        recurse(times - 1);
}

recurse(13);
</code></pre>
<p>If you pass in the magic number 13 (or anything higher), this recursion is going to fail with our stack overflow pop up. No problem, you say? You&#8217;ve fought Internet Explorer before, and you know how to get down to business. Fire up the trusty IE 8 debugger and get to work! Unfortunately for you, the debugger won&#8217;t be triggered. Just a pop up for you. If you&#8217;re feeling extra ambitious, maybe you&#8217;ll try installing Visual Studio and hooking up the advanced debugger directly to IE; I did. No such luck. </p>
<p>I should mention that the code above wasn&#8217;t what forced me to investigate this bug. I&#8217;m not usually in the habit of writing recursive functions that don&#8217;t actually do anything. And when your code base is tens of thousands of lines long, and your coworker has pushed a<br />
couple thousand new lines of code (which radically alter the load process), tracking down any problem without a debugger starts to get hairy. At one point in the process, I actually stepped line by line through every single new line of code, certain I&#8217;d track down the bug. I didn&#8217;t, because not only does IE not trigger the normal exception mechanism, it doesn&#8217;t even report the error until after any waiting script executions are finished. Fun.</p>
<p>Thankfully, <a href="http://joel.franusic.com">my neighbor</a> works at Microsoft, so I was able to get an inside look into the issue. That&#8217;s where our test function comes in (thanks Microsoft). Let&#8217;s get back to it:</p>
<pre><code style="border: 1px solid rgb(100, 255, 100);">
var recurse = function(times)
{
    if (times !== 0)
        recurse(times - 1);
}

recurse(13);
recurse(10000);
</code></pre>
<p>Our new version works. Can you spot the difference? We&#8217;re using a &#8220;local&#8221; (but really global considering our current scope) variable here, instead of assigning the function to a property on the window object. This tells us that it has something to do with the window &#8220;host&#8221; object, but it isn&#8217;t the whole piece of the puzzle just yet.</p>
<pre><code style="border: 1px solid rgb(100, 255, 100);">
(function(){
    var recurse = function(times)
    {
        if (times !== 0)
            recurse(times - 1);
    }

    //we won't have access outside to recurse, so add a global ref
    window.recurse = recurse;
})();

recurse(13);
</code></pre>
<p>This test also works, and is pretty much the last piece of the puzzle. From this we can see that simply assigning a variable through the window object isn&#8217;t the problem, the problem is actually recursing through that variable.</p>
<p>In the block above, the recursion is happening through the local var, not the global reference, and so it isn&#8217;t triggering the bug. To prove that this is the case, let&#8217;s try the opposite test:</p>
<pre><code style="border: 1px solid rgb(255, 100, 100);">
(function(){
    var r = function(times)
    {
        if (times !== 0)
            recurse(times - 1);
    }

    //we won't have access outside to recurse, so add a global ref
    window.recurse = r;
})();

recurse(13);
</code></pre>
<p>Here, we&#8217;re doing the recursion through the global reference, and as we expected it fails. So, the lesson to learn here is that any recursion that happens through the window object is limited to a stack depth of 12. If there was a tl;dr; to this post, it would be that.</p>
<p>To dig just a little bit deeper into some of the oddities of what&#8217;s going on here (and how it impacted Cappuccino), you&#8217;ll want to see this unbelievably strange (but not technically incorrect) behavior:</p>
<pre><code>
window === window;           //true
window.window === window;    //false

function global(){
    return (function(){return this;})();
}

global() === window;         //true
global().window === window;  //false
</code></pre>
<p>Technically, the behavior of the window object isn&#8217;t defined by ECMAScript or any browser standard; it&#8217;s a native object provided by the browser to the runtime environment. As a result, even though IE&#8217;s behavior here is strange, and the opposite of all other major browsers, it isn&#8217;t technically wrong. It&#8217;s absolutely terrible, though.</p>
<p>Why did we have this problem in the first place? To answer that, you need to know a bit about CommonJS modules. In the CommonJS &#8220;spec&#8221; modules have their own scope, and don&#8217;t export their vars as globals to the outside world. Instead, the module loader passes in an &#8220;exports&#8221; object, and the module author assigns properties to that object. Another way to put it would be to say that the public API of any module has to be explicitly created by assigning methods to the exports object.</p>
<p>In addition to Cappuccino, we&#8217;re also the authors of Narwhal, the most popular implementation of the CommonJS spec. We&#8217;ve already migrated most of our tools to run on top of Narwhal, and we&#8217;re continuing to improve the integration between Objective-J and Narwhal. Part of that means changing some of our code to use the exports technique, and using that same code in the browser.</p>
<p>What we ended up with was something like this:</p>
<pre><code style="border: 1px solid rgb(255, 100, 100);">
var exports = {};
(function(global, exports){

    //lots of methods...

    function objj_msgSend(){
        //do some stuff;
    }

    //lots of exports...
    exports.objj_msgSend = objj_msgSend;

    // make exports global
    for (var export in exports)
        if (exports.hasOwnProperty(export))
            global[export] = exports[export];

})(window, exports)
</code></pre>
<p>The final loop assigns the exports to the global scope, since that&#8217;s how Objective-J code is expected to run. This last step was the cause of all of our problems, because as you can see, we&#8217;re creating all global methods on the window object, which means all calls to them are going to go through the host object, and be subject to our exceptionally low recursion limit.</p>
<p>Our first fix looked like this:</p>
<pre><code style="border: 1px solid rgb(100, 255, 100);">
    for (var export in exports)
        if (exports.hasOwnProperty(export))
            eval(export +" = global[""+export+""];");
</code></pre>
<p>The eval creates a global implicitly, rather than explicitly, which doesn&#8217;t trigger the trip through the host object. We explored a few different ways to get around the bug, including working with Microsoft, but found no other viable solution.</p>
<p>Rather than ship this code in Cappuccino 0.8, though, we decided to take a step back and re-examine our initial requirements. The desire to strictly adhere to the CommonJS proposal was requiring that our code become more complex and harder to maintain, so we dropped that requirement.</p>
<p>The final version of the code is almost exactly the same, except rather than doing things like global.foo = function(){}, we&#8217;re simply using implicit global creation directly. This is more in line with the way all existing JavaScript runtimes actually work. It&#8217;s also the way Narwhal works, and probably the way CommonJS <em>should</em> work.</p>
<p>I want to give another thank you to all the folks at Microsoft who helped us track down the problem and provided us with a simple test case that reproduced the problem. They were quite helpful, and we (along with all of our users) appreciate it. Now hopefully we&#8217;ll see this issue addressed in IE9, along with a faster JavaScript engine <img src='http://cappuccino.org/discuss/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
	</channel>
</rss>
