21 April 2008

Left-leaning red-black trees are hard to implement

Back in 2002, I needed balanced trees for a project I was working on, so I used the description and pseudo-code in Introduction to Algorithms to implement red-black trees. I vaguely recall spending perhaps two days on implementation and testing. That implementation uses C preprocessor macros in order to make it possible to link data structures into one or more red-black trees without requiring container objects.

About the same time, Niels Provos added a similar implementation to OpenBSD, which was imported into FreeBSD, so when I imported jemalloc into FreeBSD, I switched from my own red-black tree implementation to the standard one. Unfortunately, both implementations use nodes that include four pieces of information: parent, left child, right child, and color (red or black). That typically adds up to 16 or 32 bytes on 32- and 64-bit systems, respectively. A few months ago I fixed some scalability issues Stuart Parmenter found in jemalloc by replacing linear searches with tree searches, but that meant adding more tree links. These trees now take up ~2% of all mapped memory, so I have been contemplating ways to reduce the overhead.

A couple of weeks ago, I came across some slides for a talk that Robert Sedgewick recently gave on left-leaning red-black trees. His slides pointedly disparage the use of parent pointers, and they also make left-leaning red-black trees look simple to implement. Left-leaning red-black trees maintain a logical 1:1 correspondence with 2-3-4 B-trees, which is a huge help in understanding seemingly complex tree transformations.

Last Monday, I started implementing left-leaning red-black trees, expecting to spend perhaps 15 hours on the project. I'm here more than 60 hours of work later to tell you that left-leaning red-black trees are hard to implement, and contrary to Sedgewick's claims, their implementation appears to require approximately the same amount of code and complexity as standard red-black trees. Part of the catch is that although standard red-black trees have additional cases to deal with due to 3-nodes that can lean left or right, left-leaning red-black trees have a universal asymmetry between the left and right versions of the algorithms.

If memory overhead weren't my primary concern for this project, I would have dropped red-black trees in favor of treaps. Unfortunately, treaps require either recursive implementation or parent pointers, and they also require an extra "priority" field, whereas red-black trees can be implemented without recursion or parent pointers, and it is possible to stuff the red-black bit in the least significant bit of one of the left/right pointers.

For the curious or those in need of such a beast, here is my left-leaning red-black tree implementation. One point of interest is that my benchmarks show it to be ~25% slower than my standard red-black tree implementation. The red-black bit twiddling overhead only accounts for about 1/5 of the slowdown. I attribute the other 4/5 to the overhead of transforming the tree on the down pass, rather than lazily fixing up tree structure violations afterward.

[26 April 2008] I did some further experimentation to understand the performance disparity between implementations. The benchmarks mentioned above were flawed, in that they always searched for the most recently inserted item. Since top-down insertion/deletion is more disruptive than lazy fixup, the searches significantly favored the old implementation. I fixed the benchmarks to compute the times for random searches, random insertions/deletions, and in-order tree traversal.

The old rb.h and sys/tree.h perform essentially the same for all operations. The new rb.h takes almost twice as long for insertion/deletion, is the same speed for searches, and is slightly faster for iteration. Red/black bit twiddling overhead accounts for ~6% of insertion/deletion time, and <3% of search time.

I am actually quite pleased with these benchmark results, because they show that for random inputs, left-leaning red-black trees do not noticeably suffer from the fact that tree height is O(3h) rather than O(2h), where h is the height of an equivalent fully balanced tree.

03 April 2008

Using Mercurial patch queues for daily development

I recently watched a video (slides) of Bryan O'Sullivan speaking about Mercurial. The presentation was mainly a (great) introduction to Mercurial, but I was surprised to learn that Mercurial patch queues could be useful even when using a repository that I have full commit access to. In a nutshell, Bryan described how he uses patch queues to checkpoint his work without cluttering the permanent revision history. Checkpointing is mainly useful to me when I am about to try a risky programming solution on top of reasonable code that only partially implements a feature. Historically, I have archived my entire sandbox at such critical points, but patch queues are a much cleaner solution; they make it possible to separate work into distinct patches and checkpoint regularly without performing heavyweight archiving operations. Note that reverting to an earlier state is much easier with patch queues, which makes failed experiments much less costly. This all sounds great, but it took me several hours and a lot of mistakes to actually figure out how to use patch queues in this fashion, so I'm recording the solution here with the hope that it will be useful to others.

