Gauche Devlog

2016/01/28

Automatic port selection for httpd

When you run a small http server temporarily, sometimes you want the server to pick an unused port number automatically, instead of your specifying one. For example, a test program may need to spawn a server, and hardcoding the port number will prevent you from running more than one instance of the test program simultaneously.

Giving 0 as the port number to make-server-socket or make-server-sockets let the system choose a port number for you. You need to know which port number is picked. With Gauche-makiki, you can use :startup-callback argument to examine server sockets to find out the port number. The following snippet shows echoing the port number to stdout after starting the server:

Note that server may open multiple sockets (e.g. one for ipv4, one for ipv6) so the callback receives a list of sockets. Their port numbers should be the same, though.

With this setup, you can spawn a server in a subprocess and talk to it, for example:

Tags: makiki, Tips

2016/01/02

Hygienic macro intro

(I just wrote the introduction of Macro chapter of Gauche manual. It may be useful for general introduction to the topic, so I put it here, too. For other Scheme implementation users: Keep in mind that ^ is lambda and (^x ...) is (lambda (x) ...) in Gauche.)


Lisp macro is a programmatic transformation of source code. A macro transformer is a procedure that takes a subtree of source code, and returns a reconstructed tree of source code.

The traditional Lisp macros take the input source code as an S-expression, and returns the output as another S-expression. Gauche supports that type of macro, too, with define-macro form. Here's the simple definition of when with the traditional macro.

(define-macro (when test . body)
  `(if ,test (begin ,@body)))

For example, if the macro is used as (when (zero? x) (print "zero") 'zero), the above macro transformer rewrites it to (if (zero? x) (begin (print "zero") 'zero)). So far, so good.

But what if the when macro is used in an environment where the names begin or if is bound?

(let ([begin list])
  (when (zero? x) (print "zero") 'zero))

The expanded result would be as follows:

(let ([begin list])
  (if (zero? x) (begin (print "zero") 'zero)))

This obviously won't work as the macro writer intended.

This is a form of variable capture. Note that, when Lisp people talk about variable capture of macros, it often means another form of capture, where the temporary variables inserted by a macro would unintentionally capture the variables passed to the macro. That kind of variable capture can be avoided easily by naming the temporary variables something that never conflict, using gensym.

On the other hand, the kind of variable capture in the above example can't be avoided by gensym, because (let ([begin list]) ...) part isn't under macro writer's control. As a macro writer, you can do nothing to prevent the conflict, just hoping the macro user won't do such a thing. Sure, rebinding begin is a crazy idea that nobody perhaps wants to do, but it can happen on any global variable, even the ones you define for your library.

Various Lisp dialects have tried to address this issue in different ways. Common Lisp somewhat relies on the common sense of the programmer---you can use separate packages to reduce the chance of accidental conflict but can't make the chance zero. (The Common Lisp spec says it is undefined if you locally rebind names of CL standard symbols; but it doesn't prevent you from locally rebinding symbols that are provided by user libraries.)

Clojure introduced a way to directly refer to the toplevel variables by a namespace prefix, so it can bypass whatever local bindings of the same name (also, it has a sophisticated quasiquote form that automatically renames free variables to refer to the toplevel ones). It works, as far as there are no local macros. With local macros, you need a way to distinguish different local bindings of the same name, as we see in the later examples. Clojure's way can only distinguish between local and toplevel bindings. It's ok for Clojure which doesn't have local macros, but in Scheme, we prefer uniform and orthogonal axioms---if functions can be defined locally with lexical scope, why not macros?

Let's look at the local macro with lexical scope. For the sake of explanation, suppose we have hypothetical local macro binding form, let-macro, that binds a local identifiers to a macro transformer. (We don't actually have let-macro; what we have is let-syntax and letrec-syntax, which have slightly different way to call macro transformers. But here let-macro may be easier to understand as it is similar to define-macro.)

(let ([f (^x (* x x))])
  (let-macro ([m (^[expr1 expr2] `(+ (f ,expr1) (f ,expr2)))])
    (let ([f (^x (+ x x))])
      (m 3 4))))    ; [1]

The local identifier m is bound to a macro transformer that takes two expressions, and returns a form. So, the (m 3 4) form [1] would be expanded into (+ (f 3) (f 4)). Let's rewrite the above expression with the expanded form. (After expansion, we no longer need let-macro form, so we don't include it.)

(let ([f (^x (* x x))])
  (let ([f (^x (+ x x))])
    (+ (f 3) (f 4))))  ; [2]

