codequality.py 19.7 KB
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 129 130 131 132 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 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 294 295 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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

"""
TODO
  1 builtin variable names
  2 shadowed types
  3 binary op spacing between operands
  4 dead store
  5 loop iterator with increment inside instead of separate variable
  6 if/else redundancy with just assignment inside
  7 magic numbers
  8 check camel case checker
  9     updatedValues_m
 10 elipses
 11 print statements
 12 return None
 13 duplication except constants
"""

import copy
import tokenize
from typing import Any as Aany, Callable, Iterable
import os
import json
import re
import sys
from typing import Sequence
import ast
from io import StringIO, TextIOWrapper
import subprocess


try:
    from termcolor import colored
except ImportError:
    subprocess.check_call([sys.executable, "-m", "ensurepip"])
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'termcolor'])
finally:
    from termcolor import colored

try:
    import mypy
    import mypy.api
except ImportError:
    subprocess.check_call([sys.executable, "-m", "ensurepip"])
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'mypy'])
finally:
    import mypy
    import mypy.api


class Any(ast.Constant):
    pass


class AnyNot(ast.Constant):
    pass


class AnyOf(ast.Constant):
    pass


class AnyStar(ast.Constant):
    pass


ANY = Any(value=0)
NoneC = ast.Constant(value=None)
TrueC = ast.Constant(value=True)
FalseC = ast.Constant(value=False)
BoolC = AnyOf([TrueC, FalseC])
Eq = ast.Eq()
Nq = ast.NotEq()
EqNq = AnyOf([Eq, Nq])

Is = ast.Is()
Ns = ast.IsNot()
IsNs = AnyOf([Is, Ns])


def camel_case_variables(node: ast.AST | str):
    check = ""
    if isinstance(node, str):
        check = node
    elif isinstance(node, ast.Name):
        check = node.id
    elif isinstance(node, ast.FunctionDef):
        check = node.name
    if not check:
        return None
    return re.match(r"[a-z0-9]+([A-Z0-9]+[a-z])+", check)


def funcs_have_doc_string(body: list[ast.AST], contents: str, whole: ast.AST):
    for node in body:
        if isinstance(node, ast.FunctionDef):
            if not ast.get_docstring(node):
                return node
    return None


STYLE_ANTI_PATTERNS: list[tuple[ast.AST | Callable[[ast.AST, str | list[ast.AST]], bool], str]] = [
    (ast.Compare(ANY, [EqNq], [BoolC]),  # type: ignore
     "comparing to boolean"),  # type: ignore
    (ast.Compare(BoolC, [EqNq], ANY), "comparing to boolean"),  # type: ignore
    (ast.Compare(ANY, [IsNs], [AnyNot([NoneC])]),  # type: ignore
     "Using 'is' instead of '=='"),
    (ast.If(ANY, [ast.Return(BoolC)], [ast.Return(BoolC)]), "boolean zen"),
    (ast.If(ANY, [ast.Pass()], []), "unncessary if statement"),
    (ast.If(ANY, [ast.Pass()], [ANY]), "negate if statement"),  # type: ignore
    (ast.If(ANY, [ANY], [ast.Pass()]),  # type: ignore
     "unnecessary else case"),  # type: ignore

    (ast.UnaryOp(ast.Not(), ast.Compare(
        ANY, [Eq], ANY)), "use != instead"),  # type: ignore
    (ast.UnaryOp(ast.Not(), ast.Compare(
        ANY, [Nq], ANY)), "use == instead"),  # type: ignore
    (ast.UnaryOp(ast.Not(), ast.Compare(
        ANY, [Is], ANY)), "use 'is not' instead"),  # type: ignore
    (ast.UnaryOp(ast.Not(), ast.Compare(
        ANY, [Ns], ANY)), "use 'is' instead")  # type: ignore
]

# TODO: nested if statements
# TODO: bad demorgan