The first step is to enable the mq extension (see Configuration directions), though it is enabled by default on my Ubuntu 7.10 systems, and in fact following the standard configuration directions blindly causes some strange warnings.

Following is a terse example of how to perform every operation that I find useful when using patch queues for daily development:
~> hg init pizza # Create repository.
~> cd pizza
~/pizza> echo "pepperoni" > ingredients
~/pizza> echo "black olives" >> ingredients
~/pizza> echo "hand-tossed" > crust
~/pizza> hg add ingredients crust
~/pizza> hg commit -m "Initial pizza recipe."
~/pizza> hg qinit # Initialize unversioned patch queue repository.
~/pizza> hg qnew more-ingredients.patch # Create new working patch.
~/pizza> echo "mushrooms" >> ingredients
~/pizza> hg qrefresh # Checkpoint before creating a new patch.
~/pizza> hg qnew specify-sauce.patch
~/pizza> hg qseries # Look at the patch queue.
more-ingredients.patch
specify-sauce.patch
~/pizza> hg qapplied # See which patches are applied.
more-ingredients.patch
specify-sauce.patch
~/pizza> echo "tomato" > sauce
~/pizza> hg add sauce
~/pizza> hg qrefresh
~/pizza> hg qpop # Pop patch, in order to work on more-ingredients.patch again.
Now at: more-ingredients.patch
~/pizza> hg qapplied
more-ingredients.patch
~/pizza> hg qunapplied
specify-sauce.patch
~/pizza> echo "green peppers" >> ingredients
~/pizza> hg diff
diff -r 4f3f2d833e6f ingredients
--- a/ingredients Thu Apr 03 15:38:01 2008 -0700
+++ b/ingredients Thu Apr 03 15:40:55 2008 -0700
@@ -1,3 +1,4 @@ pepperoni
pepperoni
black olives
mushrooms
+green peppers
~/pizza> hg qrefresh
~/pizza> hg qpush # Go back to specify-sauce.patch.
applying specify-sauce.patch
Now at: specify-sauce.patch
~/pizza> echo "marinara" > sauce
~/pizza> hg qdiff
diff -r aadd3ecd3c8e sauce
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/sauce Thu Apr 03 15:43:00 2008 -0700
@@ -0,0 +1,1 @@
+marinara
~/pizza> hg qrefresh
~/pizza> hg qpop
Now at: more-ingredients.patch
~/pizza> hg qrefresh -e # Edit commit message.
~/pizza> hg qpush
applying specify-sauce.patch
Now at: specify-sauce.patch
~/pizza> hg qrefresh -e
~/pizza> hg log
changeset: 2:6714598e1ccc
tag: qtip
tag: tip
tag: specify-sauce.patch
user: Jason Evans
date: Thu Apr 03 15:44:32 2008 -0700
summary: Specify which sauce to use.

changeset: 1:cc9c1fdf1038
tag: qbase
tag: more-ingredients.patch
user: Jason Evans
date: Thu Apr 03 15:44:01 2008 -0700
summary: Specify more ingredients.

changeset: 0:d3ee82132d36
tag: qparent
user: Jason Evans
date: Thu Apr 03 15:34:29 2008 -0700
summary: Initial pizza recipe.

~/pizza> hg qseries
more-ingredients.patch
specify-sauce.patch
~/pizza> hg qdelete -r more-ingredients.patch # Commit patch.
~/pizza> hg qdelete -r specify-sauce.patch
~/pizza> hg log
changeset: 2:6714598e1ccc
tag: tip
user: Jason Evans
date: Thu Apr 03 15:44:32 2008 -0700
summary: Specify which sauce to use.

changeset: 1:cc9c1fdf1038
user: Jason Evans
date: Thu Apr 03 15:44:01 2008 -0700
summary: Specify more ingredients.

changeset: 0:d3ee82132d36
user: Jason Evans
date: Thu Apr 03 15:34:29 2008 -0700
summary: Initial pizza recipe.