Now, the question. Which binding f in the expanded form [2] should refer? If we literally interpret the expansion, it would refer to the inner binding (^x (+ x x)). However, Scheme uniformly adopts lexical scoping---if the binding of m were ordinary let, the f in it would have referred to the outer binding (^x (* x x)), no matter where m is actually used.

In order to keep the consistency, we need some way to mark the names inserted by the macro transformer m---which are f and +---so that we can distinguish two f's (we can also mark + as free, which would refer to the toplevel binding.)

For example, if we would rewrite the entire form and renames corresponding local identifiers as follows:

(let ([f_1 (^x (* x x))])
  (let-macro ([m (^[expr1 expr2] `(+ (f_1 ,expr1) (f_1 ,expr2)))])
    (let ([f_2 (^x (+ x x))])
      (m 3 4))))

Then the naive expansion would correctly preserve scopes; that is, expansion of m refers f_1, which wouldn't conflict with inner name f_2:

(let ([f_1 (^x (* x x))])
  (let ([f_2 (^x (+ x x))])
    (+ (f_1 3) (f_1 4))))

(You may notice that this is similar to lambda calculus treating lexical bindings with higher order functions.)

The above example deal with avoiding f referred from the macro definition (which is, in fact, f_1) from being shadowed by the binding of f at the macro use (which is f_2).

Another type of variable capture (the one most often talked about, and can be avoided by gensym) is that a variable in macro use site is shadowed by the binding introduced by a macro definition. We can apply the same renaming strategy to avoid that type of capture, too. Let's see the following example:

(let ([f (^x (* x x))])
  (let-macro ([m (^[expr1] `(let ([f (^x (+ x x))]) (f ,expr1)))])
    (m (f 3))))

The local macro inserts binding of f into the expansion. The macro use (m (f 3)) also contains a reference to f, which should be the outer f, since the macro use is lexically outside of the let inserted by the macro.

We could rename f's according to its lexical scope:

