blob: 6000616d0b098e1e89eee90fb1d2c72ae1806e57 [file] [log] [blame]
Daniel Jasper4ecc8b32014-12-09 10:02:51 +00001#!/usr/bin/env python
2#
3#===- add_new_check.py - clang-tidy check generator ----------*- python -*--===#
4#
5# The LLVM Compiler Infrastructure
6#
7# This file is distributed under the University of Illinois Open Source
8# License. See LICENSE.TXT for details.
9#
10#===------------------------------------------------------------------------===#
11
12import os
13import re
14import sys
15
16
17# Adapts the module's CMakelist file. Returns 'True' if it could add a new entry
18# and 'False' if the entry already existed.
19def adapt_cmake(module_path, check_name_camel):
20 filename = os.path.join(module_path, 'CMakeLists.txt')
21 with open(filename, 'r') as f:
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000022 lines = f.readlines()
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000023
24 cpp_file = check_name_camel + '.cpp'
25
26 # Figure out whether this check already exists.
27 for line in lines:
28 if line.strip() == cpp_file:
29 return False
30
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000031 print('Updating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +000032 with open(filename, 'wb') as f:
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000033 cpp_found = False
34 file_added = False
35 for line in lines:
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000036 cpp_line = line.strip().endswith('.cpp')
Alexander Kornienkoc0ebfbe52015-09-04 14:56:57 +000037 if (not file_added) and (cpp_line or cpp_found):
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000038 cpp_found = True
Alexander Kornienkoc0ebfbe52015-09-04 14:56:57 +000039 if (line.strip() > cpp_file) or (not cpp_line):
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000040 f.write(' ' + cpp_file + '\n')
41 file_added = True
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000042 f.write(line)
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000043
44 return True
45
46
47# Adds a header for the new check.
48def write_header(module_path, module, check_name, check_name_camel):
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000049 check_name_dashes = module + '-' + check_name
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000050 filename = os.path.join(module_path, check_name_camel) + '.h'
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000051 print('Creating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +000052 with open(filename, 'wb') as f:
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000053 header_guard = ('LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_' + module.upper() +
54 '_' + check_name.upper().replace('-', '_') + '_H')
55 f.write('//===--- ')
56 f.write(os.path.basename(filename))
57 f.write(' - clang-tidy')
58 f.write('-' * max(0, 43 - len(os.path.basename(filename))))
59 f.write('*- C++ -*-===//')
60 f.write("""
61//
62// The LLVM Compiler Infrastructure
63//
64// This file is distributed under the University of Illinois Open Source
65// License. See LICENSE.TXT for details.
66//
67//===----------------------------------------------------------------------===//
68
69#ifndef %(header_guard)s
70#define %(header_guard)s
71
72#include "../ClangTidy.h"
73
74namespace clang {
75namespace tidy {
Alexander Kornienko821ca472015-12-16 15:05:27 +000076namespace %(module)s {
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000077
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000078/// FIXME: Write a short description.
79///
80/// For the user-facing documentation see:
81/// http://clang.llvm.org/extra/clang-tidy/checks/%(check_name_dashes)s.html
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000082class %(check_name)s : public ClangTidyCheck {
83public:
84 %(check_name)s(StringRef Name, ClangTidyContext *Context)
85 : ClangTidyCheck(Name, Context) {}
86 void registerMatchers(ast_matchers::MatchFinder *Finder) override;
87 void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
88};
89
Alexander Kornienko821ca472015-12-16 15:05:27 +000090} // namespace %(module)s
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000091} // namespace tidy
92} // namespace clang
93
94#endif // %(header_guard)s
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000095""" % {'header_guard': header_guard,
Alexander Kornienko3285f1b2015-09-10 13:56:39 +000096 'check_name': check_name_camel,
Alexander Kornienko821ca472015-12-16 15:05:27 +000097 'check_name_dashes': check_name_dashes,
98 'module': module})
Daniel Jasper4ecc8b32014-12-09 10:02:51 +000099
100
101# Adds the implementation of the new check.
Alexander Kornienko821ca472015-12-16 15:05:27 +0000102def write_implementation(module_path, module, check_name_camel):
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000103 filename = os.path.join(module_path, check_name_camel) + '.cpp'
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000104 print('Creating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +0000105 with open(filename, 'wb') as f:
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000106 f.write('//===--- ')
107 f.write(os.path.basename(filename))
108 f.write(' - clang-tidy')
109 f.write('-' * max(0, 52 - len(os.path.basename(filename))))
110 f.write('-===//')
111 f.write("""
112//
113// The LLVM Compiler Infrastructure
114//
115// This file is distributed under the University of Illinois Open Source
116// License. See LICENSE.TXT for details.
117//
118//===----------------------------------------------------------------------===//
119
120#include "%(check_name)s.h"
121#include "clang/AST/ASTContext.h"
122#include "clang/ASTMatchers/ASTMatchFinder.h"
123
124using namespace clang::ast_matchers;
125
126namespace clang {
127namespace tidy {
Alexander Kornienko821ca472015-12-16 15:05:27 +0000128namespace %(module)s {
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000129
130void %(check_name)s::registerMatchers(MatchFinder *Finder) {
131 // FIXME: Add matchers.
132 Finder->addMatcher(functionDecl().bind("x"), this);
133}
134
135void %(check_name)s::check(const MatchFinder::MatchResult &Result) {
136 // FIXME: Add callback implementation.
Alexander Kornienko423236b2014-12-09 12:43:09 +0000137 const auto *MatchedDecl = Result.Nodes.getNodeAs<FunctionDecl>("x");
138 if (MatchedDecl->getName().startswith("awesome_"))
139 return;
140 diag(MatchedDecl->getLocation(), "function '%%0' is insufficiently awesome")
141 << MatchedDecl->getName()
142 << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_");
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000143}
144
Alexander Kornienko821ca472015-12-16 15:05:27 +0000145} // namespace %(module)s
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000146} // namespace tidy
147} // namespace clang
Alexander Kornienko821ca472015-12-16 15:05:27 +0000148""" % {'check_name': check_name_camel,
149 'module': module})
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000150
151
152# Modifies the module to include the new check.
153def adapt_module(module_path, module, check_name, check_name_camel):
Aaron Ballmanaaa40802015-10-06 13:31:00 +0000154 modulecpp = filter(lambda p: p.lower() == module.lower() + "tidymodule.cpp", os.listdir(module_path))[0]
155 filename = os.path.join(module_path, modulecpp)
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000156 with open(filename, 'r') as f:
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000157 lines = f.readlines()
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000158
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000159 print('Updating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +0000160 with open(filename, 'wb') as f:
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000161 header_added = False
162 header_found = False
163 check_added = False
164 check_decl = (' CheckFactories.registerCheck<' + check_name_camel +
165 '>(\n "' + module + '-' + check_name + '");\n')
166
167 for line in lines:
168 if not header_added:
169 match = re.search('#include "(.*)"', line)
170 if match:
171 header_found = True
172 if match.group(1) > check_name_camel:
173 header_added = True
174 f.write('#include "' + check_name_camel + '.h"\n')
175 elif header_found:
176 header_added = True
177 f.write('#include "' + check_name_camel + '.h"\n')
178
179 if not check_added:
180 if line.strip() == '}':
181 check_added = True
182 f.write(check_decl)
183 else:
184 match = re.search('registerCheck<(.*)>', line)
185 if match and match.group(1) > check_name_camel:
186 check_added = True
187 f.write(check_decl)
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000188 f.write(line)
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000189
190
191# Adds a test for the check.
192def write_test(module_path, module, check_name):
Alexander Kornienko423236b2014-12-09 12:43:09 +0000193 check_name_dashes = module + '-' + check_name
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000194 filename = os.path.normpath(
195 os.path.join(module_path, '../../test/clang-tidy',
196 check_name_dashes + '.cpp'))
197 print('Creating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +0000198 with open(filename, 'wb') as f:
Alexander Kornienko423236b2014-12-09 12:43:09 +0000199 f.write(
Matthias Gehre9ec20032015-10-26 21:48:08 +0000200"""// RUN: %%check_clang_tidy %%s %(check_name_dashes)s %%t
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000201
Alexander Kornienko423236b2014-12-09 12:43:09 +0000202// FIXME: Add something that triggers the check here.
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000203void f();
Alexander Kornienko423236b2014-12-09 12:43:09 +0000204// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'f' is insufficiently awesome [%(check_name_dashes)s]
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000205
Alexander Kornienko423236b2014-12-09 12:43:09 +0000206// FIXME: Verify the applied fix.
207// * Make the CHECK patterns specific enough and try to make verified lines
208// unique to avoid incorrect matches.
209// * Use {{}} for regular expressions.
210// CHECK-FIXES: {{^}}void awesome_f();{{$}}
211
212// FIXME: Add something that doesn't trigger the check here.
213void awesome_f2();
214""" % {"check_name_dashes" : check_name_dashes})
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000215
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000216# Recreates the list of checks in the docs/clang-tidy/checks directory.
217def update_checks_list(module_path):
Aaron Ballmanf5f9bf42016-01-11 16:48:26 +0000218 docs_dir = os.path.join(module_path, '../../docs/clang-tidy/checks')
219 filename = os.path.normpath(os.path.join(docs_dir, 'list.rst'))
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000220 with open(filename, 'r') as f:
221 lines = f.readlines()
Aaron Ballmanf5f9bf42016-01-11 16:48:26 +0000222 doc_files = filter(
223 lambda s: s.endswith('.rst') and s != 'list.rst',
224 os.listdir(docs_dir))
225 doc_files.sort()
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000226
Aaron Ballmanf5f9bf42016-01-11 16:48:26 +0000227 def format_link(doc_file):
228 check_name = doc_file.replace('.rst', '')
229 with open(os.path.join(docs_dir, doc_file), 'r') as doc:
230 match = re.search('.*:http-equiv=refresh: \d+;URL=(.*).html.*', doc.read())
231 if match:
232 return ' %(check)s (redirects to %(target)s) <%(check)s>\n' % {
233 'check' : check_name, 'target' : match.group(1) }
234 return ' %s\n' % check_name
235
236 checks = map(format_link, doc_files)
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000237
238 print('Updating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +0000239 with open(filename, 'wb') as f:
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000240 for line in lines:
241 f.write(line)
242 if line.startswith('.. toctree::'):
243 f.writelines(checks)
244 break
245
246# Adds a documentation for the check.
247def write_docs(module_path, module, check_name):
248 check_name_dashes = module + '-' + check_name
249 filename = os.path.normpath(
250 os.path.join(module_path, '../../docs/clang-tidy/checks/',
251 check_name_dashes + '.rst'))
252 print('Creating %s...' % filename)
Aaron Ballman017bfee2015-10-06 19:11:12 +0000253 with open(filename, 'wb') as f:
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000254 f.write(
Alexander Kornienko785e5222015-12-22 17:36:49 +0000255""".. title:: clang-tidy - %(check_name_dashes)s
256
257%(check_name_dashes)s
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000258%(underline)s
259
260FIXME: Describe what patterns does the check detect and why. Give examples.
261""" % {"check_name_dashes" : check_name_dashes,
262 "underline" : "=" * len(check_name_dashes)})
263
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000264def main():
265 if len(sys.argv) != 3:
266 print 'Usage: add_new_check.py <module> <check>, e.g.\n'
Alexander Kornienko423236b2014-12-09 12:43:09 +0000267 print 'add_new_check.py misc awesome-functions\n'
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000268 return
269
270 module = sys.argv[1]
271 check_name = sys.argv[2]
272 check_name_camel = ''.join(map(lambda elem: elem.capitalize(),
273 check_name.split('-'))) + 'Check'
274 clang_tidy_path = os.path.dirname(sys.argv[0])
275 module_path = os.path.join(clang_tidy_path, module)
276
277 if not adapt_cmake(module_path, check_name_camel):
278 return
279 write_header(module_path, module, check_name, check_name_camel)
Alexander Kornienko821ca472015-12-16 15:05:27 +0000280 write_implementation(module_path, module, check_name_camel)
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000281 adapt_module(module_path, module, check_name, check_name_camel)
282 write_test(module_path, module, check_name)
Alexander Kornienko3285f1b2015-09-10 13:56:39 +0000283 write_docs(module_path, module, check_name)
284 update_checks_list(module_path)
285 print('Done. Now it\'s your turn!')
Daniel Jasper4ecc8b32014-12-09 10:02:51 +0000286
287if __name__ == '__main__':
288 main()