Monday Troll: the syntax extension myth
By Didier Verna on Monday, May 14 2012, 17:09 - Lisp - Permalink
Here's a little Monday Troll.
To my greatest disappointment, I discovered today that it is not possible to replace Lisp parenthesis by, say, ... curly braces. What a shame. Hell, it's not even possible to freely mix the two. Very naively, I had expected that:
(set-macro-character #\{ (get-macro-character #\()) (set-macro-character #\} (get-macro-character #\)))
would suffice, but no. All implementations that I have tested seem to agree on this, although the error messages may differ. For instance, trying to evaluate {and}
gives you an "unmatched close parenthesis error" except for CMU-CL which chooses to ignore it, but then report an end-of-file error. The unmatched close parenthesis, of course, is the closing curly brace! So what is going on here?
When an opening curly brace is read, the original left paren macro function is called. In SBCL for instance, this is SB-IMPL::READ-LIST, which looks for a hardwired right paren on the stream. Yuck. It doesn't find one, but it finds my closing brace which triggers the "standalone" right paren behavior (spurious paren alert). In passing, it also surprised me that SB-IMPL::READ-LIST is not implemented in terms of READ-DELIMITED-LIST.
EDIT: as mentioned in several comments, we could use read-delimited-list
to look for a closing curly brace, but even this won't work completely. The problem is with dotted lists (see Pascal's comment). SBCL hard-wires #\) in its dotted lists parsing procedures.
So it appears that dispatching macro characters are only shaky. What we miss is a true concept of syntactic categories (Common Lisp character syntax types are close, but not quite there yet). In fact, TeX, with its notion of catcodes (category codes), seems to be the only language that gets this right. Ideally, any character with associated status LIST TERMINATOR should do as good as a right paren (the problem is only with closing, not opening).
Instead of hard-wiring the right paren in the Lisp parser, a quick workaround would be to check whether the next character on the stream is a dispatching one, and in such a case, whether its macro function is the one originally associated with the right paren. If so, it should then simply stand as a list terminator. This is actually an interesting idea I think: could the built-in macro functions become equivalent to actual category codes, and could we completely remove hard-wired characters in Lisp parsers?
Anyway, this whole story is a true scandal because it ruined an otherwise cool live demo of mine. So much for syntax extensibility. I will immediately complain to the concerned authorities.
Looking for the concerned authorities to complain to... please wait.
Comments
Indeed, the main point is that CL doesn't export facilities to read dotted-lists, only proper lists. And implementing dotted list reading is not even easy (you cannot just use peek-char and read, you need lower level parsing).
Nonetheless, syntax extensibility can be as easy as:
cl-user> (make-lisp-list-macro-character #\{)
#\}
cl-user> '{a {1 2 3} {} c . d}
(a (1 2 3) nil c . d)
See http://paste.lisp.org/display/12944...
PS: Thanks for that blog entry, I found a bug in my lisp reader ;-)
This is explained in CLTL2, just the way you found it to be, in the entry for set-syntax-from-char, p.541, 542.
You can achieve your goal almost as simply, though:
(set-macro-character #\{ (lambda (stream char) (read-delimited-list #\} stream t)))
(set-macro-character #\} (get-macro-character #\)))
The problem with your original attempt, IMO, is that if CL were defined in a way that allowed that, the result would be to allow (and} and {and) in addition to the expected {and}, which seems very non-intuitive to me.
If you want to (} and {) to work, it's possible, but it does (and should) require more work to do so.
That said, with Unicode, an implementation might be able to define #\( such that it matched the mirrored character in the Unicode DB, and then (set-macro-character #\{ (get-macro-character #\()) could work in the intuitive way, but I don't know if that would be conforming, and it certainly wouldn't be portable.
Interesting. I have a toy project for a future lisp I'm working on; I'll be sure to keep this in mind
I'm sorry you're disappointed, but think that your expectation is simply not in accord with the CL reader's implementation model. You should be able to quite easily do what you wanted thus:
(set-macro-character #\{ (lambda (stream char) (read-delimited-list #\} stream)))
(set-macro-character #\} (lambda (stream char) (error "an object cannot start an object with #\\}")))
The second call serves two purposes: It causes the closing brace to be treated as something other than a constituent character when it appears alone, and (because the optional non-terminating-p argument to set-macro-character is allowed to default to nil) makes it terminate a symbol without becoming part of it.
So you can do what you want easily with no additional infrastructure.
This is quite elegant and requires no further
@Pascal: exactly. There are 2 other places in SBCL where #\) is hard-wired, and these have to do with reading dotted lists. Thanks for the paste BTW!
@Eivind: thank you for the pointer.
@Greg, Cosman, Dan: yes, you can use read-delimited-list, but this will still not function properly in all cases. See Pascal's comment (I should have mentionned this in my original post).
Yes, CLforJava and I are still around and working. When I saw post, I went to see how CLforJava handles your test. Of course, it had a similar result. However, after reading the rest of your text, I remembered that we devised a character syntax type system into the base of the reader. Might be an interesting job for a student...
Tex gets it right, except it does not have enough introspection.
It's darn nigh impossible to get it to regurgitate text and fudge with the catcodes, leading to appendix D and the very obscure \afterassignment hack.
Hey There. I found your blog using msn. This is an extremely well written article.
I'll be sure to bookmark it and come back to read more of your useful information. Thanks for
the post. I'll certainly return.
I am in fact grateful to the holder of this web page who has shared this fantastic piece of
writing at here.
Do you mind if I quote a few of your articles as long as
I provide credit and sources back to your website?
My blog site is in the very same area of interest as yours
and my users would really benefit from a lot of
the information you provide here. Please let me know if this ok with you.
Appreciate it!
My partner and I stumbled over here coming from a different
website and thought I might as well check things out.
I like what I see so i am just following you.
Look forward to checking out your web page for a second time.
Найкращі українські фільми 2021 року link
Фільми та серiали 2020 українською мовою в HD якості link
Дивитися фільми онлайн в HD якості українською мовою link
Дивитися фільми українською онлайн link
Фільми та серiали 2020 українською мовою в HD якості link
Нові сучасні фільми дивитися українською мовою онлайн в хорошій якості HD link
Нові фільми 2021 року. link
Новинки фільми, серіали, мультфільми 2021 року, які
вже вийшли Ви можете дивитися українською на нашому сайті link
Не пропустіть кращі новинки кіно українською 2021 року Золото 17 серия
Нові сучасні фільми дивитися українською мовою онлайн в хорошій якості
HD Папы 2022
Найкращі українські фільми 2021 року Link
Дивитися фільми українською онлайн Папы 2022
Всі фільми новинки 2020 року онлайн
українською в хорошій якості Сказка о Хвосте Феи 242 серия
Нові сучасні фільми дивитися українською мовою онлайн в хорошій якості HD форсаж хоббс и шоу смотреть
онлайн
Дивитися фільми українською мовою онлайн в HD якості Рассказ Служанки
Найкращі українські фільми 2021 року Link
Найкращі фільми 2021 Link
Дивитися фільми онлайн в HD якості українською мовою Link
Фільми та серiали 2020 українською мовою в HD
якості Вечер с Владимиром Соловьевым
Нові фільми 2021 року. z.globus-kino.ru
Дивитися фільми онлайн в HD якості українською мовою filmiwap.store
Не пропустіть кращі новинки кіно українською
2021 року Захар Беркут
Нові фільми 2021 року. link
Нові фільми 2021 року. link
Топ Ган Мэверик
RRR смотреть онлайн
Watch the best Xvideos com videos, free movies, mobile xvideos, and download
for on this tube https://t.me/xvideos_xvideo
Watch the best Xvideos com videos, free movies, mobile xvideos, and download for on this
tube https://t.me/xvideos_xvideo
Watch the best Xvideos com videos, free movies,
mobile xvideos, and download for on this
tube https://t.me/xvideos_xvideo
Watch the best Xvideos com videos, free movies, mobile xvideos, and download for
on this tube https://t.me/xvideos_xvideo
Дивитися фільми українською мовою
онлайн в HD якості Link
Дивитися фільми онлайн в HD якості українською мовою Уэльс Украина смотреть онлайн трансляцию
Смотреть Фильм онлайн без
регистрации, бесплатно..
Фильм смотри ты у. Фильмы в хорошем
качестве 720 HD. Фильм.
RU: Фильмы онлайн высокого качества..
Здесь тор любовь и гром смотреть киного.
Сериалы и фильмы смотреть онлайн видео HD.
RU: Фильмы онлайн высокого качества..
Кино джошуа 2 усик 2022. Зарубежные
фильмы онлайн Дата выхода
Смотреть онлайн бесплатно в качестве HD..
Хотя кино онлайн смотреть бесплатно новинки.
Фильм смотреть онлайн бесплатно.
Смотреть сериалы онлайн бесплатно и легально..
По ссылке в хорошем качестве бесплатно.
Бесплатный онлайн кинотеатр.
Фильм смотреть онлайн бесплатно..
Тут смотреть онлайн в хорошем качестве бесплатно фильмы.
Смотреть фильм онлайн в хорошем качестве HD - приятного просмотра.
Видео смотреть онлайн.. Открыто онлайн фільми.
ТОП 250 фильмов смотреть онлайн версия бесплатно
Russia-Ukraine War Live Updates
donetsk killings
фильм Вышка артур
Quality content is the srcret to attract thhe users to pay a
visit the website, that's what this site is providing.
пацаны 3 сезон смотреть 4
site
site
site
site
Просто помиловать онлайн в HD качестве 720p
site
site
site
Мажор 4 сезон 1 4 5 6 серия
Кино — Смотреть онлайн: Фильм..
Доступ смотреть онлайн в хорошем качестве бесплатно
фильмы. Фильм онлайн. Фильм онлайн бесплатно в HD качестве.
Гештальт-терапия Нейропсихология
Фильмы в хорошем качестве 720 HD. Фильм..
Фильм фильм здесь. Фильмы и Сериалы
· Первый канал.
Где смотреть онлайн бесплатно.
Тут онлайн бесплатно в хорошем качестве фильмы.
Фильм смотреть онлайн бесплатно.
Смотреть фильмы онлайн бесплатно в
хорошем качестве.. Кино Онлайн фильмы.
Поиск фильмов, новости кино, отзывы пользователей.
Йип! кино смотреть онлайн. Iep! 2010 год..
Тут Онлайн фильмы. Можете смотреть кино без субтитров
Просмотр телеканала в режиме онлайн..
Доступ Онлайн фильмы. Смотреть онлайн фильм
123movies free online movie streaming sites
123movies Gomovies
serial
url Url
url More
link Site
site More
предвестники смерти близкого человека Залип В Телефоне
Зарубежные сериалы смотреть онлайн Кино
фильм Молодой человек Смотрите Фильм Молодой Человек
Быстрее пули без регистрации Фильм Быстрее
Пули 2022 Года Полностью Доступен Бесплатно
И Без Регистрации
odnoklassniki-film.store
wwwi.odnoklassniki-film.ru
https://bitbin.it/JI5X9Xvu/
Частные психологи в Москве
шинчи легенда 10 колец смотреть онлайн
смотреть онлайн в хорошем качестве бесплатно
makulatura-sp.ru
94
Вампиры средней полосы 2 сезон 2 серия
Hentai
hentaihavenxxx.ru
переводчик с английского на русский по фото
поляков егэ
гдз по английскому языку четвёртый класс
окружающий мир 2 класс рабочая тетрадь гдз
свойство прямоугольного треугольника
гдз по английскому пятый класс
гдз по английскому 4 класс учебник
гдз по английскому 9 класс
вербицкая
гдз по математике 4 класс 2 часть моро
гдз по физике 9 класс перышкин
задачник
решу впр 4 класс
гдз по немецкому языку 5 класс
гдз по английскому языку четвёртый класс
геометрия 11 класс атанасян
алгебра 8 класс колягин
гдз по английскому 6 класс биболетова
9xflix in m bollywood movies 2023
xnx movie
все по новой
скачать сериал легенда об искателе 2 сезон
солнечный удар скачать фильм
123 mov ies
гра престолів 2 сезон
striplife.ru
1663
Пантомима
Howdy just wanted to give you a brief heads up and let you know a
few of the pictures aren't loading properly. I'm not sure
why but I think its a linking issue. I've tried it in two different browsers and both show the same results.
смотреть онлайн
Психолог консультация
Пацаны 1 сезон
Всё везде и сразу
web page
mgfmail.ru
medunitsa.ru
film.vipspark.ru
крым 2023
Really when someone doesn't understand then its up to
other viewers that they will help, so here it takes place.