docstring_checker.py 10.2 KB
Newer Older
G
gongweibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocstringChecker is used to check python doc string's style."""

import six
import astroid

from pylint.checkers import BaseChecker, utils
from pylint.interfaces import IAstroidChecker

from collections import defaultdict
import re


def register(linter):
    """Register checkers."""
    linter.register_checker(DocstringChecker(linter))


class Docstring(object):
    """Docstring class holds the parsed doc string elements.
    """

    def __init__(self):
        self.d = defaultdict(list)  #name->[]
        self.clear()

    def clear(self):
        self.d['Args'] = []
        self.d['Examples'] = []
        self.d['Returns'] = []
        self.d['Raises'] = []
        self.args = {}  #arg_name->arg_type

    def get_level(self, string, indent='    '):
        level = 0
        unit_size = len(indent)
        while string[:unit_size] == indent:
            string = string[unit_size:]
            level += 1

        return level

    def parse(self, doc):
        """parse gets sections from doc
        Such as Args, Returns, Raises, Examples s
        Args:
            doc (string): is the astroid node doc string.
        Returns:
            True if doc is parsed successfully.
        """
        self.clear()

        lines = doc.splitlines()
        state = ("others", -1)
        for l in lines:
            c = l.strip()
            if len(c) <= 0:
                continue

            level = self.get_level(l)
            if c.startswith("Args:"):
                state = ("Args", level)
            elif c.startswith("Returns:"):
                state = ("Returns", level)
            elif c.startswith("Raises:"):
                state = ("Raises", level)
            elif c.startswith("Examples:"):
                state = ("Examples", level)
            else:
                if level > state[1]:
                    self.d[state[0]].append(c)
                    continue

                state = ("others", -1)
                self.d[state[0]].append(c)

        self._arg_with_type()
        return True

    def get_returns(self):
        return self.d['Returns']

    def get_raises(self):
        return self.d['Raises']

    def get_examples(self):
        return self.d['Examples']

    def _arg_with_type(self):

        for t in self.d['Args']:
            m = re.search('([A-Za-z0-9_-]+)\s{0,4}(\(.+\))\s{0,4}:', t)
            if m:
                self.args[m.group(1)] = m.group(2)

        return self.args


class DocstringChecker(BaseChecker):
    """DosstringChecker is pylint checker to
    check docstring style.
    """
    __implements__ = (IAstroidChecker, )

    POSITIONAL_MESSAGE_ID = 'str-used-on-positional-format-argument'
    KEYWORD_MESSAGE_ID = 'str-used-on-keyword-format-argument'

    name = 'doc-string-checker'
    symbol = "doc-string"
    priority = -1
    msgs = {
        'W9001': ('One line doc string on > 1 lines', symbol + "-one-line",
                  'Used when a short doc string is on multiple lines'),
        'W9002':
        ('Doc string does not end with "." period', symbol + "-end-with",
         'Used when a doc string does not end with a period'),
129 130 131 132
        'W9003':
        ('All args with their types must be mentioned in doc string %s',
         symbol + "-with-all-args",
         'Used when not all arguments are in the doc string '),
G
gongweibao 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        'W9005': ('Missing docstring or docstring is too short',
                  symbol + "-missing", 'Add docstring longer >=10'),
        'W9006': ('Docstring indent error, use 4 space for indent',
                  symbol + "-indent-error", 'Use 4 space for indent'),
        'W9007': ('You should add `Returns` in comments',
                  symbol + "-with-returns",
                  'There should be a `Returns` section in comments'),
        'W9008': ('You should add `Raises` section in comments',
                  symbol + "-with-raises",
                  'There should be a `Raises` section in comments'),
    }
    options = ()

    def visit_functiondef(self, node):
        """visit_functiondef checks Function node docstring style.
        Args:
            node (astroid.node): The visiting node.
        Returns:
            True if successful other wise False.
        """

        self.check_doc_string(node)

        if node.tolineno - node.fromlineno <= 10:
            return True

        if not node.doc:
            return True

        doc = Docstring()
        doc.parse(node.doc)

        self.all_args_in_doc(node, doc)
        self.with_returns(node, doc)
        self.with_raises(node, doc)

    def visit_module(self, node):
        self.check_doc_string(node)

    def visit_classdef(self, node):
        self.check_doc_string(node)

    def check_doc_string(self, node):
        self.missing_doc_string(node)
        self.one_line(node)
        self.has_period(node)
        self.indent_style(node)

    def missing_doc_string(self, node):