~/pizza> hg qnew modify-crust.patch
~/pizza> echo "deep dish" > crust
~/pizza> hg qrefresh
~/pizza> hg qnew experiment.patch
~/pizza> echo "pesto" > sauce
~/pizza> hg qrefresh
~/pizza> hg log
changeset: 4:173178d3d17d
tag: qtip
tag: tip
tag: experiment.patch
user: Jason Evans
date: Thu Apr 03 16:16:10 2008 -0700
summary: [mq]: experiment.patch

changeset: 3:4961f95336c5
tag: modify-crust.patch
tag: qbase
user: Jason Evans
date: Thu Apr 03 16:14:55 2008 -0700
summary: [mq]: modify-crust.patch

changeset: 2:6714598e1ccc
tag: qparent
user: Jason Evans
date: Thu Apr 03 15:44:32 2008 -0700
summary: Specify which sauce to use.

changeset: 1:cc9c1fdf1038
user: Jason Evans
date: Thu Apr 03 15:44:01 2008 -0700
summary: Specify more ingredients.

changeset: 0:d3ee82132d36
user: Jason Evans
date: Thu Apr 03 15:34:29 2008 -0700
summary: Initial pizza recipe.

~/pizza> hg qpop
Now at: modify-crust.patch
~/pizza> hg qdelete experiment.patch # Discard horrible experiment.
~/pizza> hg log
changeset: 3:4961f95336c5
tag: qtip
tag: tip
tag: modify-crust.patch
tag: qbase
user: Jason Evans
date: Thu Apr 03 16:14:55 2008 -0700
summary: [mq]: modify-crust.patch

changeset: 2:6714598e1ccc
tag: qparent
user: Jason Evans
date: Thu Apr 03 15:44:32 2008 -0700
summary: Specify which sauce to use.

changeset: 1:cc9c1fdf1038
user: Jason Evans
date: Thu Apr 03 15:44:01 2008 -0700
summary: Specify more ingredients.

changeset: 0:d3ee82132d36
user: Jason Evans
date: Thu Apr 03 15:34:29 2008 -0700
summary: Initial pizza recipe.

~/pizza> cat sauce
marinara
The trickiest parts of the above are committing/deleting with the qdelete command, and editing the commit message with qrefresh. I omitted the many ways of messing up the order of operations, so tread lightly and experiment with a toy repository before you use this mode of operation for real.

11 March 2008

Migrating from Subversion to Mercurial

jemalloc has settled into Firefox pretty nicely at this point, so after having mostly worked on Lyken for a few weeks while waiting for the dust to settle, I'm planning to start working on adding the necessary functionality to allow the Tamarin JavaScript engine to integrate without requiring a separately managed heap for garbage collection. One of the first things I ran into was that the Tamarin source code is available as a Mercurial repository, so it seemed like a good time to become familiar with yet another version control system (VCS).

Over the past ten years, there has been a proliferation of VCS's, especially those supporting distributed development models (Arch, darcs, BitKeeper, git, svk, Mercurial, Bazaar, etc.), but for some reason I've found it difficult to get excited about them. The biggest barrier for me has been perceived complexity, but that is perhaps attributable in part to lack of exposure. Well, I've been exposed to Mercurial now, and I really like it so far.

I've primarily been using Subversion for the past several years, and much to my surprise, Mercurial felt completely natural almost right away. In fact, it was immediately easier to deal with branching and merging than it has ever been for me with any other VCS. I have historically avoided branched development when at all possible, because it has been hard to make sure that the VCS was doing what I intended.

While Stuart and I were getting jemalloc working in Firefox, we were tossing patches back and forth constantly. I spent a total of ~2 days just dealing with patch merges, and changes were dropped on the floor on multiple occasions. It occurs to me now that I could have avoided the majority of this work if we had been using something like Mercurial. We wouldn't have lost changes, we wouldn't have had mystery failures due to subtle patch conflicts, and so on.

