Add the ->> symbol to the lambda prettyprinter.
[matthijs/master-project/report.git] / pret-lam.lua
1 -- filename : type-lam.lua
2 -- comment  : Pretty printing of (extended) lambda calculus
3 -- author   : Matthijs Kooijman, Universiteit Twente, NL
4 -- copyright: Matthijs Kooijman
5 -- license  : None
6
7 local utf = unicode.utf8
8
9 local vis = buffers.newvisualizer("lam")
10
11 local colors = {
12     "prettytwo",
13     "prettyone",
14     "prettythree",
15     "prettyfour"
16 }
17
18 -- Symbols that should have a different representation
19 local symbols = {
20     -- Note, the space we replace with is a Unicode non-breaking space
21     -- (U+00A0).
22     {symbol = ' ', repr = ' '},
23     {symbol = '_', repr = '\\_'},
24     {symbol = '->>', repr = '\\twoheadrightarrow'},
25     {symbol = '->', repr = '→'},
26     {symbol = '=>', repr = '⇒'},
27     -- The default * sits very high above the baseline, \ast (u+2217) looks
28     -- better.
29     {symbol = '*', repr = '\\ast'},
30     {symbol = '~', repr = '\\HDLine[width=.20 * \\the\\textwidth]'},
31     {symbol = '|', repr = '\\char' .. utf.byte('|')},
32     -- Use ▶ from our roman font, since Iwona doesn't have the glyph
33     {symbol = '▶', repr = '{\\rm{}▶}'},
34 }
35
36 -- Keywords that should be bold
37 local keywords = {
38     ['case'] = {},
39     ['of'] = {},
40     ['let'] = {},
41     ['letrec'] = {},
42     ['letnonrec'] = {},
43     ['in'] = {},
44     ['DEFAULT'] = {small = true},
45 }
46
47 local in_block = 0
48 local submatches = {}
49 local bases = {}
50 -- Store the last line for each indent level
51 local indentlines = {}
52
53 function array_concat(a1, a2)
54     local res = a1
55     for k,v in ipairs(a2) do
56         table.insert(res, v)
57     end
58     return res
59 end
60
61
62 -- See if str starts with a symbol, and return the remaining string and that
63 -- symbol. If no symbol from the table is matched, just returns the first
64 -- character.  We can do a lookup directly, since symbols can be different in
65 -- length, so we just loop over all symbols, trying them in turn.
66 local function take_symbol(str)
67     for i,props in ipairs(symbols) do
68         -- Try to remove symbol from the start of str 
69         symbol, newstr = utf.match(str, "^(" .. props.symbol .. ")(.*)")
70         if symbol then
71             -- Return this tokens repr, or just the token if it has no
72             -- repr.
73             res = props.repr or symbol
74             -- Enclose the token in {\style .. }
75             if props.style then
76                 res = "{\\" .. props.style ..  " " .. res ..  "}"
77             end
78             return res, newstr
79         end
80     end
81     -- No symbol found, just return the first character
82     return utf.match(str, "^(.)(.*)")
83 end
84
85 -- Take a single word from str, if posible. Returns the rest of the string and
86 -- the word taken.
87 local function take_word(str)
88         -- A word must always start with a-z (in particular, λ is not a valid
89         -- start of a word).
90         res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]+)(.*)")
91         return res, newstr or str
92 end
93
94 -- Tries to match each of the patterns and returns the captures of the first
95 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
96 -- matches.
97 local function match_mul(str, patterns)
98     for i, pat in ipairs(patterns) do
99         a, b, c, d, e = utf.match(str, pat)
100         if a then
101             return a, b, c, d, e
102         end
103     end
104     return nil
105 end
106
107 -- Find any subscripts in the given word and typeset them
108 local function do_subscripts(word)
109     base, sub = match_mul(res, submatches)
110     if sub then
111         word = base .. "\\low{" .. sub .. "}"
112         -- After a word has been used as a base, allow subscripts
113         -- without _, even for non-numbers.
114         if not bases[base] then
115             -- Register that we've added this base
116             bases[base] = true
117             -- Add a patterns for this base. First, the base with a single
118             -- letter or number subscript.
119             submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
120             -- Seconde, the base with a longer prefix that includes at least
121             -- one of +-, (to catch things like ri+1, but not return).
122             submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+,]+[%a%d%-%+,]*)$"
123         end
124     end
125     return word
126 end
127
128 -- Do proper aligning for subsequent lines. For example, in 
129 --   foo = bar
130 --       | baz
131 -- We replace the spaces in the second line with a skip with the same with as
132 -- "foo ", to align the | with the =.
133 -- For this, we keep a table "indentlines", which contains all previous lines
134 -- with smaller indent levels that are still "in scope" (e.g., have not yet
135 -- been followed by a line with a smaller indent level). For example:
136 --   line1
137 --     line2
138 --       line3
139 --     line4
140 --       line5
141 -- After the last line, the table will contain:
142 --   { 0 = "line1", 2 = "  line4", 4 = "    line5"}
143 --   In other words, line3 is no longer in scope since it is "hidden" by
144 --   line4, and line is no longer in scope since it is replaced by line4.
145 local function do_indent(line)
146     newind, rest = utf.match(line, '^(%s*)(.*)')
147     prev = -1
148     -- Loop all the previous lines
149     for indent, unused in pairs(indentlines) do
150         if indent > #newind then
151             -- Remove any lines with a larger indent
152             indentlines[indent] = nil
153         elseif indent < #newind and indent > prev then
154             -- Find the last line (e.g, with the highest indent) with an
155             -- indent smaller than the new indent. This is the line from which
156             -- we need to copy the indent.
157             prev = indent
158         end
159     end
160     
161     -- Always store this line, possibly overwriting a previous line with the
162     -- same indent
163     indentlines[#newind] = line
164
165     if prev ~= -1 then
166         -- If there is a previous line with a smaller indent, make sure we
167         -- align with it. We do this by taking a prefix from that previous
168         -- line just as long as our indent. This gives us a bunch of
169         -- whitespace, with a few non-whitespace characters. We find out the
170         -- width of this prefix, and put whitespace just as wide as that
171         -- prefix before the current line, instead of the whitespace
172         -- characters that were there.
173         -- Doing this is slightly risky, since the prefix might contain
174         -- unfinished markup (e.g., \foo{bar without the closing }). We might
175         -- need to solve this later.
176         copyind = utf.sub(indentlines[prev], 1, #newind)
177         setwidth = "\\setwidthof{" .. copyind .. "}\\to\\pretlamalignwidth"
178         hskip = "\\hskip\\pretlamalignwidth"
179         return "{" .. setwidth .. hskip .. "}" .. rest
180     end
181         -- No previous line? Just return the unmodified line then
182         return line
183 end
184
185
186 -- Mark the begin of a block of lambda formatted buffers or expressions. This
187 -- means that, until you call end_of_block again, the subscript bases are
188 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
189 -- single block, the yn will properly get subscripted. Be sure to call
190 -- end_of_block again!
191 --
192 -- Blocks can be partially nested, meaning that the block
193 -- won't be closed until end_of_block was called exactly as often as
194 -- begin_of_block. However, subscripts from the inner block can still
195 -- influence subscripts in the outer block.
196 function vis.begin_of_block()
197     vis.begin_of_display()
198     in_block = in_block + 1
199 end
200
201 -- Ends the current block
202 function vis.end_of_block()
203     in_block = in_block - 1
204 end
205
206 function vis.begin_of_display()
207     if in_block == 0 then
208         -- Initially allow subscripts using _ or just appending a number (later,
209         -- we will add extra patterns here.
210         submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)(%d[%d,]+)$"}
211         -- This stores all the bases we've encountered so far (to prevent
212         -- duplicates). For each of them there will be a pattern in submatches
213         -- above.
214         bases = {}
215     end
216     indentlines = {}
217 end
218     
219
220 -- Make things work for inline typeing (e.g., \type{}) as well.
221 vis.begin_of_inline = vis.begin_of_display
222 vis.end_of_inline = vis.end_of_display
223
224 function vis.flush_line(str,nested)
225     buffers.flush_result(vis.do_line(str, false), nested)   
226 end
227
228 function vis.do_line(str, no_indent)
229     local result = {}
230     if not no_indent then
231         -- Allow ignore of the indentation stuff when we're calling ourselves
232         -- for a partial line.
233         str = do_indent(str)
234     end
235     while str ~= "" do
236         local found = false
237         local word, symbol
238         local text, rest = utf.match(str, "^%-%-(.-)%-%-(.*)")
239         if text then
240             table.insert(result, '\\strikethrough{')
241             -- Recursively call ourselves to handle spaces gracefully.
242             result = array_concat(result, vis.do_line(text, true))
243             table.insert(result, '}')
244             -- Eat the processed characters
245             str = rest
246         elseif utf.match(str, "^%-%-") then
247             table.insert(result, '{\\italic{--')
248             -- Recursively call ourselves to handle spaces gracefully.
249             result = array_concat(result, vis.do_line(utf.sub(str, 3), true))
250             table.insert(result, '}}')
251             -- Done with this line
252             str = ''
253         else
254             -- See if the next token is a word
255             word, str = take_word(str)
256             if word then
257                 if keywords[res] then
258                     -- Make all keywords bold
259                     word = "{\\bold " .. word ..  "}"
260                     if keywords[res].small then
261                         word = "\\small" .. word -- Curlies were added above
262                     end
263                 else
264                     -- Process any subscripts in the word
265                     word = do_subscripts(word)
266                 end
267                 table.insert(result, word)
268             else
269                 -- The next token is not a word, it must be a symbol
270                 symbol, str = take_symbol(str)
271                 table.insert(result, symbol)
272             end
273         end
274     end
275
276     return result
277 end
278
279 -- vim: set sw=4 sts=4 expandtab ai: