<?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>Where&#039;s Walden? &#187; mozilla</title>
	<atom:link href="http://whereswalden.com/tag/mozilla/feed/" rel="self" type="application/rss+xml" />
	<link>http://whereswalden.com</link>
	<description>Mozilla, politics, economics, law, backpacking, cycling, and other random desiderata</description>
	<lastBuildDate>Thu, 03 May 2012 09:13:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Introducing mozilla/FloatingPoint.h: methods for floating point types and values</title>
		<link>http://whereswalden.com/2012/04/19/introducing-mozillafloatingpoint-h-methods-for-floating-point-types-and-values/</link>
		<comments>http://whereswalden.com/2012/04/19/introducing-mozillafloatingpoint-h-methods-for-floating-point-types-and-values/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 02:00:25 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[double]]></category>
		<category><![CDATA[floating point]]></category>
		<category><![CDATA[gcc]]></category>
		<category><![CDATA[ieee-754]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[msvc]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3755</guid>
		<description><![CDATA[The latest addition to the Mozilla Framework Based on Templates (mfbt) is mozilla/FloatingPoint.h. This header implements various floating point functionality. Functionality overview mozilla/FloatingPoint.h currently implements the following functionality, all centered around working with double-precision floating point numbers. (There&#8217;s no single-precision support only because Mozilla seemingly doesn&#8217;t need it. The only code I can find that [...]]]></description>
			<content:encoded><![CDATA[<p>The latest addition to the Mozilla Framework Based on Templates (<abbr title="Mozilla Framework Based on Templates">mfbt</abbr>) is <code>mozilla/FloatingPoint.h</code>.  This header implements various floating point functionality.</p>
<h2>Functionality overview</h2>
<p><code>mozilla/FloatingPoint.h</code> currently implements the following functionality, all centered around working with double-precision floating point numbers.  (There&#8217;s no single-precision support only because Mozilla seemingly doesn&#8217;t need it.  The only code I can find that does this sort of thing for single-precision numbers is <a href="http://hg.mozilla.org/mozilla-central/file/3e2557ca55d6/gfx/src/nsCoord.h#l58"><code>nsCoord.h</code></a>, and that only barely.  We can add single-precision equivalents when we need them.)</p>
<dl>
<dt><code>MOZ_DOUBLE_IS_NaN(double d)</code></dt>
<dd>Determines whether a value is <code>NaN</code> (not a number).</dd>
<dt><code>MOZ_DOUBLE_IS_INFINITE(double d)</code></dt>
<dd>Determines whether a value is positive or negative infinity.</dd>
<dt><code>MOZ_DOUBLE_IS_FINITE(double d)</code></dt>
<dd>Determines whether a number is finite &mdash; that is, not <code>NaN</code> or positive or negative infinity.</dd>
<dt><code>MOZ_DOUBLE_IS_NEGATIVE(double d)</code></dt>
<dd>Determines whether a number is negative.  This is useful because <code>d &lt; 0</code> <em>does not</em> answer this question!  There are two zero values, <code>+0</code> and <code>-0</code>, and <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE-754</a> requires that <code>(-0 < 0)</code> be <em>false</em>.  (There are good reasons for this, but this isn't the place to get into them.  If you haven't read it, read <a href="https://www.ualberta.ca/~kbeach/phys420_580_2010/docs/ACM-Goldberg.pdf">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a> <em>right now</em>.  It probably gives the answer, and much much more knowledge as well.)  This method properly distinguishes <code>-0</code> as being negative.</dd>
<dt><code>MOZ_DOUBLE_IS_NEGATIVE_ZERO(double d)</code></dt>
<dd>Determines whether a number is <code>-0</code>.</dd>
<dt><code>MOZ_DOUBLE_EXPONENT(double d)</code>
<dt>
<dd>Returns the exponent portion of the number.  Floating point numbers are represented as a sign bit <code>s</code>, a binary fraction <code>b<sub>0..p</sub></code>, and an exponent <code>E</code>.  The represented number, then, is <code>(-1)<sup>s</sup>(b<sub>0..p</sub>)2<sup>E</sup></code>.  This method returns the number <code>E</code> for a floating point number.</dd>
<dt><code>MOZ_DOUBLE_POSITIVE_INFINITY()</code></dt>
<dd>Returns positive infinity.</dd>
<dt><code>MOZ_DOUBLE_NEGATIVE_INFINITY()</code></dt>
<dd>Returns negative infinity.</dd>
<dt><code>MOZ_DOUBLE_SPECIFIC_NaN(int signbit, uint64_t significand)</code></dt>
<dd>Computes a specific <code>NaN</code> value, with a bit pattern specified by provided parameters.  The bit layout IEEE-754 specifies for floating point formats interestingly requires that multiple bit patterns be treated as <code>NaN</code> values.  This method allows the user to create such custom <code>NaN</code> values if he needs to.  (99% of code should never, ever touch this method.  Instead, most code should use...)</dd>
<dt><code>MOZ_DOUBLE_NaN()</code>
<dt>
<dd>Computes an unspecified <code>NaN</code> value.  If you need a <code>NaN</code> value and you don't <em>know</em> that you need a specific <code>NaN</code>, use this method instead to get one.</dd>
<dt><code>MOZ_DOUBLE_MIN_VALUE()</code></dt>
<dd>Returns the smallest non-zero positive double value.</dd>
<dt><code>MOZ_DOUBLE_IS_INT32(double d, int32_t* i)</code></dt>
<dd>Determines if the provided number is a signed 32-bit integer.  (<code>-0</code> doesn't count as such; <code>+0</code>, the "normal" zero value, does.)  If it is, <code>*i</code> will be set to that value when the method returns.</dd>
</dl>
<p>(There's one more method in the header, currently, that used to have users.  Sometime in the last couple months, however, that method's users all disappeared, and I didn't notice it when rebasing.  Thus I'll be removing it shortly, and I haven't mentioned it here.)</p>
<h2>Why add some of these methods?  Aren't <code>isinf</code>, <code>isnan</code>, and so on good enough?</h2>
<p>There are standard methods implementing some (but not all) of this functionality.  In the best of all possible worlds we could simply use <code>isnan</code> and other such methods directly.  In practice we've encountered a number of problems.</p>
<p>First, Microsoft's compilers gratuitously Think Different and don't expose <code>isnan</code> and friends, so on those platforms you'd have to use <code>_isnan</code> instead.  (<code>std::isnan</code> isn't usable there because some of our code still must work as both C and C++.)  Obviously, we don't want to <code>#ifdef</code> every place we need to use the method.</p>
<p>Second, we've found various compilers have bugs when using either the standard methods or Microsoft's bogo-named methods.  Most commonly this bustage occurs with <abbr title="profile-guided optimization">PGO</abbr> builds; interestingly, both MSVC and gcc have problems here, despite their optimizers obviously not sharing any code.</p>
<p>Third, we've found even some obvious bitwise algorithms trigger PGO build failures, again on entirely different compilers.  (You can't win.)</p>
<p>Basically, then, we can't use the standard methods, we can't use some bitwise methods, and whatever we do we have to be really careful about to make sure we don't break anything.  Hopefully this header will satisfy those requirements.</p>
<h2>Where's this header again?</h2>
<p>The header is located at <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/FloatingPoint.h"><code>mfbt/FloatingPoint.h</code></a> in the source tree.  However, per standard mfbt practice, you should use <code>#include "mozilla/FloatingPoint.h"</code> to include it.  Knock yourself out using it.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2012/04/19/introducing-mozillafloatingpoint-h-methods-for-floating-point-types-and-values/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Memes</title>
		<link>http://whereswalden.com/2012/03/13/memes/</link>
		<comments>http://whereswalden.com/2012/03/13/memes/#comments</comments>
		<pubDate>Tue, 13 Mar 2012 15:29:45 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[dr. strangelove]]></category>
		<category><![CDATA[lulz]]></category>
		<category><![CDATA[meme]]></category>
		<category><![CDATA[meme gap]]></category>
		<category><![CDATA[mineshaft gap]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[webkit]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3740</guid>
		<description><![CDATA[WebKit (well, one twisted soul, I think) has started a meme collection. It&#8217;s true that Mozilla has a quotes database, which sometimes we are even gracious enough to share with them [more here]). But we have no meme collection. Mozilla Internetizens, fix this. Pronto. UPDATE: jdm follows through with Mozilla Memes. Next step: ADDRESS THE [...]]]></description>
			<content:encoded><![CDATA[<p>WebKit (well, <a href="https://twitter.com/awesomekling">one twisted soul</a>, I think) has started a <a href="http://webkitmemes.tumblr.com/">meme collection</a>.  It&#8217;s true that Mozilla has <a href="http://quotes.burntelectrons.org/browse">a quotes database</a>, which sometimes we are even gracious enough to <a href="http://quotes.burntelectrons.org/6306">share with them</a> [<a href="http://quotes.burntelectrons.org/search?query=tag%3A%23webkit">more</a> <a href="http://quotes.burntelectrons.org/search?query=tag%3Awebkit">here</a>]).  But we have no meme collection.</p>
<div><figure id="attachment_3741"  class="aligncenter"  style="width: 410px"><a href="http://whereswalden.com/wp-content/uploads/2012/03/meme-gap.jpg"><img src="http://whereswalden.com/wp-content/uploads/2012/03/meme-gap.jpg" alt="Gentlemen, we must not allow a meme gap!" title="Buck Turgidson does not approve." width="400" height="302" class="size-full wp-image-3741" /></a>
<figcaption><div>Buck Turgidson does not approve.</div></figcaption></figure></div>
<p>Mozilla Internetizens, fix this.  Pronto.</p>
<p><strong>UPDATE</strong>: <a href="http://www.joshmatthews.net/">jdm</a> follows through with <a href="http://mozillamemes.tumblr.com/">Mozilla Memes</a>.  Next step: ADDRESS THE GAP.</p>
<p><strong>UPDATE 2</strong>: The gauntlet <a href="http://webkitmemes.tumblr.com/post/19243637421/scumbag-firefox-copies-another-webkit-feature">has been</a> <a href="http://webkitmemes.tumblr.com/post/19243913380/hipster-webkitmemes">thrown down</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2012/03/13/memes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PSA: If you get an xpidllex.py failure building mozilla-central, rm $topsrcdir/xpcom/idl-parser/*.pyc (bug 723861) (eom)</title>
		<link>http://whereswalden.com/2012/03/02/psa-if-you-get-a-xpidllex-py-failure-building-mozilla-central-rm-topsrcdirxpcomidl-parser-pyc-bug-723861-eom/</link>
		<comments>http://whereswalden.com/2012/03/02/psa-if-you-get-a-xpidllex-py-failure-building-mozilla-central-rm-topsrcdirxpcomidl-parser-pyc-bug-723861-eom/#comments</comments>
		<pubDate>Sat, 03 Mar 2012 00:40:47 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[building]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[psa]]></category>
		<category><![CDATA[public service announcement]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[xpidllex.py]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3731</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2012/03/02/psa-if-you-get-a-xpidllex-py-failure-building-mozilla-central-rm-topsrcdirxpcomidl-parser-pyc-bug-723861-eom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SpiderMonkey no longer supports sharp variables</title>
		<link>http://whereswalden.com/2012/01/25/spidermonkey-no-longer-supports-sharp-variables/</link>
		<comments>http://whereswalden.com/2012/01/25/spidermonkey-no-longer-supports-sharp-variables/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 18:17:19 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[sharp variables]]></category>
		<category><![CDATA[spidermonkey]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3701</guid>
		<description><![CDATA[ECMAScript object literals ECMAScript, the standard underlying the JavaScript language, can represent simple objects and arrays using literals. var arr = [1, 2, 3]; var obj = { property: "ohai" }; But it can&#8217;t represent all objects and arrays. Cyclic and non-tree objects ECMAScript literals can&#8217;t represent circular objects and arrays which (perhaps at some [...]]]></description>
			<content:encoded><![CDATA[<h2>ECMAScript object literals</h2>
<p>ECMAScript, the standard underlying the JavaScript language, can represent simple objects and arrays using literals.</p>
<pre class="code" data-language="javascript">
var arr = [1, 2, 3];
var obj = { property: "ohai" };
</pre>
<p>But it can&#8217;t represent all objects and arrays.</p>
<h2>Cyclic and non-tree objects</h2>
<p>ECMAScript literals can&#8217;t represent <em>circular</em> objects and arrays which (perhaps at some nesting distance) have properties referring to themselves (in other words, the objects form cyclic graphs).  Nor can they (faithfully) represent objects which contain some other object multiple times (in other words, the objects form a directed acyclic graph which is not also a tree).</p>
<pre class="code" data-language="javascript">
var arr = [1, "overwritten", 3];
arr[1] = arr; // cyclic
var obj = { property: "ohai", nest: {} };
obj.nest.parent = obj; // cyclic
obj.secondCopy = obj.nest; // non-tree, obj.nest is repeated
</pre>
<h2>Sharp variables</h2>
<p>SpiderMonkey historically supported extension syntax to represent such graphs under the name <dfn>sharp variables</dfn>.  <a href="https://developer.mozilla.org/en/Sharp_variables_in_JavaScript">Sharp variables</a> were inspired by Common Lisp syntax, and they enabled naming an object or array literal before it had been fully evaluated (even, to a limited extent, interacting with it).  Netscape proposed sharp variables for inclusion in <abbr title="ECMAScript, 3rd. edition">ES3</abbr>, but the proposal was rejected as being too domain-specific and being arguably ugly.  Since then the extension has lingered in SpiderMonkey but has seen very little use.</p>
<pre class="code" data-language="javascript">
// Identical semantics using sharp variables
var arr = #1=[1, #1#, 3]; // #n= names an object being created, #n# refers to it
var obj = #1={ property: "ohai", nest: #2={ parent: #1# }, secondCopy: #2# };
</pre>
<p>No other ECMAScript implementer has since shown interest in implementing sharp variables.  And with renewed efforts to evolve ECMAScript syntax, special characters like <code>#</code> are increasingly precious.  Thus we&#8217;ve decided it&#8217;s time to remove sharp variable support from SpiderMonkey.</p>
<p>One benefit to removing sharp variables is that we can remove a good chunk of rarely-used code (and attack surface: sharp variables have been a source of some number of likely vulnerabilities) from SpiderMonkey.  A syntax-removal patch added 79 lines and removed <strong>1112 lines</strong>, including tests; not including tests, it added 42 lines and removed <strong>677 lines</strong>.  A subsequent patch to remove generation of sharp variable syntax from object decompilation added 65 lines and removed <strong>128 lines</strong>.  Removing sharp variables will also permit some simplifications now that evaluating a literal can&#8217;t have side effects beyond those in any nested property initializers.</p</p>
<h2>Alternatives to sharp variables</h2>
<p>Sharp variables may have been sometimes convenient, but they were mere syntactic sugar.  It should be simple to convert any use of sharp variables to an equivalent sequence of property additions.  If you were sufficiently aware of sharp variables to use them to represent non-tree objects, I trust I don&#8217;t have to explain how to do this.</p>
<p>Somewhat more interesting are the cases where decompiling an object produced sharp variable syntax, as when decompiling a cyclic object during debugging.  (It&#8217;s worth noting in passing that decompilation will not infinitely recur: instead, it&#8217;ll bottom out with an empty object or an omitted property.)  <a href="http://blog.mozilla.com/jorendorff/">Jason Orendorff</a> has written a <a href="https://github.com/jorendorff/sharps">sharps mini-library</a> implementing decompilation of cyclic and non-tree objects which may be useful for this task.</p>
<h2>When to expect this change</h2>
<p>The sharp variable <a href="https://developer.mozilla.org/en/JavaScript/Sharp_variables_in_JavaScript">documentation</a> on <a href="https://developer.mozilla.org/">MDN</a> has long noted that sharp variables were deprecated and would likely to be removed; a few months ago that warning was upgraded to a firm statement that they <em>would</em> be removed.  The sharp variable removal patch that landed yesterday completes the process.  The removal will first appear in either today or tomorrow&#8217;s <a href="http://nightly.mozilla.org/">nightly</a>; in a week&#8217;s time it&#8217;ll make its way into the aurora branch, then the beta branch, and finally into Firefox 12.  Versions of Firefox prior to 12 will not be affected by this removal, including the extended-support release Firefox 10.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2012/01/25/spidermonkey-no-longer-supports-sharp-variables/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Introducing mozilla/Assertions.h to mfbt</title>
		<link>http://whereswalden.com/2011/12/26/introducing-mozillaassertions-h-to-mfbt/</link>
		<comments>http://whereswalden.com/2011/12/26/introducing-mozillaassertions-h-to-mfbt/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 17:17:34 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[assertion]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[MOZ_ALWAYS_FALSE]]></category>
		<category><![CDATA[MOZ_ALWAYS_TRUE]]></category>
		<category><![CDATA[MOZ_ASSERT]]></category>
		<category><![CDATA[MOZ_ASSERT_IF]]></category>
		<category><![CDATA[MOZ_NOT_REACHED]]></category>
		<category><![CDATA[MOZ_STATIC_ASSERT]]></category>
		<category><![CDATA[static assertion]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3639</guid>
		<description><![CDATA[Recently I landed changes to the Mozilla Framework Based on Templates (mfbt) implementing Assertions.h, the new canonical assertions implementation in C/C++ Mozilla code. Runtime assertions Using assertions, a developer can efficiently detect when his code goes awry because internal invariants were broken. Mozilla has many assertion facilities. NS_ASSERTION is the oldest, but unfortunately it can [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I landed changes to the Mozilla Framework Based on Templates (<a href="https://developer.mozilla.org/en/mfbt"><abbr title="Mozilla Framework Based on Templates">mfbt</abbr></a>) implementing <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/Assertions.h"><code>Assertions.h</code></a>, the new canonical assertions implementation in C/C++ Mozilla code.</p>
<h2>Runtime assertions</h2>
<p>Using assertions, a developer can efficiently detect when his code goes awry because internal invariants were broken.  Mozilla has many assertion facilities.  <code>NS_ASSERTION</code> is the oldest, but unfortunately it can be ignored, and therefore historically has been.  We later introduced <code>NS_ABORT_IF_FALSE</code> as as an actual assertion that fails hard, and it&#8217;s now widely used.  But it&#8217;s quite unwieldy, and it can&#8217;t be used by code that doesn&#8217;t want to depend on <abbr title="Cross-platform component object model">XPCOM</abbr>.  (Who would?)</p>
<p>mfbt addresses latent concerns with existing runtime assertions by introducing <code>MOZ_ASSERT</code>, <code>MOZ_ASSERT_IF</code>, <code>MOZ_ALWAYS_TRUE</code>, <code>MOZ_ALWAYS_FALSE</code>, and <code>MOZ_NOT_REACHED</code> macros to make performing true assertions dead simple.</p>
<h3><code>MOZ_ASSERT(expr)</code> and <code>MOZ_ASSERT_IF(ifexpr, expr)</code></h3>
<p><code>MOZ_ASSERT(expr)</code> is straightforward: pass an expression as its sole argument, and in debug builds, if that expression is falsy, the assertion fails and execution halts in a debuggable way.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

void frobnicate(Thing* thing)
{
  MOZ_ASSERT(thing);
  thing->frob();
}
</pre>
<p><code>MOZ_ASSERT_IF(ifexpr, expr)</code> addresses the case when you want to assert something, where the check to decide whether to assert isn&#8217;t otherwise needed.  You&#8217;d rather not muddy up your code by adding an <code>#ifdef</code> and <code>if</code> statement around your assertion.  (<code>MOZ_ASSERT(!ifexpr || expr)</code> is a workaround, but it&#8217;s not very readable.)  SpiderMonkey&#8217;s experience suggests Mozilla code will get good mileage from <code>MOZ_ASSERT_IF</code>.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

class Error
{
    const char* optionalDescription;

  public:
    /* If specified, desc must not be empty. */
    Error(const char* desc = NULL)
    {
      MOZ_ASSERT_IF(desc != NULL, desc[0] != '\0');
      optionalDescription = desc;
    }
};
</pre>
<h3><code>MOZ_ALWAYS_TRUE(expr)</code> and <code>MOZ_ALWAYS_FALSE(expr)</code></h3>
<p>Sometimes the expression for an assertion must always be executed for its side effects, and it can&#8217;t just be executed in debug builds.  <code>MOZ_ALWAYS_TRUE(expr)</code> and <code>MOZ_ALWAYS_FALSE(expr)</code> support this idiom.  These macros always evaluate their argument, and in debug builds that argument is asserted truthy or falsy.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

/* JS_ValueToBoolean was fallible but no longer is. */
MOZ_ALWAYS_TRUE(JS_ValueToBoolean(cx, v, &#038;b));
</pre>
<h3><code>MOZ_NOT_REACHED(reason)</code></h3>
<p><code>MOZ_NOT_REACHED(reason)</code> indicates that the given point can&#8217;t be reached during execution: simply hitting it is a bug.  (Think of it as a more-explicit form of asserting <code>false</code>.)  It takes as an argument an explanation of why that point shouldn&#8217;t have been reachable.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

// ...in a language parser...
void handle(BooleanLiteralNode node)
{
  if (node.isTrue())
    handleTrueLiteral();
  else if (node.isFalse())
    handleFalseLiteral();
  else
    MOZ_NOT_REACHED("boolean literal that's not true or false?");
}
</pre>
<h2>Compile-time assertions</h2>
<p>Most assertions must happen at runtime.  But some assertions are static, depending only on constants, and could be checked during compilation.  A compile time check is better than a runtime check: the developer need not ensure a test exercises that code, because the compiler itself enforces the assertion.  Properly crafted static assertions can never be unwittingly broken.</p>
<h3><code>MOZ_STATIC_ASSERT(cond, reason)</code></h3>
<p><code>MOZ_STATIC_ASSERT(cond, reason)</code> asserts a condition at compile time.  In newer compilers, if the assertion fails, the compiler will also include <code>reason</code> in diagnostics.</p>
<pre class="code" data-language="c++">
#include "mozilla/Assertions.h"

struct S { ... };
MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
                  "S should be a multiple of word size for efficiency");
</pre>
<p><code>MOZ_STATIC_ASSERT</code> is implemented with <a href="http://hg.mozilla.org/mozilla-central/file/45206fca898d/mfbt/Assertions.h#l62">an impressive pile of hacks</a> which should work perfectly everywhere &mdash; except, rarely, gcc 4.2 (the current OS X compiler) when compiling C++ code.  The failure mode requires <code>MOZ_STATIC_ASSERT</code> on line <var>N</var> not in an <code>extern "C"</code> code block and a second <code>MOZ_STATIC_ASSERT</code> on the <em>same</em> line <var>N</var> (in a different file) in an <code>extern "C"</code> block.  <em>And</em> those two files have to be used when compiling a single file, with the <code>extern "C"</code>&#8216;d assertion second.  This seems improbable, so we&#8217;ll risk it til we drop gcc 4.2 support.</p>
<h2>Possible improvements</h2>
<p><code>Assertions.h</code> is reasonably complete, but I have a few ideas I&#8217;ve been considering for improvements.  Let me know what you think of them in comments.</p>
<h3>Add an optional <code>reason</code> argument to <code>MOZ_ASSERT</code>, and maybe to <code>MOZ_ALWAYS_TRUE</code> and <code>MOZ_ALWAYS_FALSE</code></h3>
<p><code>MOZ_ASSERT</code> takes only the condition to test as an argument.  In contrast <code>NS_ASSERTION</code> and <code>NS_ABORT_IF_FALSE</code> take the condition and an explanatory string.  <code>MOZ_ASSERT</code>&#8216;s lack of explanation derives purely from its ancestry in the <code>JS_ASSERT</code> macro: it wasn&#8217;t deliberate.</p>
<p>Would it be helpful if <code>MOZ_ASSERT</code>, <code>MOZ_ALWAYS_TRUE</code>, and <code>MOZ_ALWAYS_FALSE</code> optionally took a reason?  (Optional because some assertions, <abbr title="exempli gratia, for example" lang="la">e.g.</abbr> many non-null assertions, are self-explanatory.)  We&#8217;d have to disable assertions for compilers not implementing variadic macros (I think our supported compilers implement them), or <em>possibly</em> lose the condition expression in the assertion failure message.  A reason would make it easier to convert existing <code>NS_ABORT_IF_FALSE</code>s to <code>MOZ_ASSERT</code>s.  Should we add an optional second argument to <code>MOZ_ASSERT</code> and the others?</p>
<h3>Include <code>__assume(0)</code> or <code>__builtin_unreachable()</code> in <code>MOZ_NOT_REACHED</code></h3>
<p><a href="http://clang.llvm.org/docs/LanguageExtensions.html#__builtin_unreachable"><code>__builtin_unreachable()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/1b3fsfxw.aspx"><code>__assume(0)</code></a> inform the compiler that subsequent code can&#8217;t be executed, providing optimization opportunities.  It&#8217;s unclear how this affects debugging feedback like stack traces.  If the optimizations destroy Breakpad-ability, that may be too big a loss.  More research is needed here.</p>
<p>Another possibility might be to use <a href="http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005ftrap-3216"><code>__builtin_trap()</code></a>.  This may not communicate an optimization opportunity comparable to that provided by the other two options.  (It can&#8217;t be equally informative because execution must be able to continue past a trap.  Thus the two have different impacts on variable lifetimes.  Whether <code>__builtin_trap</code> otherwise communicates &#8220;unlikelihood&#8221; well enough isn&#8217;t clear.)  Perhaps <code>__builtin_trap</code> could be used in debug builds, and <code>__builtin_unreachable</code> could be used in optimized builds.  Again: more research needed.</p>
<h3>Use C11&#8242;s <code>_Static_assert</code> in <code>MOZ_STATIC_ASSERT</code></h3>
<p>New editions of C and C++ include built-in static assertion syntax.  <code>MOZ_STATIC_ASSERT</code> expands to C++11&#8242;s <code>static_assert(2 + 2 == 4, "ya rly")</code> syntax when possible.  It could be made to expand to C11&#8242;s <code>_Static_assert('A' == 'A', "no wai")</code> syntax in some other cases, but frankly I don&#8217;t hack enough C code to care as long as the static assertion actually happens.  <img src='http://whereswalden.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   This is <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=713531">bug 713531</a> if you&#8217;re interested in investigating.</p>
<h2>Want more information?</h2>
<p>Read <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/Assertions.h"><code>Assertions.h</code></a>.  mfbt code has a high standard for code comments in interface descriptions, and for file names (the current <code>Util.h</code> being a notable exception <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=713082">which will be fixed</a>).  We want it to be reasonably obvious where to find what you need and how to use it by skimming <a href="http://mxr.mozilla.org/mozilla-central/source/mfbt/"><code>mfbt/</code></a>&#8216;s contents and then skimming a few files&#8217; contents.  Good comments are key to that.  You should find <code>Assertions.h</code> quite readable; please <a href="https://bugzilla.mozilla.org/enter_bug.cgi?product=Core&amp;product=MFBT">file a bug</a> if you have improvements to suggest.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/12/26/introducing-mozillaassertions-h-to-mfbt/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Seen during a recent compile of mozilla-central with Clang, offered without comment</title>
		<link>http://whereswalden.com/2011/12/15/seen-during-a-recent-compile-of-mozilla-central-with-clang-offered-without-comment/</link>
		<comments>http://whereswalden.com/2011/12/15/seen-during-a-recent-compile-of-mozilla-central-with-clang-offered-without-comment/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 03:56:15 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[beard]]></category>
		<category><![CDATA[building]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[offered without comment]]></category>
		<category><![CDATA[warning]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3633</guid>
		<description><![CDATA[TestStartupCache.cpp /home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:119:15: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings] char* buf = "Market opportunities for BeardBook"; ^ /home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:120:14: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings] char* id = "id"; ^ /home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:148:15: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings] char* buf = "BeardBook competitive [...]]]></description>
			<content:encoded><![CDATA[<pre class="code">
TestStartupCache.cpp
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:119:15</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* buf = "Market opportunities for BeardBook";
              ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:120:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:148:15</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* buf = "BeardBook competitive analysis";
              ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:149:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:197:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:288:15</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* buf = "Find your soul beardmate on BeardBook";
              ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:289:14</strong>: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
  char* id = "id";
             ^
<strong>/home/jwalden/moz/inttypes/startupcache/test/TestStartupCache.cpp:323:12</strong>: warning: unused variable 'rv2' [-Wunused-variable]
  nsresult rv2;
           ^
8 warnings generated.
</pre>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/12/15/seen-during-a-recent-compile-of-mozilla-central-with-clang-offered-without-comment/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Party like it&#8217;s 1999: &lt;stdint.h&gt; comes to Mozilla!</title>
		<link>http://whereswalden.com/2011/12/08/party-like-its-1999-stdint-h-comes-to-mozilla/</link>
		<comments>http://whereswalden.com/2011/12/08/party-like-its-1999-stdint-h-comes-to-mozilla/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 20:08:11 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[c89]]></category>
		<category><![CDATA[c99]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[msvc]]></category>
		<category><![CDATA[our long national nightmare is over]]></category>
		<category><![CDATA[stdint.h]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3544</guid>
		<description><![CDATA[tl;dr Need an integer type with guaranteed size? If you&#8217;re not defining a cross-file interface, #include "mozilla/StdInt.h"#include "mozilla/StandardInteger.h" and use uint32_t or any other type defined by &#60;stdint.h&#62;. (If you are defining an interface, use PRUint32 and similar &#8212; for now.) mozilla/StdInt.hmozilla/StandardInteger.h is a cross-platform implementation of &#60;stdint.h&#62;&#8216;s functionality usable in any code. Embedders may [...]]]></description>
			<content:encoded><![CDATA[<h2><abbr title="too long; didn't read">tl;dr</abbr></h2>
<p>Need an integer type with guaranteed size?  If you&#8217;re not defining a cross-file interface, <del><code>#include "mozilla/StdInt.h"</code></del><ins><code>#include "mozilla/StandardInteger.h"</code></ins> and use <code>uint32_t</code> or any other type defined by <code>&lt;stdint.h&gt;</code>.  (If you <em>are</em> defining an interface, use <code>PRUint32</code> and similar &mdash; for now.)  <del><code>mozilla/StdInt.h</code></del><ins><code>mozilla/StandardInteger.h</code></ins> is a cross-platform implementation of <code>&lt;stdint.h&gt;</code>&#8216;s functionality usable in any code.</p>
<p>Embedders may find that the <del><code>mozilla/StdInt.h</code></del><ins><code>mozilla/StandardInteger.h</code></ins> <code>typedef</code>s conflict with ones they have already been using.  To work around this conflict, write a <code>stdint.h</code> compatible with the embedding&#8217;s <code>typedef</code>s (more likely: adapt an existing implementation), then set the preprocessor variable <code>MOZ_CUSTOM_STDINT_H</code> to a quoted path to that reimplementation when <del><code>mozilla/StdInt.h</code></del><ins><code>mozilla/StandardInteger.h</code></ins> is included.  It may be simplest to add this to command line flags when invoking the compiler.</p>
<h2>Fixed-size integer types</h2>
<p><dfn>Fixed-size integer types</dfn> are signed or unsigned types with exactly <var>N</var> bits.  They contrast with the built-in C and C++ types (<code>char</code>, <code>short</code>, <code>int</code>, <abbr title="et cetera, and so on" lang="la">&amp;c.</abbr>) with compiler-dependent sizes.  Fixed-size integer types are quite useful:</p>
<ul>
<li>They work well when serializing an object to a sequence of bytes, where the size of a serialized item <em>must</em> be constant for correctness.</li>
<li>They minimize memory use in <code>class</code>es and <code>struct</code>s, also making padding-based waste more obvious.</li>
<li>They work well in cross-platform <abbr title="Application Programming Interfaces">APIs</abbr>, eliminating the challenge of implementing correct behavior when types have different sizes across platforms.</li>
</ul>
<p>Fixed-size integer types are useful in the same way <code>size_t</code>, <code>off_t</code>, and other non-built-in types are: they fit some problem domains better than built-in types.</p>
<p>C99 and C++11 finally standardized fixed-size integer types in <code>&lt;stdint.h&gt;</code> and <code>&lt;cstdint&gt;</code>.  They define <code>{u,}int{8,16,32,64}_t</code> types, plus useful constants for their limits (<code>INT8_MIN</code>, <code>INT8_MAX</code>, <code>UINT8_MAX</code>, <code>INT16_MIN</code>, <span lang="la">&amp;c.</span>).  One would expect projects to quickly use these types, but it didn&#8217;t happen.</p>
<p>Old projects predating <code>&lt;stdint.h&gt;</code> have been particularly slow to adopt it.  Many such projects already rolled their own non-<code>&lt;stdint.h&gt;</code>-named fixed-size integer types; switching would be a hassle.  And not all compilers shipped <code>&lt;stdint.h&gt;</code>: Visual Studio didn&#8217;t have it until 2010!  (ಠ_ಠ)  Projects implementing their own <code>&lt;stdint.h&gt;</code>-compatible types posed another problem, because different projects&#8217; implementations might be incompatible.</p>
<p>New projects fare better, but not always.  Sometimes their dependence on old projects anchors them to the old, pre-<code>&lt;stdint.h&gt;</code> world.</p>
<h2>Fixed-size integer types in Mozilla</h2>
<p>Mozilla sits squarely in the old-project category, facing every rationale noted above for using its own types.  These have long been <abbr title="Netscape Portable Runtime">NSPR</abbr>&#8216;s <code>PR{Ui,I}nt{8,16,32,64}</code> and SpiderMonkey&#8217;s <code>{u,}int{8,16,32,64}</code> types.  But recently the landscape has changed.</p>
<p>As Mozilla has imported more external code, fixed-size integer types have proliferated.  Most imported code uses <code>&lt;stdint.h&gt;</code>, with fallback <code>typedef</code>s for Visual Studio; some code (<abbr title="Inter-process communication">IPC</abbr> code from Chromium) defines and uses <code>{u,}int{8,16,32,64}</code>.  As type definitions have proliferated, surprising problems have arisen.</p>
<h2>The woes of multiplicity</h2>
<p><code>#include</code>-order issues are the simplest problem.  For example, the IPC <code>uint32</code>-style definitions are incompatible with SpiderMonkey&#8217;s definitions with some compilers.  <code>#include</code> IPC and SpiderMonkey headers in the wrong order, and the compiler will error on incompatible <code>typedef</code>s.  This problem is easy to diagnose but harder to resolve, and sometimes it causes considerable pain.  Mass refactorings that add <code>#include</code>s have fallen afoul of this, with the least bad solution usually being to fix the first error, recompile, and repeat until done (twenty-odd times <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=693469#c13">in one instance</a>).</p>
<p>Worse than <code>#include</code> mis-ordering and conflict are linking problems.  <code>int</code> and <code>long</code> <a href="http://msdn.microsoft.com/en-us/library/s3f49ktz%28v=VS.80%29.aspx">could</a> be 32-bit integers yet <a href="http://www.kegel.com/mangle.html#types">appear different when linked</a>.  Suppose a method taking an <code>int32</code> argument defined <code>int32 = int</code> during compilation, but a user of it saw <code>int32 = long</code> during compilation.  Each alone would compile.  But beneath <code>typedef</code>s they&#8217;d be incompatible and wouldn&#8217;t link.</p>
<p>As we&#8217;ve imported more code in Mozilla, more and more developers have been bitten by these problems.  We&#8217;ve reached a breaking point.  We could use <code>PRUint32</code>, <code>JSUint32</code>, and other types which never trample upon each other.  Yet no one likes them given the standardized types, and it&#8217;s not possible to change &#8220;upstream&#8221; code to such a scheme.  Thus a second solution: use <code>&lt;stdint.h&gt;</code> definitions for everything.</p>
<h2>Switching to <code>&lt;stdint.h&gt;</code></h2>
<p>Using the <code>&lt;stdint.h&gt;</code> types in Mozilla code is now as simple as <del><code>#include "mozilla/StdInt.h"</code></del><ins><code>#include "mozilla/StandardInteger.h"</code></ins>.  <del><code>mozilla/StdInt.h</code></del><ins><code>mozilla/StandardInteger.h</code></ins> implements the <code>&lt;stdint.h&gt;</code> interface even in the edge cases: for compilers not supporting it, and for embedders who can&#8217;t use the regular definitions.  It works as follows:</p>
<ol>
<li>If the preprocessor definition <code>MOZ_CUSTOM_STDINT_H</code> is defined, then <code>#include MOZ_CUSTOM_STDINT_H</code>.  Embedders who can&#8217;t use the default definitions should use this to adapt.  (<code>MOZ_CUSTOM_STDINT_H</code> may also be passed into the Mozilla build system using an environment variable.  Note that while the preprocessor definition must be a quoted path, the environment variable must be an unquoted path.)</li>
<li>Otherwise, if the compiler doesn&#8217;t provide <code>&lt;stdint.h&gt;</code>, use a custom implementation.  This is currently limited to Visual Studio prior to 2010, using an implementation imported from <a href="https://code.google.com/p/msinttypes/source/browse/trunk/stdint.h">msinttypes</a> on Google Code.</li>
<li>Otherwise use <code>&lt;stdint.h&gt;</code>.</li>
</ol>
<p>We&#8217;re only providing these types now, but shortly we&#8217;ll start switching code using non-<code>&lt;stdint.h&gt;</code> fixed-size integer types to use them.  Adding <del><code>mozilla/StdInt.h</code></del><ins><code>mozilla/StandardInteger.h</code></ins> is merely the first step toward removing the other fixed-size integer types (except when they&#8217;re necessary to interact with external libraries).</p>
<h2>Conclusion</h2>
<p>It&#8217;s been a dozen years since <code>&lt;stdint.h&gt;</code> was standardized.  Now it finally comes to Mozilla.  Let&#8217;s lower a barrier to hackability in Mozilla and start using it.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/12/08/party-like-its-1999-stdint-h-comes-to-mozilla/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Introducing MOZ_FINAL: prevent inheriting from a class, or prevent overriding a virtual function</title>
		<link>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/</link>
		<comments>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 17:17:39 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[final]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_final]]></category>
		<category><![CDATA[sealed]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3533</guid>
		<description><![CDATA[The inexorable march of progress continues in the Mozilla Framework Based on Templates with the addition of MOZ_FINAL, through which you can limit various forms of inheritance in C++. Traditional C++ inheritance mostly can&#8217;t be controlled In C++98 any class can be inherited. (An extremely obscure pattern will prevent this, but it has down sides.) [...]]]></description>
			<content:encoded><![CDATA[<p>The inexorable march of progress continues in the Mozilla Framework Based on Templates with the addition of <code>MOZ_FINAL</code>, through which you can limit various forms of inheritance in C++.</p>
<h2>Traditional C++ inheritance mostly can&#8217;t be controlled</h2>
<p>In C++98 any class can be inherited.  (An extremely obscure pattern will prevent this, but it has down sides.)  Sometimes this makes sense: it&#8217;s natural to subclass an abstract <code>List</code> class as <code>LinkedList</code>, or <code>LinkedList</code> as <code>CircularLinkedList</code>.  But sometimes this doesn&#8217;t make sense.  <code>StringBuilder</code> certainly could inherit from <code>Vector&lt;char&gt;</code>, but doing so might expose many <code>Vector</code> methods that don&#8217;t belong in the <code>StringBuilder</code> concept.  It would be more sensible for <code>StringBuilder</code> to contain a private <code>Vector&lt;char&gt;</code> which <code>StringBuilder</code> member methods manipulated.  Preventing <code>Vector</code> from being used as a base class would be one way (not necessarily the best one) to avoid this conceptual error.  But C++98 doesn&#8217;t let you easily do that.</p>
<p>Even when inheritance is desired, sometimes you don&#8217;t want completely-virtual methods.  Sometimes you&#8217;d like a class to implement a virtual method (virtual perhaps because <em>its</em> base declared it so) which derived classes can&#8217;t override.  Perhaps you want to rely on that method being implemented only by your base class, or perhaps you want it &#8220;fixed&#8221; as an optimization.  Again in C++98, you can&#8217;t do this: public virtual functions are overridable.</p>
<h2>C++11&#8242;s contextual <code>final</code> keyword</h2>
<p>C++11 introduces a contextual <code>final</code> keyword for these purposes.  To prevent a class from being inheritable, add <code>final</code> to its definition just after the class name (the class can&#8217;t be unnamed).</p>
<pre class="code" data-language="c++">
struct Base1 final
{
  virtual void foo();
};

// ERROR: can't inherit from B.
struct Derived1 : public Base1 { };

struct Base2 { };

// Derived classes can be final too.
struct Derived2 final : public Base2 { };
</pre>
<p>Similarly, a virtual member function can be marked as not overridable by placing the contextual <code>final</code> keyword at the end of its declaration, before a terminating semicolon, body, or <code>= 0</code>.</p>
<pre class="code" data-language="c++">
struct Base
{
  virtual void foo() final;
};

struct Derived : public Base
{
  // ERROR: Base::foo was final.
  virtual void foo() { }
};
</pre>
<h2>Introducing <code>MOZ_FINAL</code></h2>
<p><abbr title="Mozilla Framework Based on Templates">mfbt</abbr> now includes support for marking classes and virtual member functions as final using the <code>MOZ_FINAL</code> macro in <code>mozilla/Attributes.h</code>.  Simply place it in the same position as <code>final</code> would occur in the C++11 syntax:</p>
<pre class="code" data-language="c++">
#include "mozilla/Attributes.h"

class Base
{
  public:
    virtual void foo();
};

class Derived final : public Base
{
  public:
    /*
     * MOZ_FINAL and MOZ_OVERRIDE are composable; as a matter of
     * style, they should appear in the order MOZ_FINAL MOZ_OVERRIDE,
     * not the other way around.
     */
    virtual void foo() MOZ_FINAL MOZ_OVERRIDE { }
    virtual void bar() MOZ_FINAL;
    virtual void baz() MOZ_FINAL = 0;
};
</pre>
<p><code>MOZ_FINAL</code> expands to the C++11 syntax or its compiler-specific equivalent whenever possible, turning violations of <code>final</code> semantics into compile-time errors.  The same compilers that usefully expand <a href="http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/"><code>MOZ_OVERRIDE</code></a> also usefully expand <code>MOZ_FINAL</code>, so misuse will be quickly noted.</p>
<p>One interesting use for <code>MOZ_FINAL</code> is to tell the compiler that one worrisome C++ trick sometimes isn&#8217;t.  This is the <em>virtual-methods-without-virtual-destructor</em> trick.  It&#8217;s used when a class must have virtual functions, but code doesn&#8217;t want to pay the price of destruction having virtual-call overhead.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual void method() { }
    ~Base() { }
};

void destroy(Base* b)
{
  delete b; // may cause a warning
}
</pre>
<p>Some compilers warn when they instantiate a class with virtual methods but without a virtual destructor.  Other compilers only emit this warning when a pointer to a class instance is <code>delete</code>d.  The reason is that in C++, behavior is undefined if the static type of the instance being deleted isn&#8217;t the same as its runtime type <em>and</em> its destructor isn&#8217;t virtual.  In other words, if <code>~Base()</code> is non-virtual, <code>destroy(new Base)</code> is perfectly fine, but <code>destroy(new DerivedFromBase)</code> is not.  The warning makes sense if destruction might miss a base class &mdash; but if the class is marked <code>final</code>, it never will!  Clang silences its warning if the class is <code>final</code>, and I hope that <a href="https://connect.microsoft.com/VisualStudio/feedback/details/707497/msvc-should-not-emit-the-optional-warning-c4265-virtual-functions-non-virtual-destructor-for-a-class-marked-as-sealed">MSVC will shortly do the same</a>.</p>
<h2>What about <code>NS_FINAL_CLASS</code>?</h2>
<p>As with <code>MOZ_OVERRIDE</code> we had a gunky <abbr title="Cross-platform component-object model">XPCOM</abbr> static-analysis <code>NS_FINAL_CLASS</code> macro for final classes.  (We had no equivalent for final methods.)  <code>NS_FINAL_CLASS</code> too was misplaced as far as C++11 syntax was concerned, and it too has been deprecated.  Almost all uses of <code>NS_FINAL_CLASS</code> have now been removed (the one remaining use I&#8217;ve left for the moment due to an apparent Clang bug I haven&#8217;t tracked down yet), and it shouldn&#8217;t be used.</p>
<p>(Side note: In replacing <code>NS_FINAL_CLASS</code> with <code>MOZ_FINAL</code>, I discovered that some of the existing annotations have been buggy for months!  Clearly no one&#8217;s done static analysis builds in awhile.  The moral of the story: compiler static analyses that happen for every single build are vastly superior to user static analyses that happen only in special builds.)</p>
<h2>Summary</h2>
<p>If you don&#8217;t want a class to be inheritable, add <code>MOZ_FINAL</code> to its definition after the class name.  If you don&#8217;t want a virtual member function to be overridden in derived classes, add <code>MOZ_FINAL</code> at the end of its declaration.  Some compilers will then enforce your wishes, and you can rely on these requirements rather than hope for the best.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/26/introducing-moz_final-prevent-inheriting-from-a-class-or-prevent-overriding-a-virtual-function/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Introducing MOZ_OVERRIDE to annotate virtual functions which override base-class virtual functions</title>
		<link>http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/</link>
		<comments>http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 17:55:41 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[help wanted]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_override]]></category>
		<category><![CDATA[override]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3515</guid>
		<description><![CDATA[Overriding inherited virtual functions One way C++ supports code reuse is through inheritance. One base class implements common functionality. Then other classes inherit from it, essentially copying functionality from it. These other classes can add their own new functionality, or, more powerfully, they can override the base class functionality. class Base { public: virtual const [...]]]></description>
			<content:encoded><![CDATA[<h2>Overriding inherited virtual functions</h2>
<p>One way C++ supports code reuse is through inheritance.  One base class implements common functionality.  Then other classes <dfn>inherit</dfn> from it, essentially copying functionality from it.  These other classes can add their own new functionality, or, more powerfully, they can override the base class functionality.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual const char* type() { return "Base"; }
};
class Derived : public Base
{
  public:
    virtual const char* type() { return "Derived"; }
};
</pre>
<p>Overriding base class functionality is simple.  Keeping such overrides working correctly is sometimes harder.  The problem is that the override relationship is implicit: if the override doesn&#8217;t exactly match the signature of the desired function in the base class, it may not work correctly.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    // Perhaps as part of an incomplete refactoring,
    // the base class's function changed its name.
    virtual const char* kind() { return "Base"; }
};
class DerivedIncorrectly : public Base
{
  public:
    virtual const char* type() { return "Derived"; }
};

// BAD: code expecting kind() to work and sometimes
// indicate Derived-ness no longer will.
</pre>
<h2>Making the override relationship explicit</h2>
<p>Some languages (Scala, C#, probably others) provide the ability to mark a derived class&#8217;s function as an override of an inherited function.  C++98 included no such ability, but C++11 does, through the contextual <code>override</code> keyword.  When <code>override</code> is used, that virtual member function must override one found on a base class.  If it does not, it is a compile error.</p>
<pre class="code" data-language="c++">
class Base
{
  public:
    virtual const char* kind() { return "Base"; }
};
class DerivedIncorrectly : public Base
{
  public:
    // This will cause a compile error: there's no type()
    // method on Base that this overrides.
    virtual const char* type() override { return "Derived"; }

    // This will work as intended.
    virtual const char* kind() override { return "Derived"; }
};
</pre>
<h2>Introducing <code>MOZ_OVERRIDE</code></h2>
<p>The Mozilla Framework Based on Templates now includes support for the C++11 contextual <code>override</code> keyword, encapsulated in the <code>MOZ_OVERRIDE</code> macro in <del><code>mozilla/Types.h</code></del><ins><code>mozilla/Attributes.h</code></ins>.  Simply place it at the end of the declaration of the relevant method, before any <code>= 0</code> or method body, like so:</p>
<pre class="code" data-language="c++">
<del>#include "mozilla/Types.h"</del> // MOZ_OVERRIDE has since moved...
<ins>#include "mozilla/Attributes.h"</ins> // ...to here

class Base
{
  public:
    virtual void f() = 0;
};
class Derived1 : public Base
{
  public:
    virtual void f() MOZ_OVERRIDE;
};
class Derived2 : public Base
{
  public:
    virtual void f() MOZ_OVERRIDE = 0;
};
class Derived3 : public Base
{
  public:
    virtual void f() MOZ_OVERRIDE { }
};
</pre>
<p><code>MOZ_OVERRIDE</code> will expand to use the C++11 construct in compilers which support it.  Thus in such compilers misuse of <code>MOZ_OVERRIDE</code> is an error.  Even better, some of the compilers used by tinderbox support <code>override</code>, so in many cases tinderbox will detect misuse.  (Specifically, <abbr title="Microsoft Visual C++ 2005">MSVC++ 2005</abbr> and later support it, so errors in cross-platform and Windows code won&#8217;t pass tinderbox .  Much more recent versions of <abbr title="GNU Compiler Collection">GCC</abbr> and Clang support it as well, but these versions are too new for tinderbox to have picked them up yet &mdash; in the case of GCC too new to even have been released yet.  <img src='http://whereswalden.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  )</p>
<h2>What about <code>NS_OVERRIDE</code>?</h2>
<p>It turns out there&#8217;s already a macro annotation to indicate an override relationship: <code>NS_OVERRIDE</code>.  This gunky <abbr title="Cross-platform component object model">XPCOM</abbr> macro expands to a user attribute under gcc-like compilers.  It&#8217;s only used by static analysis right now, so its value is limited.  Unfortunately its position is different &mdash; necessarily so, because in the C++11 <code>override</code> position it would attach to the return value of the method:</p>
<pre class="code" data-language="c++">
class OldAndBustedDerived : public Base
{
  public:
    NS_OVERRIDE virtual void f(); // annotates the method
    __attribute__(...) virtual void g(); // its expansion
};
class Derived2 : public Base
{
  public:
    // But in the MOZ_OVERRIDE position, it would annotate
    // f()'s return value.
    virtual void f() __attribute__(...);
};
</pre>
<p><code>NS_OVERRIDE</code> is now deprecated and should be replaced with <code>MOZ_OVERRIDE</code>.  With a little work, static analysis with new-enough compilers can likely look for <code>MOZ_OVERRIDE</code> just as easily as for <code>NS_OVERRIDE</code>.  And since <code>MOZ_OVERRIDE</code> works in non-static analysis builds, it&#8217;s arguably better in the majority of cases anyway.  If you&#8217;re looking for an easy way to improve Mozilla code, changing <code>NS_OVERRIDE</code> uses to use <code>MOZ_OVERRIDE</code> would be a simple way to help.</p>
<h2>Summary</h2>
<p>If you&#8217;ve overridden an inherited virtual member function and you&#8217;re worried that that override might silently break at some point, annotate your override with <code>MOZ_OVERRIDE</code>.  This will cause some compilers to enforce an override relationship, making it much less likely that your intended relationship will break.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/16/introducing-moz_override-to-annotate-virtual-functions-which-override-base-class-virtual-functions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Introducing MOZ_DELETE, a macro improving upon the deliberately-unimplemented method idiom</title>
		<link>http://whereswalden.com/2011/11/09/introducing-moz_delete-a-macro-improving-upon-the-deliberately-unimplemented-method-idiom/</link>
		<comments>http://whereswalden.com/2011/11/09/introducing-moz_delete-a-macro-improving-upon-the-deliberately-unimplemented-method-idiom/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 22:12:33 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[c++98]]></category>
		<category><![CDATA[copy constructor]]></category>
		<category><![CDATA[default assignment]]></category>
		<category><![CDATA[help wanted]]></category>
		<category><![CDATA[mfbt]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[moz_delete]]></category>

		<guid isPermaLink="false">http://whereswalden.com/?p=3487</guid>
		<description><![CDATA[C++ default operators and the sole-ownership idiom Often a C++ class will solely manage some value: for example, a GtkWindow* or a void* for malloc&#8216;d memory. The class will then release ownership in its destructor as appropriate. It would be extremely problematic to release ownership multiple times &#8212; think security-vulnerability-problematic. C++ copy construction and default [...]]]></description>
			<content:encoded><![CDATA[<h2>C++ default operators and the sole-ownership idiom</h2>
<p>Often a C++ class will solely manage some value: for example, a <code>GtkWindow*</code> or a <code>void*</code> for <code>malloc</code>&#8216;d memory.  The class will then release ownership in its destructor as appropriate.  It would be extremely problematic to release ownership multiple times &mdash; think security-vulnerability-problematic.  C++ copy construction and default assignment exacerbate this issue, because C++ automatically generates these methods for all classes, even when the default behavior breaks sole-ownership.  The C++98 idiom solving this is to privately declare a copy constructor and a default assignment operator, then never define them:</p>
<pre class="code" data-language="c++">
struct Struct
{
  private:
    Struct(const Struct&amp; other);
    void operator=(const Struct&amp; other);
};
</pre>
<p>Declaring the methods privately prevents any code but friends of <code>Struct</code> from calling them.  And by never defining them, even such friends will cause a link-time error if they try.</p>
<h2>Disabling the default operators in C++11</h2>
<p>Once you&#8217;re familiar with this idiom it&#8217;s not too bad.  But initially, it&#8217;s pretty unclear.  And nothing prevents someone from actually defining these methods.  (They could only be used by <code>Struct</code> or friends of <code>Struct</code>, to be sure, but for sufficiently complex code it&#8217;s possible someone might make a mistake.)  C++11 improves upon this trick by introducing deleted function syntax:</p>
<pre class="code" data-language="c++">
struct Struct
{
  private: // no longer necessary, but doesn't hurt
    Struct(const Struct&amp; other) = delete;
    void operator=(const Struct&amp; other) = delete;
};
</pre>
<p>Deleted functions are effectively removed from name lookup: using, defining, or referring to a deleted function produces a compile error &mdash; far better than a link error or, even worse, no error at all.</p>
<h2><code>= delete</code> support in <abbr title="Mozilla Framework Based on Templates">mfbt</abbr></h2>
<p>The Mozilla Framework Based on Templates now includes support for declaring a function only to prevent its use (or use of an inherited version).  The <code>MOZ_DELETE</code> macro encapsulates this support:</p>
<pre class="code" data-language="c++">
<del>#include "mozilla/Types.h"</del> // MOZ_DELETE has since moved...
<ins>#include "mozilla/Attributes.h"</ins> // ...to here

struct Struct
{
  private:
    Struct(const Struct&amp; other) MOZ_DELETE;
    void operator=(const Struct&amp; other) MOZ_DELETE;
};
</pre>
<p><code>MOZ_DELETE</code> isn&#8217;t as readable or understandable as <code>= delete</code>, but it&#8217;s searchable, and <a href="http://hg.mozilla.org/integration/mozilla-inbound/file/b5373c0d5a88/mfbt/Types.h#l93">the comment next to its definition</a> will clarify matters.  If the declarations are private, <code>MOZ_DELETE</code> is just as good as the traditional idiom, and in compilers supporting C++11 deleted functions it&#8217;s better.</p>
<p>Which compilers support C++11 deleted functions?  I&#8217;m aware of <abbr title="GNU Compiler Collection">GCC</abbr> <a href="http://gcc.gnu.org/projects/cxx0x.html">since 4.4</a>, Clang <a href="http://clang.llvm.org/cxx_status.html">since 2.9</a>, and <abbr title="Intel C/C++ Compiler">ICC</abbr> <a href="http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler/">since 12.0</a>.  Rightly, if unfortunately, you must specify <code>-std=c++0x</code> or similar to use deleted function syntax without causing a warning.  For various reasons Mozilla can&#8217;t do that yet, so <code>MOZ_DELETE</code> only produces the C++11 syntax when compiling with Clang (where we can pass <code>-Wno-c++0x-extensions</code> to disable the warning).  I&#8217;d love to see it use C++11 syntax in GCC and ICC as well, but I don&#8217;t have the time to solve the <code>-std=c++0x</code> problem now, or to figure out another workaround.  I&#8217;ve filed <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=701183">bug 701183</a> for this problem &mdash; help there is much appreciated.</p>
<h2>Summary</h2>
<p>Use <code>MOZ_DELETE</code> when declaring any method you will intentionally not implement.  It&#8217;ll work better, and produce better errors, in some compilers.  Those compilers don&#8217;t include GCC or ICC yet, but <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=701183">with your help</a> they could.  Any takers?</p>
<p><strong>Update</strong>, evening of November 10, 2011: I just landed further changes to make <code>MOZ_DELETE</code> use C++11 syntax with GCC when compiling with <code>-std=c++0x</code> (which we apparently do more often than I&#8217;d thought), so you should now get its goodness in GCC as well &mdash; most of the time.  In some &#8220;exotic&#8221; situations we don&#8217;t compile anything with <code>-std=c++0x</code>, so you won&#8217;t get any benefit there.  Also, the JavaScript engine is never compiled with it.  So if you want this to work fully, everywhere, you should use Clang.</p>
]]></content:encoded>
			<wfw:commentRss>http://whereswalden.com/2011/11/09/introducing-moz_delete-a-macro-improving-upon-the-deliberately-unimplemented-method-idiom/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