Mercurial is so cool that I spent almost two full days trying to migrate my Subversion repositories. In particular, I was initially trying to convert the Lyken repository, which consisted of 1023 revisions and perhaps 1000 files, with a couple of vendor code imports and one temporary branch (all pretty straightforward as repositories go). I tried all of the following:
  • hgsvn silently failed to commit 233 files, which made the resulting repository almost completely useless. I poked around in the code a bit and determined that fixing the problem myself would be a major undertaking.
  • yahg2svn could only handle 'trunk', 'branches', and 'tags' at the top level, and I had 'vendor' as well. I hacked on the code a bit and probably could have gotten it to work eventually, but I moved on in pursuit of easier solutions.
  • hg convert, which is an extension that comes with Mercurial, failed to do more than throw exceptions due to pickling failures.
  • Tailor mostly worked, though it was completely broken as installed on my Ubuntu/amd64 7.10 system, so I had to install it manually. It got confused by a handful of revisions, but it merely left them as unmerged branches, and the fallout was minimal.
I never did find a complete example of how to use Tailor to convert a Subversion repository to Mercurial format, so here's a bit more detail, in the hope that it will be of use to someone.

The command line I used was:
tailor -D -v -F "" --configfile lyken.tailor
The hard part though was coming up with the configuration file. Of course, the manual might have helped, had I found it before writing this blog post.
[DEFAULT]
verbose = True

[lyken]
target = hg:target
start-revision = INITIAL
root-directory = /home/jasone/tmp
state-file = tailor.state
source = svn:source
subdir = hg_lyken

[hg:target]

[svn:source]
module = /
repository = file:///home/jasone/tmp/svn_lyken
You can peruse the resulting repository to see what sorts of warts I had to clean up after the conversion. I have successfully converted several other repositories using the same method. The Onyx repository is giving Tailor a real workout though, since it consists of 3475 revisions and (this is the killer) due to how cvs2svn did things back when I switched to Subversion from CVS, there are 180 extant branches, 47 extant tags, and [gasp] 89087 extant files in the latest revision. It will probably take most of a day for Tailor to complete the conversion, and I can see in the log output that there are going to be a lot of problems in all the spontaneous branches cvs2svn generated.

26 January 2008

Perceived jemalloc memory footprint

For the past couple of months I have been working with the Mozilla folks to integrate jemalloc into Firefox. This past week, Stuart has been doing lots of performance testing to make sure jemalloc is actually an improvement, and he ran into an interesting problem on Windows: jemalloc appears to use more memory than the default allocator, because Windows' task manager reports mapped memory rather than actual working set. As near as we could tell, jemalloc was actually reducing the working set a bit, but the perception from looking at the task manager statistics was that jemalloc was a huge pessimization. This is because jemalloc manages memory in chunks, and leaves each chunk mapped until it is completely empty. Unfortunately, even though there is a way to tell Windows that unused pages can be discarded if memory becomes tight, appearances make it seem as if jemalloc is hogging memory. Well, appearances do matter, so I have been working frantically the past few days to come up with a solution. The upshot is that I may have ended up with a solution to related problems for jemalloc in FreeBSD, its native setting.

In FreeBSD, there is an optional runtime flag that tells malloc to call madvise(3) for pages that are still mapped, but for which the data are no longer needed. This would be great, but madvise() is quite expensive to call, which leaves us with little choice but to disable those calls by default. What that means is that when memory becomes tight and the kernel needs to free up some RAM, it has to swap out the junk in those pages, just as if the junk were critical data. The repercussions are system-wide, since pretty much every application has those madvise() calls disabled.

The solution is pretty straightforward: rather than calling madvise() as soon as pages of memory can be discarded, simply make a note that those pages are dirty. Then, if the amount of dirty discardable memory exceeds some threshold, march down through memory and call madvise() until the amount of dirty memory has been brought under control. This tends to vastly reduce the number of madvise() calls, but without ever leaving very much dirty memory laying around.

I still need to do a bunch of performance analysis before integrating this change into FreeBSD, but my expectation is that as an indirect result of trying to make jemalloc look good on Windows, FreeBSD is going to benefit.

28 November 2007

Firefox fragmentation?

As Firefox 3 nears release, some of its developers are taking a close look at memory fragmentation issues. There is good information over at pavlov.net that I won't repeat here. One recurring theme though is that memory usage in version 2 was reported by some users to be problematic, and fragmentation is a suspected culprit. This has motivated an investigation of memory fragmentation before version 3 is released.

