Sunday, August 2, 2026

Lisp-p

I needed a function that could tell whether a string was a valid Common Lisp program. In theory, you could just call read on the string and see if it throws an error, but I don't want to throw random text at read. It could contain a reader macro or something nasty. It also would intern a ton of random symbols into the current package. I wanted a function that would act mostly like the reader, but not CONS any data or intern any symbols.

So I vibe coded a function that does just that. It implements the reader algorithm as a state machine but does not actually read any data. The state machine tracks the list and string delimeters and tokenizes the string, but it discards the tokens and does not intern any symbols. It just checks that the state machine is in `top level' state at the end of the string. If it returns NIL, the string is definitely going to cause an error if you try to read it. If it returns T, it does not guarantee that the string represents a valid Common Lisp program, but rather that it is not obvious that the reader will throw an immediate error.

A curious edge case is that of an unpunctuated string. The words in the string will read as a simple sequence of symbols, which is perfectly valid.

The code is in lisp-p on GitHub. You call the function lisp-p with a string or a stream and it will return T or NIL.

2 comments:

  1. Hey Claude: solve the halting problem. Make no mistakes.

    Heh, just kidding! This is pretty cool, and an interesting approach.

    ReplyDelete
  2. One of my favorite jokes. Two Lisp programmers are discussing lunch plans. One asks (split-p? soup).

    ReplyDelete