timeit

Програмиране с Python

Курс във Факултета по Математика и Информатика към СУ

Решение на Статичен анализ на python код от Даниел Делчев

Обратно към всички решения

Към профила на Даниел Делчев

Резултати

  • 9 точки от тестове
  • 0 бонус точки
  • 9 точки общо
  • 10 успешни тест(а)
  • 1 неуспешни тест(а)

Код

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
from collections import defaultdict
import ast
import re


class VisitorOne(ast.NodeVisitor):
    level_line = 0

    def __init__(self, own_level=0):
        self.own_level = own_level
        self.visited = list()

    def visit_FunctionDef(self, node):
        next_level = self.own_level + 1
        for subnode in ast.iter_child_nodes(node):
            subvisitor = VisitorOne(next_level)
            if subnode not in self.visited:
                self.visited.append(subnode)
                subvisitor.visited = self.visited
                subvisitor.visit(subnode)
                if subvisitor.own_level > self.own_level:
                    self.own_level = subvisitor.own_level
                    if node.lineno > VisitorOne.level_line:
                        VisitorOne.level_line = node.lineno

    visit_If = visit_Try = visit_While = visit_With = visit_For = \
        visit_FunctionDef

    def visit_ClassDef(self, node):
        for sub in ast.iter_child_nodes(node):
            subvisitor = VisitorOne()
            subvisitor.visit(sub)


def ends_with_space(line):
    pattern1 = r'^.* $'
    pattern2 = r'^.*    $'
    return bool(re.search(pattern1, line)) or bool(re.search(pattern2, line))


def multiple_expressions(line):
    pattern = r'^.*;.*$'
    return bool(re.search(pattern, line, re.X))


def not_empty_line(line):
    return not(bool(not line or line.isspace()))


def count_indentation(line):
    count = 0
    length = len(line)
    for i in range(0, length):
        if line[i] == " ":
            count += 1
        else:
            break
    return count