def more_boolean_zen(body: list[ast.AST], contents: str, whole: ast.AST):
    return body[-1] if (len(body) >= 2
                        and match_ast(ast.If(ANY, [ast.Return(BoolC)], []), body[-2], contents)
                        and match_ast(ast.Return(BoolC), body[-1], contents)) else None


def all_same_returns_func(body: list[ast.AST], contents: str, whole: ast.AST, val: Aany = None, top: bool = True):
    returns: list[ast.AST] = []
    for x in body[::-1]:
        if isinstance(x, ast.Return):
            returns.append(x.value)  # type: ignore
        if hasattr(x, 'body'):
            ret = all_same_returns_func(x.body, contents, val,  # type: ignore
                                        top=False)  # type: ignore
            if ret:
                returns += [ret]
        if hasattr(x, 'orelse'):
            ret = all_same_returns_func(
                x.orelse, contents, val, top=False)  # type: ignore
            if ret:
                returns += [ret]
    return returns[0] if (len(set([x and ast.dump(x) for x in returns])) == 1 and len(returns) > (0 if not top else 1)) else None


def all_same_returns(body: list[ast.AST], contents: str, whole: ast.AST) -> ast.AST | None:
    for x in body:
        if isinstance(x, ast.FunctionDef):
            xx = copy.copy(x.body)
            while isinstance(xx[0], ast.Expr) and isinstance(xx[0].value, ast.Constant):
                xx.pop(0)
            result = all_same_returns_func(xx, contents, whole)  # type: ignore
            if result:
                return result
    return None


def extra_return(body: list[ast.AST], contents: str, whole: ast.AST):
    if len(body) > 0 and isinstance(body[-1], ast.Return) and body[-1].value == None:
        return body[-1]
    return None


def dead_code(body: list[ast.AST], contents: str, whole: ast.AST):
    if len(body) > 1:
        for i in range(len(body) - 1):
            if isinstance(body[i], ast.Return):
                return body[i + 1]
    return None

# TODO: add banned functions (e.g., tuple, dict,)


def banned_imports(body: list[ast.AST], contents: str, whole: ast.AST):
    BANNED = set(['re'])
    for node in body:
        if isinstance(node, ast.Import) and set([x.name for x in node.names]) & BANNED != set():
            return node
        if isinstance(node, ast.ImportFrom) and node.module in BANNED:
            return node


def repeated_function_calls(body: list[ast.AST], contents: str, whole: ast.AST):
    TO_IGNORE = set(['range', 'random\\..*', 'choice'])
    for node in body:
        if isinstance(node, ast.FunctionDef):
            calls: list[ast.AST] = []
            p = ast.unparse(node)
            for n in ast.walk(node):
                if isinstance(n, ast.Call):
                    calls.append(n)
            if len(calls) > 1:
                processed = sorted([((ast.unparse(x.func), [ast.unparse(y) for y in x.args]), x)  # type: ignore
                                    for x in calls], key=lambda x: x[0])
                for i in range(len(processed) - 1):
                    if not any([re.match(patt, processed[i][0][0]) is None for patt in TO_IGNORE]) and processed[i][0] == processed[i+1][0]:
                        ty = infer_return_type(processed[i][0][0], p)
                        if ty and not any([x[1] is None for x in ty]):
                            return processed[i][1]
    return None


def duplicated_code(body: list[ast.AST], contents: str, whole: ast.AST) -> ast.AST | None:
    node_counter: dict[str, tuple[int, ast.AST]] = {}
    for node in body:
        for n in ast.walk(node):
            if hasattr(n, 'body'):
                s = ast.unparse(n)
                if s in node_counter:
                    node_counter[s] = (node_counter[s][0] + 1, n)
                else:
                    node_counter[s] = (1, n)
    out: list[ast.AST] = []
    for x in node_counter:
        if node_counter[x][0] > 1:
            out.append(node_counter[x][1])
    if out:
        return out[0]
    return None


