#!/usr/bin/env python3
"""Count comments in library source code, one open-source project per language.

This is the script behind
https://www.turbotype.co/blog/comment-syntax-in-programming

What it counts
--------------
For every source file it finds strings and comments with a small tokenizer per
language (strings first, so // inside a URL is not a comment), then classifies
each non-blank line:

  comment line   everything on the line is inside a comment
  code line      anything else; a code line with a comment after the code is
                 also counted as a "trailing" line, but it is still code

Comments are split into:

  doc      /** */ blocks, and in Rust, C++ and Java also /// and //!
           (but not ////, the rule rustdoc uses)
  plain    every other //, /* */ and # comment
  licence  the comment block before the first line of code in a file, when it
           mentions a licence or copyright; reported separately and left out
           of the shares

Python docstrings are strings, not comments, so they are counted on their own.

Left out: test and benchmark folders, test files, and generated files. A file
counts as generated only when it declares that itself near the top (see
GENERATED below); the output lists every file left out for that reason.

How to run it
-------------
1. Fetch each project at the commit the post used, source folders only
   (about 180 MB in all). <root> is any empty folder:

     get() { name=$1; url=$2; sha=$3; shift 3
       git init -q "<root>/$name/repo" && cd "<root>/$name/repo" &&
       git remote add origin "$url" && git sparse-checkout set "$@" &&
       git fetch -q --depth 1 --filter=blob:none origin "$sha" &&
       git checkout -q FETCH_HEAD; }

     get node    https://github.com/nodejs/node.git       a04590e0b60e4e32a13bdf8bc7f45bad2e0571b7 lib
     get rust    https://github.com/rust-lang/rust.git    b2238fc4e6a5d91a6199868df5c3b75694832bd6 library/core/src library/alloc/src library/std/src
     get stl     https://github.com/microsoft/STL.git     0cabaf3c7e0a73fe3040aabce40cd8833e80392b stl
     get laravel https://github.com/laravel/framework.git d0c59697a609b295ed8633a0b307a8937a6002ab src
     get vue     https://github.com/vuejs/core.git        6a04291c82f6e4f82864d5ac3b13970862d8bf91 packages
     get jdk     https://github.com/openjdk/jdk.git       4824e351680944d84773304377c713c1ff8a0971 src/java.base/share/classes

     git clone https://git.musl-libc.org/git/musl <root>/musl/repo
     git -C <root>/musl/repo checkout 7813e9119eb5fe681b6750b8a033a0490bca0941

2. Point it at a CPython 3.13.7 standard library folder (the "Lib" folder of a
   source checkout, or lib/python3.13 of an install):

     python3 count-comments.py <root> /path/to/lib/python3.13 [results.json]

It needs Python 3.8 or later and nothing outside the standard library.

Limits
------
One project per language, so the numbers describe eight code bases, not eight
languages. The tokenizers are regular expressions, not parsers: they handle
the string and comment forms these projects use, and can be fooled by unusual
code (a regular expression literal in JavaScript that contains //, for one).
"""
import collections
import json
import os
import re
import sys

# name -> (folder under <root>, file extensions, tokenizer)
PROJECTS = {
    'C (musl libc)': ('musl/repo/src', ('.c', '.h'), 'c'),
    'C++ (Microsoft STL)': ('stl/repo/stl', None, 'cpp'),
    'Java (OpenJDK java.base)': ('jdk/repo/src/java.base/share/classes', ('.java',), 'java'),
    'JavaScript (Node.js lib)': ('node/repo/lib', ('.js', '.mjs'), 'js'),
    'TypeScript (Vue core)': ('vue/repo/packages', ('.ts',), 'ts'),
    'PHP (Laravel)': ('laravel/repo/src', ('.php',), 'php'),
    'Python (CPython 3.13 Lib)': (None, ('.py',), 'python'),  # path comes from argv[2]
    'Rust (Rust std, core, alloc)': ('rust/repo/library', ('.rs',), 'rust'),
}

SKIP_DIRS = {'test', 'tests', '__tests__', 'idle_test', 'site-packages',
             '__pycache__', 'benches', 'testing', 'testdata'}

# Tokens are matched left to right: whichever of comment or string starts
# first wins, so comment markers inside strings are skipped and vice versa.
STR_DQ = r'"(?:\\.|[^"\\\n])*"'
STR_SQ = r"'(?:\\.|[^'\\\n])*'"
CHAR_LIT = r"'(?:\\[^'\n]{1,10}|[^'\\\n])'"
LINE = r'//[^\n]*'
BLOCK = r'/\*.*?\*/'
TEMPLATE = r'`(?:\\.|[^`\\])*`'
PY_PREFIX = r'(?:[rRbBuUfF]{0,2})'
TOKENS = {
    'c': re.compile('|'.join([LINE, BLOCK, STR_DQ, CHAR_LIT]), re.S),
    'cpp': re.compile('|'.join([r'R"([^(\s]{0,16})\(.*?\)\1"', LINE, BLOCK, STR_DQ, CHAR_LIT]), re.S),
    'java': re.compile('|'.join([r'""".*?"""', LINE, BLOCK, STR_DQ, CHAR_LIT]), re.S),
    'js': re.compile('|'.join([LINE, BLOCK, TEMPLATE, STR_DQ, STR_SQ]), re.S),
    'ts': re.compile('|'.join([LINE, BLOCK, TEMPLATE, STR_DQ, STR_SQ]), re.S),
    'php': re.compile('|'.join([LINE, BLOCK, r'#(?!\[)[^\n]*', STR_DQ, STR_SQ]), re.S),
    'rust': re.compile('|'.join([r'r(#*)".*?"\1', r'b?"(?:\\.|[^"\\])*"', LINE, BLOCK, r'b?' + CHAR_LIT]), re.S),
    'python': re.compile('|'.join([
        r'#[^\n]*',
        PY_PREFIX + r'(?:"""|\'\'\').*?(?:"""|\'\'\')',
        PY_PREFIX + r'"(?:\\.|[^"\\\n])*"',
        PY_PREFIX + r"'(?:\\.|[^'\\\n])*'",
    ]), re.S),
}

LICENCE = re.compile(r'licen[cs]e|copyright|SPDX|GNU|Apache', re.I)
# A file is left out as generated only when it says so itself, near the top:
#   "This file is generated by ...", "this entire header is generated by ...",
#   "Auto-generated by ...", "DO NOT EDIT" / "DO NOT MODIFY" in capitals,
#   an unindented comment line "// Generated by ..." or "# Generated by ...",
#   or the header of CPython's codec tables ("generated from '...' with gencodec.py").
# Prose such as "the key generated by the server" does not count. Every file this
# rule drops is listed under "skipped_files" in the output, so it can be checked.
GENERATED = re.compile(
    r"(?i:this (?:entire )?(?:file|header) (?:is|was) (?:automatically |auto-?)?generated)"
    r"|(?i:auto-?generated by)"
    r"|DO NOT (?:EDIT|MODIFY)"
    r"|@generated"
    r"|^(?://|#) ?Generated by "
    r"|generated from '[^'\n]+' with \w+\.py",
    re.M)
# Written by the build of one particular Python install; not part of CPython's Lib.
GENERATED_NAMES = re.compile(r'^_sysconfigdata_')
TAGS = re.compile(r'\b(TODO|FIXME|XXX|HACK)\b')
# Project-specific comment conventions mentioned in the post.
CONVENTIONS = {
    'rust': ('// SAFETY:', re.compile(r'//\s*SAFETY:')),
    'cpp': ('// TRANSITION', re.compile(r'//\s*TRANSITION')),
}

CODE, PLAIN, DOC, DOCSTRING, STRING, SPACE = 0, 1, 2, 3, 4, 9


def source_files(base, exts):
    for folder, dirs, names in os.walk(base):
        dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
        for name in sorted(names):
            if name in ('tests.rs', 'benches.rs'):
                continue
            if name.endswith('.d.ts') or '.spec.' in name or '.test.' in name:
                continue
            if exts is None:
                # Microsoft STL: headers have no extension; also take .h .hpp .cpp .ixx
                if '.' in name and not name.endswith(('.h', '.hpp', '.cpp', '.ixx')):
                    continue
            elif not name.endswith(exts):
                continue
            yield os.path.join(folder, name)


def analyse(text, lang):
    """Return (kind, comments): kind[i] is the category of character i,
    comments is a list of (start, end, kind, text)."""
    kind = bytearray(len(text))
    comments = []
    for m in TOKENS[lang].finditer(text):
        t = m.group(0)
        a, b = m.start(), m.end()
        if lang == 'python':
            if t.startswith('#'):
                k = PLAIN
            elif re.match(r'[rRbBuUfF]{0,2}("""|\'\'\')', t):
                # A docstring is a triple-quoted string that is a statement of its
                # own and opens a module, or follows a line ending in a colon.
                line_start = text.rfind('\n', 0, a) + 1
                before = text[:line_start].rstrip()
                alone = not text[line_start:a].strip()
                k = DOCSTRING if alone and (not before or before.endswith(':')) else STRING
            else:
                k = STRING
        else:
            if t.startswith('/**') and not t.startswith('/**/'):
                k = DOC
            elif (t.startswith(('///', '//!', '/*!')) and lang in ('rust', 'cpp', 'java')
                  and not t.startswith('////')):
                k = DOC
            elif t.startswith(('//', '/*')) or (lang == 'php' and t.startswith('#')):
                k = PLAIN
            else:
                k = STRING
        if k in (PLAIN, DOC):
            comments.append((a, b, k, t))
        kind[a:b] = bytes([k]) * (b - a)
    return kind, comments


def marker_of(t, k):
    if t.startswith(('///', '//!')) and k == DOC:
        return '/// //!'
    if t.startswith('/**') and k == DOC:
        return '/** */'
    if t.startswith('/*'):
        return '/* */'
    if t.startswith('//'):
        return '//'
    return '#'


