Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/javadoc/JavadocTransformer.java

raw symbols SCIP
1 /* ****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 **************************************************************************** */
16 package org.jpype.javadoc;
17
18 import java.nio.file.Path;
19 import java.nio.file.Paths;
20 import java.util.HashMap;
21 import java.util.LinkedList;
22 import java.util.Map;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import org.jpype.html.Html;
26 import org.w3c.dom.Document;
27 import org.w3c.dom.Element;
28 import org.w3c.dom.Node;
29 import org.w3c.dom.Text;
30
31 /**
32 * Transform the document into a form suitable for ReStructured Text.
33 *
34 * The goal of this is to convert all inline markup into rst and leave markup by
35 * section, paragraph to be used by the renderer.
36 *
37 * @author nelson85
38 */
39 public class JavadocTransformer
40 {
41
42 final static Pattern ARGS_PATTERN = Pattern.compile(".*\\((.*)\\).*");
43
44 public Node transformDescription(Class cls, Node node)
45 {
46 try
47 {
48 Workspace ws = new Workspace(cls);
49 DomUtilities.traverseDFS(node, this::fixEntities, Node.TEXT_NODE);
50 DomUtilities.traverseChildren(node, this::handleDescription, Node.ELEMENT_NODE, ws);
51 DomUtilities.traverseDFS(node, this::pass1, Node.ELEMENT_NODE, ws);
52 return node;
53 } catch (Exception ex)
54 {
55 throw new JavadocException(node, ex);
56 }
57 }
58
59 /**
60 * Convert a Javadoc member description into markup for ReStructure Text
61 * rendering.
62 *
63 * This will mutilate the node.
64 *
65 * @param node
66 */
67 public Node transformMember(Class cls, Node node)
68 {
69 try
70 {
71 Workspace ws = new Workspace(cls);
72 DomUtilities.traverseDFS(node, this::fixEntities, Node.TEXT_NODE);
73 DomUtilities.traverseChildren(node, this::handleMembers, Node.ELEMENT_NODE, ws);
74 DomUtilities.traverseDFS(node, this::pass1, Node.ELEMENT_NODE, ws);
75 return node;
76 } catch (Exception ex)
77 {
78 throw new JavadocException(node, ex);
79 }
80
81 }
82
83 //<editor-fold desc="members" defaultstate="description">
84 void handleDescription(Node node, Workspace data)
85 {
86 Element e = (Element) node;
87 String name = e.getTagName();
88 Document doc = e.getOwnerDocument();
89 Node parent = node.getParentNode();
90 if (name.equals("dl") && !data.hr)
91 {
92 parent.removeChild(node);
93 } else if (name.equals("br"))
94 {
95 parent.removeChild(node);
96 } else if (name.equals("hr"))
97 {
98 data.hr = true;
99 parent.removeChild(node);
100 } else if (name.equals("pre")
101 || // Javadoc pre-17
102 (name.equals("div") && e.getAttribute("class").equals("type-signature"))) // Javadoc 17+
103 {
104 DomUtilities.removeWhitespace(node);
105 doc.renameNode(node, null, "signature");
106 } else if (name.equals("div"))
107 {
108 doc.renameNode(node, null, "description");
109 DomUtilities.clearAttributes(node);
110 } else if (name.equals("dl"))
111 {
112 doc.renameNode(node, null, "details");
113 DomUtilities.traverseChildren(node, this::handleDetails,
114 Node.ELEMENT_NODE, data);
115 } else
116 {
117 throw new RuntimeException("Unknown item at top level " + name);
118 }
119 }
120
121 //</editor-fold>
122 //<editor-fold desc="members" defaultstate="collapsed">
123 void handleMembers(Node node, Workspace ws)
124 {
125 Element e = (Element) node;
126 String name = e.getTagName();
127 Document doc = e.getOwnerDocument();
128
129 if (name.equals("h4") || name.equals("h3")) // h4 for Javadoc pre-17, h3 for Javadoc 17+
130 {
131 doc.renameNode(node, null, "title");
132 } else if (name.equals("pre")
133 || // Javadoc pre-17
134 (name.equals("div") && (e.getAttribute("class").equals("member-signature")))) // Javadoc 17+
135 {
136 doc.renameNode(node, null, "signature");
137 DomUtilities.traverseDFS(node, this::pass1, Node.ELEMENT_NODE, ws);
138 // We need to get the types from here for the parameters
139 DomUtilities.removeWhitespace(node);
140 String content = node.getTextContent();
141 Matcher m = ARGS_PATTERN.matcher(content);
142 if (m.matches())
143 {
144 LinkedList<String> types = new LinkedList<>();
145 for (String s : m.group(1).split(", "))
146 {
147 String[] parts = s.split("\u00a0", 2);
148 types.add(parts[0]);
149 }
150 ws.types = types;
151 }
152 } else if (name.equals("div"))
153 {
154 doc.renameNode(node, null, "description");
155 DomUtilities.clearAttributes(node);
156 } else if (name.equals("dl"))
157 {
158 doc.renameNode(node, null, "details");
159 DomUtilities.traverseChildren(node, this::handleDetails,
160 Node.ELEMENT_NODE, ws);
161 } else
162 {
163 throw new RuntimeException("Unknown item at top level " + name);
164 }
165 }
166
167 public final static Map<String, String> DETAIL_SECTIONS;
168
169 static
170 {
171 DETAIL_SECTIONS = new HashMap<>();
172 Map<String, String> ds = DETAIL_SECTIONS;
173 ds.put("Author:", "author");
174 ds.put("Since:", "since");
175 ds.put("Parameters:", "parameters");
176 ds.put("Returns:", "returns");
177 ds.put("Overrides:", "overrides");
178 ds.put("See Also:", "see");
179 ds.put("API Note:", "api_note");
180 ds.put("Version:", "version");
181 ds.put("Type Parameters:", "typeparams");
182 ds.put("Specified by:", "specified");
183 ds.put("Throws:", "throws");
184 ds.put("Implementation Requirements:", "requirements");
185 ds.put("Implementation Note:", "impl_note");
186 }
187
188 void handleDetails(Node node, Workspace ws)
189 {
190 Element e = (Element) node;
191 String name = e.getTagName();
192 Document doc = e.getOwnerDocument();
193 Node parent = e.getParentNode();
194 if (name.equals("dt"))
195 {
196 String key = node.getTextContent().trim();
197 if (DETAIL_SECTIONS.containsKey(key))
198 {
199 doc.renameNode(node, null, DETAIL_SECTIONS.get(key));
200 } else if (key.startsWith("See "))
201 {
202 doc.renameNode(node, null, "jls");
203 } else
204 {
205 System.err.println("Bad detail key '" + key + "'");
206 }
207 ws.key = node.getNodeName();
208 ws.section = node;
209 DomUtilities.clearChildren(ws.section);
210 }
211 if (name.equals("dd"))
212 {
213 if (ws.key.equals("parameters"))
214 {
215 Node first = node.getFirstChild(); // First is <code>varname</code>
216 Node second = first.getNextSibling(); // Second is " - desc"
217 Element elem = doc.createElement("parameter");
218 elem.setAttribute("name", first.getTextContent());
219 elem.setAttribute("type", ws.types.removeFirst());
220 String value = second.getNodeValue();
221 second.setNodeValue(value.substring(3)); // Remove " - "
222 node.removeChild(first);
223 DomUtilities.transferContents(elem, node);
224 ws.section.appendChild(elem);
225 parent.removeChild(node);
226 } else if (ws.key.equals("throws"))
227 {
228 Node first = node.getFirstChild(); // First is <code><a>exc</a></code>
229 Node second = first.getNextSibling(); // Second is " - desc"
230 Element elem = doc.createElement("exception");
231 DomUtilities.traverseDFS(first, this::pass1, Node.ELEMENT_NODE, ws);
232 elem.setAttribute("name", first.getTextContent());
233 if (second != null)
234 {
235 String value = second.getNodeValue();
236 second.setNodeValue(value.substring(3)); // Remove " - "
237 }
238 node.removeChild(first);
239 DomUtilities.transferContents(elem, node);
240 ws.section.appendChild(elem);
241 parent.removeChild(node);
242 } else
243 {
244 // Normalize the node and transfer it to the section
245 DomUtilities.transferContents(ws.section, node);
246 DomUtilities.traverseDFS(ws.section, this::pass1, Node.ELEMENT_NODE, ws);
247 DomUtilities.removeWhitespace(ws.section);
248 parent.removeChild(node);
249 return;
250 }
251 }
252 }
253
254 static class Workspace
255 {
256
257 private final Class cls;
258 boolean hr = false;
259 String key;
260 Node section;
261 private LinkedList<String> types;
262
263 Workspace(Class cls)
264 {
265 this.cls = cls;
266 }
267 }
268
269 //</editor-fold>
270 //<editor-fold desc="contents" defaultstate="collapsed">
271 /**
272 * Convert any html entities found the text.
273 *
274 * @param node
275 */
276 void fixEntities(Node node)
277 {
278 Text n = (Text) node;
279 String s = Html.decode(n.getTextContent());
280 n.setTextContent(s);
281 }
282
283 // This corresponds to any simple inline markup transformation.
284 final static String[] PASS1 = new String[]
285 {
286 "cite", "\"%s\"",
287 "code", ":code:`%s`",
288 "pre", ":code:`%s`",
289 "tt", "``%s``",
290 "i", "*%s*",
291 "em", "*%s*",
292 "strong", "**%s**",
293 "b", "**%s**",
294 "sup", " :sup:`%s` ",
295 "sub", " :sub:`%s` ",
296 "small", ":sub:`%s`",
297 "span", "%s",
298 "nop", "%s",
299 "font", "%s",
300 "var", "*%s*",
301 };
302
303 /**
304 * Get a bunch of simple substitutions.
305 *
306 * @param node
307 */
308 void pass1(Node node, Workspace ws)
309 {
310 Element e = (Element) node;
311 String name = e.getTagName();
312 Document doc = e.getOwnerDocument();
313 Node parent = e.getParentNode();
314 if (parent == null)
315 return;
316
317 // Pre is something used to mark code.
318 if (name.equals("pre"))
319 {
320 if (DomUtilities.containsNL(e))
321 {
322 doc.renameNode(node, null, "codeblock");
323 name = "codeblock";
324 } else
325 {
326 doc.renameNode(node, null, "code");
327 name = "code";
328 }
329 }
330
331 // <pre><code> is a common javadoc idiom.
332 if (name.equals("code") && (parent.getNodeName().equals("pre")
333 || parent.getNodeName().equals("blockquote")))
334 {
335 doc.renameNode(parent, null, "codeblock");
336 DomUtilities.mergeNode(parent, node);
337 return;
338 }
339
340 if (name.equals("codeblock") && parent.getNodeName().equals("pre"))
341 {
342 if (DomUtilities.containsNL(node))
343 {
344 doc.renameNode(parent, null, "codeblock");
345 } else
346 doc.renameNode(parent, null, "code");
347 DomUtilities.mergeNode(parent, node);
348 return;
349 }
350
351 // <a ...><code> is used to reference members and classes.
352 if (name.equals("code") && parent.getNodeName().equals("a"))
353 {
354 Element eparent = (Element) parent;
355 String href = this.toReference(ws, eparent.getAttribute("href"));
356 DomUtilities.clearChildren(parent);
357 parent.appendChild(doc.createTextNode(href));
358 return;
359 }
360
361 // <code><a> is also used.
362 if (name.equals("a") && parent.getNodeName().equals("code"))
363 {
364 String href = this.toReference(ws, e.getAttribute("href"));
365 DomUtilities.clearChildren(parent);
366 doc.renameNode(parent, null, "nop");
367 parent.appendChild(doc.createTextNode(href));
368 return;
369 }
370
371 // <a> by itself is usually external references.
372 if (name.equals("a"))
373 {
374 String href = e.getAttribute("href");
375 if (href.startsWith("http:") || href.startsWith("shttp:"))
376 {
377 String content = node.getTextContent();
378 content = String.format("`%s <%s>`", content, href);
379 parent.replaceChild(doc.createTextNode(content), node);
380 return;
381 }
382 href = this.toReference(ws, href);
383 if (href == null)
384 parent.replaceChild(doc.createTextNode(node.getTextContent()), node);
385 else
386 parent.replaceChild(doc.createTextNode(href), node);
387 return;
388 }
389
390 // Apply inline transformations.
391 for (int i = 0; i < PASS1.length; i += 2)
392 {
393 if (name.equals(PASS1[i]))
394 {
395 String s2 = e.getTextContent();
396 if (s2 == null)
397 e.getParentNode().removeChild(e);
398 else
399 e.getParentNode().replaceChild(doc.createTextNode(String.format(PASS1[i + 1], s2.trim())), e);
400 return;
401 }
402 }
403
404 }
405
406 /**
407 * Convert a reference into method or class.
408 *
409 * This currently only deals with local links. External links are elsewhere.
410 *
411 * @param ws
412 * @param href
413 * @return
414 */
415 public String toReference(Workspace ws, String href)
416 {
417 try
418 {
419 Path p = Paths.get(ws.cls.getName().replace('.', '/'));
420 if (href.startsWith("#"))
421 {
422 // technically it may be a field, but we can't tell currently.
423 Path q = p.resolve(href.substring(1).trim())
424 .normalize();
425 if (q.startsWith(".."))
426 q = q.subpath(2, q.getNameCount());
427 String r = q.toString()
428 .replace('/', '.')
429 .replace('\\', '.')
430 .replaceAll("\\(.*\\)", "")
431 .replaceAll("-.*", "");
432 return String.format(":meth:`~%s`", r);
433 } else if (href.contains("#"))
434 {
435 // technically it may be a field, but we can't tell currently.
436 Path q = p.getParent()
437 .resolve(href.trim())
438 .normalize();
439 if (q.startsWith(".."))
440 q = q.subpath(2, q.getNameCount());
441 String r = q.toString()
442 .replace('/', '.')
443 .replace('\\', '.')
444 .replaceAll("\\(.*\\)", "")
445 .replaceAll("-.*", "")
446 .replaceAll(".html#", ".");
447 return String.format(":meth:`~%s`", r);
448 } else
449 {
450 Path q = p.getParent()
451 .resolve(href.trim())
452 .normalize();
453 if (q.startsWith(".."))
454 q = q.subpath(2, q.getNameCount());
455 String r = q.toString()
456 .replace('/', '.')
457 .replace('\\', '.')
458 .replaceAll("-.*", "")
459 .replaceAll(".html", "");
460 return String.format(":class:`~%s`", r);
461 }
462 } catch (Exception ex)
463 {
464 // There is a lot of ways this can go wrong. If all else fails
465 // return null so that we can just remove the hyperlink.
466 return null;
467 }
468 }
469
470 //</editor-fold>
471 }