mbutterick / pollen-users

please use https://forums.matthewbutterick.com/c/typesetting/ instead
https://forums.matthewbutterick.com/c/typesetting/
52 stars 0 forks source link

Source location info in tag functions #28

Open otherjoel opened 4 years ago

otherjoel commented 4 years ago

In #27 @odanoburu asked about tag functions having info about where they are located in the Pollen source doc:

I wonder if it's possible to include the location of the error in the source file (i.e., the location of the tag in the source file, not of the location of the tag function in pollen.rkt). is this location information available to the tag function? if not, can it be made available?

This info is available at compile time, so if you write your tag function as a macro you absolutely can get to it. I recently cooked up a proof of concept:

#lang racket/base ; ~~~ pollen.rkt ~~~

(require pollen/tag)
(require (for-syntax racket/base syntax/parse))

(provide root note)

(define (root . elems)
  `(body ,@elems))

(define-syntax (note stx)
  (syntax-parse stx
    [(_ args ...)
     (with-syntax ([srcdoc (format "~a" (syntax-source stx))]
                   [srcline (number->string (syntax-line stx))])

       #'(note-tag #:src srcdoc #:line srcline args ...))]))

(define note-tag (default-tag-function 'div))

Paste this into example.html.pm and save it into the same folder:

#lang pollen

◊note[#:date "2019"]{This is going to be cool.}

“Running” it in DrRacket produces:

'(body
  (div
   ((date "2019")
    (line "3")
    (src
     "/Users/joel/Documents/code/sandbox/srcloc/example.html.pm"))
   "This is going to be cool."))

So you see that the output div contains the file and line number where ◊note occurs in the Pollen source. In order to make full use of this code you really need to delve into how macros and syntax objects work. I found it kind of brain-melting at first (still do, a bit). But it’s another example of Racket’s power, and it’s really cool that this is available to us in Pollen.

I haven’t used this for error reporting (I do as little error reporting in Pollen as possible since I’m the only user of my tag functions and can spot any issues pretty quickly). But I wanted to make it possible to have output that could link back to its source file and location.