def count_project(base, exts, lang):
    st = collections.Counter()
    markers = collections.Counter()
    tags = collections.Counter()
    skipped = []
    for path in source_files(base, exts):
        with open(path, encoding='utf-8', errors='replace') as fh:
            text = fh.read()
        if GENERATED.search(text[:3000]) or GENERATED_NAMES.match(os.path.basename(path)):
            skipped.append(os.path.relpath(path, base))
            continue
        st['files'] += 1
        kind, comments = analyse(text, lang)

        # Licence header: the comments before the first code, if they mention one.
        first_code = next((i for i, ch in enumerate(text)
                           if kind[i] in (CODE, STRING) and not ch.isspace()), len(text))
        head = [c for c in comments if c[1] <= first_code]
        licence_end = 0
        if head and LICENCE.search(' '.join(c[3] for c in head)):
            licence_end = head[-1][1]

        for a, b, k, t in comments:
            if lang in CONVENTIONS and CONVENTIONS[lang][1].match(t):
                st['convention'] += 1
            if b <= licence_end:
                continue
            markers[marker_of(t, k)] += 1
            for tag in TAGS.findall(t):
                tags[tag] += 1

        # Per line: which categories do its non-space characters belong to?
        cells = bytearray(kind)
        for m in re.finditer(r'\s', text):
            cells[m.start()] = SPACE
        pos = 0
        for line in text.split('\n'):
            end = pos + len(line)
            cats = set(cells[pos:end]) - {SPACE}
            if cats:
                st['lines'] += 1
                if cats <= {PLAIN, DOC}:
                    if end <= licence_end:
                        st['licence_lines'] += 1
                    elif DOC in cats:
                        st['doc_lines'] += 1
                    else:
                        st['plain_lines'] += 1
                elif cats == {DOCSTRING}:
                    st['docstring_lines'] += 1
                else:
                    st['code_lines'] += 1
                    if cats & {PLAIN, DOC}:
                        st['trailing_lines'] += 1
            pos = end + 1
        st['chars'] += len(cells) - cells.count(SPACE)
        tail = cells[licence_end:]
        st['comment_chars'] += tail.count(PLAIN) + tail.count(DOC)
    return {'stats': dict(st), 'markers': dict(markers), 'tags': dict(tags), 'skipped_files': skipped}


def main():
    if len(sys.argv) < 3:
        sys.exit(__doc__)
    root, python_lib = sys.argv[1], sys.argv[2]
    out_path = sys.argv[3] if len(sys.argv) > 3 else 'comment-counts.json'
    results = {}
    head = f"{'project':30} {'files':>6} {'lines':>9} {'comment':>8} {'doc':>6} {'plain':>6} {'docstr':>7} {'chars':>6}  tags/1k"
    print(head)
    total_files = total_lines = total_licence = total_skipped = 0
    for name, (sub, exts, lang) in PROJECTS.items():
        base = python_lib if sub is None else os.path.join(root, sub)
        if not os.path.isdir(base):
            sys.exit(f'missing folder: {base}')
        r = count_project(base, exts, lang)
        s = collections.Counter(r['stats'])
        lines = s['lines'] - s['licence_lines']  # non-blank lines outside licence headers
        pct = lambda n: 100.0 * n / lines
        r['summary'] = {
            'files': s['files'],
            'lines': lines,
            'licence_lines': s['licence_lines'],
            'comment_pct': round(pct(s['doc_lines'] + s['plain_lines']), 1),
            'doc_pct': round(pct(s['doc_lines']), 1),
            'plain_pct': round(pct(s['plain_lines']), 1),
            'docstring_pct': round(pct(s['docstring_lines']), 1),
            'comment_chars_pct': round(100.0 * s['comment_chars'] / s['chars'], 1),
            'tags_per_1000_lines': round(1000.0 * sum(r['tags'].values()) / lines, 2),
            'generated_files_skipped': len(r['skipped_files']),
        }
        if lang in CONVENTIONS:
            r['summary'][CONVENTIONS[lang][0]] = s['convention']
        results[name] = r
        m = r['summary']
        print(f"{name:30} {m['files']:6,} {m['lines']:9,} {m['comment_pct']:7.1f}% {m['doc_pct']:5.1f}% "
              f"{m['plain_pct']:5.1f}% {m['docstring_pct']:6.1f}% {m['comment_chars_pct']:5.1f}%  {m['tags_per_1000_lines']:.2f}")
        total_files += m['files']
        total_lines += m['lines']
        total_licence += m['licence_lines']
        total_skipped += m['generated_files_skipped']
    print(f"{'total':30} {total_files:6,} {total_lines:9,}   licence header lines left out: {total_licence:,}; "
          f"generated files skipped: {total_skipped}")
    with open(out_path, 'w') as fh:
        json.dump(results, fh, indent=1)
    print('wrote', out_path)


if __name__ == '__main__':
    main()
