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