def extra_parentheses(body: list[ast.AST], contents: str, whole: ast.AST):
    for i in range(len(body)):
        if isinstance(body[i], ast.If):
            source = ast.get_source_segment(contents, body[i])
            if source and (re.match(r"^\s*((if)|(elif))\s*\([^:]*\)\s*:", source)):
                return body[i]
            for el in body[i].orelse:  # type: ignore
                source2 = ast.get_source_segment(contents, el)  # type: ignore
                if isinstance(el, ast.If) and source2 and (re.match(r"^\s*((if)|(elif))\s*\([^:]*\)\s*:", source2)):
                    return el


def outside_camel_case(body: list[ast.AST], contents: str, whole: ast.AST):
    for node in body:
        for desc in ast.walk(node):
            if camel_case_variables(desc) is not None:
                return desc


def else_if_needed_elif(body: list[ast.AST], contents: str, whole: ast.AST):
    for node in body:
        if isinstance(node, ast.If) and len(node.orelse) == 1:
            source2 = ast.get_source_segment(contents, node.orelse[0])
            if source2 and re.match(r'^\s*if .*:\s*', source2):
                return node.orelse[0]
    return None


def missing_boolean_op(body: list[ast.AST], contents: str, whole: ast.AST):
    for node in body:
        if isinstance(node, ast.If):
            if not node.orelse:
                if isinstance(node.body[0], ast.If):
                    return node.body[0]
    return None


def todo_comments(tokens: Sequence[tokenize.TokenInfo]):
    for token in tokens:
        if token.type == tokenize.COMMENT:
            if token.string.lower().strip('# ').startswith('todo'):
                return token
    return None


PATTERN_FUNCTIONS: list[tuple[Callable[[list[ast.AST], str, ast.AST], ast.AST | None], str]] = [
    (extra_return, "unnecessary return"),
    (dead_code, "statement is unreachable"),
    (extra_parentheses, "parentheses around an if statement"),
    (outside_camel_case, "camelCase variable or function name"),
    (more_boolean_zen, "boolean zen"),
    (all_same_returns, "all same returns"),
    (funcs_have_doc_string, "every function should have a non-empty docstring"),
    (else_if_needed_elif, "instead of using else with an if, you should use 'elif'"),
    (missing_boolean_op, "multiple if statements can be condensed into one with and/or"),
    (repeated_function_calls, "a function call is repeated with the same arguments"),
    (duplicated_code, "you have written the same code in two places"),
    (banned_imports, "you have imported a banned package"),
]

SOURCE_FUNCTIONS: list[tuple[Callable[[Sequence[tokenize.TokenInfo]], tokenize.TokenInfo | None], str]] = [
    (todo_comments, "remove all 'todo' comments before submission")
]


def match_ast(match: ast.AST | Callable[[Aany, Aany], bool] | Sequence[ast.AST], node: ast.AST | Callable[[Aany, Aany], bool] | Sequence[ast.AST], content: str) -> bool | None:
    if match == ANY:
        return True
    if isinstance(match, AnyNot):
        return not any([match_ast(v, node, content) for v in match.value])
    if isinstance(match, AnyOf):
        return any([match_ast(v, node, content) for v in match.value])
    elif callable(match):
        return match(node, content)
    elif type(match) != type(node):
        return False
    elif isinstance(match, ast.Constant) and isinstance(node, ast.Constant):
        return match.value is node.value
    elif isinstance(match, Sequence) and isinstance(node, Sequence):
        if len(match) != len(node):
            return False

        # type: ignore
        return all(match_ast(x, y, content) for x, y in zip(match, node))

    tyattrs = [getattr(match, x) for x in match._fields]  # type: ignore
    deattrs = [getattr(node, x) for x in match._fields]  # type: ignore

    for t, d in zip(tyattrs, deattrs):
        if not match_ast(t, d, content):
            return False
    return True


INFERRED_TYPES: dict[str, Sequence[tuple[str, str] | tuple[str, None]]] = {}