As the author of jemalloc, I have a deep (read: obsessive) interest in memory fragmentation issues, so I spent some time brushing off my malloc plotting tools today. Here is a plot from a run of firefox 2.0.0.9 running on FreeBSD-current. In order to generate the allocation trace, I launched firefox, then went through several cycles of opening lots of tabs/windows and then closing most of them.
Time starts at the left, and execution ends at the right. Each vertical column of pixels represents a snapshot of memory usage at a particular moment during program execution (time is measured by allocation events). Since there are millions of allocation events, most snapshots are left out to make the plot size manageable. Similarly, there are many bytes of memory that must be represented by each vertical column of pixels, so each pixel represents a bucket of 256kB. Low addresses are at the bottom of the plot.

Note the peaks that are mostly green. Those occur during peak memory usage periods, and overall, the plot shows that fragmentation isn't bad. Take this with a grain of salt though, since the plot only represents perhaps 15 minutes of heavy web browsing.

If you want to see much more detail (each bucket is 4kB -- one page), take a look at this image. It is big enough to cause most image viewers to choke, so beware.

10 November 2007

Fixed-precision (n choose k) and overflow

I recently found myself needing to compute (n choose k) with 64-bit integers. Recall that (n choose k) is equal to n!/[k!(n-k)!]. Mathematically, this is not a difficult computation, but when considered in the context of integer overflow, the problem becomes much harder.

To illustrate the problem, consider the computation of (9 choose 4) using 8-bit signed integers. We can start off by doing some straightforward cancellation, which leaves us with [9*8*7*6]/[4*3*2]. Where do we go from here though? If we multiply all of the terms in the numerator first, we get an intermediate result of [3024]/[4*3*2], which clearly does not fit in the [-128..127] range. The method that we are taught on paper is to cancel factors until none are left in the denominator, then multiply the remaining factors in the numerator to get the answer. We can write a program that effectively does the same thing, but do we really have to create vectors of terms and duplicate the hand method?

I searched high and low for information about how best to implement (n choose k) with fixed precision integers, without success. While considering the mechanics of coding the hand method, I realized that computing greatest common divisors (GCDs) would be a critical component. I then began to wonder if there might be an iterative algorithm that does not require manipulating vectors of integers. Here is what I came up with. (n choose k) is [n*(n-1)*...*(n-k+1)] / [k*(k-1)*...*1]. Let us call the vectors of terms in the numerator and denominator [C] and [D], respectively, so (n choose k) is [C]/[D].
  1. If (k > n/2), set k <-- n-k. This does not change the result, but it reduces the computational overhead for later steps.
  2. Initialize accumulators A and B for the numerator and denominator of the result to 1, so that A/B is 1/1. Note that upon completion, B will always be 1, thus leaving the result in A, but during computation, B may be greater than 1.
  3. While possible without overflowing A (and while [C] is non-empty), repeatedly merge the first term of [C] (call it c) into A and remove the term from [C]. This is achieved via the following steps:
    1. Divide g <-- GCD(c, B).
    2. B <-- B/g and c <-- c/g. This removes common factors.
    3. A <-- A*c.
  4. While possible without overflowing B (and while [D] is non-empty), repeatedly merge the first term of [D] into B and remove the term from [D]. This is achieved using the same algorithm as for step 3.
  5. If no progress was made in steps 3 or 4, fail due to unavoidable overflow.
  6. If [C] or [D] is non-empty, go back to step 3.
Here is a reference implementation in C.

Since implementing the algorithm, I have been troubled by a seemingly simple question: does this algorithm ever fail even though the final result can be expressed without overflow? My intuition is that the algorithm always succeeds, but a proof has thus far eluded me. I have exhaustively tested the algorithm for 32-bit integers, and the algorithm never fails. Unfortunately, I really need to move on to other work, since the algorithm certainly works well enough for my needs.

09 July 2007

Tagged unboxed floating point numbers

Several modern programming language implementations employ a representation of object reference slots that is self-describing, in order to facilitate run-time type checks and automatic garbage collection. By reserving one or more bits to indicate the type of data stored within the slot, it is possible to differentiate a pointer (also known as a reference to a "boxed" object) from, say, an integer (also known as an "unboxed" integer).

Suppose that reference slots are 64-bits wide, and that 61 bits can be used to store an unboxed integer. Assuming signed integers, we can store an integer in [-2^60..2^60), but outside that range, we are forced to create a boxed integer object and store a reference to that object. This is in fact how Lyken implements integers (though it preserves 62 bits of accuracy for integers).

Now, suppose that we want to support double-precision floating point numbers. The fundamental approaches taken by every implementation I have found in the literature are to either 1) box all floating point numbers, or 2) to use a combination of boxed floating point numbers and untagged floating point numbers. As one might imagine, (1) can cause serious performance degradation for numerically intensive programs, due to the need to create new boxed objects to store the result of each floating point computation. As for (2), there are numerous papers that discuss various compilation strategies for finding opportunities to use untagged unboxed floating point numbers, but these techniques appear to to be limited to particular problem domains, since they mainly try to convert vectors of floating point numbers to be untagged and unboxed. Nowhere have I found any mention whatsoever of using tagged unboxed floating point numbers.

Let us consider the IEEE 754 floating point number format to see what challenges there are to tagged unboxed double-precision floating point numbers. (If you are unfamiliar with the format, I suggest taking a look at the Wikipedia page for an overview.) There are three fields: 1) sign, 2) exponent, and 3) fraction.

seeeeeee eeeeffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff

Suppose we were to steal 3 bits from the fraction field. In order to avoid losing precision, we would have to box all numbers that did not have a particular bit pattern for those 3 stolen bits, thus allowing us to unbox perhaps 12.5% of the time. This is not compelling.

What if we were to instead steal bits from the exponent? This is much more useful, because it allows us to accurately store all values except those with the most extreme exponent values. Of course, there are programs that actually need the full range of exponent values, but they are by no means the common case.

There are some details that make such unboxing more work than for integers:
  • The exponent must be re-biased.
  • It is harder to remove the exponent bits, since they are internal.
  • There are special values that require special handling (+-0.0, +-Inf, NaN).
Explaining the nuances in words is rather tedious, so actual code follows instead.
typedef union {
uint64_t u;
int64_t i;
double r;
} LktRealUnion;

void
LkRealNew(LktSlot *aReal, double aVal) {
LktRealUnion val;
val.r = aVal;

// Check whether +-0.0.
if (val.u & 0x7fffffffffffffffLLU) {
LktRealUnion unboxed;

// Re-bias the exponent by subtracting 896. This makes the useful
// exponent range for unboxed reals [-127..128].
unboxed.u = val.u - 0x3800000000000000LLU;
// Check that the most significant 3 exponent bits are 0.
if (unboxed.u & 0x7000000000000000LLU) {
if ((val.u & 0x7ff0000000000000LLU) == 0x7ff0000000000000LLU) {
// Special value (Inf or NaN).
uint64_t sign = (val.u & 0x8000000000000000LLU);
unboxed.u <<= 3;
unboxed.u &= 0x7fffffffffffffffLLU; // Clear sign bit.
unboxed.u |= sign;
unboxed.u |= 0x3; // Tag.
aReal->u.b = unboxed.u;
} else {
// Overflow; box.

// [...]
}
} else {
uint64_t sign = (val.u & 0x8000000000000000LLU);
unboxed.u <<= 3;
// Sign bit is already cleared as a result of exponent re-biasing.
unboxed.u |= sign;
unboxed.u |= 0x3; // Tag.
aReal->u.b = unboxed.u;
}
} else {
// +-0.0.
aReal->u.b = val.u | 0x3; // Tag.
}
}

double
LkRealGet(LktSlot *aReal) {
LktRealUnion val;

LkmAssert(LkSlotTypeGet(aReal) == LkRealType());

// Checked whether boxed.
val.u = aReal->u.b;
if ((val.u & 0x7) == 0x3) {
// Check whether +-0.0.
if (val.u & 0x7ffffffffffffff8LLU) {
val.i >>= 3; // Sign-extended shift preserves the sign bit.
val.u &= 0x8fffffffffffffffLLU; // Clear upper exponent bits.
// Check whether a special value (Inf or NaN).
if ((val.u & 0x0ff0000000000000LLU) != 0x0ff0000000000000LLU) {
// Re-bias the exponent by adding 896.
val.u += 0x3800000000000000LLU;
} else {
// Special value. Set all exponent bits.
val.u |= 0x7ff0000000000000LLU;
}
} else {
// +-0.0.
val.u &= 0x8000000000000000LLU;
}
return val.r;
} else {
// Boxed.
LktReal *r = (LktReal *) aReal->u.p;
return r->val;
}
}
As you can see, unboxed floating point numbers do incur some overhead, but for typical applications, they appear to me to be a big improvement over uniformly boxed floating point numbers.