def critic(code, **rules):
    result = defaultdict(list)

    if "line_length" in rules:
        max_length = rules["line_length"]
    else:
        max_length = 79

    if "forbid_trailing_white_space" in rules:
        no_ending_white_space = rules["forbid_trailing_white_space"]
    else:
        no_ending_white_space = True

    if "forbid_semicolons" in rules:
        semi_colon_forbidden = rules["forbid_semicolons"]
    else:
        semi_colon_forbidden = True

    if "indentation_size" in rules:
        allowed_indentation = rules["indentation_size"]
    else:
        allowed_indentation = 4

    lines = code.splitlines()

    used_indentation = 4
    for line in lines:
        cur = count_indentation(line)
        if cur >= 1:
            used_indentation = cur
            break

    current_line = 0
    for line in lines:
        current_line += 1
        current_line_length = len(line)
        if current_line_length > max_length:
            result[current_line].append("line too long ({0} > {1})".format(
                current_line_length, max_length))
        if no_ending_white_space and ends_with_space(line):
            result[current_line].append("trailing whitespace")
        if semi_colon_forbidden and multiple_expressions(line):
            result[current_line].append("multiple expressions"
                                        " on the same line")
        if current_line != 1 and not_empty_line(lines[current_line-1]):

            current_ind = count_indentation(line)
            if current_ind == 0:
                for i in range(current_line, len(lines)):
                    cur2 = count_indentation(lines[i])
                    if cur2 >= 1:
                        used_indentation = cur2
                        break

            if current_ind != 0:
                should_be = (current_ind // used_indentation) \
                            * allowed_indentation
                if current_ind != should_be:
                    strn = "indentation is {0} instead of {1}".format(
                        current_ind, should_be
                    )
                    if strn not in result[current_line]:
                        result[current_line].append(strn)
    tree = ast.parse(code)

    if "max_nesting" in rules:
        nesting_max = rules["max_nesting"]
    else:
        nesting_max = None

    if nesting_max is not None:
        class VisitorTwo(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                it = VisitorOne()
                VisitorOne.level_line = 0
                it.visit(node)
                if it.own_level > nesting_max:
                    msg = "nesting too deep ({0} > {1})".format(
                        it.own_level, nesting_max)
                    at_level = VisitorOne.level_line + 1
                    if msg not in result[at_level]:
                        result[at_level].append(msg)

            def visit_ClassDef(self, node):
                for sub in ast.iter_child_nodes(node):
                    subvisitor22 = VisitorTwo()
                    subvisitor22.visit(sub)

            visit_If = visit_Try = visit_While = visit_With = visit_For =\
                visit_FunctionDef

        parse1 = VisitorTwo()
        parse1.visit(tree)

    if "max_arity" in rules:
        arity_max = rules["max_arity"]
    else:
        arity_max = None

    if arity_max is not None:
        class VisitorThree(ast.NodeVisitor):

            def __init__(self, _parameters_count=0):
                self.parameters_count = _parameters_count
                self.line = -1

            def visit_FunctionDef(self, node):
                self.parameters_count = len(node.args.args)
                self.line = node.lineno
                if self.parameters_count > arity_max:
                    msg = "too many arguments({0} > {1})".format(
                        self.parameters_count, arity_max)
                    if msg not in result[node.lineno]:
                        result[node.lineno].append(msg)
                for sub in ast.iter_child_nodes(node):
                    it = VisitorThree()
                    it.visit(sub)

            def visit_ClassDef(self, node):
                for sub in node.body:
                    if not isinstance(sub, ast.FunctionDef) and not\
                            isinstance(sub, ast.ClassDef):
                        continue
                    subvisitor = VisitorThree()
                    subvisitor.visit(sub)

        class OuterVisitor(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                v3 = VisitorThree()
                v3.visit(node)

            def visit_ClassDef(self, node):
                v33 = VisitorThree()
                v33.visit(node)

        starter = OuterVisitor()
        starter.visit(tree)

    if "methods_per_class" in rules:
        max_methods = rules["methods_per_class"]
    else:
        max_methods = None

    if max_methods is not None:

        class VisitorFour(ast.NodeVisitor):

            def __init__(self, _line=-1):
                self.methods_count = 0
                self.line = _line

            def visit_ClassDef(self, node):
                self.line = node.lineno
                for sub in ast.iter_child_nodes(node):
                    if isinstance(sub, ast.FunctionDef):
                        self.methods_count += 1
                if self.methods_count > max_methods:
                    strng = "too many methods in class({0} > {1})".format(
                        self.methods_count, max_methods)
                    if strng not in result[self.line]:
                        result[self.line].append(strng)

                for sub in ast.iter_child_nodes(node):
                    it = VisitorFour()
                    it.visit(sub)

            def visit_FunctionDef(self, node):
                for sub in ast.iter_child_nodes(node):
                    it = VisitorFour()
                    it.visit(sub)

        class OuterVisitor2(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                v4 = VisitorFour()
                v4.visit(node)

            def visit_ClassDef(self, node):
                v44 = VisitorFour(node.lineno)
                v44.visit(node)

        starter2 = OuterVisitor2()
        starter2.visit(tree)

    if "max_lines_per_function" in rules:
        max_lines_in_function = rules["max_lines_per_function"]
    else:
        max_lines_in_function = None

    if max_lines_in_function is not None:
        class VisitorFive(ast.NodeVisitor):

            def visit_ClassDef(self, node):
                for sub in ast.iter_child_nodes(node):
                    it = VisitorFive()
                    it.visit(sub)

            def visit_FunctionDef(self, node):
                d = node.lineno
                line = lines[d-1]
                indentation = count_indentation(line)
                sublines = 0
                for lower_line in range(d, len(lines)):
                    if count_indentation(lines[lower_line]) <= indentation:
                        break
                    else:
                        if not_empty_line(lines[lower_line]):
                            sublines += 1
                if sublines > max_lines_in_function:
                    issue = "method with too many lines ({0} > {1})".format(
                        sublines, max_lines_in_function)
                    if issue not in result[node.lineno]:
                        result[node.lineno].append(issue)

                for sub in ast.iter_child_nodes(node):
                    v555 = VisitorFive()
                    v555.visit(sub)

        class OuterVisitor3(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                vv5 = VisitorFive()
                vv5.visit(node)

            def visit_ClassDef(self, node):
                vvv5 = VisitorFive()
                vvv5.visit(node)

        starter3 = OuterVisitor3()
        starter3.visit(tree)
    return result

Лог от изпълнението

......F....
======================================================================
FAIL: test_multiple_issues_all_over_the_place (test.TestCritic)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/data/rails/pyfmi-2016/releases/20160307095126/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: Items in the second set but not the first:
'nesting too deep (4 > 3)'

----------------------------------------------------------------------
Ran 11 tests in 0.121s

FAILED (failures=1)

История (1 версия и 0 коментара)

Даниел обнови решението на 17.05.2016 10:07 (преди над 1 година)

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
from collections import defaultdict
import ast
import re


class VisitorOne(ast.NodeVisitor):
    level_line = 0

    def __init__(self, own_level=0):
        self.own_level = own_level
        self.visited = list()

    def visit_FunctionDef(self, node):
        next_level = self.own_level + 1
        for subnode in ast.iter_child_nodes(node):
            subvisitor = VisitorOne(next_level)
            if subnode not in self.visited:
                self.visited.append(subnode)
                subvisitor.visited = self.visited
                subvisitor.visit(subnode)
                if subvisitor.own_level > self.own_level:
                    self.own_level = subvisitor.own_level
                    if node.lineno > VisitorOne.level_line:
                        VisitorOne.level_line = node.lineno

    visit_If = visit_Try = visit_While = visit_With = visit_For = \
        visit_FunctionDef

    def visit_ClassDef(self, node):
        for sub in ast.iter_child_nodes(node):
            subvisitor = VisitorOne()
            subvisitor.visit(sub)


def ends_with_space(line):
    pattern1 = r'^.* $'
    pattern2 = r'^.*    $'
    return bool(re.search(pattern1, line)) or bool(re.search(pattern2, line))


def multiple_expressions(line):
    pattern = r'^.*;.*$'
    return bool(re.search(pattern, line, re.X))


def not_empty_line(line):
    return not(bool(not line or line.isspace()))


def count_indentation(line):
    count = 0
    length = len(line)
    for i in range(0, length):
        if line[i] == " ":
            count += 1
        else:
            break
    return count


def critic(code, **rules):
    result = defaultdict(list)

    if "line_length" in rules:
        max_length = rules["line_length"]
    else:
        max_length = 79

    if "forbid_trailing_white_space" in rules:
        no_ending_white_space = rules["forbid_trailing_white_space"]
    else:
        no_ending_white_space = True

    if "forbid_semicolons" in rules:
        semi_colon_forbidden = rules["forbid_semicolons"]
    else:
        semi_colon_forbidden = True

    if "indentation_size" in rules:
        allowed_indentation = rules["indentation_size"]
    else:
        allowed_indentation = 4

    lines = code.splitlines()

    used_indentation = 4
    for line in lines:
        cur = count_indentation(line)
        if cur >= 1:
            used_indentation = cur
            break

    current_line = 0
    for line in lines:
        current_line += 1
        current_line_length = len(line)
        if current_line_length > max_length:
            result[current_line].append("line too long ({0} > {1})".format(
                current_line_length, max_length))
        if no_ending_white_space and ends_with_space(line):
            result[current_line].append("trailing whitespace")
        if semi_colon_forbidden and multiple_expressions(line):
            result[current_line].append("multiple expressions"
                                        " on the same line")
        if current_line != 1 and not_empty_line(lines[current_line-1]):

            current_ind = count_indentation(line)
            if current_ind == 0:
                for i in range(current_line, len(lines)):
                    cur2 = count_indentation(lines[i])
                    if cur2 >= 1:
                        used_indentation = cur2
                        break

            if current_ind != 0:
                should_be = (current_ind // used_indentation) \
                            * allowed_indentation
                if current_ind != should_be:
                    strn = "indentation is {0} instead of {1}".format(
                        current_ind, should_be
                    )
                    if strn not in result[current_line]:
                        result[current_line].append(strn)
    tree = ast.parse(code)

    if "max_nesting" in rules:
        nesting_max = rules["max_nesting"]
    else:
        nesting_max = None

    if nesting_max is not None:
        class VisitorTwo(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                it = VisitorOne()
                VisitorOne.level_line = 0
                it.visit(node)
                if it.own_level > nesting_max:
                    msg = "nesting too deep ({0} > {1})".format(
                        it.own_level, nesting_max)
                    at_level = VisitorOne.level_line + 1
                    if msg not in result[at_level]:
                        result[at_level].append(msg)

            def visit_ClassDef(self, node):
                for sub in ast.iter_child_nodes(node):
                    subvisitor22 = VisitorTwo()
                    subvisitor22.visit(sub)

            visit_If = visit_Try = visit_While = visit_With = visit_For =\
                visit_FunctionDef

        parse1 = VisitorTwo()
        parse1.visit(tree)

    if "max_arity" in rules:
        arity_max = rules["max_arity"]
    else:
        arity_max = None

    if arity_max is not None:
        class VisitorThree(ast.NodeVisitor):

            def __init__(self, _parameters_count=0):
                self.parameters_count = _parameters_count
                self.line = -1

            def visit_FunctionDef(self, node):
                self.parameters_count = len(node.args.args)
                self.line = node.lineno
                if self.parameters_count > arity_max:
                    msg = "too many arguments({0} > {1})".format(
                        self.parameters_count, arity_max)
                    if msg not in result[node.lineno]:
                        result[node.lineno].append(msg)
                for sub in ast.iter_child_nodes(node):
                    it = VisitorThree()
                    it.visit(sub)

            def visit_ClassDef(self, node):
                for sub in node.body:
                    if not isinstance(sub, ast.FunctionDef) and not\
                            isinstance(sub, ast.ClassDef):
                        continue
                    subvisitor = VisitorThree()
                    subvisitor.visit(sub)

        class OuterVisitor(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                v3 = VisitorThree()
                v3.visit(node)

            def visit_ClassDef(self, node):
                v33 = VisitorThree()
                v33.visit(node)

        starter = OuterVisitor()
        starter.visit(tree)

    if "methods_per_class" in rules:
        max_methods = rules["methods_per_class"]
    else:
        max_methods = None

    if max_methods is not None:

        class VisitorFour(ast.NodeVisitor):

            def __init__(self, _line=-1):
                self.methods_count = 0
                self.line = _line

            def visit_ClassDef(self, node):
                self.line = node.lineno
                for sub in ast.iter_child_nodes(node):
                    if isinstance(sub, ast.FunctionDef):
                        self.methods_count += 1
                if self.methods_count > max_methods:
                    strng = "too many methods in class({0} > {1})".format(
                        self.methods_count, max_methods)
                    if strng not in result[self.line]:
                        result[self.line].append(strng)

                for sub in ast.iter_child_nodes(node):
                    it = VisitorFour()
                    it.visit(sub)

            def visit_FunctionDef(self, node):
                for sub in ast.iter_child_nodes(node):
                    it = VisitorFour()
                    it.visit(sub)

        class OuterVisitor2(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                v4 = VisitorFour()
                v4.visit(node)

            def visit_ClassDef(self, node):
                v44 = VisitorFour(node.lineno)
                v44.visit(node)

        starter2 = OuterVisitor2()
        starter2.visit(tree)

    if "max_lines_per_function" in rules:
        max_lines_in_function = rules["max_lines_per_function"]
    else:
        max_lines_in_function = None

    if max_lines_in_function is not None:
        class VisitorFive(ast.NodeVisitor):

            def visit_ClassDef(self, node):
                for sub in ast.iter_child_nodes(node):
                    it = VisitorFive()
                    it.visit(sub)

            def visit_FunctionDef(self, node):
                d = node.lineno
                line = lines[d-1]
                indentation = count_indentation(line)
                sublines = 0
                for lower_line in range(d, len(lines)):
                    if count_indentation(lines[lower_line]) <= indentation:
                        break
                    else:
                        if not_empty_line(lines[lower_line]):
                            sublines += 1
                if sublines > max_lines_in_function:
                    issue = "method with too many lines ({0} > {1})".format(
                        sublines, max_lines_in_function)
                    if issue not in result[node.lineno]:
                        result[node.lineno].append(issue)

                for sub in ast.iter_child_nodes(node):
                    v555 = VisitorFive()
                    v555.visit(sub)

        class OuterVisitor3(ast.NodeVisitor):

            def visit_FunctionDef(self, node):
                vv5 = VisitorFive()
                vv5.visit(node)

            def visit_ClassDef(self, node):
                vvv5 = VisitorFive()
                vvv5.visit(node)

        starter3 = OuterVisitor3()
        starter3.visit(tree)
    return result