def infer_return_type(function: str, code: str):
    query: str = ""
    if '.' in function:
        query = "from typing import Any; from typing import builtins\n" + code.strip().replace(
            "return", f"reveal_type({function.split('.')[0]}); return")
        result = mypy.api.run(['--ignore-missing-imports', '-c', query])
        tys = set([re.sub(
            r'^.*note: Revealed type is "(.*)"$', r'\1', x) for x in result[0].splitlines()
            if 'note: Revealed type is ' in x])
        if len(tys) != 1:
            return None
        t: str = list(tys)[0]
        _ty: str = re.sub("_T(`[0-9]*)?", "Any", t).replace("builtins.", "")
        function = _ty + "." + function.split(".")[1]
    if function in FUNCTION_TYPE_DEFINITIONS:
        return FUNCTION_TYPE_DEFINITIONS[function]['signature']
    if function in INFERRED_TYPES:
        return INFERRED_TYPES[function]
    try:
        query = "from typing import Any; from typing import builtins\n" + \
            all_code + f"\nreveal_type({function})"
        result = mypy.api.run(['-c', query])
        ty: list[str] = [re.sub("_T(`[0-9]*)?", "Any", x) for x in result[0].splitlines()
                         if 'note: Revealed type is ' in x]
        if len(ty) != 1:
            return None
        partials: Sequence[tuple[str, str] | tuple[str, None]] = [tuple([z.strip("()= ") for z in x.strip().strip("),").split(" -> ")]) for x in re.sub(  # type: ignore
            r'^.*note: Revealed type is "(.*)"$', r'\1', ty[0]).replace("builtins.", "").replace("typing.", "").split("def ") if 'Overload' not in x and x]

        partials = [
            x if len(x) == 2 else (x[0], None) for x in partials]
        INFERRED_TYPES[function] = partials

        return INFERRED_TYPES[function]
    except Exception as e:  # type: ignore
        return None


all_code: str = ""

FUNCTION_TYPE_DEFINITIONS: dict[str, dict[str, Aany]] = {}


def checked_parse(filename: str, f: TextIOWrapper) -> tuple[ast.AST, str] | tuple[None, str]:
    contents: str = f.read()
    try:
        return ast.parse(contents), contents
    except SyntaxError:
        print(colored("    SyntaxError in " + filename, "red"))
        return None, contents
    except UnicodeDecodeError:
        return None, ""


def run_mypy(filename: str, add_anns: bool = False) -> list[str]:
    try:
        if not add_anns:
            result = mypy.api.run(
                ['--warn-unreachable', '--ignore-missing-imports', filename])
        else:
            with open(filename, 'r') as f:
                code = re.sub(
                    '(\\s*)(def )([^ (]*)(.*[^\n]*:)\n', r'\1\2\3\4\n\1    reveal_type("\3");reveal_type(\3)\n', f.read())
                code = re.sub('return', 'reveal_locals(); return', code)
                result = mypy.api.run(
                    ['--warn-unreachable', '--ignore-missing-imports', '-c', code])
        if result[0]:
            return result[0].splitlines()[:-1]
    except KeyError:
        pass
    return []


