Debian Codegraph @

documentation/source/codeguide.rst

raw
1
2 .. _codeguide:
3
4 How It Works
5 ============
6
7
8 There are three main sections to Breathe: parser, finders and renderers.
9 Briefly:
10
11 **parser**
12 Responsible for reading the doxygen xml output and creating objects
13 representing the data. Found in ``breathe.parser``.
14
15 **finders**
16 Responsible for finding reference objects within the output from the
17 parser. Found in ``breathe.finder``.
18
19 **renderers**
20 Responsible for producing reStructuredText nodes to represent the objects
21 that the finders have found. The renderers generally descend through the
22 object hierarchies rendering the objects, their children, their children's
23 children and so on. Found in ``breathe.renderer``.
24
25 The following flow chart shows how the different components of Breathe transform
26 data. The shaded region indicates which components are part of Breathe.
27
28 .. image:: ../assets/BreatheFlowChart.svg
29 :width: 500
30 :alt: A flow chart showing that the initial input format is code. Doxgyen converts
31 code to XML. The Breathe parser converts XML to a hierarchy of python objects.
32 The Breathe Filter identifies which of these objects need to be rendered. The
33 Breathe Renderer converts these objects into reStructuredText (RST) nodes.
34 Finally, the RST node objects are passed to Sphinx to be turned into actual
35 HTML or LaTeX documents.
36 :class: only-light
37 :align: center
38
39 .. image:: ../assets/BreatheFlowChart_DarkMode.svg
40 :width: 500
41 :alt: A flow chart showing that the initial input format is code. Doxgyen converts
42 code to XML. The Breathe parser converts XML to a hierarchy of python objects.
43 The Breathe Filter identifies which of these objects need to be rendered. The
44 Breathe Renderer converts these objects into reStructuredText (RST) nodes.
45 Finally, the RST node objects are passed to Sphinx to be turned into actual
46 HTML or LaTeX documents.
47 :class: only-dark
48 :align: center
49
50
51 Parser
52 ------
53
54 The parser's job is to parse the doxygen xml output and create a hierarchy of
55 Python objects to represent the xml data.
56
57 Doxygen XML Output
58 ~~~~~~~~~~~~~~~~~~
59
60 The xml output from doxygen comes in multiple files. There is always an
61 ``index.xml`` file which is a central reference point and contains a list of all
62 the other files that have been generated by doxygen and an indication of what
63 they contain.
64
65 For example, in ``examples/doxygen/func/xml`` directory, the ``index.xml`` file
66 contains:
67
68 .. code-block:: xml
69
70 <?xml version='1.0' encoding='UTF-8' standalone='no'?>
71 <doxygenindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="index.xsd" version="1.7.2">
72 <compound refid="class_test" kind="class"><name>Test</name>
73 <member refid="class_test_1a45b6a232a4499f8ce37062eab5451570" kind="function"><name>member</name></member>
74 </compound>
75 <compound refid="func_8h" kind="file"><name>func.h</name>
76 </compound>
77 </doxygenindex>
78
79 This suggests there is additional information about a class called **Test**
80 which has a function called **member**. Additionally there is some more
81 information about a file called **func.h**.
82
83 Now, the ``refid`` attribute on the ``compound`` xml nodes gives an indication
84 of where the additional information can be found. So for the **Test** class, we
85 should look in ``class_test.xml``, which we get by simply appending ``.xml`` to
86 the ``refid`` value, and for the **func.h** file we should look in
87 ``func_8h.xml``.
88
89 So the ``index.xml`` file is unique in its role and has its own structure which
90 is defined in the ``index.xsd`` file which you will also find in the same
91 directory. All the other files, the ones referenced by the ``index.xml`` file, follow
92 another structure. This is described in ``compound.xsd`` file so we call these
93 other files **compound** files. These are generally longer than the
94 ``index.xml`` file and contain all the specific information you might expect
95 from doxygen, including any documentation you added to your code as doxygen
96 markup.
97
98 Have a look at ``examples/doxygen/func/xml/class_test.xml`` for a fairly short
99 example.
100
101
102 Doing the Parsing
103 ~~~~~~~~~~~~~~~~~
104
105 To get things up and running quickly, I have used the `generateDS
106 <https://pypi.org/project/generateDS/>`_ project to help create
107 classes to parse the doxygen xml output. The script automatically creates the
108 ``compound.py``, ``compoundsuper.py``, ``index.py`` and ``indexsuper.py`` files
109 that you can see inside ``breathe/parser/doxygen``.
110
111 So what is the difference between ``index.py`` and ``indexsuper.py``, and
112 ``compound.py`` and ``compoundsuper.py``? These files allow us to separate the
113 bulk of the automatically generated code from the code changes we might want to
114 make. There are a large number of classes in the ``...super.py`` files and each
115 one has a basic derived class in the corresponding non-super files.
116
117 It is designed so that all the hard work done by the generated code is
118 done in the ``...super.py`` files and if we need to make changes we can do them
119 in the derived classes in the non-super files and if we ever need to regenerate
120 the code, we only regenerate the ``...super.py`` files and so we don't lose our
121 changes in the process.
122
123 The end result is that for the parsing, we have written relatively little code,
124 but have a large amount automatically generated for us. This has only been done
125 once and it seems relatively unlikely that we'll do it again. The entry points to
126 the parsing code is the ``parse`` functions at the bottom of the
127 ``breathe.parser.doxygen.compound`` and ``breathe.parser.doxygen.index``.
128
129 I have never really examined the details of the parsing but you can see that
130 there is a class for each node type you are likely to find in the xml files. I
131 say "node type" instead of just "node" because different nodes can share the
132 same type and there is one class per type. For example, there are
133 **detaileddescription** nodes and **briefdescription** nodes which are both of
134 type **descriptionType**. If we look in ``breathe.parser.doxygen.compoundsuper``
135 we see a **descriptionType** class and in
136 ``breathe.parser.doxygen.compound`` we see a **descriptionTypeSub** class which
137 is derived from **descriptionType**.
138
139
140 Our Changes
141 ~~~~~~~~~~~
142
143 You'll notice there are some classes in the non-super files that have some
144 additional code in them. This tends to be adjusting the ``buildChildren`` member
145 function in the derived class to extend or override the one in the
146 automatically generated base class.
147
148 We have to do this sometimes as it seems the original code we generated with
149 ``generateDS`` fails to construct the children of some classes. The
150 ``generateDS`` scripts uses the descriptions in the ``.xsd`` files to determine
151 what classes to generate and what nodes can be the children of other nodes. It
152 is possible that the doxygen ``.xsd`` files contain levels of abstraction that
153 the ``generateDS`` project did not cope with at the time I used it. It is
154 possible that newer versions would handle it better but for the moment I'm
155 content updating the derived classes to handle the cases I see missing.
156
157
158
159 Finders
160 -------
161
162 The finder classes have a relatively small but important job of finding objects
163 in the hierarchy generated by the parsers. For example, when a user specifies a
164 particular class for the :ref:`doxygenclass directive <doxygenclass>`, we use
165 the finder classes to go and find the object corresponding to that class.
166
167 In fact, if you look closely, it is the finders that use the parser entry points
168 to parse the xml and then find the objects. The finders also use ``Filter``
169 objects to actually figure out if they have found what they are looking for.
170
171 The finder is given a hierarchy of filter objects which are designed to match
172 at different levels of the XML hierarchy. Filters can also represent logical
173 conditions such as 'and' and 'or'.
174
175 More Details, Please
176 ~~~~~~~~~~~~~~~~~~~~
177
178 So initially, we create a finder to look at the root of the hierarchy: the
179 **doxygenTypeSub** node. That finder, handily called
180 **DoxygenTypeSubItemFinder** (you'll notice a lot of that) looks through all the
181 child compound nodes of the **doxygenTypeSub** node and tries a compound-level
182 match against each of them and if something matches it creates a
183 **CompoundTypeSubItemFinder** to look further.
184
185 In turn, that checks each of its member child nodes with a member-level match
186 and if it finds one it creates a **MemberTypeSubItemFinder** (see the pattern?)
187 and that does another check. The interesting part is, if that is successful, the
188 **CompoundTypeSubItemFinder** finds the corresponding xml file that has more
189 information in it (remember ``refid + .xml``?) and parses that and creates
190 another finder to start looking in there. This time it is a
191 **DoxygenTypeSubItemFinder** from the ``breathe.finder.doxygen.compound``
192 module. And the search goes on until we find an object to return for rendering.
193
194 If the **CompoundTypeSubItemFinder** fails to find any deeper levels to match
195 against then it returns itself as it must be the target we're interested in.
196
197 As stated, the job of the finder is to find a single node for the renderers to
198 starting rendering to reStructuredText. That is all the finder does.
199
200
201 Renderers
202 ---------
203
204 Finally, the bit that really does something we care about. Rendering is the art
205 of turning whatever object we've found in the hierarchy into reStructuredText
206 nodes. This almost invariably means most of its children as well.
207
208 Much like with the finder classes, we start off creating a renderer for a
209 particular parser object and then it looks at its children and uses the renderer
210 factory to create appropriate renderers for those objects and tells them to
211 render and they look at their object's children and create appropriate renderers
212 for those and so on and so forth.
213
214 The node we start at is determined by the finder and ultimately by the user. The
215 whole process is kicked off by the ``Builder`` class, though it doesn't really
216 do much. The aim of the renderers is to return a list of reStructuredText nodes
217 which is passed back to Sphinx to render into whatever you're final output
218 format is.
219
220 There are two complicated bits here. All the different renderers and all the
221 different reStructuredText nodes.
222
223 Different Renderers
224 ~~~~~~~~~~~~~~~~~~~
225
226 Just like with the parsers, there is one renderer per node type. In fact there
227 is one renderer class per parser class and they are named almost the same and
228 are designed to match up. The renderers look at the data on the instance
229 of the corresponding parser class that they have been given and grab the
230 interesting bits and return reStructuredText nodes.
231
232 For reference on what there is to render, you can look at the parser class
233 definitions or at the raw xml to see what attributes there are to render.
234 Sometimes if something isn't appearing in the final output, it is because the
235 renderer isn't returning an reStructuredText representation of it so the
236 rendering code needs to be updated, and sometimes it is because the parser
237 classes are not picking it up properly so both the parser and the renderer code
238 needs to be updated.
239
240 Given a little bit of time, you get used to chasing through the xml nodes,
241 the parser classes and the corresponding renderers to figure out where all the
242 information is ending up.
243
244
245 reStructuredText Nodes
246 ~~~~~~~~~~~~~~~~~~~~~~
247
248 We use the reStructuredText API as provided by the fabulous docutils project
249 and extended by Sphinx itself. For the most part, they are fairly straight
250 forward and they are certainly well named.
251
252 Unfortunately there are a lot of nodes and only certain ways of combining them.
253 It is also not always clear what arguments their constructs take. Whilst I'm
254 sure it would be possible to figure it out with time and the appropriate source
255 code, the use of them is not something I've found very well documented and my
256 code largely operates on a basis of trial and error.
257
258 One day I'm sure I'll be enlightened, until then expect fairly naive code.
259
260 Testing
261 -------
262
263 Tests for Breathe can be found in the ``tests`` directory. They can be run by
264 running ``make test`` in your terminal (assuming that you have pytest installed).
265 The bulk of Breathe's test suite is in ``tests/test_renderer.py``, and this is
266 where any renderer-related tests should be added. This documentation will focus
267 on how to write more renderer tests, as this is the most common region of the code
268 to add new features to and perhaps the hardest to test.
269
270 Creating Python Doxygen Nodes
271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
272
273 As indicated in the diagram at the top of this page, the renderer is expecting to
274 be run after the parser has created a hierarchy of python objects. Thus, there is
275 a lot of set-up that would usually happen before the renderer is invoked. For ease
276 of testing, it is often expedient to skip straight to the step where you have a
277 hierarchy of Python objects representing some hypothetical XML that doxygen could
278 have produced.
279
280 ``test_renderer.py`` contains a number of classes designed to assist with this
281 process. For just about any node that could show up in the XML produced by doxygen,
282 there is a class that quickly instantiates it in Python. For example, if you want
283 to test the rendering of a member definition, you can use the ``WrappedMemebrDef``
284 class. Figuring out how nodes fit together can be challenging; until you're
285 comfortable with the type of XML produced by doxygen, the easiest process is likely:
286
287 #. Write C++ code containing the behavior you would like to test.
288 #. Run Doxygen on it, which will produce an XML file (likely inside a directory
289 called xml within your doxygen output directory)
290 #. Re-build the relevant part of the xml file in Python using the ``Wrapped*``
291 classes.
292
293 For example, lets say you have a struct representing a cat.
294
295 Your C++ might look something like this (inspired by Sy Brand's
296 `blog post <https://devblogs.microsoft.com/cppblog/clear-functional-c-documentation-with-sphinx-breathe-doxygen-cmake/>`_):
297
298 .. code-block:: cpp
299
300 /**
301 A fluffy feline
302 */
303 struct cat {
304 /**
305 Make this cat look super cute
306 */
307 void make_cute();
308 };
309
310 Running Doxygen on this might give you XML something like this:
311
312 .. code-block:: xml
313
314 <?xml version='1.0' encoding='UTF-8' standalone='no'?>
315 <doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.9.7" xml:lang="en-US">
316 <compounddef id="structcat" kind="struct" language="C++" prot="public">
317 <compoundname>cat</compoundname>
318 <includes refid="test__cpp_8hpp" local="no">test_cpp.hpp</includes>
319 <sectiondef kind="public-func">
320 <memberdef kind="function" id="structcat_1" prot="public" static="no" const="no" explicit="no" inline="no" virt="non-virtual">
321 <type>void</type>
322 <definition>void cat::make_cute</definition>
323 <argsstring>()</argsstring>
324 <name>make_cute</name>
325 <qualifiedname>cat::make_cute</qualifiedname>
326 <briefdescription>
327 </briefdescription>
328 <detaileddescription>
329 <para>Make this cat look super cute </para>
330 </detaileddescription>
331 <inbodydescription>
332 </inbodydescription>
333 <location file="test_cpp.hpp" line="8" column="8"/>
334 </memberdef>
335 </sectiondef>
336 <briefdescription>
337 </briefdescription>
338 <detaileddescription>
339 <para>A fluffy feline </para>
340 </detaileddescription>
341 <location file="test_cpp.hpp" line="4" column="1" bodyfile="test_cpp.hpp" bodystart="4" bodyend="15"/>
342 <listofallmembers>
343 <member refid="structcat_1" prot="public" virt="non-virtual"><scope>cat</scope><name>make_cute</name></member>
344 </listofallmembers>
345 </compounddef>
346 </doxygen>
347
348 There's a lot here. For now, let's just say we're testing something related to
349 member function definitions, and we only need to test that part of the
350 hierarchy. We can load the ``memberdef`` part of this XML into a
351 ``WrappedMemberDef`` object as follows:
352
353 .. code-block:: python
354
355 member_def = WrappedMemberDef(
356 kind="function", # From "kind" in open memberdef tag
357 definition="void cat::make_cute", # From <definition> tag
358 type="void", # From <type> tag
359 name="make_cute", # From <name> tag
360 argstring="()", # From <argstring> tag
361 virt="non-virtual", # From "virt" in open memberdef tag
362 )
363
364 As you can see, all of the arguments to the constructor are pulled directly out
365 of the XML, either from options on the original memberdef or tags nested under
366 it. There are a lot more optional arguments that can be provided to specify
367 additional details of the memberdef.
368
369 More advanced hierarchies can be represented by nesting nodes inside each
370 other. For example, if our function took arguments, it would have ``<param>``
371 tags nested within it. We could represent these as a list of ``WrappedParam``
372 objects passed into the ``param`` keyword argument.
373
374 To test that the node renders correctly, you can use the ``render`` function
375 provided in ``test_renderer.py``:
376
377 .. code-block:: python
378
379 # Render the node and grab its description
380 signature = find_node(render(app, member_def), "desc_signature")
381 # You can now examine the contents of signature.astext() and assert that
382 # they are as expected
383
384
385 Mocks
386 ~~~~~
387
388 If you want to do more elaborate tests, it is useful to be aware of the various
389 Mock objects provided in ``test_renderer.py``. Because the renderer is
390 expecting to be executing in the context of a full Sphinx run, there are a lot
391 of objects that it is expecting to have access to. For example, rendering some
392 nodes requires making reference to a context object. The ``MockContext`` class
393 can serve as a stand-in.