Add sphinx documentation, integrated into our navigation and colour scheme
[ndcode_site.git] / sphinx / _sources / cli.rst.txt
1 The ``cli`` module
2 ==================
3
4 .. automodule:: ndcode.piyacc.cli
5   :members:
6
7 Design of the module
8 --------------------
9
10 Step 1 is fairly straightforward Python code using ``getopt.getopt()``.
11
12 Step 2 is more complicated, it uses a πlex/πyacc/πtree generated parser which
13 automatically creates an abstract syntax tree representing the input, and then
14 it performs several passes over the tree to extract the needed information such
15 as lists of terminals and non-terminals, the rules, the alternatives of each
16 rule, and the symbols and/or actions and other directives of each alternative.
17 How it does this is somewhat beyond the scope of this documentation, as we
18 would first have to refer you to tutorials in how to use πlex/πyacc/πtree.
19
20 Step 3 is the focus of this document. Internally it uses a Python class library
21 that we have developed for dealing with LR1 grammars and automata. See the
22 classes ``ndcode.piyacc.lr1.LR1`` and ``ndcode.piyacc.lr1dfa.LR1DFA``. These
23 classes are general-purpose and there is nothing to stop you pulling them out
24 and using them in your project (subject to the license which is GPLv2). At the
25 moment the classes are only used for generating automata to be used later, but
26 there are commented functions in each class that can perform parsing directly.
27
28 Step 4 is fairly straightforward Python code using ``str.format()``. Basically
29 it reads a skeleton file line-by-line looking for special lines similar to::
30
31   # GENERATE SECTION1
32
33 and then expands these into a sequence like::
34
35   # GENERATE SECTION1 BEGIN
36   ...
37   # GENERATE SECTION1 END
38
39 where the middle part (denoted ``...``) is printed with a ``str.format()``
40 format string containing the C or Python code to be inserted into the skeleton.
41
42 Often this C or Python code will contain repetitive material (e.g. switch cases
43 or action handler functions or similar) and these are sent into the format
44 string as an string argument, which is a ``str.join()`` of a list of items,
45 each formatted in turn with ``str.format()``. These may also contain repetitive
46 material embedded in a similar manner, up to several levels deep. To illustrate
47 how this works, here's an example where we are given a list of strings in the
48 variable ``lines`` and we generate C code to write them out with ``fwrite()``::
49
50   sys.stdout.write(
51     '''#include <stdio.h>
52
53   int main(void) {{
54   {0:s}}}
55   '''.format(
56       ''.join(
57         [
58           '  fwrite(stdout, 1, {0:d}, "{1:s}");\n'.format(
59             len(line),
60             line
61           )
62           for line in lines
63         ]
64       )
65     )
66   )