#!/usr/bin/env python3 """Measure C/C++ coding-style features consistently across corpora in ./corpus/*.""" import os, re, sys, csv, collections, statistics as st ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'corpus') EXT = ('.c', '.cpp', '.h', '.hpp', '.txt', '.java', '.js') def read(p): with open(p, 'rb') as fh: t = fh.read().decode('latin-1') return t.replace('\r\n', '\n').replace('\r', '\n') def strip_comments_strings(src): """Return (code_without_comments_and_string_contents, list_of_comments). Keeps line structure.""" out = []; comments = []; i = 0; n = len(src) while i < n: c = src[i] if src.startswith('//', i): j = src.find('\n', i); j = n if j < 0 else j comments.append(('line', src[i:j])); out.append(' ' * (j - i)); i = j elif src.startswith('/*', i): j = src.find('*/', i + 2); j = n if j < 0 else j + 2 comments.append(('block', src[i:j])); out.append(''.join('\n' if ch == '\n' else ' ' for ch in src[i:j])); i = j elif c in '"\'': j = i + 1 while j < n and src[j] != c and src[j] != '\n': j += 2 if src[j] == '\\' else 1 j = min(j + 1, n); out.append(c + ' ' * max(0, j - i - 2) + c); i = j else: out.append(c); i += 1 return ''.join(out), comments SATOSHI_PREFIX = re.compile(r'^(vch|psz|str|map|set|pindex|pfrom|pto|pnode|ptx|vec|n|f|p|v|ch|hash|wtx|tx)[A-Z]') WIN_HUNGARIAN = re.compile(r'^(dw|lp|lpsz|sz|w|b|by|u|ul|l|i|h|hwnd|c|cb|ch|pb|pv)[A-Z]') GENERIC_NONHUNG = re.compile(r'^[a-z][a-z0-9]*$') # all-lowercase single word e.g. "count" KEYWORDS = set('if else for while do switch case return break continue goto sizeof typedef struct class union enum public private protected virtual static const extern inline unsigned signed int char long short void bool float double auto register volatile template typename namespace using new delete this true false NULL operator friend throw try catch default include define ifdef ifndef endif pragma undef elif'.split()) def analyze(name, files, line_only=False): m = collections.Counter(); linelens = []; funclens = []; idents = collections.Counter(); decl_idents = collections.Counter() comment_words = collections.Counter() for p in files: raw = read(p); code, comments = strip_comments_strings(raw) rlines = raw.split('\n'); clines = code.split('\n') for kind, ctext in comments: m['cmt_' + kind] += 1 if kind == 'line' and re.match(r'^/{6,}\s*$', ctext.strip()): m['banner_slash'] += 1 if kind == 'block' and re.match(r'^/\*[*=\-]{5,}', ctext): m['banner_block'] += 1 if kind == 'line' and ctext.startswith('///'): m['cmt_tripleslash'] += 1 prev = '' depth0_start = None; depth = 0 for k, (rl, cl) in enumerate(zip(rlines, clines)): if rl.strip() == '': m['blank'] += 1; continue m['nonblank'] += 1 linelens.append(len(rl.expandtabs(4))) s = cl.strip() if s == '': m['comment_only_lines'] += 1; continue m['code_lines'] += 1 ind = re.match(r'^[ \t]*', cl).group(0) if ind: m['indented'] += 1 if ind.startswith('\t'): m['indent_tab'] += 1 elif '\t' not in ind: m['indent_space'] += 1; m['space_ind_%d' % len(ind)] += 1 # braces if s == '{': m['brace_alone'] += 1 elif s.endswith('{') and not s.startswith('{'): m['brace_eol'] += 1 if re.match(r'^\}\s*else\b', s): m['cuddled_else'] += 1 if s.startswith('else') : m['else_newline'] += 1 if re.search(r'\{[^{}]*;\s*\}\s*$', s) and re.search(r'\)\s*(const\s*)?\{', s): m['oneline_body'] += 1 # keyword-paren spacing for kw in ('if', 'for', 'while', 'switch'): m['kw_space'] += len(re.findall(r'\b%s \(' % kw, s)); m['kw_nospace'] += len(re.findall(r'\b%s\(' % kw, s)) m['comma_space'] += len(re.findall(r',[ \t]', s)); m['comma_nospace'] += len(re.findall(r',[^ \t\n]', s)) m['paren_pad'] += len(re.findall(r'\( \S', s)) ; m['paren_nopad'] += len(re.findall(r'\([^ )]', s)) m['assign_spaced'] += len(re.findall(r'\w \= \w', s)); m['assign_tight'] += len(re.findall(r'\w=\w', s)) # single-statement if on one line without braces if re.match(r'^(if|else if)\s*\(.*\)\s*[^{;\s][^{]*;$', s) : m['if_oneline'] += 1 if re.match(r'^(if|else if|for|while)\b.*\)$', s): m['ctl_header_alone'] += 1 # pointer style m['ptr_type_side'] += len(re.findall(r'\b[A-Za-z_]\w*[*&] [A-Za-z_]', s)) m['ptr_name_side'] += len(re.findall(r'\b[A-Za-z_]\w* [*&][A-Za-z_]', s)) # null checks m['eq_null'] += len(re.findall(r'[!=]= ?NULL|NULL ?[!=]=', s)); m['yoda_null'] += len(re.findall(r'NULL ?[!=]=', s)) m['loop_macro'] += len(re.findall(r'^\s*loop\b', cl)); m['for_ever'] += len(re.findall(r'for ?\( ?; ?; ?\)|while ?\( ?(1|true|TRUE) ?\)', s)) m['foreach_macro'] += len(re.findall(r'\b(foreach|BOOST_FOREACH)\s*\(', s)) m['critical_block'] += len(re.findall(r'\bCRITICAL_BLOCK\b', s)) m['printf_family'] += len(re.findall(r'\b(printf|fprintf|sprintf|snprintf|strprintf|_snprintf|wsprintf)\s*\(', s)) m['cout_cerr'] += len(re.findall(r'\b(cout|cerr)\b', s)) m['define'] += 1 if re.match(r'^#\s*define\b', s) else 0 m['typedef'] += len(re.findall(r'\btypedef\b', s)) m['int64_name'] += len(re.findall(r'\b(int64|uint64|__int64|int64_t|uint64_t|u_int64_t|word64|LONGLONG|ULONGLONG)\b', s)) m['long_long'] += len(re.findall(r'\blong long\b', s)) m['const_ref_param'] += len(re.findall(r'\bconst [\w:<>, ]+&\s*\w', s)) m['stl'] += len(re.findall(r'\b(std::)?(vector|map|multimap|set|list|deque|string|pair)\s*<', s)) m['boost'] += len(re.findall(r'\bboost::', s)) + (1 if '#include >', s)) for t in re.findall(r'\b[A-Za-z_]\w*\b', s): if t not in KEYWORDS: idents[t] += 1 # declared names: "Type name =|;|,|)|[" for t in re.findall(r'\b(?:int|unsigned|char|bool|long|short|double|float|void|string|uint256|int64|DWORD|BOOL|BYTE|size_t|word32|byte|[A-Z]\w*)\s*[*&]?\s*[*&]?\s*([A-Za-z_]\w*)\s*(?=[=;,)\[])', s): if t not in KEYWORDS and len(t) > 1: decl_idents[t] += 1 # function length (top-level '{' at column 0 after a ')' line) if not line_only: if cl.startswith('{') and depth == 0 and re.search(r'\)\s*(const)?\s*$', prev): depth0_start = k if depth0_start is not None and cl.startswith('}'): funclens.append(k - depth0_start - 1); depth0_start = None prev = s r = {'corpus': name, 'files': len(files)} r.update(m) nb = max(m['nonblank'], 1); kloc = max(m['code_lines'], 1) / 1000.0 def ratio(a, b): return round(m[a] / (m[a] + m[b]), 3) if (m[a] + m[b]) else '' r['tab_indent_ratio'] = ratio('indent_tab', 'indent_space') sp = {int(k.split('_')[2]): v for k, v in m.items() if k.startswith('space_ind_')} # infer indent unit: most common among small indents small = {k: v for k, v in sp.items() if 0 < k <= 8} r['dominant_space_indent'] = max(small, key=small.get) if small else '' r['allman_ratio'] = ratio('brace_alone', 'brace_eol') r['kw_space_ratio'] = ratio('kw_space', 'kw_nospace') r['comma_space_ratio'] = ratio('comma_space', 'comma_nospace') r['assign_spaced_ratio'] = ratio('assign_spaced', 'assign_tight') r['ptr_type_side_ratio'] = ratio('ptr_type_side', 'ptr_name_side') r['preinc_ratio'] = ratio('preinc', 'postinc') r['line_comment_ratio'] = ratio('cmt_line', 'cmt_block') r['hex_lower_ratio'] = ratio('hex_lower', 'hex_upper') r['comment_lines_pct'] = round(100 * m['comment_only_lines'] / nb, 1) r['mean_line_len'] = round(st.mean(linelens), 1) if linelens else '' r['p95_line_len'] = sorted(linelens)[int(0.95 * len(linelens))] if linelens else '' r['pct_lines_gt100'] = round(100 * sum(1 for x in linelens if x > 100) / len(linelens), 1) if linelens else '' r['median_func_len'] = st.median(funclens) if funclens else '' r['n_funcs_measured'] = len(funclens) for key in ('if_oneline', 'oneline_body', 'banner_slash', 'banner_block', 'loop_macro', 'for_ever', 'foreach_macro', 'critical_block', 'printf_family', 'cout_cerr', 'define', 'typedef', 'int64_name', 'long_long', 'const_ref_param', 'stl', 'boost', 'win_api', 'wx', 'ifdef_win', 'throw', 'goto', 'return_bool', 'return_TF', 'return_error_fn', 'return_negnum', 'return_paren', 'templates', 'eq_null', 'IMPLEMENT_SERIALIZE', 'cuddled_else', 'ctl_header_alone'): r[key + '_per_kloc'] = round(m[key] / kloc, 2) r['class_C_prefix_ratio'] = round(m['class_C_prefix'] / m['class_decl'], 3) if m['class_decl'] else '' # Hungarian on declared identifiers (distinct) D = list(decl_idents) if D: r['decl_distinct'] = len(D) r['decl_satoshi_prefix_pct'] = round(100 * sum(1 for t in D if SATOSHI_PREFIX.match(t)) / len(D), 1) r['decl_win_hungarian_pct'] = round(100 * sum(1 for t in D if WIN_HUNGARIAN.match(t)) / len(D), 1) r['decl_lowercase_word_pct'] = round(100 * sum(1 for t in D if GENERIC_NONHUNG.match(t)) / len(D), 1) r['decl_snake_pct'] = round(100 * sum(1 for t in D if re.match(r'^[a-z]+(_[a-z0-9]+)+$', t)) / len(D), 1) r['decl_camel_lower_pct'] = round(100 * sum(1 for t in D if re.match(r'^[a-z]{2,}[A-Z]', t) and not SATOSHI_PREFIX.match(t) and not WIN_HUNGARIAN.match(t)) / len(D), 1) r['decl_m_prefix_pct'] = round(100 * sum(1 for t in D if re.match(r'^m_?[A-Z]', t)) / len(D), 1) r['decl_g_prefix_pct'] = round(100 * sum(1 for t in D if re.match(r'^g_?[A-Z]', t)) / len(D), 1) # specific satoshi prefixes on all identifier tokens for pre in ('vch', 'psz', 'str', 'map', 'pindex', 'n', 'f', 'p'): r['tok_%s_per_kloc' % pre] = round(sum(c for t, c in idents.items() if re.match(r'^%s[A-Z]' % pre, t)) / kloc, 1) r['top_decl_examples'] = ' '.join(t for t, _ in decl_idents.most_common(25)) return r def corpus_files(d): out = [] for dp, _, fs in os.walk(d): for f in fs: if f.lower().endswith(EXT): out.append(os.path.join(dp, f)) return sorted(out) if __name__ == '__main__': rows = [] for name in sorted(os.listdir(ROOT)): fs = corpus_files(os.path.join(ROOT, name)) rows.append(analyze(name, fs, line_only=name.endswith(('_blame', '_added', '_cvs')))) keys = [] for r in rows: for k in r: if k not in keys and not k.startswith('space_ind_'): keys.append(k) with open(os.path.join(os.path.dirname(ROOT), 'metrics.csv'), 'w', newline='') as fh: w = csv.DictWriter(fh, fieldnames=keys, extrasaction='ignore'); w.writeheader(); [w.writerow(r) for r in rows] # transposed print for k in keys: print(k.ljust(30), ' | '.join(str(r.get(k, ''))[:14].rjust(14) for r in rows))