19 June 2007

Unicode strings for Lyken

Lyken, a programming language I am currently developing, uses Unicode for all strings. Lyken is just one of many languages that has to overcome a set of design challenges associated with Unicode, though at least Lyken itself has no legacy support requirements. However, since Lyken's runtime library is written in C, I still have to devise a way to provide pure Unicode string support in Lyken, without making runtime library development overly cumbersome.

A couple of years ago I decided to use a simplistic internal representation for strings in Lyken. The idea was to maintain an ASCII representation of each string that was purely ASCII, but to also maintain a UCS-4 representation of every string (lazily created for pure ASCII strings). This had a critical problem though: C library interfaces use (char *) strings, thus making it impossible to use non-ASCII strings for many purposes. This problem made it clear that I needed to somehow support UTF-8 in Lyken's runtime library.

One possible approach would be to internally store each string both as UTF-8 and UCS-4, but that is a tremendous waste of memory both for ASCII and non-ASCII strings. Instead, I have decided to just store strings as UTF-8, but that has performance issues for indexed access.

In order to mitigate the indexed access performance issue for UTF-8, I store a lazily initialized table that records the location of every nth character (n=32 for now). Immutable strings make lazy table initialization safe for multi-threaded programs, with no need for synchronization. The table is only needed for non-ASCII strings and is known to be present just past the end of the string itself iff the string's byte/character lengths differ.

I have searched for information on better approaches to solving the indexed access problem for UTF-8 strings, but have found nothing. If you know of anything better, please let me know.

06 May 2007

Why the overwhelming silence?

I uploaded an updated version of the Parsing module. The changes are minor, which is a good indicator of the code's maturity when you consider that I continue to use it heavily to create new parsers. This is a really solid parser generator, yet the public reception has been overwhelming silence.

I can guess why this might be, but given the generally sad state of Python-based parser generator software, I expected that at least someone would find Parsing useful. I would really appreciate hearing from people who evaluate the software, why you decide not to use it, so that I can potentially do a better job of meeting the programming community's needs.

22 March 2007

A simple Parsing-based parser example

As requested by several people, I have uploaded a simple example parser that uses the Parsing module. It is pretty self explanatory, so I encourage you to take a look at it, run it, and experiment with changes.

That done, I should say a bit more about how I actually use the Parsing module. Well, the first thing I did with it was to write a parser for a parser generator input language similar to what Elkhound supports. The parser translates the input to two output files, Token.py and Ast.py, which contain code that the Parsing module can generate a parser from. Here are a few example productions from Lyken's grammar specification:
token comment=xclass:"comment" {
inline Init ${
self.val = raw
}$
}

fail pStmtList <{pExpr};
nonterm StmtList=[e] {
-> Stmt(Stmt, semicolon);
-> DelimitedExpr(DelimitedExpr) [pStmtList];

-> ExtendStmt(StmtList, Stmt, semicolon);
-> ExtendDelimitedExpr(StmtList, DelimitedExpr) [pStmtList];
}

nonterm Stmts {
-> Empty;
-> Stmt(Stmt);
-> StmtList(StmtList);
}

start Module=[S] {
-> Module(boi, DocStr, ModuleDecl, Version, InitialCBlock, Stmts);
}
There are numerous features not represented above, but the general idea should be apparent. Note that embedded code can be associated with productions. This allows me to do some pretty highly stylized code generation, yet still embed custom code where necessary.

One of the non-obvious clauses above is the "=[S]" that follows "start Module". This is extra annotation that says the Module production provides an outer lexical scope. By supporting such custom annotations, I am able to automatically generate code that deals with many aspects of semantic analysis. This is also one of the main reasons I haven't seen fit to release the grammar specification parser -- it is not obvious to me how to generalize such features in a way that everyone can benefit. At the moment I am of the opinion that the low level docstring-based interface to the Parsing module is good for small- to medium-size parsers, and that for large parsers, you need to write a custom translator that I can't hope to guess the needs of.