Monday, December 12, 2011

CWEB

It turns out there is some interesting stuff to do with CWEB.

First off, you program in chunks/modules called "sections". Each section contains either code or documentation. Each section begins with @.

The skeleton of a CWEB program might look like:

% this is a comment
\def\title{My awesome program!!!!} % this sets the title
\datethis % this sets the date
@*Introduction. % create the introduction section
This program will solve all my problems.

[Code not shown]

@*Index.

The line of code @*Introduction. will create a section with a title, it would look like "1. Introduction. ". It's TeX equivalent would be \medbreak\noindent{\bf 1.\quad Introduction.\quad}, and yes those \quad spacings are correct.

The first line of code puts a time stamp between the first section and the title.

The last line produces an index of all the variables.

The Code

How do we actually write code in CWEB?

We can use @c to start writing code, just as @ is used to write documentation.

And just as we had @*[title]., we have something analogous for code @<[title]>

However, the first time we use @<section name>, we are defining it. When we use it later on, we are calling it. Note the difference!

Comments

A simple comment is formatted by @q ... and it is not printed to the TeX file.

Write to Different Files

If one writes @(foo>, then the contents of the section (onwards?) is written to the file foo.

Macro Definitions

Instead of that ungodly #define ..., we write @d ... to do the same thing.

Some example code (from string.w):

@s string int
@s Xstring int @q -- a hint for the typesetter -- @>
@(xstring.h@>=
#ifndef XSTRING_H
#define XSTRING_H // prevent multiple inclusions
@#
class Xstring {
 @<private |Xstring| members@>@;
public:@/
 @<public |Xstring| members@>@;
};
@#
#endif

What does the @# line do? Well, it forces a line break, and that's all.

Similarly, the @/ line forces CWEAVE to put a line break in the C code.

But what do those @>= lines mean? We are initializing and declaring an identifier for a section. For us, that is xstring.h, and since we have prefaced it with @( it means we are working with the code in a separate file.

Observe that @<public |Xstring| members@>@; simply loads the code defined in section public |Xstring| members since the section ended without an equal sign, i.e. @> instead of >=.

More notes to come, but one might also be interested in Knuth's straighten.w program for computing irreps of the symmetric group.

Addendum

Here is the obligatory "Hello World!" type program:

@*Introduction.
This is a simple ``Hello World!'' program using literate
programming. I hope it works! (It does work!)

@c
#include <stdio.h>

int main(int argc, char** argv)
{
 printf("Hello world! I am literate programming?\n");
 return 1;
}

@*Index.

No comments: