001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2021 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.meta;
021
022import java.util.ArrayDeque;
023import java.util.Arrays;
024import java.util.Collections;
025import java.util.Deque;
026import java.util.HashMap;
027import java.util.HashSet;
028import java.util.LinkedHashSet;
029import java.util.Locale;
030import java.util.Map;
031import java.util.Optional;
032import java.util.Set;
033import java.util.regex.Matcher;
034import java.util.regex.Pattern;
035import java.util.stream.Collectors;
036
037import javax.xml.parsers.ParserConfigurationException;
038import javax.xml.transform.TransformerException;
039
040import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
041import com.puppycrawl.tools.checkstyle.api.DetailAST;
042import com.puppycrawl.tools.checkstyle.api.DetailNode;
043import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
044import com.puppycrawl.tools.checkstyle.api.TokenTypes;
045import com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck;
046import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
047
048/**
049 * Class for scraping module metadata from the corresponding class' class-level javadoc.
050 */
051@FileStatefulCheck
052public class JavadocMetadataScraper extends AbstractJavadocCheck {
053
054    /** Module details store used for testing. */
055    private static final Map<String, ModuleDetails> MODULE_DETAILS_STORE = new HashMap<>();
056
057    /** Regular expression for property location in class-level javadocs. */
058    private static final Pattern PROPERTY_TAG = Pattern.compile("\\s*Property\\s*");
059
060    /** Regular expression for property type location in class-level javadocs. */
061    private static final Pattern TYPE_TAG = Pattern.compile("^ Type is\\s.*");
062
063    /** Regular expression for property validation type location in class-level javadocs. */
064    private static final Pattern VALIDATION_TYPE_TAG =
065            Pattern.compile("\\s.*Validation type is\\s.*");
066
067    /** Regular expression for property default value location in class-level javadocs. */
068    private static final Pattern DEFAULT_VALUE_TAG = Pattern.compile("^ Default value is:*.*");
069
070    /** Regular expression for check example location in class-level javadocs. */
071    private static final Pattern EXAMPLES_TAG =
072            Pattern.compile("\\s*To configure the (default )?check.*");
073
074    /** Regular expression for module parent location in class-level javadocs. */
075    private static final Pattern PARENT_TAG = Pattern.compile("\\s*Parent is\\s*");
076
077    /** Regular expression for module violation messages location in class-level javadocs. */
078    private static final Pattern VIOLATION_MESSAGES_TAG =
079            Pattern.compile("\\s*Violation Message Keys:\\s*");
080
081    /** Regular expression for detecting ANTLR tokens(for e.g. CLASS_DEF). */
082    private static final Pattern TOKEN_TEXT_PATTERN = Pattern.compile("([A-Z_]{2,})+");
083
084    /** Regular expression for removal of @code{-} present at the beginning of texts. */
085    private static final Pattern DESC_CLEAN = Pattern.compile("-\\s");
086
087    /** Regular expression for file separator corresponding to the host OS. */
088    private static final Pattern FILE_SEPARATOR_PATTERN =
089            Pattern.compile(Pattern.quote(System.getProperty("file.separator")));
090
091    /** Regular expression for quotes. */
092    private static final Pattern QUOTE_PATTERN = Pattern.compile("\"");
093
094    /** Java file extension. */
095    private static final String JAVA_FILE_EXTENSION = ".java";
096
097    /**
098     * This set contains faulty property default value which should not be written to the XML
099     * metadata files.
100     */
101    private static final Set<String> PROPERTIES_TO_NOT_WRITE = Collections.unmodifiableSet(
102            new HashSet<>(Arrays.asList(
103                    "null",
104                    "the charset property of the parent <a href=https://checkstyle.org/"
105                        + "config.html#Checker>Checker</a> module"
106    )));
107
108    /**
109     * Format for exception message for missing type for check property.
110     */
111    private static final String PROP_TYPE_MISSING = "Type for property '%s' is missing";
112
113    /**
114     * Format for exception message for missing default value for check property.
115     */
116    private static final String PROP_DEFAULT_VALUE_MISSING =
117        "Default value for property '%s' is missing";
118
119    /** ModuleDetails instance for each module AST traversal. */
120    private ModuleDetails moduleDetails;
121
122    /**
123     * Boolean variable which lets us know whether violation message section is being scraped
124     * currently.
125     */
126    private boolean scrapingViolationMessageList;
127
128    /**
129     * Boolean variable which lets us know whether we should scan and scrape the current javadoc
130     * or not. Since we need only class level javadoc, it becomes true at its root and false after
131     * encountering {@code JavadocTokenTypes.SINCE_LITERAL}.
132     */
133    private boolean toScan;
134
135    /** DetailNode pointing to the root node of the class level javadoc of the class. */
136    private DetailNode rootNode;
137
138    /**
139     * Child number of the property section node, where parent is the class level javadoc root
140     * node.
141     */
142    private int propertySectionStartIdx;
143
144    /**
145     * Child number of the example section node, where parent is the class level javadoc root
146     * node.
147     */
148    private int exampleSectionStartIdx;
149
150    /**
151     * Child number of the parent section node, where parent is the class level javadoc root
152     * node.
153     */
154    private int parentSectionStartIdx;
155
156    @Override
157    public int[] getDefaultJavadocTokens() {
158        return new int[] {
159            JavadocTokenTypes.JAVADOC,
160            JavadocTokenTypes.PARAGRAPH,
161            JavadocTokenTypes.LI,
162            JavadocTokenTypes.SINCE_LITERAL,
163        };
164    }
165
166    @Override
167    public int[] getRequiredJavadocTokens() {
168        return getAcceptableJavadocTokens();
169    }
170
171    @Override
172    public void beginJavadocTree(DetailNode rootAst) {
173        if (isTopLevelClassJavadoc()) {
174            moduleDetails = new ModuleDetails();
175            toScan = false;
176            scrapingViolationMessageList = false;
177            propertySectionStartIdx = -1;
178            exampleSectionStartIdx = -1;
179            parentSectionStartIdx = -1;
180
181            final String filePath = getFileContents().getFileName();
182            String moduleName = getModuleSimpleName();
183            final String checkModuleExtension = "Check";
184            if (moduleName.contains(checkModuleExtension)) {
185                moduleName = moduleName.substring(0, moduleName.indexOf(checkModuleExtension));
186            }
187            moduleDetails.setName(moduleName);
188            moduleDetails.setFullQualifiedName(getPackageName(filePath));
189            moduleDetails.setModuleType(getModuleType());
190        }
191    }
192
193    @Override
194    public void visitJavadocToken(DetailNode ast) {
195        if (toScan) {
196            scrapeContent(ast);
197        }
198
199        if (ast.getType() == JavadocTokenTypes.JAVADOC) {
200            final DetailAST parent = getParent(getBlockCommentAst());
201            if (parent.getType() == TokenTypes.CLASS_DEF) {
202                rootNode = ast;
203                toScan = true;
204            }
205        }
206        else if (ast.getType() == JavadocTokenTypes.SINCE_LITERAL) {
207            toScan = false;
208        }
209    }
210
211    @Override
212    public void finishJavadocTree(DetailNode rootAst) {
213        moduleDetails.setDescription(getDescriptionText());
214        if (isTopLevelClassJavadoc()) {
215            if (getFileContents().getFileName().contains("test")) {
216                MODULE_DETAILS_STORE.put(moduleDetails.getFullQualifiedName(), moduleDetails);
217            }
218            else {
219                try {
220                    XmlMetaWriter.write(moduleDetails);
221                }
222                catch (TransformerException | ParserConfigurationException ex) {
223                    throw new IllegalStateException("Failed to write metadata into XML file for "
224                            + "module: " + getModuleSimpleName(), ex);
225                }
226            }
227        }
228    }
229
230    /**
231     * Method containing the core logic of scraping. This keeps track and decides which phase of
232     * scraping we are in, and accordingly call other subroutines.
233     *
234     * @param ast javadoc ast
235     */
236    public void scrapeContent(DetailNode ast) {
237        if (ast.getType() == JavadocTokenTypes.PARAGRAPH) {
238            if (isParentText(ast)) {
239                parentSectionStartIdx = getParentIndexOf(ast);
240                moduleDetails.setParent(getParentText(ast));
241            }
242            else if (isViolationMessagesText(ast)) {
243                scrapingViolationMessageList = true;
244            }
245            else if (exampleSectionStartIdx == -1
246                    && isExamplesText(ast)) {
247                exampleSectionStartIdx = getParentIndexOf(ast);
248            }
249        }
250        else if (ast.getType() == JavadocTokenTypes.LI) {
251            if (isPropertyList(ast)) {
252                if (propertySectionStartIdx == -1) {
253                    propertySectionStartIdx = getParentIndexOf(ast);
254                }
255                moduleDetails.addToProperties(createProperties(ast));
256            }
257            else if (scrapingViolationMessageList) {
258                moduleDetails.addToViolationMessages(getViolationMessages(ast));
259            }
260        }
261    }
262
263    /**
264     * Create the modulePropertyDetails content.
265     *
266     * @param nodeLi list item javadoc node
267     * @return modulePropertyDetail object for the corresponding property
268     */
269    private static ModulePropertyDetails createProperties(DetailNode nodeLi) {
270        final ModulePropertyDetails modulePropertyDetails = new ModulePropertyDetails();
271
272        final Optional<DetailNode> propertyNameNode = getFirstChildOfType(nodeLi,
273                JavadocTokenTypes.JAVADOC_INLINE_TAG, 0);
274        if (propertyNameNode.isPresent()) {
275            final DetailNode propertyNameTag = propertyNameNode.get();
276            final String propertyName = getTextFromTag(propertyNameTag);
277
278            final DetailNode propertyType = getFirstChildOfMatchingText(nodeLi, TYPE_TAG)
279                .orElseThrow(() -> {
280                    return new MetadataGenerationException(String.format(
281                        Locale.ROOT, PROP_TYPE_MISSING, propertyName)
282                    );
283                });
284            final String propertyDesc = DESC_CLEAN.matcher(
285                    constructSubTreeText(nodeLi, propertyNameTag.getIndex() + 1,
286                            propertyType.getIndex() - 1))
287                    .replaceAll(Matcher.quoteReplacement(""));
288
289            modulePropertyDetails.setDescription(propertyDesc.trim());
290            modulePropertyDetails.setName(propertyName);
291            modulePropertyDetails.setType(getTagTextFromProperty(nodeLi, propertyType));
292
293            final Optional<DetailNode> validationTypeNodeOpt = getFirstChildOfMatchingText(nodeLi,
294                VALIDATION_TYPE_TAG);
295            if (validationTypeNodeOpt.isPresent()) {
296                final DetailNode validationTypeNode = validationTypeNodeOpt.get();
297                modulePropertyDetails.setValidationType(getTagTextFromProperty(nodeLi,
298                    validationTypeNode));
299            }
300
301            final String defaultValue = getFirstChildOfMatchingText(nodeLi, DEFAULT_VALUE_TAG)
302                .map(defaultValueNode -> getPropertyDefaultText(nodeLi, defaultValueNode))
303                .orElseThrow(() -> {
304                    return new MetadataGenerationException(String.format(
305                        Locale.ROOT, PROP_DEFAULT_VALUE_MISSING, propertyName)
306                    );
307                });
308            if (!PROPERTIES_TO_NOT_WRITE.contains(defaultValue)) {
309                modulePropertyDetails.setDefaultValue(defaultValue);
310            }
311        }
312        return modulePropertyDetails;
313    }
314
315    /**
316     * Get tag text from property data.
317     *
318     * @param nodeLi javadoc li item node
319     * @param propertyMeta property javadoc node
320     * @return property metadata text
321     */
322    private static String getTagTextFromProperty(DetailNode nodeLi, DetailNode propertyMeta) {
323        final Optional<DetailNode> tagNodeOpt = getFirstChildOfType(nodeLi,
324                JavadocTokenTypes.JAVADOC_INLINE_TAG, propertyMeta.getIndex() + 1);
325        DetailNode tagNode = null;
326        if (tagNodeOpt.isPresent()) {
327            tagNode = tagNodeOpt.get();
328        }
329        return getTextFromTag(tagNode);
330    }
331
332    /**
333     * Clean up the default token text by removing hyperlinks, and only keeping token type text.
334     *
335     * @param initialText unclean text
336     * @return clean text
337     */
338    private static String cleanDefaultTokensText(String initialText) {
339        final Set<String> tokens = new LinkedHashSet<>();
340        final Matcher matcher = TOKEN_TEXT_PATTERN.matcher(initialText);
341        while (matcher.find()) {
342            tokens.add(matcher.group(0));
343        }
344        return String.join(",", tokens);
345    }
346
347    /**
348     * Performs a DFS of the subtree with a node as the root and constructs the text of that
349     * tree, ignoring JavadocToken texts.
350     *
351     * @param node root node of subtree
352     * @param childLeftLimit the left index of root children from where to scan
353     * @param childRightLimit the right index of root children till where to scan
354     * @return constructed text of subtree
355     */
356    private static String constructSubTreeText(DetailNode node, int childLeftLimit,
357                                               int childRightLimit) {
358        final StringBuilder result = new StringBuilder(1024);
359        DetailNode detailNode = node;
360
361        final Deque<DetailNode> stack = new ArrayDeque<>();
362        stack.addFirst(detailNode);
363        final Set<DetailNode> visited = new HashSet<>();
364        while (!stack.isEmpty()) {
365            detailNode = stack.getFirst();
366            stack.removeFirst();
367
368            if (!visited.contains(detailNode)) {
369                final String childText = detailNode.getText();
370                if (detailNode.getType() != JavadocTokenTypes.LEADING_ASTERISK
371                        && !TOKEN_TEXT_PATTERN.matcher(childText).matches()) {
372                    result.insert(0, detailNode.getText());
373                }
374                visited.add(detailNode);
375            }
376
377            for (DetailNode child : detailNode.getChildren()) {
378                if (child.getParent().equals(node)
379                        && (child.getIndex() < childLeftLimit
380                        || child.getIndex() > childRightLimit)) {
381                    continue;
382                }
383                if (!visited.contains(child)) {
384                    stack.addFirst(child);
385                }
386            }
387        }
388        return result.toString().trim();
389    }
390
391    /**
392     * Create the description text with starting index as 0 and ending index would be the first
393     * valid non zero index amongst in the order of {@code propertySectionStartIdx},
394     * {@code exampleSectionStartIdx} and {@code parentSectionStartIdx}.
395     *
396     * @return description text
397     */
398    private String getDescriptionText() {
399        final int descriptionEndIdx;
400        if (propertySectionStartIdx > -1) {
401            descriptionEndIdx = propertySectionStartIdx;
402        }
403        else if (exampleSectionStartIdx > -1) {
404            descriptionEndIdx = exampleSectionStartIdx;
405        }
406        else {
407            descriptionEndIdx = parentSectionStartIdx;
408        }
409        return constructSubTreeText(rootNode, 0, descriptionEndIdx - 1);
410    }
411
412    /**
413     * Create property default text, which is either normal property value or list of tokens.
414     *
415     * @param nodeLi list item javadoc node
416     * @param defaultValueNode default value node
417     * @return default property text
418     */
419    private static String getPropertyDefaultText(DetailNode nodeLi, DetailNode defaultValueNode) {
420        final Optional<DetailNode> propertyDefaultValueTag = getFirstChildOfType(nodeLi,
421                JavadocTokenTypes.JAVADOC_INLINE_TAG, defaultValueNode.getIndex() + 1);
422        final String result;
423        if (propertyDefaultValueTag.isPresent()) {
424            result = getTextFromTag(propertyDefaultValueTag.get());
425        }
426        else {
427            final String tokenText = constructSubTreeText(nodeLi,
428                    defaultValueNode.getIndex(), nodeLi.getChildren().length);
429            result = cleanDefaultTokensText(tokenText);
430        }
431        return result;
432    }
433
434    /**
435     * Get the violation message text for a specific key from the list item.
436     *
437     * @param nodeLi list item javadoc node
438     * @return violation message key text
439     */
440    private static String getViolationMessages(DetailNode nodeLi) {
441        final Optional<DetailNode> resultNode = getFirstChildOfType(nodeLi,
442                JavadocTokenTypes.JAVADOC_INLINE_TAG, 0);
443        return resultNode.map(JavadocMetadataScraper::getTextFromTag).orElse("");
444    }
445
446    /**
447     * Get text from {@code JavadocTokenTypes.JAVADOC_INLINE_TAG}.
448     *
449     * @param nodeTag target javadoc tag
450     * @return text contained by the tag
451     */
452    private static String getTextFromTag(DetailNode nodeTag) {
453        return Optional.ofNullable(nodeTag).map(JavadocMetadataScraper::getText).orElse("");
454    }
455
456    /**
457     * Returns the first child node which matches the provided {@code TokenType} and has the
458     * children index after the offset value.
459     *
460     * @param node parent node
461     * @param tokenType token type to match
462     * @param offset children array index offset
463     * @return the first child satisfying the conditions
464     */
465    private static Optional<DetailNode> getFirstChildOfType(DetailNode node, int tokenType,
466                                                            int offset) {
467        return Arrays.stream(node.getChildren())
468                .filter(child -> child.getIndex() >= offset && child.getType() == tokenType)
469                .findFirst();
470    }
471
472    /**
473     * Get joined text from all text children nodes.
474     *
475     * @param parentNode parent node
476     * @return the joined text of node
477     */
478    private static String getText(DetailNode parentNode) {
479        return Arrays.stream(parentNode.getChildren())
480                .filter(child -> child.getType() == JavadocTokenTypes.TEXT)
481                .map(node -> QUOTE_PATTERN.matcher(node.getText().trim()).replaceAll(""))
482                .collect(Collectors.joining(" "));
483    }
484
485    /**
486     * Get first child of parent node matching the provided pattern.
487     *
488     * @param node parent node
489     * @param pattern pattern to match against
490     * @return the first child node matching the condition
491     */
492    private static Optional<DetailNode> getFirstChildOfMatchingText(DetailNode node,
493                                                                    Pattern pattern) {
494        return Arrays.stream(node.getChildren())
495                .filter(child -> pattern.matcher(child.getText()).matches())
496                .findFirst();
497    }
498
499    /**
500     * Returns parent node, removing modifier/annotation nodes.
501     *
502     * @param commentBlock child node.
503     * @return parent node.
504     */
505    private static DetailAST getParent(DetailAST commentBlock) {
506        final DetailAST parentNode = commentBlock.getParent();
507        DetailAST result = parentNode;
508        if (result.getType() == TokenTypes.ANNOTATION) {
509            result = parentNode.getParent().getParent();
510        }
511        else if (result.getType() == TokenTypes.MODIFIERS) {
512            result = parentNode.getParent();
513        }
514        return result;
515    }
516
517    /**
518     * Traverse parents until we reach the root node (@code{JavadocTokenTypes.JAVADOC})
519     * child and return its index.
520     *
521     * @param node subtree child node
522     * @return root node child index
523     */
524    private static int getParentIndexOf(DetailNode node) {
525        DetailNode currNode = node;
526        while (currNode.getParent().getIndex() != -1) {
527            currNode = currNode.getParent();
528        }
529        return currNode.getIndex();
530    }
531
532    /**
533     * Get module parent text from paragraph javadoc node.
534     *
535     * @param nodeParagraph paragraph javadoc node
536     * @return parent text
537     */
538    private static String getParentText(DetailNode nodeParagraph) {
539        return getFirstChildOfType(nodeParagraph, JavadocTokenTypes.JAVADOC_INLINE_TAG, 0)
540                .map(JavadocMetadataScraper::getTextFromTag)
541                .orElse(null);
542    }
543
544    /**
545     * Get module type(check/filter/filefilter) based on file name.
546     *
547     * @return module type
548     */
549    private ModuleType getModuleType() {
550        final String simpleModuleName = getModuleSimpleName();
551        final ModuleType result;
552        if (simpleModuleName.endsWith("FileFilter")) {
553            result = ModuleType.FILEFILTER;
554        }
555        else if (simpleModuleName.endsWith("Filter")) {
556            result = ModuleType.FILTER;
557        }
558        else {
559            result = ModuleType.CHECK;
560        }
561        return result;
562    }
563
564    /**
565     * Extract simple file name from the whole file path name.
566     *
567     * @return simple module name
568     */
569    private String getModuleSimpleName() {
570        final String fullFileName = getFileContents().getFileName();
571        final String[] pathTokens = FILE_SEPARATOR_PATTERN.split(fullFileName);
572        final String fileName = pathTokens[pathTokens.length - 1];
573        return fileName.substring(0, fileName.length() - JAVA_FILE_EXTENSION.length());
574    }
575
576    /**
577     * Retrieve package name of module from the absolute file path.
578     *
579     * @param filePath absolute file path
580     * @return package name
581     */
582    private static String getPackageName(String filePath) {
583        final Deque<String> result = new ArrayDeque<>();
584        final String[] filePathTokens = FILE_SEPARATOR_PATTERN.split(filePath);
585        for (int i = filePathTokens.length - 1; i >= 0; i--) {
586            if ("java".equals(filePathTokens[i]) || "resources".equals(filePathTokens[i])) {
587                break;
588            }
589            result.addFirst(filePathTokens[i]);
590        }
591        final String fileName = result.removeLast();
592        result.addLast(fileName.substring(0, fileName.length() - JAVA_FILE_EXTENSION.length()));
593        return String.join(".", result);
594    }
595
596    /**
597     * Getter method for {@code moduleDetailsStore}.
598     *
599     * @return map containing module details of supplied checks.
600     */
601    public static Map<String, ModuleDetails> getModuleDetailsStore() {
602        return Collections.unmodifiableMap(MODULE_DETAILS_STORE);
603    }
604
605    /**
606     * Check if the current javadoc block comment AST corresponds to the top-level class as we
607     * only want to scrape top-level class javadoc.
608     *
609     * @return true if the current AST corresponds to top level class
610     */
611    public boolean isTopLevelClassJavadoc() {
612        final DetailAST parent = getParent(getBlockCommentAst());
613        final Optional<DetailAST> className = TokenUtil
614                .findFirstTokenByPredicate(parent, child -> {
615                    return parent.getType() == TokenTypes.CLASS_DEF
616                            && child.getType() == TokenTypes.IDENT;
617                });
618        return className.isPresent()
619                && getModuleSimpleName().equals(className.get().getText());
620    }
621
622    /**
623     * Checks whether the paragraph node corresponds to the example section.
624     *
625     * @param ast javadoc paragraph node
626     * @return true if the section matches the example section marker
627     */
628    private static boolean isExamplesText(DetailNode ast) {
629        return isChildNodeTextMatches(ast, EXAMPLES_TAG);
630    }
631
632    /**
633     * Checks whether the list item node is part of a property list.
634     *
635     * @param nodeLi {@code JavadocTokenType.LI} node
636     * @return true if the node is part of a property list
637     */
638    private static boolean isPropertyList(DetailNode nodeLi) {
639        return isChildNodeTextMatches(nodeLi, PROPERTY_TAG);
640    }
641
642    /**
643     * Checks whether the {@code JavadocTokenType.PARAGRAPH} node is referring to the violation
644     * message keys javadoc segment.
645     *
646     * @param nodeParagraph paragraph javadoc node
647     * @return true if paragraph node contains the violation message keys text
648     */
649    private static boolean isViolationMessagesText(DetailNode nodeParagraph) {
650        return isChildNodeTextMatches(nodeParagraph, VIOLATION_MESSAGES_TAG);
651    }
652
653    /**
654     * Checks whether the {@code JavadocTokenType.PARAGRAPH} node is referring to the parent
655     * javadoc segment.
656     *
657     * @param nodeParagraph paragraph javadoc node
658     * @return true if paragraph node contains the parent text
659     */
660    private static boolean isParentText(DetailNode nodeParagraph) {
661        return isChildNodeTextMatches(nodeParagraph, PARENT_TAG);
662    }
663
664    /**
665     * Checks whether the first child {@code JavadocTokenType.TEXT} node matches given pattern.
666     *
667     * @param ast parent javadoc node
668     * @param pattern pattern to match
669     * @return true if one of child text nodes matches pattern
670     */
671    private static boolean isChildNodeTextMatches(DetailNode ast, Pattern pattern) {
672        return getFirstChildOfType(ast, JavadocTokenTypes.TEXT, 0)
673                .map(DetailNode::getText)
674                .map(pattern::matcher)
675                .map(Matcher::matches)
676                .orElse(false);
677    }
678}