(let ([f_1 (^x (* x x))])
  (let-macro ([m (^[expr1] `(let ([f_2 (^x (+ x x))]) (f_2 ,expr1)))])
    (m (f_1 3))))

Then expansion unambiguously distinguish two f's.

(let ([f_1 (^x (* x x))])
  (let ([f_2 (^x (+ x x))])
    (f_2 (f_1 3))))

This is, in principle, what hygienic macro is about (well, almost). In reality, we don't rename everything in batch. One caveat is in the latter example---we statically renamed f to f_2, but it is possible that the macro recursively calls itself, and we have to distinguish f's introduced in every individual expansion of m. So macro expansion and renaming should work together.

There are multiple strategies to implement it, and the Scheme standard doesn't want to bind implementations to single specific strategy. The standard only states the properties the macro system should satisfy, in two concise sentences:

If a macro transformer inserts a binding for an identifier (variable or keyword), the identifier will in effect be renamed throughout its scope to avoid conflicts with other identifiers.

If a macro transformer inserts a free reference to an identifier, the reference refers to the binding that was visible where the transformer was specified, regardless of any local bindings that surround the use of the macro.

It may not be obvious how to realize those properties, and the existing hygienic macro mechanisms (e.g. syntax-rules) hide the how part. That's probably one of the reason some people feel hygienic macros are difficult to grasp. It's like continuations---its description is concise but at first you have no idea how it works; then, through experience, you become familiarized yourself to it, and then you reread the original description and understand it says exactly what it is.

This introduction may not answer how the hygienic macro realizes those properties, but I hope it showed what it does and why it is needed. In the following chapters we introduce a couple of hygienic macro mechanisms Gauche supports, with examples, so that you can familiarize yourself to the concept.

Tag: macro

2015/09/06

Small REPL info improvement

You could browse info document from REPL (ref:info), but it showed entire info page containing the searched entry. Even though it uses the pager, it's sometimes inconvenient if the page is lengthy.

I improved it a bit by the last commit. Now (1) info function shows only the entry searched for, and (2) you can invoke info function using top-level command.

gosh> ,info filter
 -- Function: filter pred list
 -- Function: filter! pred list
     [SRFI-1] A procedure PRED is applied on each element of LIST, and
     a list of elements that PRED returned true on it is returned.
          (filter odd? '(3 1 4 5 9 2 6)) => (3 1 5 9)
     `filter!' is the linear-update variant.  It may destructively
     modifies LIST to produce the result.

gosh>

If you still wants to view the entire page, info-page function does the same job as the previous info function did (I didn't make it toplevel REPL command yet.)

Tags: 0.9.5, repl

2015/08/19

Top-level REPL commands

Another little feature I'm playing for REPL improvements.

S-expression is great to represent tree structure, but it's a bit cumbersome to give simple commands in interactive shell; If the command line is short, the relative verbosity added by open and close parentheses gets in a way. Also in many cases simple commands take string arguments (e.g. to change working directory or to load file) and that require extra double quotes.

I'm not the only one to feel that way. In Allegro CL, if you type a line begins with :, it is interpreted as special toplevel command. Scheme 48 has similar command mode, beginning with ,. I guess there are other implementations with similar features.

So I started adding Scheme 48-ish command syntax. If the first thing you type in the REPL prompt is a comma, an entire line is read by read-line and parsed as a toplevel command, instead of being read with read.

You can see current directory or move around:

gosh> ,pwd
/home/shiro/src/Gauche/src
gosh> ,cd
"/home/shiro"
gosh> ,cd src/Gauche
"/home/shiro/src/Gauche"

You can run apropos:

gosh> ,a cons
%tree-map-check-consistency    (gauche)
acons                          (gauche)
cons                           (scheme)
cons*                          (gauche)
define-constant                (gauche)
lcons                          (gauche)
lcons*                         (gauche)
gosh> ,a trim srfi-13
string-trim                    (srfi-13)
string-trim-both               (srfi-13)
string-trim-right              (srfi-13)

or describe:

gosh> ,d 31415926
31415926 is an instance of class <integer>
  (#x1df5e76, ~ 29Mi, 1970-12-30T14:38:46Z as unix-time)

You can omit the argument for describe, in which case it takes the last value of REPL. Whenever you want to see the details of the last evaluation result, just type comma-d:

gosh> (sys-stat "Makefile")
#<<sys-stat> 0x14e01e0>
gosh> ,d
#<<sys-stat> 0x14e01e0> is an instance of class <sys-stat>
slots:
  type      : regular
  perm      : 436
  mode      : 33204
  ino       : 3295167
  dev       : 2097
  rdev      : 0
  nlink     : 1
  uid       : 500
  gid       : 500
  size      : 4599
  atime     : 1440031322
  mtime     : 1440031177
  ctime     : 1440031177

I'll gradually add more commands. Let me know your ideas.

Tags: 0.9.5, repl

2015/08/07

Write control variables

Oh well. More than a year since the last entry. So many things has loaded into HEAD and I have to wrap it up as 0.9.5. Some small issues to address, though.

As a part of improving REPL experience, I implemented CL-like write control variables. Those like *print-length*. In Gauche it looks like a parameter.

gosh> (parameterize ((print-length 5)) (write (iota 10)))
(0 1 2 3 4 ...)#<undef>

I wanted them every time I accidentally evaluated huge data structure on REPL and just waited Emacs to finish showing it until the end (Ctrl-C can stop Gauche printing it, but it's mostly Emacs that's taking time to fill the buffer, especially when font-lock mode is on.)

By the way, print-base comes handy as desktop calculator for base conversion:

gosh> (print-base 16)
a
gosh> (print-radix #t)
#f
gosh> 4758375874
#x11b9f0dc2

Now I've implemented four of various CL's printer control variables, and sit back and am thinking. Are they really useful as they seem to be?

The global nature of those controls is the problem. I'd like to limit print-length on REPL output to avoid excessive output. But doing so globally affects every operation, such as serialization to file or network connection, which is almost certainly undesirable. I can create a custom printer for REPL that changes the controls only when it prints the result, but then I need another set of API to set those values REPL would use.

Worse, now every routine that writes out values expecting it to be read back must be wrapped with parameterize to ensure those control variables are in the default value, otherwise it can be broken accidentally when called with print-level set to 5.

The more I think, the more dubious I became about the CL's choice of making them dynamic variables.

Another idea I had before is to have a "context" object that packages those controls, and you can set it to a parameter, instead of parameterizing individual controls (the name ScmWriteContext in the source was somewhat intended for that, but ended up for different purpose.) With that, the REPL can have just one repl-default-context and use that for just printing.

Recently I got yet another idea; let a port have those controls. We already have port-attributes to associate key-value pairs to ports. For serialization you'll usually create a fresh ports so the chance of inadvertent interference is very low. For REPL output, we can create a wrapper port connected to stdout so that it can have separate attributes, and use it for printing the results.

Some more pondering.

Tags: REPL, 0.9.5

More entries ...