182 183
        if node.name.startswith("__") or node.name.startswith("_"):
            return True
G
gongweibao 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        if node.tolineno - node.fromlineno <= 10:
            return True

        if node.doc is None or len(node.doc) < 10:
            self.add_message('W9005', node=node, line=node.fromlineno)
        return False

    # FIXME(gongwb): give the docstring line-no
    def indent_style(self, node, indent=4):
        """indent_style checks docstring's indent style
        Args:
            node (astroid.node): The visiting node.
            indent (int): The default indent of style
        Returns:
            True if successful other wise False.
        """
        if node.doc is None:
            return True

        doc = node.doc
        lines = doc.splitlines()
205
        line_num = 0
G
gongweibao 已提交
206 207

        for l in lines:
208 209
            if line_num == 0:
                continue
G
gongweibao 已提交
210 211 212 213
            cur_indent = len(l) - len(l.lstrip())
            if cur_indent % indent != 0:
                self.add_message('W9006', node=node, line=node.fromlineno)
                return False
214
            line_num += 1
G
gongweibao 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

        return True

    def one_line(self, node):
        """one_line checks if docstring (len < 40) is on one line.
        Args:
            node (astroid.node): The node visiting.
        Returns:
            True if successful otherwise False.
        """

        doc = node.doc
        if doc is None:
            return True

        if len(doc) > 40:
            return True
        elif sum(doc.find(nl) for nl in ('\n', '\r', '\n\r')) == -3:
            return True
        else:
            self.add_message('W9001', node=node, line=node.fromlineno)
            return False

        return True

    def has_period(self, node):
        """has_period checks if one line doc end-with '.' .
        Args:
            node (astroid.node): the node is visiting.
        Returns:
            True if successful otherwise False.
        """
        if node.doc is None:
            return True

        if len(node.doc.splitlines()) > 1:
            return True

        if not node.doc.strip().endswith('.'):
            self.add_message('W9002', node=node, line=node.fromlineno)
            return False

        return True

    def with_raises(self, node, doc):
        """with_raises checks if one line doc end-with '.' .
        Args:
            node (astroid.node): the node is visiting.
            doc (Docstring): Docstring object.
        Returns:
            True if successful otherwise False.
        """

        find = False
        for t in node.body:
            if not isinstance(t, astroid.Raise):
                continue

            find = True
            break

        if not find:
            return True

        if len(doc.get_raises()) == 0:
            self.add_message('W9008', node=node, line=node.fromlineno)
            return False

        return True

    def with_returns(self, node, doc):
        """with_returns checks if docstring comments what are returned .
        Args:
            node (astroid.node): the node is visiting.
            doc (Docstring): Docstring object.
        Returns:
            True if successful otherwise False.
        """

Y
yi.wu 已提交
294 295
        if node.name.startswith("__") or node.name.startswith("_"):
            return True
G
gongweibao 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        find = False
        for t in node.body:
            if not isinstance(t, astroid.Return):
                continue

            find = True
            break

        if not find:
            return True

        if len(doc.get_returns()) == 0:
            self.add_message('W9007', node=node, line=node.fromlineno)
            return False

        return True

    def all_args_in_doc(self, node, doc):
        """all_args_in_doc checks if arguments are mentioned in doc
        Args:
            node (astroid.node): the node is visiting.
            doc (Docstring): Docstring object
        Returns:
            True if successful otherwise False.
        """
Y
yi.wu 已提交
321 322
        if node.name.startswith("__") or node.name.startswith("_"):
            return True
G
gongweibao 已提交
323 324 325 326 327 328 329 330 331 332 333
        args = []
        for arg in node.args.get_children():
            if (not isinstance(arg, astroid.AssignName)) \
                or arg.name == "self":
                continue
            args.append(arg.name)

        if len(args) <= 0:
            return True

        parsed_args = doc.args
334
        args_not_documented = set(args) - set(parsed_args)
G
gongweibao 已提交
335
        if len(args) > 0 and len(parsed_args) <= 0:
336 337 338 339 340
            self.add_message(
                'W9003',
                node=node,
                line=node.fromlineno,
                args=list(args_not_documented))
G
gongweibao 已提交
341 342 343 344
            return False

        for t in args:
            if t not in parsed_args:
345 346
                self.add_message(
                    'W9003', node=node, line=node.fromlineno, args=[t, ])
G
gongweibao 已提交
347 348 349
                return False

        return True