def check_style() -> str | None:
    global all_code, FUNCTION_TYPE_DEFINITIONS
    log = StringIO()
    with open("manifest.json", "r") as manifest:
        for filename in json.load(manifest)["upload"]:
            if filename.startswith(".") or not filename.endswith(".py") or not os.path.exists(filename):
                continue

            i = 0
            anns = run_mypy(filename, add_anns=True)
            while i < len(anns):
                ann = re.sub('.*note: ', '', anns[i])
                if ann.startswith('Revealed type is '):
                    func = re.sub(
                        '.*Revealed type is "Literal..(.*)..\\?.*"', r'\1', ann)
                    i += 1
                    ty = re.sub("_T(`[0-9]*)?", "Any", anns[i])
                    partials = [tuple([z.strip("()= ") for z in x.strip().strip("),").split(" -> ")]) for x in re.sub(
                        r'^.*note: Revealed type is "(.*)"$', r'\1', ty).replace("builtins.", "").replace("typing.", "").split("def ") if 'Overload' not in x and x]

                    sig = [x if len(x) == 2 else (x[0], None)
                           for x in partials]
                    i += 1
                    while i < len(anns) and 'Revealed local types are' in anns[i]:
                        i += 1
                    local_vars = {}
                    while i < len(anns) and 'Revealed type is ' not in anns[i]:
                        loc = [x.strip() for x in anns[i].split(":")][3:]
                        if len(loc) == 2:
                            local_vars[loc[0]] = loc[1].replace(
                                "builtins.", "").replace("typing.", "")
                        i += 1
                    FUNCTION_TYPE_DEFINITIONS[func] = {
                        'signature': sig, 'locals': local_vars}
                else:
                    i += 1

            with open(filename, 'r') as f:
                node, contents = checked_parse(filename, f)
                if not node:
                    continue

                all_code += "\n" + contents

                lines_iter = iter(contents.splitlines(keepends=True))
                tokens: Sequence[tokenize.TokenInfo] = list(tokenize.generate_tokens(
                    lambda: next(lines_iter)))

                for matcher, msg in SOURCE_FUNCTIONS:
                    m = matcher(tokens)
                    if m:
                        print(colored(msg, "red") + " in " +
                              colored(filename + ":" + str(m.start[0]), "yellow"), file=log)
                mypy_output = run_mypy(filename)
                for rule in mypy_output:
                    if '<typing special form>' in rule or 'PendAttrs' in rule or '[import-untyped]' in rule or '[' not in rule or 'Any' in rule or 'object]' in rule:
                        continue
                    if 'untyped functions' in rule:
                        continue

                    fi = re.sub('^([^:]*:[^:]*).*$', '\\1', rule)
                    msg = re.sub('^.*: ([^:]*)\\s\\[.*\\]$',
                                 '\\1', rule).strip()
                    msg = msg[0].lower() + msg[1:]
                    print(colored("* " + msg, "red") + " in " +
                          colored(fi, "yellow"), file=log)

                for desc in ast.walk(node):
                    # if type(desc) == ast.Name:
                    #    print(ast.dump(desc))
                    if hasattr(desc, 'body'):
                        for pattern, msg in PATTERN_FUNCTIONS:
                            if isinstance(desc.body, Iterable):  # type: ignore
                                pt: ast.AST | None = pattern(
                                    desc.body, contents, node)  # type: ignore
                                if pt is not None:
                                    print(colored("* " + msg, "red") + " in " + colored(
                                        # type: ignore
                                        filename + ":" + str(pt.lineno), "yellow"), file=log)  # type: ignore
                    for tt, msg in STYLE_ANTI_PATTERNS:
                        if callable(tt):
                            if tt(desc, contents):
                                print(colored("* " + msg, "red") + " in " + colored(
                                    # type: ignore
                                    filename + ":" + str(desc.lineno), "yellow"), file=log)  # type: ignore

                        elif type(desc) == type(tt):
                            if not match_ast(tt, desc, contents):
                                continue
                            print(colored(msg, "red") + " in " + colored(
                                # type: ignore
                                filename + ":" + str(desc.lineno), "yellow"), file=log)  # type: ignore

    # Check local variable names
    for ff in FUNCTION_TYPE_DEFINITIONS:
        for loc in FUNCTION_TYPE_DEFINITIONS[ff]['locals']:
            ty = FUNCTION_TYPE_DEFINITIONS[ff]['locals'][loc]
            if 'dict' in ty and loc == 'k':
                continue
            if isinstance(loc, str) and loc in [chr(x) for x in range(ord('i'), ord('m'))] and ty not in ['int', 'float']:
                # print('in ' + ff + ",", 'the variable "' + loc + '"', 'has type', ty)
                pass

    return log.getvalue()


if __name__ == '__main__':
    if not os.path.exists('tests'):
        print()
        print()
        print('\x1b[1m\x1b[31mCould not find the tests directory. :(\x1b[0m')
        print()
        exit(1)

    result = check_style()

    if '--json' in sys.argv:
        print(json.dumps(
            {'success': not result, 'output': result.strip().split(os.linesep) if result else ""}))

    print(result.strip() if result else "", file=sys.stderr)