aboutsummaryrefslogtreecommitdiffstats
path: root/dev-scripts/generate.py
blob: 7d6668df1f58b881089913b6eb30401a04d60cfe (plain)
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
#!/usr/bin/env python3

_license_text = \
"""/*
  This file is part of the clazy static checker.

  Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  Author: Sérgio Martins <sergio.martins@kdab.com>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/
"""

import sys, os, json, argparse

CHECKS_FILENAME = 'checks.json'
_checks = []
_available_categories = []

def checkSortKey(check):
    return str(check.level) + check.name

def level_num_to_enum(n):
    if n == -1:
        return 'ManualCheckLevel'
    if n >= 0 and n <= 3:
        return 'CheckLevel' + str(n)

    return 'CheckLevelUndefined'

def level_num_to_name(n):
    if n == -1:
        return 'Manual Level'
    if n >= 0 and n <= 3:
        return 'Level ' + str(n)

    return 'undefined'

def clazy_source_path():
    return os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/..") + "/"

def templates_path():
    return clazy_source_path() + "dev-scripts/templates/"

class Check:
    def __init__(self):
        self.name = ""
        self.class_name = ""
        self.level = 0
        self.categories = []
        self.minimum_qt_version = 40000 # Qt 4.0.0
        self.fixits = []
        self.visits_stmts = False
        self.visits_decls = False
        self.ifndef = ""

    def include(self):
        headername = self.name + ".h"
        filename = self.basedir() + "/" + headername
        if not os.path.exists(clazy_source_path() + 'src/' + filename):
            filename = filename.replace('-', '')

        return filename

    def cpp_filename(self):
        filename = self.include()
        filename = filename.replace(".h", ".cpp")
        return filename

    def basedir(self, with_src=False):
        level = 'level' + str(self.level)
        if self.level == -1:
            level = 'manuallevel'

        if with_src:
            return "src/checks/" + level
        return "checks/" + level

    def readme_path(self):
        return clazy_source_path() + self.basedir(True) + "/" + "README-" + self.name + ".md"


    def supportsQt4(self):
        return self.minimum_qt_version < 50000

    def get_class_name(self):
        if self.class_name:
            return self.class_name

        # Deduce the class name
        splitted = self.name.split('-')
        classname = ""
        for word in splitted:
            word = word.title()
            if word.startswith('Q'):
                word = 'Q' + word[1:].title()

            classname += word

        return classname

    def valid_name(self):
        if self.name in ['clazy']:
            return False
        if self.name.startswith('level'):
            return False
        if self.name.startswith('fix'):
            return False
        return True

    def fixits_text(self):
        if not self.fixits:
            return ""

        text = ""
        fixitnames = []
        for f in self.fixits:
            fixitnames.append("fix-" + f)

        text = ','.join(fixitnames)

        return "(" + text + ")"


def load_json(filename):
    f = open(filename, 'r')
    jsonContents = f.read()
    f.close()
    decodedJson = json.loads(jsonContents)

    if 'checks' not in decodedJson:
        print("No checks found in " + filename)
        return False

    checks = decodedJson['checks']

    global _available_categories, _checks
    if 'available_categories' in decodedJson:
        _available_categories = decodedJson['available_categories']

    for check in checks:
        c = Check()
        try:
            c.name = check['name']
            c.level = check['level']
            c.categories = check['categories']
            for cat in c.categories:
                if cat not in _available_categories:
                    print('Unknown category ' + cat)
                    return False
        except KeyError:
            print("Missing mandatory field while processing " + str(check))
            return False

        if 'class_name' in check:
            c.class_name = check['class_name']

        if 'ifndef' in check:
            c.ifndef = check['ifndef']

        if 'minimum_qt_version' in check:
            c.minimum_qt_version = check['minimum_qt_version']

        if 'visits_stmts' in check:
            c.visits_stmts = check['visits_stmts']

        if 'visits_decls' in check:
            c.visits_decls = check['visits_decls']

        if 'fixits' in check:
            for fixit in check['fixits']:
                if 'name' not in fixit:
                    print('fixit doesnt have a name. check=' + str(check))
                    return False
                c.fixits.append(fixit['name'])

        if not c.valid_name():
            print("Invalid check name: %s" % (c.name()))
            return False
        _checks.append(c)

    _checks = sorted(_checks, key=checkSortKey)
    return True

def print_checks(checks):
    for c in checks:
        print(c.name + " " + str(c.level) + " " + str(c.categories))

#-------------------------------------------------------------------------------
def generate_register_checks(checks):
    text = '#include "checkmanager.h"\n'
    for c in checks:
        text += '#include "' + c.include() + '"\n'
    text += \
