20 May 2006

Conversation

Me:  Math.floor(6530219459687219.0)
Mozilla:  6530219459687220
Me:  (sigh)

19 May 2006

Small, complete environments

If I were to design a programming language today, I wouldn't.

Instead, I would design a programming environment. The basic requirements would be something like this:

  • It's generally pleasant and productive. To me, this means the environment itself is small, simple, and fast.

  • It produces the kind of programs people like (featureful, unburdensome, fast enough, small enough, easy to use, and on time :)).

  • It interoperates. You can drop in external stuff (source code, binary libraries, editors, tools) and it'll work smoothly. And vice versa: you can drop your project into an existing environment that has lots of other stuff going on, and it'll work.

What would this environment look like? I'll know it when I see it. In the meantime, here are some thoughts. It would have:

  1. A language with these properties:

    1. I can compile it to a raw executable that doesn't require the end user to install a VM. The simplest deployment model is, end user drops a single executable file into a directory of his or her choosing. End of story. (Almost nobody attempts this these days, since it's hard to reconcile this with rich libraries, portability across hardware, and good high-level language features. But it can be done.)

    2. I can add a third-party library to my project just by dropping it into the appropriate place in the source tree. (The Java WAR deployment model gets this right.)

    3. It's easy to integrate with pieces written in other languages. (This is really hard to get right. Microsoft .NET interop comes closest, as far as I know.)

    4. Build dependencies are present in the source code. (I haven't thought much about this, but the build system needs it.)

    5. The ability to express basic metadata about a project in source code. If it's a program, as opposed to a shared library, the source code reflects that.

    6. ...And of course the various properties any good language should have, things like well-designed libraries, readable syntax, decent support for refactoring, stupid mistake checking, portability, similar behavior across operating systems and hardware architectures, debugability, and as few irritating features as possible. (Nobody has it all, but there are plenty of nice languages out there.)

  2. A build system with these properties:

    1. It ordinarily works without any makefiles. Dependencies are determined by looking at the source code. Things like linker options are determined by looking at the metadata, which is also in the source code.

    2. You can type something ridiculously simple, like "build foo", and it builds foo, including dependencies, relatively quickly.

    3. It can handle generated code.

  3. An installer system with these properties:

    1. Extremely basic, intentionally anemic compared to, say, MSI. Can't install e.g. registry keys. It only installs files; it's parameterizable. But it groks versions.

    2. You can type something ridiculously simple, like "build foo.msi", and it builds foo.msi. Creates an MSI file on Windows, an RPM on Linux, whatever.

    3. It's optional. You can always use the "simple deployment model" (see 1a.)

  4. A decent IDE and debugger that work well without project files. (Microsoft Visual C++ 2003 and later score high marks here.)

The language requirements alone are nowhere near being met, but of course you pick the language of your choice and work toward implementing the features that are missing.

Small, complete programming languages hold appeal for lots of people. It seems weird that I haven't seen a small, complete programming environment since vi+cc+make.

14 May 2006

Nixie tubes

Today I learned:

From the early 1950's to the 1970's Nixie tubes were the dominant display service.

They only display digits, and they look a little like neon signs and a little bit like the filament of a light bulb.

04 May 2006

Inform 7

Inform 7 looks fantastic. I wish I had time to play with it.

03 May 2006

Worksheets revisited

I'm convinced that worksheets have not just a place but a central place in IDEs.

Here's the idea. A worksheet is a document that contains code. It's not like Excel: the code is visible all the time. But like Excel, it's "live": it runs the code as needed and displays the results right there on the page. If you edit some code, the worksheet automatically recompiles it and recalculates any affected results throughout the sheet.

The worksheet runs in a sandbox. It has access to useful testing resources—read access to other files in the same project, write access to a temp directory, and so on—but nothing much else.

Unlike a source file, the code in a worksheet doesn't have to be complete classes. Just a statement or an expression is enough. If you type an expression, the worksheet automatically shows you the result. If it's an object, it's displayed as some kind of nicely expandable, inspectable GUI widget. It's integrated with the debugger, of course.

It's also integrated with a word processor, so you can mix text and pictures with your code. None of this is meant to replace traditional source code; you'll have worksheets in your project alongside source files.

I don't know of any existing IDEs that have anything like this. But it sounds ideal for proof-of-concept demonstrations, API documentation, teaching, and testing.

My next side project is going into this territory. I'm kind of excited about it.

tewald

I met tewald via La Leche League.

Tim has the following interesting properties:

  • once worked on MSDN, at the software architect level, I think
  • would be named time if he followed the old-school Microsoft convention of full first name followed by last initial
  • has drunk more gallon jugs of the XML Kool-Aid than anyone else I know
  • has tons of Lego trains in a box somewhere, waiting for his toddler's third birthday so it'll be safe to take them out.

Great guy to have a beer with and talk programming languages, something I hope to do in the not-too-distant future.

02 May 2006

To do

  • Write an article, "What do objects do all day?", talking about the various roles classes play in a program. Some classes are, in no particular order, (a) collections of data, all public except for details of memory management and such: ArrayList, BigDecimal, Point, AffineTransform, org.w3c.dom.Document, and I guess String; (b) handles to software entities that live in the kernel or out of process: Socket, Process, java.sql.Connection; (c) data sources and sinks: ResultSet, OutputStream, Iterator; (d) event handlers—these don't model anything at all, you just use them to hook into other objects; (e) representations of some random programming language concept that the language doesn't have special syntactic support for, like a logic variable, a closure, or a future; (f) models of real-world "things" in the problem domain.

    I'm interested in this because I'm interested in what code means. I think having a clear idea of what you mean gets your job done faster, leads to more readable code and a more flexible design, and reduces bugs.

    The few object-oriented textbooks I remember at all focused their abstract discussion of “what objects mean” entirely on (f). It was as though the authors didn't really think about the question. But I suspect (without substantiation) that different techniques—and different programming language features—matter in different cases.

  • Find out if anyone does studies of questions like these: How many arguments does a method take, on average? (You get different answers if you count method declarations, method calls in source code, method calls at runtime.) What proportion of method calls take any complex arguments (I mean, arguments that can't be represented losslessly as smallish strings)? What proportion of methods simply delegate their job to some other object? What kind of changes do people make to existing code? Are there trends in these numbers over time?

20 April 2006

JavaScript speed test

After fiddling around with several JavaScript performance thingies online, I finally caved in and wrote my own.

14 April 2006

Miscellany

I'm searching for a way to ask the Visual Studio debugger to attach and break as soon as a given process starts. I don't care which version of Visual Studio, or if I have to attach to the parent process first, or how much scripting I have to do, as long as it's possible to get to a point where I can do this conveniently. For the world's most complicated debugger, this seems like a really obvious feature, but I can't find it.

Update: No luck yet, but I'm slightly warmer. VS.NET has macros; the EnvDTE namespace provides a tiny amount of programmatic access to the debugger; VS2005 allows you to set breakpoints in DLLs that are not loaded.

Firefox has a menu option, View → Page Style → No Style, that is perfect for pages like this one.

My side project is going well. Some 300 tests are passing. I need to pause a moment and figure out specifically what to do next. There are a lot of little things I'm eager to work on.

For one thing, it's slow. I've been using the Venkman JavaScript debugger to find the worst bits. It actually has a usable profiler. Fanstastic.

I have never (in maybe 6 tries) succeeded in getting any version of the Visual Studio debugger to work with a symbol server. The error messages are totally useless.

12 April 2006

Generator syntax for state machines

I have a real-world interface that looks like this:

interface ITableScanner {
    void open(Path filename);
    void onRecord(TableRecord record);
    void onEndOfFile(int status, Exception error);
    void close();
}

It's actually a state machine. The methods are only to be called in a very specific order: open(), then zero or more calls to onRecord(), then onEndOfFile(), then close().

Here's the simplest nontrivial implementation of this interface I can come up with:

class DebugTableScanner implements ITableScanner {
    public DebugTableScanner(Writer out) {
        m_out = out;
    }

    public void open(Path filename) {
        m_out.writeln("contents of file " + filename);
    }

    public void onRecord(TableRecord record) {
        if (!isNoise(record))
            m_out.writeln("  - " + record);
    }

    public void onEndOfFile(int status, Exception error) {
        if (status != OK)
            m_out.writeln("  * End of file status: " + status);
        if (error != null)
            error.printStackTrace(m_out);
    }

    public void close() {
    }

    private Writer m_out;
}

I'm going to propose a different syntax for writing that class. Just as you can use generator syntax instead of explicitly writing an Iterator class, you could use this special syntax instead of explicitly implementing any state machine interface.

The special syntax is receive methodName(parameters). It means roughly “yield, then resume here when the appropriate method call is received”. But if this syntax occurs in an if or while test-expression, it also means “skip to the next resume statement if a different method is called instead”. Informal, I know, but I think formal semantics would be easy to hash out.

The above class, implemented using this syntax, looks like this:

ITableScanner debugTableScanner(Writer out) {
    receive open(Path filename) {
        out.writeln("contents of file " + filename);
    }

    while (receive onRecord(TableRecord record)) {
        if (!isNoise(record))
            out.writeln("  - " + record);
    }

    receive onEndOfFile(int status, Exception error) {
        if (status != OK)
            out.writeln("  * End of file status: " + status);
        if (error != null)
            error.printStackTrace(out);
    }

    receive close();
}

You would call debugTableScanner(myOut) instead of new DebugTableScanner(myOut) to create an instance.

Nice things about this:

  • The code appears in the same order that it'll execute at run time.
  • The code and its caller look the same. You could put the code side by side and see the method calls and receive statements line up.
  • No need to explicitly check the object state and throw IllegalStateException (or whatever) if stuff hasn't been called in the right order; the compiler can generate the checks.
  • You could create variables anywhere in the body, and they'll be accessible only to methods called later.
  • Similarly, there's no need to stick the Writer into a member variable. It's lexically scoped. (Yeah, lexical scoping is frequently the highlight of my day...)

Here's a funny real-world example of why my proposed syntax is nice. I had to modify the real-world version of this example to cope with errors. Here's what I ended up with:

class DebugTableScanner implements ITableScanner {
    public DebugTableScanner(Writer out) {
        m_out = out;
    }

    public void open(Path filename) {
        m_out.writeln("contents of file " + filename);
    }

    public void onRecord(TableRecord record) {
        try {
            if (!isNoise(record))
                m_out.writeln("  - " + record);
        } catch (Exception exc) {
            onError(exc);
            throw;
        }
    }

    public void onEndOfFile(int status, Exception error) {
        try {
            if (status != OK)
                m_out.writeln("  * End of file status: " + status);
            if (error != null)
                error.printStackTrace(m_out);
        } catch (Exception exc) {
            onError(exc);
            throw;
        }
    }

    public void close() {
    }

    private void onError(Exception exc) {
        reportError(
            new Exception(INTERNAL_ERROR_IN_SCANNER, exc));
    }

    private Writer m_out;
}

...and actually considerably worse, since I had code in close() which also had to be wrapped. In my proposed syntax, it would look like this, instead:

ITableScanner debugTableScanner(Writer out) {
    receive open(Path filename) {
        out.writeln("contents of file " + filename);
    }

    try {
        while (receive onRecord(TableRecord record)) {
            if (!isNoise(record))
                out.writeln("  - " + record);
        }

        receive onEndOfFile(int status, Exception error) {
            if (status != OK)
                out.writeln("  * End of file status: " + status);
            if (error != null)
                error.printStackTrace(out);
        }

        receive close();
    } catch (Exception exc) {
        reportError(
            new Exception(INTERNAL_ERROR_IN_SCANNER, exc));
        throw;
    }
}

11 April 2006

Worksheet IDEs

I've always liked using worksheet-style programs. Excel is the best-known one, but Mathcad is what I'm really talking about. They're document-oriented, yet interactive. The emphasis is clearly on making something a human can read; but it's also executable.

Hmmm.

I think a worksheet-style programming environment would be interesting. For one thing, it would make it really, really easy to accumulate test cases. I think most developers do informal testing of the variety "I just finished coding X; let's run it and see if it works." If the interactive environment in which you did this kind of testing were a worksheet, you could very easily save the thing and run it again later. It would almost be hard not to build up test cases.

04 April 2006

JavaScript, threading, and continuations

I've got a few bits and pieces of my side project working now, and I ran into something unexpected.

The annoying problem

In a simple GUI app, events (like mouse clicks and keystrokes) are all handled in a single, dedicated thread. If event-handling code takes too long to run, the application becomes unresponsive. It works like this everywhere: Java, Windows, XWin—and client-side JavaScript. But as always, JavaScript is... different:

  1. The whole browser doesn't become unresponsive, just your scripts. This is scripts don't run in the browser's main GUI thread. Rather, the browser gives you a separate thread dedicated to scripting events. But don't think this lets you off the hook, because...

  2. The browser detects unresponsive scripts, and believe me, you don't want this to happen. Firefox, for instance, pops up a warning message and offers the user the option to kill your script. If the user says no, the same warning message pops up again a few seconds later.

  3. The usual solution to this problem won't work in a browser. In any other system, you would just take the long-running code and move it into its own thread. But scripts can't spawn threads. Now what?

The annoying solution

I found a workaround using window.setTimeout(). You have to change your code to do its work in chunks and use setTimeout() as a substitute for preemptive thread-switching. It sounds like green threads. Unfortunately, it's much worse than that. Consider this:

    function hog() {
        // code that does three time-consuming things
        spellCheckWikipedia();
        findPrimesInDigitsOfPi();
        buildConcensusOnUsenet();
    }

In a language with green threads, you'd just call sleep(1) (or whatever) between steps.

In JavaScript, you have to write this:

    function hog_start() {
        setTimeout(hog_step1, 10);
    }

    function hog_step1() {
        spellCheckWikipedia();
        setTimeout(hog_step2, 10);
    }

    function hog_step2() {
        findPrimesInDigitsOfPi();
        setTimeout(hog_step3, 10);
    }

    function hog_step3() {
        buildConcensusOnUsenet();
        // phew-- done.
    }

Ugly. The really annoying case is when individual steps are too time-consuming. Suppose buildConcensusOnUsenet() takes an unbounded amount of time to run. Then the function needs to be modified to be "setTimeout()-aware"—a huge pain.

Funny thing is: this is just continuation-passing style. You use setTimeout to "jump to" a continuation. I thought this was cute, like a pun is cute. I've seen continuations simulated via exceptions, but never via event queues.

I guess theoretically I could source-transform JavaScript code written in the green-threads style into JavaScript written in continuation-passing style. Not sure I want to go that far.

To do

I have to get back to my current side project, about which more in a bit. But a definite possible future side project is:

  • Create a "foundations of math" wiki combining MediaWiki and the Metamath proof-checking engine.

31 March 2006

Metamath and the art of mathematics

My brilliant coworker G.D. thinks Metamath, and the successor I envision (in the previous entry), are sort of pointless.

I think his main beef with the idea is this: people prove things by inventing crazy new concepts that won't get formalized for a long time. This inventiveness is the really interesting part of math. I think G.D.'s impression is that just about any proof you read in a mathematical journal today probably can't be put into a formal, machine-checkable form for decades to come.

He is probably right. So my hypothetical checked theorem database can never be up-to-the-minute. Then what value could it have?

  • Exploration and education. Even if the database only covers formally grounded math, I think that could get us up to maybe 1950. Number theory is pretty well grounded, I think. Real analysis. Calculus. Euclidean geometry. Group theory. Think how huge it would be. Thousands of human-readable proofs, every step checked, and you can drill down into any step if you don't understand the reasoning. Basically every theorem an undergrad ever bumps into; every theorem I personally could ever hope to understand. It sounds exciting to me.

  • Finding assumptions. Does the fundamental theorem of calculus depend on the axiom of choice? Metamath doesn't have that theorem yet, but when it does, then you'll know. Exposing previously hidden assumptions sounds good for math.

  • Finding gaps. Check out the axiom of choice. Here's a discovery that rocked mathematics. Are there any more of these still lurking in standard math? It seems wildly unlikely... but then, it also seems unlikely that what we've got is that perfect.

  • Mathematician productivity. The ultimate (200-year) goal is to evolve the system into a work environment for mathematicians. If you started every expedition by plunking your conjecture into a worksheet, every once in a while the program could immediately respond with the (known or easily found) proof. Also, Andrew Wiles's first proof of Fermat's last theorem was found to contain a serious error that it took him a year to fix. Of course he would have preferred to have discovered that prior to publication. The current proof is 200 pages; I doubt it's been scrutinized. These thoughts make this idea seem inevitable. It just sounds too useful as a dumb tool.

And: I think the time gap between a new invention in math and its formal grounding has been shrinking. Maybe formalism will catch up to discovery!

I think the essential question is this: do you think the Zermelo-Fraenkel axioms really are one of humankind's most profound achievements? Or were these guys just mincing grammar snobs, coming in after the Newtons and Galoises of the world, acting all important, dotting the i's and crossing the t's—only to get blown out of the water by Gödel before they even finished the job?

Metamath

Q: What is Metamath?

A: Metamath is a tiny language that can express theorems in abstract mathematics, accompanied by proofs that can be verified by a computer program. This site has a collection of web pages generated from those proofs and lets you see mathematics developed formally from first principles with absolute rigor. Hopefully it will amuse you, amaze you, and possibly enlighten you in its own special way.

It has certainly amused and amazed me. (Note: If you don't consider the Zermelo-Fraenkel axioms “one of the most profound achievements of mankind” [here], Metamath might not be for you.)

Metamath is a database of machine-verifiable mathematical proofs. This is actually something of a long-term dream of mine, so I'm surprised and impressed.

Here are the frustrating bits:

  • The database is largeish, but its reach is very limited. Metamath currently comprises 6,403 theorems, of which “2+2=4” is number 5,214.

  • The proofs themselves are unenlightening. For example, Metamath has proved that there are infinitely many primes. But click the link. It's totally indecipherable.

What I'd do differently, to try and address those problems:

  • Make the database more searchable, by giving pages readable English names, not numbers or junk like caoprmo.

  • Allow anyone to edit.

  • Encourage more English text mixed in with the formal statements.

  • Allow pages with non-verifiable proofs, missing steps, syntax errors, etc. But if a proof is correct and verifiable, you'd get a nice string of green lights down one side of the page.

  • Work hard on notation. It has to be human-editable and human-readable. (This strikes me as extremely difficult.)

  • I wouldn't require contributors to prove every step formally. This requires a deep understanding of formal logic that most mathematicians frankly don't have. Instead, you'd just type all the steps in the proof, with the usual gaping logical chasms in between; and the system would use automatic theorem provers to check that each step follows from the preceding ones. This would help with both readability and reach.

  • Now theorem provers suck, so often the system won't be able to prove every step. No problem. Contributors could close a gap by (a) giving the system a hint (e.g. adding the words “...by [[Schphlebotsky's Theorem]]”), (b) inserting a clarifying intermediate step, or (c) making a separate page proving the step as a lemma. And they could work incrementally.

Metamath is already more and better than I would've thought possible. And there are extremely good reasons that Metamath exists and my idea is just a dream. But I think the dream has potential. Who knows—Metamath might evolve in this direction.