"""
template <typename T>
RegisteredCheck check(const char *name, CheckLevel level, RegisteredCheck::Options options = RegisteredCheck::Option_None)
{
    auto factoryFuntion = [name](ClazyContext *context){ return new T(name, context); };
    return RegisteredCheck{name, level, factoryFuntion, options};
}

void CheckManager::registerChecks()
{
"""

    for c in checks:
        qt4flag = "RegisteredCheck::Option_None"
        if not c.supportsQt4():
            qt4flag = "RegisteredCheck::Option_Qt4Incompatible"

        if c.visits_stmts:
            qt4flag += " | RegisteredCheck::Option_VisitsStmts"
        if c.visits_decls:
            qt4flag += " | RegisteredCheck::Option_VisitsDecls"

        qt4flag = qt4flag.replace("RegisteredCheck::Option_None |", "")

        if c.ifndef:
            text += "#ifndef " + c.ifndef + "\n"

        text += '    registerCheck(check<%s>("%s", %s, %s));\n' % (c.get_class_name(), c.name, level_num_to_enum(c.level), qt4flag)

        fixitID = 1
        for fixit in c.fixits:
            text += '    registerFixIt(%d, "%s", "%s");\n' % (fixitID, "fix-" + fixit, c.name)
            fixitID = fixitID * 2

        if c.ifndef:
            text += "#endif" + "\n"

    text += "}\n"

    comment_text = \
"""
/**
 * To add a new check you can either edit this file, or use the python script:
 * dev-scripts/generate.py > src/Checks.h
 */
"""
    text = _license_text + '\n' + comment_text + '\n' + text
    filename = clazy_source_path() + "src/Checks.h"
    f = open(filename, 'w')
    f.write(text)
    f.close()
    print("Generated " + filename)
#-------------------------------------------------------------------------------
def generate_cmake_file(checks):
    text = "set(CLAZY_CHECKS_SRCS ${CLAZY_CHECKS_SRCS}\n"
    checks_with_regexp = []
    for level in [-1, 0, 1, 2, 3]:
        for check in checks:
            if check.level == level:
                text += "  ${CMAKE_CURRENT_LIST_DIR}/src/" + check.cpp_filename() + "\n"
                if check.ifndef == "NO_STD_REGEX":
                    checks_with_regexp.append(check)
    text += ")\n"

    if checks_with_regexp:
        text += "\nif(HAS_STD_REGEX OR CLAZY_BUILD_WITH_CLANG)\n"
        for check in checks_with_regexp:
            text += "  set(CLAZY_CHECKS_SRCS ${CLAZY_CHECKS_SRCS} ${CMAKE_CURRENT_LIST_DIR}/src/" + check.cpp_filename() + ")\n"
        text += "endif()\n"

    filename = clazy_source_path() + "CheckSources.cmake"
    f = open(filename, 'w')
    f.write(text)
    f.close()
    print("Generated " + filename)
#-------------------------------------------------------------------------------
def create_readmes(checks):
    for check in checks:
        if not os.path.exists(check.readme_path()):
            f = open(templates_path() + "check-readme.md", 'r')
            contents = f.read()
            f.close()
            contents = contents.replace('[check-name]', check.name)
            f = open(check.readme_path(), 'w')
            f.write(contents)
            f.close()
            print("Created " + check.readme_path())
#-------------------------------------------------------------------------------
def generate_readme(checks):

    filename = clazy_source_path() + "README.md"
    f = open(filename, 'r')
    old_contents = f.readlines();
    f.close();

    new_text_to_insert = ""
    for level in ['-1', '0', '1', '2', '3']:
        new_text_to_insert += "- Checks from %s:" % level_num_to_name(int(level)) + "\n"
        for c in checks:
            if str(c.level) == level:
                fixits_text = c.fixits_text()
                if fixits_text:
                    fixits_text = "    " + fixits_text
                new_text_to_insert += "    - [%s](%s/README-%s.md)%s" % (c.name, c.basedir(True), c.name, fixits_text) + "\n"
        new_text_to_insert += "\n"


    f = open(filename, 'w')

    skip = False
    for line in old_contents:
        if skip and line.startswith("#"):
            skip = False

        if skip:
            continue

        if line.startswith("- Checks from Manual Level:"):
            skip = True
            f.write(new_text_to_insert)
            continue

        f.write(line)
    f.close()
    print("Generated " + filename)
#-------------------------------------------------------------------------------

complete_json_filename = clazy_source_path() + CHECKS_FILENAME

if not os.path.exists(complete_json_filename):
    print("File doesn't exist: " + complete_json_filename)
    exit(1)

if not load_json(complete_json_filename):
    exit(1)

parser = argparse.ArgumentParser()
parser.add_argument("--generate", action='store_true', help="Generate src/Checks.h, CheckSources.cmake and README.md")
args = parser.parse_args()

if args.generate:
    generate_register_checks(_checks)
    generate_cmake_file(_checks)
    generate_readme(_checks)
    create_readmes(_checks)
else:
    parser.print_help(sys.stderr)