id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
144,148
Kuniwak/vint
Kuniwak_vint/test/unit/vint/linting/config/test_config_comment_parser.py
test.unit.vint.linting.config.test_config_comment_parser.ConfigCommentAssertion
class ConfigCommentAssertion(unittest.TestCase): def assertConfigCommentEqual(self, a, b): # type: (ConfigComment, ConfigComment) -> None self.assertEqual(a.config_dict, b.config_dict) self.assertEqual(a.is_only_next_line, b.is_only_next_line)
class ConfigCommentAssertion(unittest.TestCase): def assertConfigCommentEqual(self, a, b): pass
2
0
4
0
3
1
1
0.25
1
0
0
1
1
0
1
73
5
0
4
2
2
1
4
2
2
1
2
0
1
144,149
Kuniwak/vint
Kuniwak_vint/test/unit/vint/linting/config/test_config_cmdargs_source.py
test.unit.vint.linting.config.test_config_cmdargs_source.TestConfigCmdargsSource
class TestConfigCmdargsSource(ConfigSourceAssertion, unittest.TestCase): def test_get_config_dict(self): env = { 'cmdargs': { 'verbose': True, 'style': True, 'warning': True, 'max-violations': 10, }, } expected_config_dict = { 'cmdargs': { 'verbose': True, 'severity': Level.WARNING, 'max-violations': 10, }, 'source_name': 'ConfigCmdargsSource', } config_source = self.initialize_config_source_with_env(ConfigCmdargsSource, env) self.assertConfigDict(config_source, expected_config_dict) def test_get_config_dict_with_no_severity(self): env = {'cmdargs': {}} expected_config_dict = { 'cmdargs': {}, 'source_name': 'ConfigCmdargsSource', } config_source = self.initialize_config_source_with_env(ConfigCmdargsSource, env) self.assertConfigDict(config_source, expected_config_dict) def test_get_config_dict_with_severity_style_problem(self): env = { 'cmdargs': { 'style_problem': True, }, } expected_config_dict = { 'cmdargs': { 'severity': Level.STYLE_PROBLEM, }, 'source_name': 'ConfigCmdargsSource', } config_source = self.initialize_config_source_with_env(ConfigCmdargsSource, env) self.assertConfigDict(config_source, expected_config_dict) def test_get_config_dict_with_severity_warning(self): env = { 'cmdargs': { 'warning': True, }, } expected_config_dict = { 'cmdargs': { 'severity': Level.WARNING, }, 'source_name': 'ConfigCmdargsSource', } config_source = self.initialize_config_source_with_env(ConfigCmdargsSource, env) self.assertConfigDict(config_source, expected_config_dict) def test_get_config_dict_with_severity_error(self): env = { 'cmdargs': { 'error': True, }, } expected_config_dict = { 'cmdargs': { 'severity': Level.ERROR, }, 'source_name': 'ConfigCmdargsSource', } config_source = self.initialize_config_source_with_env(ConfigCmdargsSource, env) self.assertConfigDict(config_source, expected_config_dict)
class TestConfigCmdargsSource(ConfigSourceAssertion, unittest.TestCase): def test_get_config_dict(self): pass def test_get_config_dict_with_no_severity(self): pass def test_get_config_dict_with_severity_style_problem(self): pass def test_get_config_dict_with_severity_warning(self): pass def test_get_config_dict_with_severity_error(self): pass
6
0
16
2
14
0
1
0
2
2
2
0
5
0
5
81
89
19
70
21
64
0
26
21
20
1
3
0
5
144,150
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_redir_assignment_parser.py
test.unit.vint.ast.plugin.scope_plugin.test_redir_assignment_parser.Fixtures
class Fixtures(enum.Enum): REDIR_VARIABLE = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_redir.vim')
class Fixtures(enum.Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
2
0
2
2
1
0
2
2
1
0
4
0
0
144,151
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/test_traversing.py
test.unit.vint.ast.test_traversing.TestTraverse
class TestTraverse(unittest.TestCase): def setUp(self): parser = Parser() self.ast = parser.parse(LintTargetFile(FIXTURE_FILE)) def test_traverse(self): expected_order_of_events = [ {'node_type': NodeType.TOPLEVEL, 'handler': 'enter'}, {'node_type': NodeType.LET, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'leave'}, {'node_type': NodeType.NUMBER, 'handler': 'enter'}, {'node_type': NodeType.NUMBER, 'handler': 'leave'}, {'node_type': NodeType.LET, 'handler': 'leave'}, {'node_type': NodeType.WHILE, 'handler': 'enter'}, {'node_type': NodeType.SMALLER, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'leave'}, {'node_type': NodeType.NUMBER, 'handler': 'enter'}, {'node_type': NodeType.NUMBER, 'handler': 'leave'}, {'node_type': NodeType.SMALLER, 'handler': 'leave'}, {'node_type': NodeType.ECHO, 'handler': 'enter'}, {'node_type': NodeType.STRING, 'handler': 'enter'}, {'node_type': NodeType.STRING, 'handler': 'leave'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'leave'}, {'node_type': NodeType.ECHO, 'handler': 'leave'}, {'node_type': NodeType.LET, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'leave'}, {'node_type': NodeType.NUMBER, 'handler': 'enter'}, {'node_type': NodeType.NUMBER, 'handler': 'leave'}, {'node_type': NodeType.LET, 'handler': 'leave'}, {'node_type': NodeType.ENDWHILE, 'handler': 'enter'}, {'node_type': NodeType.ENDWHILE, 'handler': 'leave'}, {'node_type': NodeType.WHILE, 'handler': 'leave'}, {'node_type': NodeType.TOPLEVEL, 'handler': 'leave'}, ] # Records visit node type name in order actual_order_of_events = [] traverse(self.ast, on_enter=lambda node: actual_order_of_events.append({ 'node_type': NodeType(node['type']), 'handler': 'enter', }), on_leave=lambda node: actual_order_of_events.append({ 'node_type': NodeType(node['type']), 'handler': 'leave', })) self.maxDiff = 2048 self.assertEqual(actual_order_of_events, expected_order_of_events) def test_traverse_ignoring_while_children(self): expected_order_of_events = [ {'node_type': NodeType.TOPLEVEL, 'handler': 'enter'}, {'node_type': NodeType.LET, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'enter'}, {'node_type': NodeType.IDENTIFIER, 'handler': 'leave'}, {'node_type': NodeType.NUMBER, 'handler': 'enter'}, {'node_type': NodeType.NUMBER, 'handler': 'leave'}, {'node_type': NodeType.LET, 'handler': 'leave'}, {'node_type': NodeType.WHILE, 'handler': 'enter'}, {'node_type': NodeType.WHILE, 'handler': 'leave'}, {'node_type': NodeType.TOPLEVEL, 'handler': 'leave'}, ] def on_enter(node): actual_order_of_events.append({ 'node_type': NodeType(node['type']), 'handler': 'enter', }) if NodeType(node['type']) is NodeType.WHILE: return SKIP_CHILDREN # Records visit node type name in order actual_order_of_events = [] traverse(self.ast, on_enter=on_enter, on_leave=lambda node: actual_order_of_events.append({ 'node_type': NodeType(node['type']), 'handler': 'leave', })) self.maxDiff = 2048 self.assertEqual(actual_order_of_events, expected_order_of_events)
class TestTraverse(unittest.TestCase): def setUp(self): pass def test_traverse(self): pass def test_traverse_ignoring_while_children(self): pass def on_enter(node): pass
5
0
24
2
21
1
1
0.03
1
3
3
0
3
2
3
75
90
10
78
12
73
2
20
12
15
2
2
1
5
144,152
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/test_node_type.py
test.unit.vint.ast.test_node_type.TestNodeType
class TestNodeType(unittest.TestCase): def test_get_node_type_name(self): self.assertIs(NodeType(1), NodeType.TOPLEVEL) self.assertIs(NodeType(89), NodeType.REG)
class TestNodeType(unittest.TestCase): def test_get_node_type_name(self): pass
2
0
3
0
3
0
1
0
1
1
1
0
1
0
1
73
4
0
4
2
2
0
4
2
2
1
2
0
1
144,153
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_variable_name_normalizer.py
test.unit.vint.ast.plugin.scope_plugin.test_variable_name_normalizer.VariableNameNormalizer
class VariableNameNormalizer(unittest.TestCase): def test_parameterized(self): test_cases = [ ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.EXPLICIT ), create_id('g:explicit_global'), 'g:explicit_global' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT ), create_id('implicit_global'), 'g:implicit_global' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT ), create_id('implicit_global', is_declarative=False), 'g:implicit_global' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.EXPLICIT ), create_id('l:explicit_function_local'), 'l:explicit_function_local' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.IMPLICIT ), create_id('implicit_function_local'), 'l:implicit_function_local' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.IMPLICIT ), create_id('implicit_function_local', is_declarative=False), 'l:implicit_function_local' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.UNRECOMMENDED_EXPLICIT ), create_id('g:ExplicitGlobalFunc', is_function=True), 'g:ExplicitGlobalFunc' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.EXPLICIT ), create_id('s:ExplicitScriptLocalFunc', is_function=True), 's:ExplicitScriptLocalFunc' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_id('ImplicitGlobalFunc', is_function=True), 'ImplicitGlobalFunc' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_id('ImplicitGlobalFunc', is_function=True), 'ImplicitGlobalFunc' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.EXPLICIT ), create_id('s:ExplicitScriptLocalFunc', is_function=True), 's:ExplicitScriptLocalFunc' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), 'ImplicitGlobalFunc' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.EXPLICIT ), create_id('l:explicit_function_local'), 'l:explicit_function_local' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.IMPLICIT ), create_id('implicit_function_local'), 'l:implicit_function_local' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.IMPLICIT ), create_id('implicit_function_local', is_declarative=False), 'l:implicit_function_local' ), ( ScopeVisibilityHint( scope_visibility=Vis.FUNCTION_LOCAL, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_id('param', is_declarative=False, is_declarative_parameter=True), 'param' ), ( ScopeVisibilityHint( scope_visibility=Vis.BUILTIN, explicity=Explicity.EXPLICIT ), create_id('v:count'), 'v:count' ), ( ScopeVisibilityHint( scope_visibility=Vis.BUILTIN, explicity=Explicity.EXPLICIT ), create_id('v:count'), 'v:count' ), ( ScopeVisibilityHint( scope_visibility=Vis.BUILTIN, explicity=Explicity.IMPLICIT ), create_id('count'), 'v:count' ), ( ScopeVisibilityHint( scope_visibility=Vis.BUILTIN, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_id('localtime', is_declarative=False, is_function=True), 'localtime' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_env('$ENV'), '$ENV' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_option('&OPT'), '&OPT' ), ( ScopeVisibilityHint( scope_visibility=Vis.GLOBAL_LIKE, explicity=Explicity.IMPLICIT_BUT_CONSTRAINED ), create_reg('@"'), '@"' ), ] for scope_visibility_hint, node, expected_variable_name in test_cases: reachability_tester = ReferenceReachabilityTesterStub(hint=scope_visibility_hint) # type: ReferenceReachabilityTester normalized_variable_name = normalize_variable_name(node, reachability_tester) self.assertEqual( expected_variable_name, normalized_variable_name, "{name}".format(name=node['value']) )
class VariableNameNormalizer(unittest.TestCase): def test_parameterized(self): pass
2
0
198
3
195
1
2
0.01
1
2
2
0
1
0
1
73
199
3
196
6
194
1
7
6
5
2
2
1
2
144,154
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_variable_name_normalizer.py
test.unit.vint.ast.plugin.scope_plugin.test_variable_name_normalizer.ReferenceReachabilityTesterStub
class ReferenceReachabilityTesterStub: def __init__(self, hint): # type: (ScopeVisibilityHint) -> None self.hint = hint def get_objective_scope_visibility(self, _): # type: (Dict[str, Any]) -> ScopeVisibilityHint return self.hint
class ReferenceReachabilityTesterStub: def __init__(self, hint): pass def get_objective_scope_visibility(self, _): pass
3
0
2
0
2
1
1
0.4
0
0
0
0
2
1
2
2
7
2
5
4
2
2
5
4
2
1
0
0
2
144,155
Kuniwak/vint
Kuniwak_vint/test/acceptance/test_cli.py
test.acceptance.test_cli.TestCLI
class TestCLI(unittest.TestCase): if sys.version_info <= (3,): def assertRegex(self, string, pattern): return super(TestCLI, self).assertRegexpMatches(string, pattern) def assertReturnedStdoutEqual(self, expected_stdout, args): got_stdout = '(no stdout)' cmd = [sys.executable, '-m', 'vint'] + args try: got_stdout = subprocess.check_output(cmd, universal_newlines=True) except subprocess.CalledProcessError as err: print('Got stderr: `{err_message}`'.format(err_message=err)) finally: print('Got stdout: `{stdout}`'.format(stdout=got_stdout)) self.assertEqual(expected_stdout, got_stdout) def test_exec_vint_with_valid_file_on_project_root(self): valid_file = str(Path('test', 'fixture', 'cli', 'valid1.vim')) expected_output = '' self.assertReturnedStdoutEqual(expected_output, [valid_file]) def test_exec_vint_with_valid_file_encoded_cp932_on_project_root(self): valid_file = str(Path('test', 'fixture', 'cli', 'valid-cp932.vim')) expected_output = '' self.assertReturnedStdoutEqual(expected_output, [valid_file]) def test_exec_vint_with_invalid_file_on_project_root(self): invalid_file = str(Path('test', 'fixture', 'cli', 'invalid1.vim')) cmd = [sys.executable, '-m', 'vint', invalid_file] with self.assertRaises(subprocess.CalledProcessError) as context_manager: subprocess.check_output(cmd, universal_newlines=True) got_output = context_manager.exception.output expected_output_pattern = '{file_path}:1:13:'.format(file_path=invalid_file) self.assertRegex(got_output, expected_output_pattern) def test_exec_vint_with_no_args(self): cmd = [sys.executable, '-m', 'vint'] with self.assertRaises(subprocess.CalledProcessError) as context_manager: subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) got_output = context_manager.exception.output expected_output_pattern = r'^vint ERROR:' self.assertRegex(got_output, expected_output_pattern) def test_exec_vint_with_unexistent_file(self): cmd = [sys.executable, '-m', 'vint', '/path/to/unexistent'] with self.assertRaises(subprocess.CalledProcessError) as context_manager: subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) got_output = context_manager.exception.output expected_output_pattern = r'^vint ERROR:' self.assertRegex(got_output, expected_output_pattern) def test_exec_vint_with_stat_flag(self): invalid_file = str(Path('test', 'fixture', 'cli', 'invalid1.vim')) cmd = [sys.executable, '-m', 'vint', '--stat', invalid_file] with self.assertRaises(subprocess.CalledProcessError) as context_manager: subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) got_output = context_manager.exception.output expected_output_pattern = '{file_path}:1:13:'.format(file_path=invalid_file) expected_stat_pattern = 'Total' self.assertRegex(got_output, expected_output_pattern) self.assertRegex(got_output, expected_stat_pattern) def test_exec_vint_with_json_flag(self): invalid_file = str(Path('test', 'fixture', 'cli', 'invalid1.vim')) cmd = [sys.executable, '-m', 'vint', '--json', invalid_file] with self.assertRaises(subprocess.CalledProcessError) as context_manager: # We should not capture STRERR because coverage plugin use it. subprocess.check_output(cmd, universal_newlines=True) got_output = context_manager.exception.output print(got_output) self.assertIsInstance(json.loads(got_output), list) def test_exec_vint_with_verbose_flag(self): valid_file = str(Path('test', 'fixture', 'cli', 'valid1.vim')) cmd = [sys.executable, '-m', 'vint', '--verbose', valid_file] got_output = subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT) expected_output_pattern = r'^vint DEBUG:' self.assertRegex(got_output, expected_output_pattern) def test_exec_vint_with_color_flag(self): invalid_file = str(Path('test', 'fixture', 'cli', 'invalid1.vim')) cmd = [sys.executable, '-m', 'vint', '--color', invalid_file] with self.assertRaises(subprocess.CalledProcessError) as context_manager: subprocess.check_output(cmd, universal_newlines=True) got_output = context_manager.exception.output expected_output_pattern = r'\033\[' self.assertRegex(got_output, expected_output_pattern) def test_exec_vint_with_pipe(self): cmd = 'echo "foo" =~ "bar" | bin/vint --stdin-display-name STDIN_TEST -' with self.assertRaises(subprocess.CalledProcessError) as context_manager: subprocess.check_output(cmd, shell=True, universal_newlines=True) got_output = context_manager.exception.output expected_output_pattern = '^STDIN_TEST:' self.assertRegex(got_output, expected_output_pattern)
class TestCLI(unittest.TestCase): def assertRegex(self, string, pattern): pass def assertReturnedStdoutEqual(self, expected_stdout, args): pass def test_exec_vint_with_valid_file_on_project_root(self): pass def test_exec_vint_with_valid_file_encoded_cp932_on_project_root(self): pass def test_exec_vint_with_invalid_file_on_project_root(self): pass def test_exec_vint_with_no_args(self): pass def test_exec_vint_with_unexistent_file(self): pass def test_exec_vint_with_stat_flag(self): pass def test_exec_vint_with_json_flag(self): pass def test_exec_vint_with_verbose_flag(self): pass def test_exec_vint_with_color_flag(self): pass def test_exec_vint_with_pipe(self): pass
13
0
10
2
8
0
1
0.01
1
5
0
0
12
0
12
84
143
50
92
56
79
1
82
48
69
2
2
1
13
144,156
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_two_way_scope_reference_attacher.py
test.unit.vint.ast.plugin.scope_plugin.test_two_way_scope_reference_attacher.TestTwoWayScopeReferenceAttacher
class TestTwoWayScopeReferenceAttacher(unittest.TestCase): def create_scope(self, scope_visibility, variables=None, child_scopes=None): return { 'scope_visibility': scope_visibility, 'variables': variables or {}, 'child_scopes': child_scopes or [], } def assertScopeTreeHasParent(self, scope_tree): for child_scope in scope_tree['child_scopes']: self.assertIs(scope_tree, child_scope['parent_scope']) self.assertScopeTreeHasParent(child_scope) def test_attach(self): scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, child_scopes=[ self.create_scope(ScopeVisibility.SCRIPT_LOCAL), ] ) attached_scope_tree = TwoWayScopeReferenceAttacher.attach(scope_tree) self.assertScopeTreeHasParent(attached_scope_tree)
class TestTwoWayScopeReferenceAttacher(unittest.TestCase): def create_scope(self, scope_visibility, variables=None, child_scopes=None): pass def assertScopeTreeHasParent(self, scope_tree): pass def test_attach(self): pass
4
0
7
1
6
0
1
0
1
2
2
0
3
0
3
75
26
6
20
7
16
0
11
7
7
2
2
1
4
144,157
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_scope_linker.py
test.unit.vint.ast.plugin.scope_plugin.test_scope_linker.TestScopeLinker
class TestScopeLinker(unittest.TestCase): def create_ast(self, file_path): parser = Parser() lint_target = LintTargetFile(file_path.value) ast = parser.parse(lint_target) return ast def create_variable(self, explicity=ExplicityOfScopeVisibility.EXPLICIT, is_builtin=False, is_explicit_lambda_argument=False): return VariableDeclaration( explicity=explicity, is_builtin=is_builtin, is_explicit_lambda_argument=is_explicit_lambda_argument ) def create_scope(self, scope_visibility, variables=None, functions=None, child_scopes=None): scope = Scope(scope_visibility=scope_visibility) scope.functions=functions or {} scope.variables=variables or {} scope.child_scopes=child_scopes or [] return scope def assertVariableDeclaration(self, expected_var_decl, actual_var_decl): # type: (VariableDeclaration, VariableDeclaration) -> None self.assertEqual(expected_var_decl.is_builtin, actual_var_decl.is_builtin, "is_builtin") self.assertEqual(expected_var_decl.is_explicit_lambda_argument, actual_var_decl.is_explicit_lambda_argument, "is_explicit_lambda_argument") self.assertEqual(expected_var_decl.explicity, actual_var_decl.explicity, "explicity") def assertVariableDeclarations(self, expected_var_decls, actual_var_decls): # type: (List[VariableDeclaration], List[VariableDeclaration]) -> None for expected_var_decl, actual_var_decl in zip(expected_var_decls, actual_var_decls): self.assertVariableDeclaration(expected_var_decl, actual_var_decl) def assertScopeTreeEqual(self, expected_scope, actual_scope): # type: (Scope, Scope) -> None self.maxDiff = 20000 self.assertEqual(expected_scope.scope_visibility, actual_scope.scope_visibility) self.assertEqual(set(expected_scope.functions.keys()), set(actual_scope.functions.keys())) for expected_func_name, actual_func_name in zip(sorted(expected_scope.functions.keys()), sorted(actual_scope.functions.keys())): self.assertVariableDeclarations(expected_scope.functions[expected_func_name], actual_scope.functions[actual_func_name]) self.assertEqual(set(expected_scope.variables.keys()), set(actual_scope.variables.keys())) for expected_var_name, actual_var_name in zip(sorted(expected_scope.variables.keys()), sorted(actual_scope.variables.keys())): self.assertVariableDeclarations(expected_scope.variables[expected_var_name], actual_scope.variables[actual_var_name]) for expected_child_scope, actual_child_scope in zip(expected_scope.child_scopes, actual_scope.child_scopes): self.assertScopeTreeEqual(expected_child_scope, actual_child_scope) # NOTE: Do not check scope.parent to avoid infinite recursion. def test_built_scope_tree_by_process_with_declaring_func(self): ast = self.create_ast(Fixtures.DECLARING_FUNC) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], }, functions={ 'ExplicitGlobalFunc': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'ImplicitGlobalFunc': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, functions={ 's:ScriptLocalFunc': [self.create_variable()] }, child_scopes=[ self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], }, ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], }, ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], }, ), ] ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_declaring_func_in_func(self): ast = self.create_ast(Fixtures.DECLARING_FUNC_IN_FUNC) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], }, functions={ 'FuncContext': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], 'ImplicitGlobalFunc': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], } ), ] ), ] ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_declaring_var(self): ast = self.create_ast(Fixtures.DECLARING_VAR) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], 'explicit_global_var': [self.create_variable()], 'b:buffer_local_var': [self.create_variable()], 'w:window_local_var': [self.create_variable()], 't:tab_local_var': [self.create_variable()], 'implicit_global_var': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT)], '$ENV_VAR': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], '@"': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], '&opt_var': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], 'count': [self.create_variable(is_builtin=True)], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], 's:script_local_var': [self.create_variable()], } ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_declaring_var_in_func(self): ast = self.create_ast(Fixtures.DECLARING_VAR_IN_FUNC) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], }, functions={ 'FuncContext': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED)], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], 'explicit_func_local_var': [self.create_variable()], 'implicit_func_local_var': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT)], } ) ] ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_declaring_with_dict_key(self): ast = self.create_ast(Fixtures.DICT_KEY) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], # Member functions are not analyzable }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], # Member functions are not analyzable }, child_scopes=[ self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'self': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'self': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], } ), ] ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_destructuring_assignment(self): ast = self.create_ast(Fixtures.DESTRUCTURING_ASSIGNMENT) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], 'for_var1': [self.create_variable()], 'for_var2': [self.create_variable()], 'let_var1': [self.create_variable()], 'let_var2': [self.create_variable()], 'let_var3': [self.create_variable()], 'rest': [self.create_variable()], # g:list members are not analyzable }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_func_param(self): ast = self.create_ast(Fixtures.FUNC_PARAM) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], }, functions={ 'FunctionWithNoParams': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'FunctionWithOneParam': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'FunctionWithTwoParams': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'FunctionWithVarParams': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'FunctionWithParamsAndVarParams': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'FunctionWithRange': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], 'FunctionWithDict': [self.create_variable(explicity=ExplicityOfScopeVisibility.UNRECOMMENDED_EXPLICIT)], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], 'a:param': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], 'a:param1': [self.create_variable()], 'a:param2': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:1': [self.create_variable()], 'a:2': [self.create_variable()], 'a:3': [self.create_variable()], 'a:4': [self.create_variable()], 'a:5': [self.create_variable()], 'a:6': [self.create_variable()], 'a:7': [self.create_variable()], 'a:8': [self.create_variable()], 'a:9': [self.create_variable()], 'a:10': [self.create_variable()], 'a:11': [self.create_variable()], 'a:12': [self.create_variable()], 'a:13': [self.create_variable()], 'a:14': [self.create_variable()], 'a:15': [self.create_variable()], 'a:16': [self.create_variable()], 'a:17': [self.create_variable()], 'a:18': [self.create_variable()], 'a:19': [self.create_variable()], 'a:20': [self.create_variable()], 'a:000': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:param_var1': [self.create_variable()], 'a:0': [self.create_variable()], 'a:1': [self.create_variable()], 'a:2': [self.create_variable()], 'a:3': [self.create_variable()], 'a:4': [self.create_variable()], 'a:5': [self.create_variable()], 'a:6': [self.create_variable()], 'a:7': [self.create_variable()], 'a:8': [self.create_variable()], 'a:9': [self.create_variable()], 'a:10': [self.create_variable()], 'a:11': [self.create_variable()], 'a:12': [self.create_variable()], 'a:13': [self.create_variable()], 'a:14': [self.create_variable()], 'a:15': [self.create_variable()], 'a:16': [self.create_variable()], 'a:17': [self.create_variable()], 'a:18': [self.create_variable()], 'a:19': [self.create_variable()], 'a:000': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'a:': [self.create_variable()], 'a:param': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], 'a:firstline': [self.create_variable()], 'a:lastline': [self.create_variable()], } ), self.create_scope( ScopeVisibility.FUNCTION_LOCAL, variables={ 'l:': [self.create_variable()], 'self': [self.create_variable()], 'a:': [self.create_variable()], 'a:0': [self.create_variable()], 'a:000': [self.create_variable()], } ), ] ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_func_call(self): ast = self.create_ast(Fixtures.CALLING_FUNC) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, # no declarative variables variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_loop_var(self): ast = self.create_ast(Fixtures.LOOP_VAR) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], 'implicit_global_loop_var': [self.create_variable(explicity=ExplicityOfScopeVisibility.IMPLICIT)] }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], } ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_scope_tree_by_process_with_redir(self): ast = self.create_ast(Fixtures.REDIR) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], 'var': [self.create_variable()] }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], } ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree) def test_built_identifier_links_by_process(self): ast = self.create_ast(Fixtures.DECLARING_AND_REFERENCING) # Function call reference identifier node ref_id_node = ast['body'][1]['left']['left'] linker = ScopeLinker() linker.process(ast) scope_tree = linker.scope_tree # Expect a script local scope expected_scope = scope_tree.child_scopes[0] link_registry = linker.link_registry actual_scope = link_registry.get_context_scope_by_identifier(ref_id_node) self.assertScopeTreeEqual(expected_scope, actual_scope) def test_built_declarative_identifier_links_by_process(self): ast = self.create_ast(Fixtures.DECLARING_AND_REFERENCING) # Function name identifier node dec_id_node = ast['body'][0]['left'] linker = ScopeLinker() linker.process(ast) scope_tree = linker.scope_tree # Expect a script local scope expected_scope = scope_tree.child_scopes[0] link_registry = linker.link_registry actual_scope = link_registry.get_context_scope_by_identifier(dec_id_node) self.assertScopeTreeEqual(expected_scope, actual_scope) def test_built_reference_variable_links_by_process(self): ast = self.create_ast(Fixtures.DECLARING_AND_REFERENCING) # Function name identifier node expected_dec_id = ast['body'][0]['left'] linker = ScopeLinker() linker.process(ast) scope_tree = linker.scope_tree # Function local scope scope = scope_tree.child_scopes[0] variable_func = scope.functions['s:Function'][0] link_registry = linker.link_registry actual_dec_id = link_registry.get_declarative_identifier_by_variable(variable_func) self.assertEqual(expected_dec_id, actual_dec_id) def test_built_scope_tree_by_process_with_lambda(self): ast = self.create_ast(Fixtures.LAMBDA) linker = ScopeLinker() linker.process(ast) expected_scope_tree = self.create_scope( ScopeVisibility.GLOBAL_LIKE, variables={ 'g:': [self.create_variable()], 'b:': [self.create_variable()], 'w:': [self.create_variable()], 't:': [self.create_variable()], 'v:': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.SCRIPT_LOCAL, variables={ 's:': [self.create_variable()], }, child_scopes=[ self.create_scope( ScopeVisibility.LAMBDA, variables={ 'i': [self.create_variable( explicity=ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED, is_explicit_lambda_argument=True, )], 'a:000': [self.create_variable()], 'a:0': [self.create_variable()], 'a:1': [self.create_variable()], 'a:2': [self.create_variable()], 'a:3': [self.create_variable()], 'a:4': [self.create_variable()], 'a:5': [self.create_variable()], 'a:6': [self.create_variable()], 'a:7': [self.create_variable()], 'a:8': [self.create_variable()], 'a:9': [self.create_variable()], 'a:10': [self.create_variable()], 'a:11': [self.create_variable()], 'a:12': [self.create_variable()], 'a:13': [self.create_variable()], 'a:14': [self.create_variable()], 'a:15': [self.create_variable()], 'a:16': [self.create_variable()], 'a:17': [self.create_variable()], 'a:18': [self.create_variable()], 'a:19': [self.create_variable()], }, ), ] ) ] ) self.assertScopeTreeEqual(expected_scope_tree, linker.scope_tree)
class TestScopeLinker(unittest.TestCase): def create_ast(self, file_path): pass def create_variable(self, explicity=ExplicityOfScopeVisibility.EXPLICIT, is_builtin=False, is_explicit_lambda_argument=False): pass def create_scope(self, scope_visibility, variables=None, functions=None, child_scopes=None): pass def assertVariableDeclaration(self, expected_var_decl, actual_var_decl): pass def assertVariableDeclarations(self, expected_var_decls, actual_var_decls): pass def assertScopeTreeEqual(self, expected_scope, actual_scope): pass def test_built_scope_tree_by_process_with_declaring_func(self): pass def test_built_scope_tree_by_process_with_declaring_func_in_func(self): pass def test_built_scope_tree_by_process_with_declaring_var(self): pass def test_built_scope_tree_by_process_with_declaring_var_in_func(self): pass def test_built_scope_tree_by_process_with_declaring_with_dict_key(self): pass def test_built_scope_tree_by_process_with_destructuring_assignment(self): pass def test_built_scope_tree_by_process_with_func_param(self): pass def test_built_scope_tree_by_process_with_func_call(self): pass def test_built_scope_tree_by_process_with_loop_var(self): pass def test_built_scope_tree_by_process_with_redir(self): pass def test_built_identifier_links_by_process(self): pass def test_built_declarative_identifier_links_by_process(self): pass def test_built_reference_variable_links_by_process(self): pass def test_built_scope_tree_by_process_with_lambda(self): pass
21
0
33
3
30
1
1
0.02
1
10
8
0
20
1
20
92
699
92
593
87
570
14
129
85
108
4
2
1
24
144,158
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_scope_linker.py
test.unit.vint.ast.plugin.scope_plugin.test_scope_linker.Fixtures
class Fixtures(enum.Enum): DECLARING_FUNC = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_func.vim') CALLING_FUNC = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_calling_func.vim') DECLARING_FUNC_IN_FUNC = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_func_in_func.vim') DECLARING_VAR = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_var.vim') DECLARING_VAR_IN_FUNC = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_var_in_func.vim') FUNC_PARAM = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_func_param.vim') LOOP_VAR = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_loop_var.vim') DICT_KEY = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_with_dict_key.vim') DESTRUCTURING_ASSIGNMENT = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_destructuring_assignment.vim') DECLARING_AND_REFERENCING = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_and_referencing.vim') REDIR = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_redir.vim') LAMBDA = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_lambda_param.vim')
class Fixtures(enum.Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
13
0
13
13
12
0
13
13
12
0
4
0
0
144,159
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_reference_reachability_tester.py
test.unit.vint.ast.plugin.scope_plugin.test_reference_reachability_tester.TestReferenceReachabilityTester
class TestReferenceReachabilityTester(unittest.TestCase): def create_ast(self, file_path): parser = Parser() ast = parser.parse(LintTargetFile(file_path.value)) return ast def test_reachable_reference_by_process(self): ast = self.create_ast(Fixtures.DECLARING_AND_REFERENCING) ref_id_node = ast['body'][1]['left']['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertTrue(is_reachable_reference_identifier(ref_id_node)) def test_referenced_variable_by_process(self): ast = self.create_ast(Fixtures.DECLARING_AND_REFERENCING) declarative_id_node = ast['body'][0]['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertTrue(is_referenced_declarative_identifier(declarative_id_node)) def test_unreachable_reference_by_process(self): ast = self.create_ast(Fixtures.MISS_DECLARATION) ref_id_node = ast['body'][1]['left']['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertFalse(is_reachable_reference_identifier(ref_id_node)) def test_unreferenced_reference_by_process(self): ast = self.create_ast(Fixtures.MISS_DECLARATION) declarative_id_node = ast['body'][0]['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertFalse(is_referenced_declarative_identifier(declarative_id_node)) def test_referenced_variable_reference_by_process(self): ast = self.create_ast(Fixtures.SAME_NAME_FUNCTION_AND_REFERENCE) declarative_variable_node = ast['body'][0]['left'] declarative_function_node = ast['body'][1]['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertTrue(is_referenced_declarative_identifier(declarative_variable_node)) self.assertFalse(is_referenced_declarative_identifier(declarative_function_node)) def test_referenced_function_reference_by_process(self): ast = self.create_ast(Fixtures.FUNCTION_REF) declarative_variable_node = ast['body'][0]['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertTrue(is_referenced_declarative_identifier(declarative_variable_node)) def test_builtin_reference_by_process(self): ast = self.create_ast(Fixtures.BUILTIN) ref_id_node = ast['body'][0]['left']['left'] tester = ReferenceReachabilityTester() tester.process(ast) self.assertTrue(is_reachable_reference_identifier(ref_id_node))
class TestReferenceReachabilityTester(unittest.TestCase): def create_ast(self, file_path): pass def test_reachable_reference_by_process(self): pass def test_referenced_variable_by_process(self): pass def test_unreachable_reference_by_process(self): pass def test_unreferenced_reference_by_process(self): pass def test_referenced_variable_reference_by_process(self): pass def test_referenced_function_reference_by_process(self): pass def test_builtin_reference_by_process(self): pass
9
0
9
3
6
0
1
0
1
4
4
0
8
0
8
80
84
35
49
33
40
0
49
33
40
1
2
0
8
144,160
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_reference_reachability_tester.py
test.unit.vint.ast.plugin.scope_plugin.test_reference_reachability_tester.Fixtures
class Fixtures(enum.Enum): DECLARING_AND_REFERENCING = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_declaring_and_referencing.vim') MISS_DECLARATION = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_missing_declaration.vim') SAME_NAME_FUNCTION_AND_REFERENCE = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_same_name_function_and_variable.vim') FUNCTION_REF = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_function_ref.vim') BUILTIN = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_using_builtin.vim')
class Fixtures(enum.Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
11
0
11
6
10
0
6
6
5
0
4
0
0
144,161
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/test_parsing.py
test.unit.vint.ast.test_parsing.TestParser
class TestParser(unittest.TestCase): def test_parse(self): parser = Parser() ast = parser.parse(LintTargetFile(FIXTURE_FILE)) self.assertIs(ast['type'], 1) def test_parse_file_on_ff_dos_and_fenc_cp932(self): parser = Parser() ast = parser.parse(LintTargetFile(FIXTURE_FILE_FF_DOS_FENC_CP932)) self.assertIs(ast['type'], 1) def test_parse_file_when_neovim_enabled(self): parser = Parser(enable_neovim=True) ast = parser.parse(LintTargetFile(FIXTURE_FILE_NEOVIM)) self.assertIs(ast['type'], 1) def test_parse_empty_file(self): parser = Parser() ast = parser.parse(LintTargetFile(FIXTURE_FILE_EMPTY)) self.assertIs(ast['type'], 1) def test_parse_redir_with_identifier(self): parser = Parser() redir_cmd_node = { 'type': NodeType.EXCMD.value, 'ea': { 'argpos': {'col': 6, 'i': 5, 'lnum': 1}, }, 'str': 'redir=>redir', } ast = parser.parse_redir(redir_cmd_node) expected_pos = { 'col': 8, 'i': 7, 'lnum': 1, 'offset': 5 } expected_node_type = NodeType.IDENTIFIER self.assertEqual(expected_node_type, NodeType(ast['type'])) self.assertEqual(expected_pos, ast['pos']) def test_parse_redir_with_dot(self): parser = Parser() redir_cmd_node = { 'type': NodeType.EXCMD.value, 'ea': { 'argpos': {'col': 7, 'i': 6, 'lnum': 1}, }, 'str': 'redir => s:dict.redir', } ast = parser.parse_redir(redir_cmd_node) expected_pos = { 'col': 16, 'i': 15, 'lnum': 1, 'offset': 11, } expected_node_type = NodeType.DOT self.assertEqual(expected_node_type, NodeType(ast['type'])) self.assertEqual(expected_pos, ast['pos']) def test_parse_string_expr(self): parser = Parser() redir_cmd_node = { 'type': NodeType.STRING.value, 'pos': {'col': 1, 'i': 1, 'lnum': 1}, 'value': '\'v:key ==# "a"\'', } nodes = parser.parse_string_expr(redir_cmd_node) expected_pos = { 'col': 7, 'i': 7, 'lnum': 1, 'offset': 11, } expected_node_type = NodeType.EQUALCS self.assertEqual(expected_node_type, NodeType(nodes[0]['type'])) self.assertEqual(expected_pos, nodes[0]['pos'])
class TestParser(unittest.TestCase): def test_parse(self): pass def test_parse_file_on_ff_dos_and_fenc_cp932(self): pass def test_parse_file_when_neovim_enabled(self): pass def test_parse_empty_file(self): pass def test_parse_redir_with_identifier(self): pass def test_parse_redir_with_dot(self): pass def test_parse_string_expr(self): pass
8
0
11
1
10
0
1
0.01
1
3
3
0
7
0
7
79
90
18
72
31
64
1
41
31
33
1
2
0
7
144,162
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_identifier_collector.py
test.unit.vint.ast.plugin.scope_plugin.test_identifier_collector.TestIdentifierCollector
class TestIdentifierCollector(unittest.TestCase): def create_ast(self, file_path): parser = Parser() ast = parser.parse(LintTargetFile(file_path)) id_classifier = IdentifierClassifier() attached_ast = id_classifier.attach_identifier_attributes(ast) return attached_ast def test_loop_var(self): ast = self.create_ast(Fixtures['LOOP_VAR']) collector = IdentifierClassifier.IdentifierCollector() bucket = collector.collect_identifiers(ast) declaring_id_values = [id_node['value'] for id_node in bucket.statically_declared_identifiers] referencing_id_values = [id_node['value'] for id_node in bucket.statically_referencing_identifiers] expected_declaring_id_values = ['implicit_global_loop_var'] expected_referencing_id_values = ['g:array'] self.assertEqual(expected_declaring_id_values, declaring_id_values) self.assertEqual(expected_referencing_id_values, referencing_id_values)
class TestIdentifierCollector(unittest.TestCase): def create_ast(self, file_path): pass def test_loop_var(self): pass
3
0
13
4
9
0
1
0
1
4
4
0
2
0
2
74
28
9
19
14
16
0
17
14
14
1
2
0
2
144,163
Kuniwak/vint
Kuniwak_vint/test/asserting/config_source.py
test.asserting.config_source.ConfigSourceAssertion
class ConfigSourceAssertion(unittest.TestCase): def initialize_config_source_with_env(self, ConfigSourceToTest, env=None): """ Returns a new config source instance by a common env. You can override the common env by the specified env argument. """ return ConfigSourceToTest(env_factory(env)) def assertConfigDict(self, config_source_to_test, expected_config_dict): """ Asserts that the specified ConfigSource returns a dict that is equivalent to the expected_config_dict. """ actual_config_dict = config_source_to_test.get_config_dict() self.assertEqual(actual_config_dict, expected_config_dict) def assertConfigValueType(self, config_source_to_test, expected_config_dict): """ Asserts that the dict that is returned by the specified ConfigSource has a expected type. You can check types by Mongo-like query: >>> self.assertConfigValueType(MyConfigSource, { >>> 'cmdargs': {'verbose': bool} >>> }) """ actual_config_dict = config_source_to_test.get_config_dict() self._assertConfigValueTypeInternal(actual_config_dict, expected_config_dict) def _assertConfigValueTypeInternal(self, actual_dict_or_value, expected_type_or_dict): # Support assertion by Mongo-like query if not isinstance(expected_type_or_dict, dict): expected_type = expected_type_or_dict actual_value = actual_dict_or_value self.assertIsInstance(actual_value, expected_type) return expected_dict = expected_type_or_dict actual_dict = actual_dict_or_value self.assertIsInstance(actual_dict, dict) for key, expected_type_or_sub_dict in expected_dict.items(): actual_value = actual_dict[key] self._assertConfigValueTypeInternal(actual_value, expected_type_or_sub_dict)
class ConfigSourceAssertion(unittest.TestCase): def initialize_config_source_with_env(self, ConfigSourceToTest, env=None): ''' Returns a new config source instance by a common env. You can override the common env by the specified env argument. ''' pass def assertConfigDict(self, config_source_to_test, expected_config_dict): ''' Asserts that the specified ConfigSource returns a dict that is equivalent to the expected_config_dict. ''' pass def assertConfigValueType(self, config_source_to_test, expected_config_dict): ''' Asserts that the dict that is returned by the specified ConfigSource has a expected type. You can check types by Mongo-like query: >>> self.assertConfigValueType(MyConfigSource, { >>> 'cmdargs': {'verbose': bool} >>> }) ''' pass def _assertConfigValueTypeInternal(self, actual_dict_or_value, expected_type_or_dict): pass
5
3
11
1
6
4
2
0.56
1
1
0
9
4
0
4
76
50
11
25
14
18
14
21
12
16
3
2
1
6
144,164
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_call_node_parser.py
test.unit.vint.ast.plugin.scope_plugin.test_call_node_parser.TestCallNodeParser
class TestCallNodeParser(unittest.TestCase): def create_ast(self, file_path): parser = Parser() ast = parser.parse(LintTargetFile(file_path.value)) return ast def test_process_with_map_function(self): ast = self.create_ast(Fixtures.MAP_AND_FILTER_VARIABLE) parser = CallNodeParser() got_ast = parser.process(ast) string_expr_nodes = get_lambda_string_expr_content(got_ast['body'][0]['left']['rlist'][1]) self.assertEqual('v:val', string_expr_nodes[0]['left'].get('value')) def test_process_with_filter_function(self): ast = self.create_ast(Fixtures.MAP_AND_FILTER_VARIABLE) parser = CallNodeParser() got_ast = parser.process(ast) string_expr_nodes = get_lambda_string_expr_content(got_ast['body'][1]['left']['rlist'][1]) self.assertEqual('v:key', string_expr_nodes[0]['left'].get('value')) def test_traverse(self): ast = self.create_ast(Fixtures.MAP_AND_FILTER_VARIABLE) parser = CallNodeParser() got_ast = parser.process(ast) is_map_and_filter_content_visited = { 'v:val': False, 'v:key': False, } def enter_handler(node): if NodeType(node['type']) is not NodeType.IDENTIFIER: return is_map_and_filter_content_visited[node['value']] = True traverse(got_ast, on_enter=enter_handler) self.assertTrue(all(is_map_and_filter_content_visited.values())) def test_issue_256(self): ast = self.create_ast(Fixtures.ISSUE_256) parser = CallNodeParser() got_ast = parser.process(ast) self.assertIsNotNone(got_ast) def test_nested_map(self): ast = self.create_ast(Fixtures.NESTED) parser = CallNodeParser() got_ast = parser.process(ast) nested_map_ast = get_lambda_string_expr_content(got_ast['body'][0]['left']['rlist'][1])[0] self.assertIsNotNone(get_lambda_string_expr_content(nested_map_ast['rlist'][1])) def test_nested_filter(self): ast = self.create_ast(Fixtures.NESTED) parser = CallNodeParser() got_ast = parser.process(ast) nested_filter_ast = get_lambda_string_expr_content(got_ast['body'][1]['left']['rlist'][1])[0] self.assertIsNotNone(get_lambda_string_expr_content(nested_filter_ast['rlist'][1])) def test_issue_274_call(self): ast = self.create_ast(Fixtures.ISSUE_274_CALL) parser = CallNodeParser() got_ast = parser.process(ast) call_node = got_ast['body'][0]['left']['rlist'][0] self.assertTrue(FUNCTION_REFERENCE_STRING_EXPR_CONTENT in call_node) self.assertEqual(len(call_node[FUNCTION_REFERENCE_STRING_EXPR_CONTENT]), 1) def test_issue_274_function(self): ast = self.create_ast(Fixtures.ISSUE_274_FUNCTION) parser = CallNodeParser() got_ast = parser.process(ast) call_node = got_ast['body'][0]['left']['rlist'][0] self.assertTrue(FUNCTION_REFERENCE_STRING_EXPR_CONTENT in call_node) self.assertEqual(len(call_node[FUNCTION_REFERENCE_STRING_EXPR_CONTENT]), 1)
class TestCallNodeParser(unittest.TestCase): def create_ast(self, file_path): pass def test_process_with_map_function(self): pass def test_process_with_filter_function(self): pass def test_traverse(self): pass def enter_handler(node): pass def test_issue_256(self): pass def test_nested_map(self): pass def test_nested_filter(self): pass def test_issue_274_call(self): pass def test_issue_274_function(self): pass
11
0
8
1
7
0
1
0
1
5
5
0
9
0
9
81
90
28
62
44
51
0
59
44
48
2
2
1
11
144,165
Kuniwak/vint
Kuniwak_vint/test/integration/vint/ast/plugin/test_scope_plugin.py
test.integration.vint.ast.plugin.test_scope_plugin.Fixtures
class Fixtures(enum.Enum): REFERENCED_ALL = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_referenced_all_vars.vim') REFERENCED_ALL_FUNC = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_referenced_all_funcs.vim') REFERENCED_ALL_FUNC_IN_FUNC = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_referenced_all_funcs_in_func.vim') REFERENCED_ALL_PARAMS = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_referenced_all_vars_in_func.vim') REFERENCED_LOOP_VAR = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_referenced_loop_var.vim') UNREFERENCED_PARAMS = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_unreferenced_params.vim') UNREFERENCED_FUNC = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_unreferenced_func.vim') UNREFERENCED_FUNC_IN_FUNC = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_unreferenced_func_in_func.vim') UNREFERENCED_VAR = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_unreferenced_var.vim') UNANALYZABLE = Path( FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_unanalyzable_variables.vim')
class Fixtures(enum.Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
21
0
21
11
20
0
11
11
10
0
4
0
0
144,166
Kuniwak/vint
Kuniwak_vint/test/integration/vint/ast/plugin/test_scope_plugin.py
test.integration.vint.ast.plugin.test_scope_plugin.TestScopePlugin
class TestScopePlugin(unittest.TestCase): def create_ast(self, file_path): parser = Parser() ast = parser.parse(LintTargetFile(file_path.value)) return ast def assertVariablesUnused(self, expected_variables_unused, scope_plugin, ast): dec_id_footstamp_map = {id_name: False for id_name in expected_variables_unused.values()} def enter_handler(node): if is_declarative_identifier(node): id_name = node['value'] pprint(node) self.assertEqual(expected_variables_unused[id_name], scope_plugin.is_unused_declarative_identifier(node)) dec_id_footstamp_map[id_name] = True traverse(ast, on_enter=enter_handler) self.assertTrue(dec_id_footstamp_map.values()) def assertVariablesUndeclared(self, expected_variables_undeclared, scope_plugin, ast): ref_id_footstamp_map = {id_name: False for id_name in expected_variables_undeclared.values()} def enter_handler(node): if is_reference_identifier(node): id_name = node['value'] pprint(node) self.assertEqual(expected_variables_undeclared[id_name], scope_plugin.is_unreachable_reference_identifier(node)) ref_id_footstamp_map[id_name] = True traverse(ast, on_enter=enter_handler) # Check all exlected identifiers were tested self.assertTrue(ref_id_footstamp_map.values()) def test_reference_reachability_with_referenced_all(self): ast = self.create_ast(Fixtures.REFERENCED_ALL) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 'g:explicit_global_var': False, 'b:buffer_local_var': False, 'w:window_local_var': False, 't:tab_local_var': False, 's:script_local_var': False, 'implicit_global_var': False, 'g:implicit_global_var': False, '$ENV_VAR': False, '@"': False, '&opt_var': False, 'v:count': False, 'count': False, 'g:': False, 'b:': False, 'w:': False, 't:': False, 'v:': False, 'v:key': False, 'v:val': False, 'filter': False, 'g:dict': True, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_reference_reachability_with_referenced_all_func(self): ast = self.create_ast(Fixtures.REFERENCED_ALL_FUNC) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 'g:ExplicitGlobalFunc': False, 's:ScriptLocalFunc': False, 'ImplicitGlobalFunc': False, 'g:ImplicitGlobalFunc': False, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_declarative_identifiers_referenced_with_referenced_all_func(self): ast = self.create_ast(Fixtures.REFERENCED_ALL_FUNC) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_unused = { 'g:ExplicitGlobalFunc': False, 's:ScriptLocalFunc': False, 'ImplicitGlobalFunc': False, } self.assertVariablesUnused(expected_variables_unused, scope_plugin, ast) def test_reference_reachability_with_referenced_all_funcs_in_func(self): ast = self.create_ast(Fixtures.REFERENCED_ALL_FUNC_IN_FUNC) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 'g:ExplicitGlobalFunc': False, 'ImplicitGlobalFunc': False, 's:ExplicitScriptLocalFunc': False, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_declarative_identifiers_referenced_with_referenced_all_funcs_in_func(self): ast = self.create_ast(Fixtures.REFERENCED_ALL_FUNC_IN_FUNC) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_unused = { 'FuncContext': True, 'g:ExplicitGlobalFunc': False, 'ImplicitGlobalFunc': False, 's:ExplicitScriptLocalFunc': False, } self.assertVariablesUnused(expected_variables_unused, scope_plugin, ast) def test_declarative_identifiers_referenced_with_referenced_all(self): ast = self.create_ast(Fixtures.REFERENCED_ALL) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_unused = { 'g:explicit_global_var': False, 'b:buffer_local_var': False, 'w:window_local_var': False, 't:tab_local_var': False, 's:script_local_var': False, 'implicit_global_var': False, '$ENV_VAR': False, '@"': False, '&opt_var': False, 'v:count': False, } self.assertVariablesUnused(expected_variables_unused, scope_plugin, ast) def test_reference_reachability_with_referenced_all_params(self): ast = self.create_ast(Fixtures.REFERENCED_ALL_PARAMS) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_unused = { 'a:': False, 'l:': False, 'a:0': False, 'a:000': False, 'a:param': False, 'a:param1': False, 'a:param2': False, 'a:param_var': False, 'a:param_with_range': False, 'a:firstline': False, 'a:lastline': False, } self.assertVariablesUndeclared(expected_variables_unused, scope_plugin, ast) def test_reference_reachability_with_referenced_loop_var(self): ast = self.create_ast(Fixtures.REFERENCED_LOOP_VAR) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 'g:array': True, 'g:implicit_global_loop_var': False, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_reference_reachability_with_unreferenced_params(self): ast = self.create_ast(Fixtures.UNREFERENCED_PARAMS) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 'param': True, 'a:1': True, 'a:firstline': True, 'a:lastline': True, 'a:18': True, 'a:19': True, 'a:20': True, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_reference_reachability_with_unreferenced_func(self): ast = self.create_ast(Fixtures.UNREFERENCED_FUNC) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 's:ImplicitGlobalFunc': True, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_declarative_identifiers_referenced_with_unreferenced_func_in_func(self): ast = self.create_ast(Fixtures.UNREFERENCED_FUNC_IN_FUNC) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_unused = { 'FuncContext': True, 'g:ExplicitGlobalFunc': True, 'ImplicitGlobalFunc': True, 's:ExplicitScriptLocalFunc': True, } self.assertVariablesUnused(expected_variables_unused, scope_plugin, ast) def test_reference_reachability_with_unreferenced_var(self): ast = self.create_ast(Fixtures.UNREFERENCED_VAR) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 's:implicit_global_var': True, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast) def test_reference_reachability_with_unanalyzable(self): ast = self.create_ast(Fixtures.UNANALYZABLE) scope_plugin = ScopePlugin() scope_plugin.process(ast) expected_variables_undeclared = { 'list_slice': True, 'dict': True, } self.assertVariablesUndeclared(expected_variables_undeclared, scope_plugin, ast)
class TestScopePlugin(unittest.TestCase): def create_ast(self, file_path): pass def assertVariablesUnused(self, expected_variables_unused, scope_plugin, ast): pass def enter_handler(node): pass def assertVariablesUndeclared(self, expected_variables_undeclared, scope_plugin, ast): pass def enter_handler(node): pass def test_reference_reachability_with_referenced_all(self): pass def test_reference_reachability_with_referenced_all_func(self): pass def test_declarative_identifiers_referenced_with_referenced_all_func(self): pass def test_reference_reachability_with_referenced_all_funcs_in_func(self): pass def test_declarative_identifiers_referenced_with_referenced_all_funcs_in_func(self): pass def test_declarative_identifiers_referenced_with_referenced_all_func(self): pass def test_reference_reachability_with_referenced_all_params(self): pass def test_reference_reachability_with_referenced_loop_var(self): pass def test_reference_reachability_with_unreferenced_params(self): pass def test_reference_reachability_with_unreferenced_func(self): pass def test_declarative_identifiers_referenced_with_unreferenced_func_in_func(self): pass def test_reference_reachability_with_unreferenced_var(self): pass def test_reference_reachability_with_unanalyzable(self): pass
19
0
16
3
13
0
1
0
1
3
3
0
16
0
16
88
302
82
219
64
200
1
103
64
84
2
2
1
20
144,167
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_abbreviation_option.py
test.integration.vint.linting.policy.test_prohibit_abbreviation_option.TestProhibitAbbreviationOption
class TestProhibitAbbreviationOption(PolicyAssertion, unittest.TestCase): def create_violation(self, line_number, col_number, path): return { 'name': 'ProhibitAbbreviationOption', 'level': Level.STYLE_PROBLEM, 'position': { 'line': line_number, 'column': col_number, 'path': path, }, } def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(VALID_VIM_SCRIPT, ProhibitAbbreviationOption) def test_get_violation_if_found_when_file_is_invalid_with_set(self): expected_violations = [ self.create_violation(1, 1, INVALID_SET_VIM_SCRIPT), self.create_violation(2, 1, INVALID_SET_VIM_SCRIPT), self.create_violation(3, 1, INVALID_SET_VIM_SCRIPT), self.create_violation(4, 1, INVALID_SET_VIM_SCRIPT), self.create_violation(5, 1, INVALID_SET_VIM_SCRIPT), ] self.assertFoundViolationsEqual(INVALID_SET_VIM_SCRIPT, ProhibitAbbreviationOption, expected_violations) def test_get_violation_if_found_when_file_is_invalid_with_var(self): expected_violations = [ self.create_violation(1, 18, INVALID_VAR_VIM_SCRIPT), self.create_violation(2, 5, INVALID_VAR_VIM_SCRIPT), ] self.assertFoundViolationsEqual(INVALID_VAR_VIM_SCRIPT, ProhibitAbbreviationOption, expected_violations)
class TestProhibitAbbreviationOption(PolicyAssertion, unittest.TestCase): def create_violation(self, line_number, col_number, path): pass def test_get_violation_if_found_when_file_is_valid(self): pass def test_get_violation_if_found_when_file_is_invalid_with_set(self): pass def test_get_violation_if_found_when_file_is_invalid_with_var(self): pass
5
0
9
1
8
0
1
0
2
2
2
0
4
0
4
79
41
8
33
7
28
0
11
7
6
1
3
0
4
144,168
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_autocmd_with_no_group.py
test.integration.vint.linting.policy.test_prohibit_autocmd_with_no_group.TestProhibitAutocmdWithNoGroup
class TestProhibitAutocmdWithNoGroup(PolicyAssertion, unittest.TestCase): def create_violation(self, line_number, path): return { 'name': 'ProhibitAutocmdWithNoGroup', 'level': Level.WARNING, 'position': { 'line': line_number, 'column': 1, 'path': path } } def test_get_violation_if_found_with_valid_file_with_augroup(self): self.assertFoundNoViolations(VALID_VIM_SCRIPT_WITH_AUGROUP, ProhibitAutocmdWithNoGroup) def test_get_violation_if_found_with_valid_file_with_group_param(self): self.assertFoundNoViolations(VALID_VIM_SCRIPT_WITH_GROUP_PARAM, ProhibitAutocmdWithNoGroup) def test_get_violation_if_found_with_invalid_file(self): expected_violations = [ self.create_violation(1, INVALID_VIM_SCRIPT), self.create_violation(6, INVALID_VIM_SCRIPT), self.create_violation(7, INVALID_VIM_SCRIPT), ] self.assertFoundViolationsEqual(INVALID_VIM_SCRIPT, ProhibitAutocmdWithNoGroup, expected_violations)
class TestProhibitAutocmdWithNoGroup(PolicyAssertion, unittest.TestCase): def create_violation(self, line_number, path): pass def test_get_violation_if_found_with_valid_file_with_augroup(self): pass def test_get_violation_if_found_with_valid_file_with_group_param(self): pass def test_get_violation_if_found_with_invalid_file(self): pass
5
0
6
0
6
0
1
0
2
2
2
0
4
0
4
79
32
6
26
6
21
0
10
6
5
1
3
0
4
144,169
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_unnecessary_double_quote.py
vint.linting.policy.prohibit_unnecessary_double_quote.ProhibitUnnecessaryDoubleQuote
class ProhibitUnnecessaryDoubleQuote(AbstractPolicy): description = 'Prefer single quoted strings' reference = get_reference_source('STRINGS') level = Level.WARNING def listen_node_types(self): return [NodeType.STRING] def is_valid(self, node, lint_context): """ Whether the specified node is valid. In this policy, valid node is only 3 cases; - single quoted - double quoted, but including a special char - double quoted inside single quoted See `:help expr-string`. """ value = node['value'] is_double_quoted = value[0] == '"' if not is_double_quoted: return True has_escaped_char = _special_char_matcher.search(value) is not None if has_escaped_char: return True return is_on_string_expr_context(node)
class ProhibitUnnecessaryDoubleQuote(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): ''' Whether the specified node is valid. In this policy, valid node is only 3 cases; - single quoted - double quoted, but including a special char - double quoted inside single quoted See `:help expr-string`. ''' pass
3
1
12
4
6
3
2
0.4
1
1
1
0
2
0
2
9
32
11
15
9
12
6
15
9
12
3
2
1
4
144,170
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_unused_variable.py
vint.linting.policy.prohibit_unused_variable.ProhibitUnusedVariable
class ProhibitUnusedVariable(AbstractPolicy): reference = ':help E738' level = Level.WARNING def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Whether the variables are used. This policy cannot determine the following node types: - Global identifier like nodes - ENV - REG - OPTION - Dynamic variables - CURLYNAME - SLICE - DOT - SUBSCRIPT """ scope_plugin = lint_context['plugins']['scope'] if not scope_plugin.is_unused_declarative_identifier(identifier): return True # Ignore global like variables. scope_visibility = scope_plugin.get_objective_scope_visibility(identifier) if (scope_visibility is ScopeVisibility.GLOBAL_LIKE or scope_visibility is ScopeVisibility.BUILTIN or scope_visibility is ScopeVisibility.UNANALYZABLE): return True identifier_value = identifier['value'] # Ignore the violation when the name is specified by "policies.ProhibitUnusedVariable.ignored_patterns". ignored_patterns = self.get_policy_config(lint_context).get("ignored_patterns", []) for ignored_pattern in ignored_patterns: if re.search(ignored_pattern, identifier_value) is not None: logging.debug("{policy_name}: {name} is unused but ignored by the ignored_pattern {ignored_pattern}.".format( policy_name=self.__class__.__name__, name=identifier_value, ignored_pattern=ignored_pattern )) return True self.description = 'Unused variable: {var_name}'.format(var_name=identifier_value) return False
class ProhibitUnusedVariable(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, identifier, lint_context): ''' Whether the variables are used. This policy cannot determine the following node types: - Global identifier like nodes - ENV - REG - OPTION - Dynamic variables - CURLYNAME - SLICE - DOT - SUBSCRIPT ''' pass
3
1
21
3
12
7
3
0.54
1
1
1
0
2
1
2
9
49
9
26
11
23
14
20
11
17
5
2
2
6
144,171
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_using_undeclared_variable.py
vint.linting.policy.prohibit_using_undeclared_variable.ProhibitUsingUndeclaredVariable
class ProhibitUsingUndeclaredVariable(AbstractPolicy): description = 'Variable is not declared' reference = ':help E738' level = Level.WARNING def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Whether all variables are used after declared. This policy cannot determine the following node types: - Global identifier like nodes - ENV - REG - OPTION - Dynamic variables - CURLYNAME - SLICE - DOT - SUBSCRIPT """ scope_plugin = lint_context['plugins']['scope'] is_reachable = not scope_plugin.is_unreachable_reference_identifier(identifier) scope_visibility = scope_plugin.get_objective_scope_visibility(identifier) is_global = scope_visibility is ScopeVisibility.GLOBAL_LIKE is_builtin = scope_visibility is ScopeVisibility.BUILTIN is_unanalyzable = scope_visibility is ScopeVisibility.UNANALYZABLE # Ignore global like variables is_valid = is_reachable or is_global or is_builtin or is_unanalyzable if not is_valid: self._make_description(identifier) return is_valid def _make_description(self, identifier): self.description = 'Undefined variable: {var_name}'.format( var_name=identifier['value'])
class ProhibitUsingUndeclaredVariable(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, identifier, lint_context): ''' Whether all variables are used after declared. This policy cannot determine the following node types: - Global identifier like nodes - ENV - REG - OPTION - Dynamic variables - CURLYNAME - SLICE - DOT - SUBSCRIPT ''' pass def _make_description(self, identifier): pass
4
1
11
2
5
4
1
0.65
1
1
1
0
3
0
3
10
43
10
20
14
16
13
19
14
15
2
2
1
4
144,172
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_encoding_opt_after_scriptencoding.py
vint.linting.policy.prohibit_encoding_opt_after_scriptencoding.ProhibitEncodingOptionAfterScriptEncoding
class ProhibitEncodingOptionAfterScriptEncoding(AbstractPolicy): description = 'Set encoding before setting scriptencoding' reference = ':help :scriptencoding' level = Level.WARNING was_scriptencoding_found = False has_encoding_opt_after_scriptencoding = False def listen_node_types(self): return [NodeType.EXCMD] def is_valid(self, excmd_node, lint_context): """ Whether the specified node is valid. This policy prohibits encoding option after scriptencoding. """ cmd_str = excmd_node['str'] if re.match(r':*scripte', cmd_str): self.was_scriptencoding_found = True if re.match(r':*set? +enc', cmd_str) and self.was_scriptencoding_found: return False return True
class ProhibitEncodingOptionAfterScriptEncoding(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, excmd_node, lint_context): ''' Whether the specified node is valid. This policy prohibits encoding option after scriptencoding. ''' pass
3
1
9
3
5
2
2
0.2
1
1
1
0
2
0
2
9
28
10
15
9
12
3
15
9
12
3
2
1
4
144,173
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_equal_tilde_operator.py
vint.linting.policy.prohibit_equal_tilde_operator.ProhibitEqualTildeOperator
class ProhibitEqualTildeOperator(AbstractPolicy): level = Level.WARNING description = 'Use the =~# or =~? operator families over the =~ family.' reference = get_reference_source('MATCHING') def listen_node_types(self): return [ NodeType.EQUAL, NodeType.NEQUAL, NodeType.GREATER, NodeType.GEQUAL, NodeType.SMALLER, NodeType.SEQUAL, NodeType.MATCH, NodeType.NOMATCH, NodeType.IS, NodeType.ISNOT, ] def is_valid(self, node, lint_context): """ Whether the specified node is valid to the policy. In this policy, comparing between a string and any value by 'ignorecase'-sensitive is invalid. This policy can detect following script: variable =~ '1' But detecting exactly string comparison without evaluation is very hard. So this policy often get false-positive/negative results. False-positive case is: '1' =~ 1 False-negative case is: ('1') =~ 1 """ node_type = NodeType(node['type']) left_node = node['left'] right_node = node['right'] left_type = NodeType(left_node['type']) right_type = NodeType(node['right']['type']) is_valid = True if left_type is NodeType.STRING: if any(c.isalpha() for c in left_node.value): is_valid = False if is_valid and right_type is NodeType.STRING: if any(c.isalpha() for c in right_node.value): is_valid = False if not is_valid: self._make_description(node_type) return is_valid def _make_description(self, node_type): good_examples = ['`' + op + '`' for op in GoodStringComparisonOperators[node_type]] formatted_good_examples = ' or '.join(good_examples) bad_example = BadStringComparisonOperators[node_type] params = { 'good_example': formatted_good_examples, 'bad_example': bad_example, } self.description = ('Use robust operators {good_example} ' 'instead of `{bad_example}`').format(**params)
class ProhibitEqualTildeOperator(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): ''' Whether the specified node is valid to the policy. In this policy, comparing between a string and any value by 'ignorecase'-sensitive is invalid. This policy can detect following script: variable =~ '1' But detecting exactly string comparison without evaluation is very hard. So this policy often get false-positive/negative results. False-positive case is: '1' =~ 1 False-negative case is: ('1') =~ 1 ''' pass def _make_description(self, node_type): pass
4
1
19
3
13
3
3
0.23
1
1
1
0
3
0
3
10
66
14
43
17
39
10
28
17
24
6
2
2
8
144,174
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_implicit_scope_builtin_variable.py
vint.linting.policy.prohibit_implicit_scope_builtin_variable.ProhibitImplicitScopeBuiltinVariable
class ProhibitImplicitScopeBuiltinVariable(AbstractPolicy): reference = ':help local-variable' level = Level.WARNING def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Implicit scope builtin variables are prohibited. Because it will make unexpected variable name conflict between builtin and implicit global/function local. For example: " This variable is not global variable but builtin variable. let count = 100 """ scope_plugin = lint_context['plugins']['scope'] # type: ScopePlugin # NOTE: This policy interest only builtin variables. scope_visibility = scope_plugin.get_objective_scope_visibility(identifier) if scope_visibility is not ScopeVisibility.BUILTIN: return True explicity = scope_plugin.get_explicity_of_scope_visibility(identifier) is_valid = explicity is not ExplicityOfScopeVisibility.IMPLICIT if not is_valid: self._make_description(identifier, scope_plugin) return is_valid def _make_description(self, identifier, scope_plugin): self.description = 'Make the scope explicit like `{good_example}` (or possibly be unexpected builtin?)'.format( good_example=scope_plugin.normalize_variable_name(identifier) )
class ProhibitImplicitScopeBuiltinVariable(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, identifier, lint_context): ''' Implicit scope builtin variables are prohibited. Because it will make unexpected variable name conflict between builtin and implicit global/function local. For example: " This variable is not global variable but builtin variable. let count = 100 ''' pass def _make_description(self, identifier, scope_plugin): pass
4
1
10
2
5
3
2
0.42
1
1
1
0
3
1
3
10
39
13
19
11
15
8
17
11
13
3
2
1
5
144,175
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_implicit_scope_variable.py
vint.linting.policy.prohibit_implicit_scope_variable.ProhibitImplicitScopeVariable
class ProhibitImplicitScopeVariable(AbstractPolicy): reference = 'Anti-pattern of vimrc (Scope of identifier)' level = Level.STYLE_PROBLEM def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Whether the identifier has a scope prefix. """ scope_plugin = lint_context['plugins']['scope'] # NOTE: This policy interest only not builtin variables. scope_visibility = scope_plugin.get_objective_scope_visibility(identifier) if scope_visibility is ScopeVisibility.BUILTIN: return True explicity = scope_plugin.get_explicity_of_scope_visibility(identifier) is_valid = explicity is not ExplicityOfScopeVisibility.IMPLICIT if not is_valid: self._make_description(identifier, scope_plugin) return is_valid def _make_description(self, identifier, scope_plugin): self.description = 'Make the scope explicit like `{good_example}`'.format( good_example=scope_plugin.normalize_variable_name(identifier) )
class ProhibitImplicitScopeVariable(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, identifier, lint_context): ''' Whether the identifier has a scope prefix. ''' pass def _make_description(self, identifier, scope_plugin): pass
4
1
8
2
5
1
2
0.11
1
1
1
0
3
1
3
10
33
12
19
11
15
2
17
11
13
3
2
1
5
144,176
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_invalid_map_call.py
vint.linting.policy.prohibit_invalid_map_call.ProhibitInvalidMapCall
class ProhibitInvalidMapCall(AbstractPolicy): def __init__(self): super(ProhibitInvalidMapCall, self).__init__() self.description = 'Number of arguments for map() must be 2 (if not, it will throw E118 or E119)' self.reference = ':help map()' self.level = Level.ERROR def listen_node_types(self): return [NodeType.CALL] def is_valid(self, node, lint_context): left_node = node['left'] if NodeType(left_node['type']) != NodeType.IDENTIFIER: return True if left_node['value'] != 'map': return True args = node['rlist'] return len(args) == 2
class ProhibitInvalidMapCall(AbstractPolicy): def __init__(self): pass def listen_node_types(self): pass def is_valid(self, node, lint_context): pass
4
0
6
1
5
0
2
0
1
3
2
0
3
3
3
10
23
7
16
9
12
0
16
9
12
3
2
1
5
144,177
Kuniwak/vint
Kuniwak_vint/vint/linting/policy_set.py
vint.linting.policy_set.PolicySet
class PolicySet(object): def __init__(self, policy_classes): self._all_policies_map = PolicySet.create_all_policies_map(policy_classes) self.enabled_policies = [] @classmethod def create_all_policies_map(cls, policy_classes): policy_map = {PolicyClass.__name__: PolicyClass() for PolicyClass in policy_classes} return policy_map def _is_policy_exists(self, name): return name in self._all_policies_map def _get_policy(self, name): return self._all_policies_map[name] def _warn_unexistent_policy(self, policy_name): logging.warning('Policy `{name}` is not defined'.format( name=policy_name)) def _get_enabling_map(self, config_dict): severity = config_dict['cmdargs']['severity'] policy_enabling_map = {} for policy_name, policy in self._all_policies_map.items(): policy_enabling_map[policy_name] = is_level_enabled(policy.level, severity) prior_policy_enabling_map = config_dict['policies'] for policy_name, policy in prior_policy_enabling_map.items(): if 'enabled' in policy: policy_enabling_map[policy_name] = policy['enabled'] return policy_enabling_map def update_by_config(self, config_dict): """ Update policies set by the config dictionary. Expect the policy_enabling_map structure to be (represented by YAML): - PolicyFoo: enabled: True - PolicyBar: enabled: False additional_field: 'is_ok' """ policy_enabling_map = self._get_enabling_map(config_dict) self.enabled_policies = [] for policy_name, is_policy_enabled in policy_enabling_map.items(): if not self._is_policy_exists(policy_name): self._warn_unexistent_policy(policy_name) continue if is_policy_enabled: enabled_policy = self._get_policy(policy_name) self.enabled_policies.append(enabled_policy) def get_enabled_policies(self): """ Returns enabled policies. """ return self.enabled_policies
class PolicySet(object): def __init__(self, policy_classes): pass @classmethod def create_all_policies_map(cls, policy_classes): pass def _is_policy_exists(self, name): pass def _get_policy(self, name): pass def _warn_unexistent_policy(self, policy_name): pass def _get_enabling_map(self, config_dict): pass def update_by_config(self, config_dict): ''' Update policies set by the config dictionary. Expect the policy_enabling_map structure to be (represented by YAML): - PolicyFoo: enabled: True - PolicyBar: enabled: False additional_field: 'is_ok' ''' pass def get_enabled_policies(self): ''' Returns enabled policies. ''' pass
10
2
7
1
4
1
2
0.24
1
0
0
0
7
2
8
8
68
22
37
20
27
9
35
19
26
4
1
2
14
144,178
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_command_rely_on_user.py
test.integration.vint.linting.policy.test_prohibit_command_rely_on_user.TestProhibitCommandRelyOnUser
class TestProhibitCommandRelyOnUser(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitCommandRelyOnUser) def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ { 'name': 'ProhibitCommandRelyOnUser', 'level': Level.WARNING, 'position': { 'line': 1, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitCommandRelyOnUser', 'level': Level.WARNING, 'position': { 'line': 2, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitCommandRelyOnUser', 'level': Level.WARNING, 'position': { 'line': 3, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitCommandRelyOnUser', 'level': Level.WARNING, 'position': { 'line': 4, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitCommandRelyOnUser', 'level': Level.WARNING, 'position': { 'line': 5, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitCommandRelyOnUser, expected_violations)
class TestProhibitCommandRelyOnUser(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
3
0
28
1
27
0
1
0
2
2
2
0
2
0
2
77
58
3
55
4
52
0
6
4
3
1
3
0
2
144,179
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_no_abort_function.py
vint.linting.policy.prohibit_no_abort_function.ProhibitNoAbortFunction
class ProhibitNoAbortFunction(AbstractPolicy): description = 'Use the abort attribute and ! for functions in autoload' reference = get_reference_source('FUNCTIONS') level = Level.WARNING def listen_node_types(self): return [NodeType.FUNCTION] def is_valid(self, node, lint_context): """ Whether the specified node is valid. This policy prohibits functions in autoload that have no 'abort' or bang """ if 'autoload' not in lint_context['lint_target'].path.parts: return True has_bang = node['ea']['forceit'] != 0 has_abort = node['attr']['abort'] != 0 return has_bang and has_abort
class ProhibitNoAbortFunction(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): ''' Whether the specified node is valid. This policy prohibits functions in autoload that have no 'abort' or bang ''' pass
3
1
8
2
4
2
2
0.25
1
1
1
0
2
0
2
9
23
8
12
8
9
3
12
8
9
2
2
1
3
144,180
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_set_nocompatible.py
vint.linting.policy.prohibit_set_nocompatible.ProhibitSetNoCompatible
class ProhibitSetNoCompatible(AbstractPolicy): description = 'Do not use nocompatible which has unexpected effects' reference = ':help nocompatible' level = Level.WARNING def listen_node_types(self): return [NodeType.EXCMD] def is_valid(self, node, lint_context): """ Whether the specified node is valid. This policy prohibit following commands: - normal without ! - substitute """ command = node['str'] is_nocompatible = re.match(r'set?\s+(?:nocp|invcp|nocompatible|invcompatible)', command) return not is_nocompatible
class ProhibitSetNoCompatible(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): ''' Whether the specified node is valid. This policy prohibit following commands: - normal without ! - substitute ''' pass
3
1
7
2
3
3
1
0.5
1
1
1
0
2
0
2
9
22
7
10
8
7
5
10
8
7
1
2
0
2
144,181
Kuniwak/vint
Kuniwak_vint/vint/linting/policy/prohibit_missing_scriptencoding.py
vint.linting.policy.prohibit_missing_scriptencoding.ProhibitMissingScriptEncoding
class ProhibitMissingScriptEncoding(AbstractPolicy): description = 'Use scriptencoding when multibyte char exists' reference = ':help :scriptencoding' level = Level.WARNING has_scriptencoding = False def listen_node_types(self): return [NodeType.TOPLEVEL] def is_valid(self, node, lint_context): """ Whether the specified node is valid. This policy prohibit scriptencoding missing when multibyte char exists. """ traverse(node, on_enter=self._check_scriptencoding) if self.has_scriptencoding: return True return not _has_multibyte_char(lint_context) def _check_scriptencoding(self, node): # TODO: Use BREAK when implemented if self.has_scriptencoding: return SKIP_CHILDREN node_type = NodeType(node['type']) if node_type is not NodeType.EXCMD: return self.has_scriptencoding = node['str'].startswith('scripte')
class ProhibitMissingScriptEncoding(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): ''' Whether the specified node is valid. This policy prohibit scriptencoding missing when multibyte char exists. ''' pass def _check_scriptencoding(self, node): pass
4
1
8
2
5
1
2
0.21
1
1
1
0
3
0
3
10
35
12
19
9
15
4
19
9
15
3
2
1
6
144,182
Kuniwak/vint
Kuniwak_vint/test/fixture/policy_set/policy_fixture_2.py
test.fixture.policy_set.policy_fixture_2.PolicyFixture2
class PolicyFixture2(object): def __init__(self): super(PolicyFixture2, self).__init__() self.description = 'PolicyFixture2' self.reference = 'PolicyFixture2' self.level = Level.STYLE_PROBLEM
class PolicyFixture2(object): def __init__(self): pass
2
0
5
0
5
0
1
0
1
2
1
0
1
3
1
1
6
0
6
5
4
0
6
5
4
1
1
0
1
144,183
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_identifier_classifier.py
test.unit.vint.ast.plugin.scope_plugin.test_identifier_classifier.TestIdentifierClassifier
class TestIdentifierClassifier(unittest.TestCase): def create_ast(self, file_path): parser = Parser() ast = parser.parse(LintTargetFile(file_path)) return ast def create_id_attr(self, is_declarative=False, is_dynamic=False, is_member=False, is_function=False, is_autoload=False, is_declarative_parameter=False, is_on_lambda_string=False, is_variadic=False, is_lambda_argument=False, is_on_lambda_body=False): return { IDENTIFIER_ATTRIBUTE_DECLARATION_FLAG: is_declarative, IDENTIFIER_ATTRIBUTE_DYNAMIC_FLAG: is_dynamic, IDENTIFIER_ATTRIBUTE_MEMBER_FLAG: is_member, IDENTIFIER_ATTRIBUTE_FUNCTION_FLAG: is_function, IDENTIFIER_ATTRIBUTE_AUTOLOAD_FLAG: is_autoload, IDENTIFIER_ATTRIBUTE_FUNCTION_ARGUMENT_FLAG: is_declarative_parameter, IDENTIFIER_ATTRIBUTE_LAMBDA_STRING_CONTEXT: is_on_lambda_string, IDENTIFIER_ATTRIBUTE_VARIADIC_SYMBOL_FLAG: is_variadic, IDENTIFIER_ATTRIBUTE_LAMBDA_ARGUMENT_FLAG: is_lambda_argument, IDENTIFIER_ATTRIBUTE_LAMBDA_BODY_CONTEXT: is_on_lambda_body, } def assertAttributesInIdentifiers(self, ast, expected_id_attr_map): footstamps = {id_name: False for id_name in expected_id_attr_map} def on_enter_handler(node): if IDENTIFIER_ATTRIBUTE not in node: return id_name = node['value'] footstamps[id_name] = True self.assertEqual( expected_id_attr_map[id_name], node[IDENTIFIER_ATTRIBUTE], "Identifier Attribute of {1}({0}) have unexpected differences".format(NodeType(node['type']), id_name) ) traverse(ast, on_enter=on_enter_handler) # Check all identifier like node was tested self.assertTrue(all(footstamps.values()), self._create_fail_message_for_assertion_attr(footstamps)) def _create_fail_message_for_assertion_attr(self, footstamps): unvisiteds = filter(lambda item: not item[1], footstamps.items()) unvisited_id_names = map(lambda footstamp: footstamp[0], unvisiteds) return 'Some identifier like node was not visited: ' + ', '.join(unvisited_id_names) def test_attach_identifier_attributes_with_declaring_func(self): ast = self.create_ast(Fixtures['DECLARING_FUNC']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:ExplicitGlobalFunc': self.create_id_attr(is_declarative=True, is_function=True), 's:ScriptLocalFunc': self.create_id_attr(is_declarative=True, is_function=True), 'ImplicitGlobalFunc': self.create_id_attr(is_declarative=True, is_function=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_calling_func(self): ast = self.create_ast(Fixtures['CALLING_FUNC']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'FunctionCall': self.create_id_attr(is_declarative=False, is_function=True), 'autoload#AutoloadFunctionCall': self.create_id_attr(is_declarative=False, is_autoload=True, is_function=True), 'dot': self.create_id_attr(is_declarative=False), 'DotFunctionCall': self.create_id_attr(is_declarative=False, is_member=True, is_function=True), 'subscript': self.create_id_attr(is_declarative=False), "'SubscriptFunctionCall'": self.create_id_attr(is_declarative=False, is_member=True, is_function=True), 'FunctionCallInExpressionContext': self.create_id_attr(is_declarative=False, is_function=True), 'FunctionToBeDeleted': self.create_id_attr(is_declarative=False, is_function=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_declaring_func_in_func(self): ast = self.create_ast(Fixtures['DECLARING_FUNC_IN_FUNC']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'FuncContext': self.create_id_attr(is_declarative=True, is_function=True), 'ImplicitGlobalFunc': self.create_id_attr(is_declarative=True, is_function=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_declaring_var(self): ast = self.create_ast(Fixtures['DECLARING_VAR']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:explicit_global_var': self.create_id_attr(is_declarative=True), 'b:buffer_local_var': self.create_id_attr(is_declarative=True), 'w:window_local_var': self.create_id_attr(is_declarative=True), 't:tab_local_var': self.create_id_attr(is_declarative=True), 's:script_local_var': self.create_id_attr(is_declarative=True), 'implicit_global_var': self.create_id_attr(is_declarative=True), '$ENV_VAR': self.create_id_attr(is_declarative=True), '@"': self.create_id_attr(is_declarative=True), '&opt_var': self.create_id_attr(is_declarative=True), 'v:count': self.create_id_attr(is_declarative=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_declaring_var_in_func(self): ast = self.create_ast(Fixtures['DECLARING_VAR_IN_FUNC']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'FuncContext': self.create_id_attr(is_declarative=True, is_function=True), 'l:explicit_func_local_var': self.create_id_attr(is_declarative=True), 'implicit_func_local_var': self.create_id_attr(is_declarative=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_declaring_with_dict_key(self): ast = self.create_ast(Fixtures['DICT_KEY']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:dict': self.create_id_attr(is_declarative=False), 'Function1': self.create_id_attr(is_declarative=True, is_member=True, is_function=True), "'Function2'": self.create_id_attr(is_declarative=True, is_member=True, is_function=True), 'key1': self.create_id_attr(is_declarative=True, is_member=True, is_function=False), "'key2'": self.create_id_attr(is_declarative=True, is_member=True, is_function=False), "g:key3": self.create_id_attr(is_declarative=False, is_member=False, is_function=False), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_destructuring_assignment(self): ast = self.create_ast(Fixtures['DESTRUCTURING_ASSIGNMENT']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:for_var1': self.create_id_attr(is_declarative=True), 'g:for_var2': self.create_id_attr(is_declarative=True), 'g:let_var1': self.create_id_attr(is_declarative=True), 'g:let_var2': self.create_id_attr(is_declarative=True), 'g:let_var3': self.create_id_attr(is_declarative=True), 'g:rest': self.create_id_attr(is_declarative=True), 'g:list': self.create_id_attr(is_declarative=False), '1': self.create_id_attr(is_declarative=True, is_member=True), 'g:index_end': self.create_id_attr(is_declarative=False, is_dynamic=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_func_param(self): ast = self.create_ast(Fixtures['FUNC_PARAM']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:FunctionWithNoParams': self.create_id_attr(is_declarative=True, is_function=True), 'g:FunctionWithOneParam': self.create_id_attr(is_declarative=True, is_function=True), 'param': self.create_id_attr(is_declarative=True, is_declarative_parameter=True), 'g:FunctionWithTwoParams': self.create_id_attr(is_declarative=True, is_function=True), 'param1': self.create_id_attr(is_declarative=True, is_declarative_parameter=True), 'param2': self.create_id_attr(is_declarative=True, is_declarative_parameter=True), 'g:FunctionWithVarParams': self.create_id_attr(is_declarative=True, is_function=True), 'g:FunctionWithParamsAndVarParams': self.create_id_attr(is_declarative=True, is_function=True), 'param_var1': self.create_id_attr(is_declarative=True, is_declarative_parameter=True), 'g:FunctionWithRange': self.create_id_attr(is_declarative=True, is_function=True), '...': self.create_id_attr(is_declarative=True, is_declarative_parameter=True, is_variadic=True), 'g:FunctionWithDict': self.create_id_attr(is_declarative=True, is_function=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_loop_var(self): ast = self.create_ast(Fixtures['LOOP_VAR']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'implicit_global_loop_var': self.create_id_attr(is_declarative=True), 'g:array': self.create_id_attr(is_declarative=False), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_redir(self): ast = self.create_ast(Fixtures['REDIR']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:var': self.create_id_attr(is_declarative=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_arithmetic_assignment(self): ast = self.create_ast(Fixtures['ARITHMETIC_ASSIGNMENT']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'g:variable_defined': self.create_id_attr(), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_attach_identifier_attributes_with_map_func(self): ast = self.create_ast(Fixtures['MAP_FUNC']) id_classifier = IdentifierClassifier() expected_id_attr_map = { 'v:val': self.create_id_attr(is_on_lambda_string=True), 'g:pattern': self.create_id_attr(is_on_lambda_string=True), 'map': self.create_id_attr(is_function=True), } attached_ast = id_classifier.attach_identifier_attributes(ast) self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map) def test_issue_274_curlyname(self): ast = self.create_ast(Fixtures['ISSUE_274_CURLYNAME']) id_classifier = IdentifierClassifier() attached_ast = id_classifier.attach_identifier_attributes(ast) curlyname_node = attached_ast['body'][0]['left'] # For debugging. pprint(curlyname_node) self.assertTrue(curlyname_node[IDENTIFIER_ATTRIBUTE][IDENTIFIER_ATTRIBUTE_DYNAMIC_FLAG]) def test_issue_274_curlyname_complex(self): ast = self.create_ast(Fixtures['ISSUE_274_CURLYNAME_COMPLEX']) id_classifier = IdentifierClassifier() attached_ast = id_classifier.attach_identifier_attributes(ast) curlyname_node = attached_ast['body'][0]['body'][1]['right'] # For debugging. pprint(curlyname_node) self.assertTrue(curlyname_node[IDENTIFIER_ATTRIBUTE][IDENTIFIER_ATTRIBUTE_DYNAMIC_FLAG]) def test_lambda(self): ast = self.create_ast(Fixtures['LAMBDA']) id_classifier = IdentifierClassifier() attached_ast = id_classifier.attach_identifier_attributes(ast) expected_id_attr_map = { 'i': self.create_id_attr(is_declarative=True, is_lambda_argument=True), 'y': self.create_id_attr(is_on_lambda_body=True), 'map': self.create_id_attr(is_function=True), '...': self.create_id_attr(is_declarative=True, is_lambda_argument=True, is_variadic=True), } self.assertAttributesInIdentifiers(attached_ast, expected_id_attr_map)
class TestIdentifierClassifier(unittest.TestCase): def create_ast(self, file_path): pass def create_id_attr(self, is_declarative=False, is_dynamic=False, is_member=False, is_function=False, is_autoload=False, is_declarative_parameter=False, is_on_lambda_string=False, is_variadic=False, is_lambda_argument=False, is_on_lambda_body=False): pass def assertAttributesInIdentifiers(self, ast, expected_id_attr_map): pass def on_enter_handler(node): pass def _create_fail_message_for_assertion_attr(self, footstamps): pass def test_attach_identifier_attributes_with_declaring_func(self): pass def test_attach_identifier_attributes_with_calling_func(self): pass def test_attach_identifier_attributes_with_declaring_func_in_func(self): pass def test_attach_identifier_attributes_with_declaring_var(self): pass def test_attach_identifier_attributes_with_declaring_var_in_func(self): pass def test_attach_identifier_attributes_with_declaring_with_dict_key(self): pass def test_attach_identifier_attributes_with_destructuring_assignment(self): pass def test_attach_identifier_attributes_with_func_param(self): pass def test_attach_identifier_attributes_with_loop_var(self): pass def test_attach_identifier_attributes_with_redir(self): pass def test_attach_identifier_attributes_with_arithmetic_assignment(self): pass def test_attach_identifier_attributes_with_map_func(self): pass def test_issue_274_curlyname(self): pass def test_issue_274_curlyname_complex(self): pass def test_lambda(self): pass
21
0
15
3
12
0
1
0.02
1
6
4
0
19
0
19
91
331
88
240
91
215
4
113
87
92
2
2
1
21
144,184
Kuniwak/vint
Kuniwak_vint/test/fixture/policy_set/policy_fixture_1.py
test.fixture.policy_set.policy_fixture_1.PolicyFixture1
class PolicyFixture1(object): def __init__(self): super(PolicyFixture1, self).__init__() self.description = 'PolicyFixture1' self.reference = 'PolicyFixture1' self.level = Level.WARNING
class PolicyFixture1(object): def __init__(self): pass
2
0
5
0
5
0
1
0
1
2
1
0
1
3
1
1
6
0
6
5
4
0
6
5
4
1
1
0
1
144,185
Kuniwak/vint
Kuniwak_vint/test/asserting/formatter.py
test.asserting.formatter.FormatterAssertion
class FormatterAssertion(unittest.TestCase): def assertFormattedViolations(self, formatter, violations, expected_output): got_output = formatter.format_violations(violations) self.assertEqual(got_output, expected_output)
class FormatterAssertion(unittest.TestCase): def assertFormattedViolations(self, formatter, violations, expected_output): pass
2
0
3
0
3
0
1
0
1
0
0
2
1
0
1
73
4
0
4
3
2
0
4
3
2
1
2
0
1
144,186
Kuniwak/vint
Kuniwak_vint/test/unit/vint/ast/plugin/scope_plugin/test_call_node_parser.py
test.unit.vint.ast.plugin.scope_plugin.test_call_node_parser.Fixtures
class Fixtures(enum.Enum): MAP_AND_FILTER_VARIABLE = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_map_and_filter.vim') ISSUE_256 = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_issue_256.vim') NESTED = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_nested_map_and_filter.vim') ISSUE_274_CALL = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_issue_274_call.vim') ISSUE_274_FUNCTION = Path(FIXTURE_BASE_PATH, 'fixture_to_scope_plugin_issue_274_function.vim')
class Fixtures(enum.Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
6
0
6
6
5
0
6
6
5
0
4
0
0
144,187
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/test_linter.py
test.integration.vint.linting.test_linter.TestLinterIntegral
class TestLinterIntegral(unittest.TestCase): class StubPolicy1(AbstractPolicy): reference = 'ref1' description = 'desc1' level = Level.WARNING def listen_node_types(self): return [NodeType.COMMENT] def is_valid(self, node, lint_context): return 'STUB_POLICY_1_INVALID' not in node['str'] class StubPolicy2(AbstractPolicy): reference = 'ref2' description = 'desc2' level = Level.WARNING def listen_node_types(self): return [NodeType.COMMENT] def is_valid(self, node, lint_context): return 'STUB_POLICY_2_INVALID' not in node['str'] class StubPolicySet(object): def __init__(self): self._enabled_policies = [] def get_enabled_policies(self): return self._enabled_policies def update_by_config(self, config_dict): self._enabled_policies = [] policy_enabling_map = config_dict['policies'] if policy_enabling_map['StubPolicy1']['enabled']: self._enabled_policies.append(TestLinterIntegral.StubPolicy1()) if policy_enabling_map['StubPolicy2']['enabled']: self._enabled_policies.append(TestLinterIntegral.StubPolicy2()) def test_lint(self): policy_set = TestLinterIntegral.StubPolicySet() config_dict_global = { 'cmdargs': { 'verbose': True, 'severity': Level.WARNING, 'error-limit': 10, }, 'policies': { 'StubPolicy1': { 'enabled': True, }, 'StubPolicy2': { 'enabled': False, }, } } linter = Linter(policy_set, config_dict_global) got_violations = linter.lint(LintTargetFile(INVALID_VIM_SCRIPT)) expected_violations = [ { 'name': 'StubPolicy1', 'level': Level.WARNING, 'description': 'desc1', 'reference': 'ref1', 'position': { 'line': 1, 'column': 1, 'path': INVALID_VIM_SCRIPT }, }, { 'name': 'StubPolicy1', 'level': Level.WARNING, 'description': 'desc1', 'reference': 'ref1', 'position': { 'line': 7, 'column': 1, 'path': INVALID_VIM_SCRIPT }, }, { 'name': 'StubPolicy2', 'level': Level.WARNING, 'description': 'desc2', 'reference': 'ref2', 'position': { 'line': 8, 'column': 1, 'path': INVALID_VIM_SCRIPT }, }, ] self.maxDiff = 1024 self.assertEqual(got_violations, expected_violations) def test_lint_with_broken_file(self): policy_set = TestLinterIntegral.StubPolicySet() config_dict_global = { 'cmdargs': { 'verbose': True, 'severity': Level.WARNING, 'error-limit': 10, }, 'policies': { 'StubPolicy1': { 'enabled': True, }, 'StubPolicy2': { 'enabled': False, }, } } linter = Linter(policy_set, config_dict_global) got_violations = linter.lint(LintTargetFile(BROKEN_VIM_SCRIPT)) expected_violations = [ { 'name': 'SyntaxError', 'level': Level.ERROR, 'description': 'unexpected token: ==', 'reference': 'vim-jp/vim-vimlparser', 'position': { 'line': 1, 'column': 6, 'path': BROKEN_VIM_SCRIPT }, }, ] self.maxDiff = 1000 self.assertEqual(got_violations, expected_violations)
class TestLinterIntegral(unittest.TestCase): class StubPolicy1(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): pass class StubPolicy2(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): pass class StubPolicySet(object): def __init__(self): pass def get_enabled_policies(self): pass def update_by_config(self, config_dict): pass def test_lint(self): pass def test_lint_with_broken_file(self): pass
13
0
13
1
12
0
1
0
1
4
4
0
2
1
2
74
152
33
119
32
106
0
45
32
32
3
2
1
11
144,188
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/test/integration/vint/linting/test_linter.py
test.integration.vint.linting.test_linter.TestLinterIntegral.StubPolicy1
class StubPolicy1(AbstractPolicy): reference = 'ref1' description = 'desc1' level = Level.WARNING def listen_node_types(self): return [NodeType.COMMENT] def is_valid(self, node, lint_context): return 'STUB_POLICY_1_INVALID' not in node['str']
class StubPolicy1(AbstractPolicy): def listen_node_types(self): pass def is_valid(self, node, lint_context): pass
3
0
2
0
2
0
1
0
1
1
1
0
2
0
2
9
12
4
8
6
5
0
8
6
5
1
2
0
2
144,189
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_using_undeclared_variable.py
test.integration.vint.linting.policy.test_prohibit_using_undeclared_variable.TestProhibitUsingUndeclaredVariable
class TestProhibitUsingUndeclaredVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitUsingUndeclaredVariable) def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 1, 'column': 6, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 5, 'column': 10, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 6, 'column': 10, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 10, 'column': 10, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 11, 'column': 10, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 12, 'column': 10, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 13, 'column': 10, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUsingUndeclaredVariable', 'level': Level.WARNING, 'position': { 'line': 16, 'column': 6, 'path': PATH_INVALID_VIM_SCRIPT }, }, ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitUsingUndeclaredVariable, expected_violations)
class TestProhibitUsingUndeclaredVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
3
0
41
1
41
0
1
0
2
2
2
0
2
0
2
77
85
3
82
4
79
0
6
4
3
1
3
0
2
144,190
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_unused_variable.py
test.integration.vint.linting.policy.test_prohibit_unused_variable.TestProhibitUnusedVariable
class TestProhibitUnusedVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(Fixtures.VALID_VIM_SCRIPT.value, ProhibitUnusedVariable) def create_violation(self, line, column, path): return { 'name': 'ProhibitUnusedVariable', 'level': Level.WARNING, 'position': { 'line': line, 'column': column, 'path': path } } def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ self.create_violation(2, 5, Fixtures.INVALID_VIM_SCRIPT.value), self.create_violation(4, 11, Fixtures.INVALID_VIM_SCRIPT.value), self.create_violation(7, 25, Fixtures.INVALID_VIM_SCRIPT.value), self.create_violation(7, 36, Fixtures.INVALID_VIM_SCRIPT.value), self.create_violation(11, 9, Fixtures.INVALID_VIM_SCRIPT.value), self.create_violation(12, 9, Fixtures.INVALID_VIM_SCRIPT.value), self.create_violation(15, 8, Fixtures.INVALID_VIM_SCRIPT.value), ] self.assertFoundViolationsEqual(Fixtures.INVALID_VIM_SCRIPT.value, ProhibitUnusedVariable, expected_violations) def test_issue_274(self): self.assertFoundNoViolations(Fixtures.ISSUE_274.value, ProhibitUnusedVariable) def test_ignored_patterns(self): expected_violations = [ self.create_violation(1, 5, Fixtures.IGNORED_PATTERNS.value), ] self.assertFoundViolationsEqual(Fixtures.IGNORED_PATTERNS.value, ProhibitUnusedVariable, expected_violations, policy_options={'ignored_patterns': ['_ignored$']}) def test_readme(self): self.assertFoundNoViolations(Fixtures.README.value, ProhibitUnusedVariable)
class TestProhibitUnusedVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def create_violation(self, line, column, path): pass def test_get_violation_if_found_when_file_is_invalid(self): pass def test_issue_274(self): pass def test_ignored_patterns(self): pass def test_readme(self): pass
7
0
7
0
7
0
1
0
2
3
3
0
6
0
6
81
51
11
40
9
33
0
15
9
8
1
3
0
6
144,191
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_unused_variable.py
test.integration.vint.linting.policy.test_prohibit_unused_variable.Fixtures
class Fixtures(enum.Enum): VALID_VIM_SCRIPT = get_fixture_path('prohibit_unused_variable_valid.vim') INVALID_VIM_SCRIPT = get_fixture_path('prohibit_unused_variable_invalid.vim') ISSUE_274 = get_fixture_path('prohibit_unused_variable_issue_274.vim') IGNORED_PATTERNS = get_fixture_path('prohibit_unused_variable_ignored_patterns.vim') README = get_fixture_path('prohibit_unused_variable_readme.vim')
class Fixtures(enum.Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
6
0
6
6
5
0
6
6
5
0
4
0
0
144,192
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_unnecessary_double_quote.py
test.integration.vint.linting.policy.test_prohibit_unnecessary_double_quote.TestProhibitUnnecessaryDoubleQuote
class TestProhibitUnnecessaryDoubleQuote(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitUnnecessaryDoubleQuote) def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ { 'name': 'ProhibitUnnecessaryDoubleQuote', 'level': Level.WARNING, 'position': { 'line': 2, 'column': 6, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitUnnecessaryDoubleQuote', 'level': Level.WARNING, 'position': { 'line': 3, 'column': 6, 'path': PATH_INVALID_VIM_SCRIPT }, }, ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitUnnecessaryDoubleQuote, expected_violations)
class TestProhibitUnnecessaryDoubleQuote(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
3
0
14
1
14
0
1
0
2
2
2
0
2
0
2
77
31
3
28
4
25
0
6
4
3
1
3
0
2
144,193
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_set_nocompatible.py
test.integration.vint.linting.policy.test_prohibit_set_nocompatible.TestProhibitSetNoCompatible
class TestProhibitSetNoCompatible(PolicyAssertion, unittest.TestCase): def create_violation(self, line_number, path): return { 'name': 'ProhibitSetNoCompatible', 'level': Level.WARNING, 'position': { 'line': line_number, 'column': 1, 'path': path } } def test_get_violation_if_found_with_valid(self): self.assertFoundNoViolations(VALID_VIM_SCRIPT, ProhibitSetNoCompatible) def test_get_violation_if_found_with_invalid_file(self): expected_violations = [ self.create_violation(1, INVALID_VIM_SCRIPT), ] self.assertFoundViolationsEqual(INVALID_VIM_SCRIPT, ProhibitSetNoCompatible, expected_violations) def test_get_violation_if_found_with_invalid_file_with_abbreviation(self): expected_violations = [ self.create_violation(1, INVALID_VIM_SCRIPT_WITH_ABBREVIATION), ] self.assertFoundViolationsEqual(INVALID_VIM_SCRIPT_WITH_ABBREVIATION, ProhibitSetNoCompatible, expected_violations)
class TestProhibitSetNoCompatible(PolicyAssertion, unittest.TestCase): def create_violation(self, line_number, path): pass def test_get_violation_if_found_with_valid(self): pass def test_get_violation_if_found_with_invalid_file(self): pass def test_get_violation_if_found_with_invalid_file_with_abbreviation(self): pass
5
0
7
0
7
0
1
0
2
2
2
0
4
0
4
79
34
6
28
7
23
0
11
7
6
1
3
0
4
144,194
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_no_abort_function.py
test.integration.vint.linting.policy.test_prohibit_no_abort_function.TestProhibitNoAbortFunction
class TestProhibitNoAbortFunction(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT_1, ProhibitNoAbortFunction) def test_get_violation_if_found_when_file_is_valid_out_of_autoload(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT_2, ProhibitNoAbortFunction) def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ { 'name': 'ProhibitNoAbortFunction', 'level': Level.WARNING, 'position': { 'line': 1, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitNoAbortFunction', 'level': Level.WARNING, 'position': { 'line': 4, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitNoAbortFunction', 'level': Level.WARNING, 'position': { 'line': 7, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT }, }, ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitNoAbortFunction, expected_violations)
class TestProhibitNoAbortFunction(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def test_get_violation_if_found_when_file_is_valid_out_of_autoload(self): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
4
0
13
0
13
0
1
0
2
2
2
0
3
0
3
78
45
5
40
5
36
0
8
5
4
1
3
0
3
144,195
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_missing_scriptencoding.py
test.integration.vint.linting.policy.test_prohibit_missing_scriptencoding.TestProhibitMissingScriptEncoding
class TestProhibitMissingScriptEncoding(PolicyAssertion, unittest.TestCase): def _create_violation_by_line_number(self, line_number): return { 'name': 'ProhibitMissingScriptEncoding', 'level': Level.WARNING, 'position': { 'line': line_number, 'column': 1, 'path': INVALID_VIM_SCRIPT } } def test_get_violation_if_found_with_valid_file_no_multibyte_char(self): self.assertFoundNoViolations(NO_MULTI_BYTE_CHAR_VIM_SCRIPT, ProhibitMissingScriptEncoding) def test_get_violation_if_found_with_valid_file_scriptencoding(self): self.assertFoundNoViolations(SCRIPT_ENCODING_VIM_SCRIPT, ProhibitMissingScriptEncoding) def test_get_violation_if_found_with_invalid_file(self): expected_violations = [ { 'name': 'ProhibitMissingScriptEncoding', 'level': Level.WARNING, 'position': { 'line': 1, 'column': 1, 'path': INVALID_VIM_SCRIPT }, }, ] self.assertFoundViolationsEqual(INVALID_VIM_SCRIPT, ProhibitMissingScriptEncoding, expected_violations)
class TestProhibitMissingScriptEncoding(PolicyAssertion, unittest.TestCase): def _create_violation_by_line_number(self, line_number): pass def test_get_violation_if_found_with_valid_file_no_multibyte_char(self): pass def test_get_violation_if_found_with_valid_file_scriptencoding(self): pass def test_get_violation_if_found_with_invalid_file(self): pass
5
0
8
0
8
0
1
0
2
2
2
0
4
0
4
79
38
6
32
6
27
0
10
6
5
1
3
0
4
144,196
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_invalid_map_call.py
test.integration.vint.linting.policy.test_prohibit_invalid_map_call.TestProhibitInvalidMapCall
class TestProhibitInvalidMapCall(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_with_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitInvalidMapCall) def test_get_violation_if_found_with_invalid(self): expected_violations = [ { 'name': 'ProhibitInvalidMapCall', 'level': Level.ERROR, 'position': { 'line': 1, 'column': 16, 'path': PATH_INVALID_VIM_SCRIPT } } ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitInvalidMapCall, expected_violations)
class TestProhibitInvalidMapCall(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_with_valid(self): pass def test_get_violation_if_found_with_invalid(self): pass
3
0
9
0
9
0
1
0
2
2
2
0
2
0
2
77
20
2
18
4
15
0
6
4
3
1
3
0
2
144,197
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_implicit_scope_variable.py
test.integration.vint.linting.policy.test_prohibit_implicit_scope_variable.TestProhibitImplicitScopeVariable
class TestProhibitImplicitScopeVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitImplicitScopeVariable) def create_violation(self, line, column): return { 'name': 'ProhibitImplicitScopeVariable', 'level': Level.STYLE_PROBLEM, 'position': { 'line': line, 'column': column, 'path': PATH_INVALID_VIM_SCRIPT } } def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ self.create_violation(2, 5), self.create_violation(4, 10), self.create_violation(9, 10), self.create_violation(13, 5), self.create_violation(16, 11), ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitImplicitScopeVariable, expected_violations)
class TestProhibitImplicitScopeVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def create_violation(self, line, column): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
4
0
8
0
8
0
1
0
2
2
2
0
3
0
3
78
30
5
25
5
21
0
8
5
4
1
3
0
3
144,198
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_implicit_scope_builtin_variable.py
test.integration.vint.linting.policy.test_prohibit_implicit_scope_builtin_variable.TestProhibitImplicitScopeBuiltinVariable
class TestProhibitImplicitScopeBuiltinVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitImplicitScopeBuiltinVariable) def create_violation(self, line, column): return { 'name': 'ProhibitImplicitScopeBuiltinVariable', 'level': Level.WARNING, 'position': { 'line': line, 'column': column, 'path': PATH_INVALID_VIM_SCRIPT } } def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ self.create_violation(4, 9), self.create_violation(5, 10), ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitImplicitScopeBuiltinVariable, expected_violations)
class TestProhibitImplicitScopeBuiltinVariable(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def create_violation(self, line, column): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
4
0
7
0
7
0
1
0
2
2
2
0
3
0
3
78
27
5
22
5
18
0
8
5
4
1
3
0
3
144,199
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_equal_tilde_operator.py
test.integration.vint.linting.policy.test_prohibit_equal_tilde_operator.TestProhibitEqualTildeOperator
class TestProhibitEqualTildeOperator(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitEqualTildeOperator) def test_get_violation_if_found_when_file_is_invalid(self): expected_violations = [ { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 2, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 3, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 4, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 5, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 6, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 7, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 8, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 9, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 10, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 11, 'column': 12, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 15, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 16, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 17, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 18, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 19, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 20, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 21, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 22, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 23, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'line': 24, 'column': 8, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'column': 12, 'line': 27, 'path': PATH_INVALID_VIM_SCRIPT }, }, { 'name': 'ProhibitEqualTildeOperator', 'level': Level.WARNING, 'position': { 'column': 12, 'line': 28, 'path': PATH_INVALID_VIM_SCRIPT }, }, ] self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitEqualTildeOperator, expected_violations)
class TestProhibitEqualTildeOperator(PolicyAssertion, unittest.TestCase): def test_get_violation_if_found_when_file_is_valid(self): pass def test_get_violation_if_found_when_file_is_invalid(self): pass
3
0
104
1
104
0
1
0
2
2
2
0
2
0
2
77
211
3
208
4
205
0
6
4
3
1
3
0
2
144,200
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_encoding_opt_after_scriptencoding.py
test.integration.vint.linting.policy.test_prohibit_encoding_opt_after_scriptencoding.TestProhibitEncodingOptionAfterScriptEncoding
class TestProhibitEncodingOptionAfterScriptEncoding(PolicyAssertion, unittest.TestCase): def _create_violation_by_line_number(self, line_number): return { 'name': 'ProhibitEncodingOptionAfterScriptEncoding', 'level': Level.WARNING, 'position': { 'line': line_number, 'column': 1, 'path': INVALID_ORDER_VIM_SCRIPT } } def test_get_violation_if_found_with_valid_file(self): self.assertFoundNoViolations(VALID_ORDER_VIM_SCRIPT, ProhibitEncodingOptionAfterScriptEncoding) def test_get_violation_if_found_with_valid_file_no_encoding_option(self): self.assertFoundNoViolations(NO_ENCODING_OPT_VIM_SCRIPT, ProhibitEncodingOptionAfterScriptEncoding) def test_get_violation_if_found_with_valid_file_no_scriptencoding(self): self.assertFoundNoViolations(NO_SCRIPT_ENCODING_VIM_SCRIPT, ProhibitEncodingOptionAfterScriptEncoding) def test_get_violation_if_found_with_invalid_file(self): expected_violations = [self._create_violation_by_line_number(2)] self.assertFoundViolationsEqual(INVALID_ORDER_VIM_SCRIPT, ProhibitEncodingOptionAfterScriptEncoding, expected_violations)
class TestProhibitEncodingOptionAfterScriptEncoding(PolicyAssertion, unittest.TestCase): def _create_violation_by_line_number(self, line_number): pass def test_get_violation_if_found_with_valid_file(self): pass def test_get_violation_if_found_with_valid_file_no_encoding_option(self): pass def test_get_violation_if_found_with_valid_file_no_scriptencoding(self): pass def test_get_violation_if_found_with_invalid_file(self): pass
6
0
5
0
5
0
1
0
2
2
2
0
5
0
5
80
34
9
25
7
19
0
12
7
6
1
3
0
5
144,201
Kuniwak/vint
Kuniwak_vint/test/integration/vint/linting/policy/test_prohibit_command_with_unintented_side_effect.py
test.integration.vint.linting.policy.test_prohibit_command_with_unintented_side_effect.TestProhibitCommandWithUnintendedSideEffect
class TestProhibitCommandWithUnintendedSideEffect(PolicyAssertion, unittest.TestCase): def _create_violation_by_line_number(self, line_number): return { 'name': 'ProhibitCommandWithUnintendedSideEffect', 'level': Level.WARNING, 'position': { 'line': line_number, 'column': 1, 'path': PATH_INVALID_VIM_SCRIPT } } def test_get_violation_if_found_with_valid_file(self): self.assertFoundNoViolations(PATH_VALID_VIM_SCRIPT, ProhibitCommandWithUnintendedSideEffect) def test_get_violation_if_found_with_invalid_file(self): expected_violations = [self._create_violation_by_line_number(line_number) for line_number in range(1, 14)] # Offset range token length expected_violations[3]['position']['column'] = 2 expected_violations[4]['position']['column'] = 6 self.assertFoundViolationsEqual(PATH_INVALID_VIM_SCRIPT, ProhibitCommandWithUnintendedSideEffect, expected_violations)
class TestProhibitCommandWithUnintendedSideEffect(PolicyAssertion, unittest.TestCase): def _create_violation_by_line_number(self, line_number): pass def test_get_violation_if_found_with_valid_file(self): pass def test_get_violation_if_found_with_invalid_file(self): pass
4
0
8
1
7
0
1
0.05
2
3
2
0
3
0
3
78
29
6
22
5
18
1
10
5
6
1
3
0
3
144,202
Kuniwak/vint
Kuniwak_vint/test/unit/vint/linting/config/test_config_next_line_comment_source.py
test.unit.vint.linting.config.test_config_next_line_comment_source.TestConfigNextLineCommentSource
class TestConfigNextLineCommentSource(ConfigSourceAssertion, unittest.TestCase): def test_simple_example(self): global_config_dict = {'cmdargs': {'severity': Level.ERROR}} policy_set = PolicySet([TestConfigNextLineCommentSource.ProhibitStringPolicy]) linter = Linter(policy_set, global_config_dict) lint_target = LintTargetFile(Fixtures.SIMPLE.value) reported_string_node_values = [violation['description'] for violation in linter.lint(lint_target)] self.assertEqual(reported_string_node_values, [ "'report me because I have no line config comments'", "'report me because I have no line config comments, but the previous line have it'", ]) def test_lambda_string_expr(self): global_config_dict = {'cmdargs': {'severity': Level.ERROR}} policy_set = PolicySet([TestConfigNextLineCommentSource.ProhibitStringPolicy]) linter = Linter(policy_set, global_config_dict) lint_target = LintTargetFile(Fixtures.LAMBDA_STRING_EXPR.value) reported_string_node_values = [violation['description'] for violation in linter.lint(lint_target)] self.assertEqual(reported_string_node_values, [ "'report me because I have no line config comments'", "'report me because I have no line config comments, but the previous line have it'", # NOTE: In the current implementation, string in string will reported twice. "'\"report me because I have no line config comments, but the parent node have it\"'", '"report me because I have no line config comments, but the parent node have it"', ]) class ProhibitStringPolicy(AbstractPolicy): def __init__(self): super(TestConfigNextLineCommentSource.ProhibitStringPolicy, self).__init__() self.description = '' self.reference = 'nothing' self.level = Level.ERROR def listen_node_types(self): return [NodeType.STRING] def is_valid(self, node, lint_context): self.description = node['value'] return False
class TestConfigNextLineCommentSource(ConfigSourceAssertion, unittest.TestCase): def test_simple_example(self): pass def test_lambda_string_expr(self): pass class ProhibitStringPolicy(AbstractPolicy): def __init__(self): pass def listen_node_types(self): pass def is_valid(self, node, lint_context): pass
7
0
8
1
7
0
1
0.03
2
6
6
0
2
0
2
78
49
12
36
20
29
1
26
20
19
1
3
0
5
144,203
Kuniwak/vint
Kuniwak_vint/test/asserting/policy.py
test.asserting.policy.PolicyAssertion
class PolicyAssertion(unittest.TestCase): def assertFoundNoViolations(self, path, Policy, policy_options=None): self.assertFoundViolationsEqual(path, Policy, [], policy_options) def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): policy_name = Policy.__name__ policy_set = PolicySet([Policy]) config_dict = { 'cmdargs': { 'severity': Level.STYLE_PROBLEM, }, 'policies': { policy_name: { 'enabled': True, } }, } if policy_options is not None: config_dict['policies'][policy_name] = policy_options linter = Linter(policy_set, config_dict) violations = linter.lint(LintTargetFile(path)) pprint(violations) self.assertEqual(len(violations), len(expected_violations)) for violation, expected_violation in zip_longest(violations, expected_violations): self.assertViolation(violation, expected_violation) def assertViolation(self, actual_violation, expected_violation): self.assertIsNot(actual_violation, None) self.assertIsNot(expected_violation, None) pprint(actual_violation) self.assertEqual(actual_violation['name'], expected_violation['name']) self.assertEqual(actual_violation['position'], expected_violation['position']) self.assertEqual(actual_violation['level'], expected_violation['level']) self.assertIsInstance(actual_violation['description'], str)
class PolicyAssertion(unittest.TestCase): def assertFoundNoViolations(self, path, Policy, policy_options=None): pass def assertFoundViolationsEqual(self, path, Policy, expected_violations, policy_options=None): pass def assertViolation(self, actual_violation, expected_violation): pass
4
0
13
3
10
0
2
0
1
5
4
15
3
0
3
75
44
12
32
10
28
0
23
10
19
3
2
1
5
144,204
Kuniwak/vint
Kuniwak_vint/test/unit/vint/linting/config/test_config_project_source.py
test.unit.vint.linting.config.test_config_project_source.TestConfigProjectSource
class TestConfigProjectSource(ConfigSourceAssertion, unittest.TestCase): def test_get_config_dict(self): env = { 'cwd': get_fixture_path('project_with_long_extname') } expected_type = { 'cmdargs': { 'verbose': bool, 'error-limit': int, 'severity': Level, }, 'source_name': str, } config_source = self.initialize_config_source_with_env(ConfigProjectSource, env) self.assertConfigValueType(config_source, expected_type) def test_get_config_dict_on_sub_directory(self): env = { 'cwd': get_fixture_path(Path('project_with_long_extname') / 'sub' / 'subsub') } expected_type = { 'cmdargs': { 'verbose': bool, 'error-limit': int, 'severity': Level, }, 'source_name': str, } config_source = self.initialize_config_source_with_env(ConfigProjectSource, env) self.assertConfigValueType(config_source, expected_type) def test_get_config_dict_for_short_extname(self): env = { 'cwd': get_fixture_path('project_with_short_extname') } expected_type = { 'cmdargs': { 'verbose': bool, 'error-limit': int, 'severity': Level, }, 'source_name': str, } config_source = self.initialize_config_source_with_env(ConfigProjectSource, env) self.assertConfigValueType(config_source, expected_type) def test_get_config_dict_for_no_extname(self): env = { 'cwd': get_fixture_path('project_with_no_extname') } expected_type = { 'cmdargs': { 'verbose': bool, 'error-limit': int, 'severity': Level, }, 'source_name': str, } config_source = self.initialize_config_source_with_env(ConfigProjectSource, env) self.assertConfigValueType(config_source, expected_type) def test_get_config_dict_with_no_global_config(self): env = { 'cwd': get_fixture_path('unexistent_project') } expected_config_dict = {'source_name': 'ConfigProjectSource'} config_source = self.initialize_config_source_with_env(ConfigProjectSource, env) self.assertConfigDict(config_source, expected_config_dict)
class TestConfigProjectSource(ConfigSourceAssertion, unittest.TestCase): def test_get_config_dict(self): pass def test_get_config_dict_on_sub_directory(self): pass def test_get_config_dict_for_short_extname(self): pass def test_get_config_dict_for_no_extname(self): pass def test_get_config_dict_with_no_global_config(self): pass
6
0
15
2
13
0
1
0
2
6
2
0
5
0
5
81
82
18
64
21
58
0
26
21
20
1
3
0
5
144,205
Kuniwak/vint
Kuniwak_vint/test/unit/vint/utils/test_array.py
test.unit.vint.utils.test_array.TestUtilsArray
class TestUtilsArray(unittest.TestCase): def test_flatten_empty(self): result = flatten([]) self.assertEqual(result, []) def test_flatten_not_empty(self): result = flatten([[0], [1, 2]]) self.assertEqual(result, [0, 1, 2]) def test_flat_map(self): result = flat_map(lambda x: [x, x * 2], [0, 1, 2]) self.assertEqual(result, [0, 0, 1, 2, 2, 4])
class TestUtilsArray(unittest.TestCase): def test_flatten_empty(self): pass def test_flatten_not_empty(self): pass def test_flat_map(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
12
2
10
7
6
0
10
7
6
1
2
0
3
144,206
Kuniwak/vint
Kuniwak_vint/test/unit/vint/linting/config/test_toggle_config_comment_source.py
test.unit.vint.linting.config.test_toggle_config_comment_source.TestToggleConfigCommentSource
class TestToggleConfigCommentSource(ConfigSourceAssertion, unittest.TestCase): def test_get_config_dict(self): expected_config_dict = { 'policies': { 'Policy1': { 'enabled': False, }, 'Policy2': { 'enabled': True, }, }, 'source_name': 'ConfigToggleCommentSource', } node = { 'type': NodeType.COMMENT, 'str': ' vint: -Policy1 +Policy2', 'pos': { 'lnum': 10, }, } config_source = ConfigToggleCommentSource() config_source.update_by_node(node) self.assertConfigDict(config_source, expected_config_dict) def test_update_by_node_by_no_switches(self): node = { 'type': NodeType.COMMENT, 'str': ' vint:', 'pos': { 'lnum': 10, }, } expected_config_dict = { 'policies': {}, 'source_name': 'ConfigToggleCommentSource', } config_source = ConfigToggleCommentSource() config_source.update_by_node(node) self.assertConfigDict(config_source, expected_config_dict) def test_update_by_node_by_single_switch(self): node = { 'type': NodeType.COMMENT, 'str': ' vint: -Policy1', 'pos': { 'lnum': 10, }, } expected_config_dict = { 'policies': { 'Policy1': { 'enabled': False, }, }, 'source_name': 'ConfigToggleCommentSource', } config_source = ConfigToggleCommentSource() config_source.update_by_node(node) self.assertConfigDict(config_source, expected_config_dict) def test_update_by_node_by_multiple_switches(self): node = { 'type': NodeType.COMMENT, 'str': ' vint: -Policy1 +Policy2', 'pos': { 'lnum': 10, }, } expected_config_dict = { 'policies': { 'Policy1': { 'enabled': False, }, 'Policy2': { 'enabled': True, }, }, 'source_name': 'ConfigToggleCommentSource', } config_source = ConfigToggleCommentSource() config_source.update_by_node(node) self.assertConfigDict(config_source, expected_config_dict)
class TestToggleConfigCommentSource(ConfigSourceAssertion, unittest.TestCase): def test_get_config_dict(self): pass def test_update_by_node_by_no_switches(self): pass def test_update_by_node_by_single_switch(self): pass def test_update_by_node_by_multiple_switches(self): pass
5
0
22
3
20
0
1
0
2
2
2
0
4
0
4
80
96
17
79
17
74
0
25
17
20
1
3
0
4
144,207
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/two_way_scope_reference_attacher.py
vint.ast.plugin.scope_plugin.two_way_scope_reference_attacher.TwoWayScopeReferenceAttacher
class TwoWayScopeReferenceAttacher(object): @classmethod def attach(cls, scope_tree): for child_scope in scope_tree['child_scopes']: child_scope['parent_scope'] = scope_tree cls.attach(child_scope) return scope_tree
class TwoWayScopeReferenceAttacher(object): @classmethod def attach(cls, scope_tree): pass
3
0
6
1
5
0
2
0
1
0
0
0
0
0
1
1
8
1
7
4
4
0
6
3
4
2
1
1
2
144,208
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/scope_linker.py
vint.ast.plugin.scope_plugin.scope_linker.ScopeLinker
class ScopeLinker(object): """ A class for scope linkers. The class link identifiers in the given AST node and the scopes where the identifier will be declared or referenced. """ class ScopeTreeBuilder(object): """ A class for event-driven builders to build a scope tree. The class interest to scope-level events rather than AST-level events. """ def __init__(self): self.link_registry = ScopeLinker.ScopeLinkRegistry() global_scope = Scope(ScopeVisibility.GLOBAL_LIKE) self._scope_stack = [global_scope] self._add_symbol_table_variables(global_scope) def enter_new_scope(self, scope_visibility): # type: (ScopeVisibility) -> None current_scope = self.get_current_scope() new_scope = Scope(scope_visibility) self._add_symbol_table_variables(new_scope) # Build a lexical scope chain current_scope.child_scopes.append(new_scope) self._scope_stack.append(new_scope) def leave_current_scope(self): # type: () -> None self._scope_stack.pop() def get_global_scope(self): # type: () -> Scope return self._scope_stack[0] def get_script_local_scope(self): # type: () -> Scope return self._scope_stack[1] def get_current_scope(self): # type: () -> Scope return self._scope_stack[-1] def handle_new_parameter_found(self, id_node, is_lambda_argument): # type: (Dict[str, Any], bool) -> None current_scope = self.get_current_scope() self._add_parameter(current_scope, id_node, is_lambda_argument) def handle_new_range_parameters_found(self): # type: () -> None # We can access "a:firstline" and "a:lastline" if the function is # declared with an attribute "range". See :func-range firstline_node = _create_virtual_identifier_node('firstline') lastline_node = _create_virtual_identifier_node('lastline') current_scope = self.get_current_scope() self._add_parameter(current_scope, firstline_node, is_explicit_lambda_argument=False) self._add_parameter(current_scope, lastline_node, is_explicit_lambda_argument=False) def handle_new_dict_parameter_found(self): # type: () -> None # We can access "l:self" is declared with an attribute "dict". # See :help self current_scope = self.get_current_scope() self._add_self_variable(current_scope) def handle_new_parameters_list_and_length_found(self): # type: () -> None # We can always access a:0 and a:000 # See :help internal-variables param_length_node = _create_virtual_identifier_node('0') param_list_node = _create_virtual_identifier_node('000') current_scope = self.get_current_scope() self._add_parameter(current_scope, param_length_node, is_explicit_lambda_argument=False) self._add_parameter(current_scope, param_list_node, is_explicit_lambda_argument=False) def handle_new_index_parameters_found(self, params_number): # type: (int) -> None current_scope = self.get_current_scope() # Max parameters number is 20. See :help E740 for variadic_index in range(20 - params_number): # Variadic parameters named 1-based index. variadic_param = _create_virtual_identifier_node(str(variadic_index + 1)) self._add_parameter(current_scope, variadic_param, is_explicit_lambda_argument=False) def handle_new_variable_found(self, id_node): # type: (Dict[str, Any]) -> None current_scope = self.get_current_scope() scope_visibility_hint = detect_possible_scope_visibility(id_node, current_scope) if scope_visibility_hint.scope_visibility is ScopeVisibility.UNANALYZABLE \ or scope_visibility_hint.scope_visibility is ScopeVisibility.INVALID: # We can not do anything return is_function = is_function_identifier(id_node) if is_builtin_variable(id_node): self._add_builtin_variable(id_node, is_function=is_function, explicity=scope_visibility_hint.explicity) return objective_scope = self._get_objective_scope(id_node) self._add_variable(objective_scope, id_node, is_function, scope_visibility_hint.explicity) def _get_objective_scope(self, node): # type: (Dict[str, Any]) -> Scope current_scope = self.get_current_scope() scope_visibility_hint = detect_possible_scope_visibility( node, current_scope) scope_visibility = scope_visibility_hint.scope_visibility if scope_visibility is ScopeVisibility.GLOBAL_LIKE: return self.get_global_scope() if scope_visibility is ScopeVisibility.SCRIPT_LOCAL: return self.get_script_local_scope() # It is FUNCTION_LOCAL or LAMBDA scope return current_scope def handle_referencing_identifier_found(self, node): # type: (Dict[str, Any]) -> None current_scope = self.get_current_scope() self.link_registry.link_identifier_to_context_scope(node, current_scope) def _add_parameter(self, objective_scope, id_node, is_explicit_lambda_argument): # type: (Scope, Dict[str, Any], bool) -> None if is_explicit_lambda_argument: # Explicit lambda arguments can not have any explicit scope prefix. variable_name = id_node['value'] explicity = ExplicityOfScopeVisibility.IMPLICIT_BUT_CONSTRAINED else: variable_name = 'a:' + id_node['value'] explicity = ExplicityOfScopeVisibility.EXPLICIT self._register_variable( objective_scope, variable_name, id_node, explicity=explicity, is_function=False, is_builtin=False, is_explicit_lambda_argument=is_explicit_lambda_argument ) def _add_self_variable(self, objective_scope): # type: (Scope) -> None variable_name = remove_optional_scope_prefix('l:self') virtual_node = _create_virtual_identifier_node(variable_name) self._register_variable( objective_scope, variable_name, virtual_node, explicity=ExplicityOfScopeVisibility.EXPLICIT, is_function=False, is_builtin=False, is_explicit_lambda_argument=False ) def _add_variable(self, objective_scope, id_node, is_function, explicity): # type: (Scope, Dict[str, Any], bool, ExplicityOfScopeVisibility) -> None variable_name = remove_optional_scope_prefix(id_node['value']) self._register_variable( objective_scope, variable_name, id_node, explicity, is_function, is_builtin=False, is_explicit_lambda_argument=False ) def _add_builtin_variable(self, id_node, explicity, is_function): # type: (Dict[str, Any], ExplicityOfScopeVisibility, bool) -> None variable_name = remove_optional_scope_prefix(id_node['value']) self._register_variable( self.get_global_scope(), variable_name, id_node, explicity, is_function, is_builtin=True, is_explicit_lambda_argument=False ) def _add_symbol_table_variables(self, objective_scope): # type: (Scope) -> None # We can always access any symbol tables such as: "g:", "s:", "l:". # See :help internal-variables scope_visibility = objective_scope.scope_visibility symbol_table_variable_names = SymbolTableVariableNames[scope_visibility] for symbol_table_variable_name in symbol_table_variable_names: virtual_node = _create_virtual_identifier_node(symbol_table_variable_name) self._register_variable( objective_scope, symbol_table_variable_name, virtual_node, # NOTE: Symbol table always have scope prefix. explicity=ExplicityOfScopeVisibility.EXPLICIT, is_builtin=False, is_function=False, is_explicit_lambda_argument=False ) def _register_variable(self, objective_scope, variable_name, node, explicity, is_function, is_builtin, is_explicit_lambda_argument): # type: (Scope, str, Dict[str, Any], ExplicityOfScopeVisibility, bool, bool, bool) -> None variable = VariableDeclaration( explicity, is_builtin, is_explicit_lambda_argument ) if is_function: objective_variable_list = objective_scope.functions else: objective_variable_list = objective_scope.variables same_name_variables = objective_variable_list.setdefault(variable_name, []) same_name_variables.append(variable) self.link_registry.link_variable_to_declarative_identifier(variable, node) current_scope = self.get_current_scope() self.link_registry.link_identifier_to_context_scope(node, current_scope) class ScopeLinkRegistry(object): """ A class for registry services for links between scopes and identifiers. """ def __init__(self): self._vars_to_declarative_ids_map = {} # type: Dict[int, Dict[str, Any]] self._ids_to_scopes_map = {} # type: Dict[int, Scope] def link_variable_to_declarative_identifier(self, variable, declaring_id_node): # type: (VariableDeclaration, Dict[str, Any]) -> None self._vars_to_declarative_ids_map[id(variable)] = declaring_id_node def get_declarative_identifier_by_variable(self, variable): # type: (VariableDeclaration) -> Dict[str, Any] variable_id = id(variable) return self._vars_to_declarative_ids_map.get(variable_id) def link_identifier_to_context_scope(self, decl_or_ref_id_node, scope): # type: (Dict[str, Any], Scope) -> None """ Link declarative identifier node or reference identifier node to the lexical context scope that the identifier is presented at. """ node_id = id(decl_or_ref_id_node) self._ids_to_scopes_map[node_id] = scope def get_context_scope_by_identifier(self, decl_or_ref_id_node): # type: (Dict[str, Any]) -> Scope """ Return the lexical context scope that the identifier is presented at by a declarative identifier node or a reference identifier node """ node_id = id(decl_or_ref_id_node) return self._ids_to_scopes_map.get(node_id) def __init__(self): self.scope_tree = None # type: Union[Scope, None] self.link_registry = None # type: ScopeLinker.ScopeLinkRegistry self._scope_tree_builder = ScopeLinker.ScopeTreeBuilder() def process(self, ast): # type: (Dict[str, Any]) -> None """ Build a scope tree and links between scopes and identifiers by the specified ast. You can access the built scope tree and the built links by .scope_tree and .link_registry. """ id_classifier = IdentifierClassifier() attached_ast = id_classifier.attach_identifier_attributes(ast) # We are already in script local scope. self._scope_tree_builder.enter_new_scope(ScopeVisibility.SCRIPT_LOCAL) traverse(attached_ast, on_enter=self._enter_handler, on_leave=self._leave_handler) self.scope_tree = self._scope_tree_builder.get_global_scope() self.link_registry = self._scope_tree_builder.link_registry def _find_variable_like_nodes(self, node): # type: (Dict[str, Any]) -> None if not is_analyzable_identifier(node): return if is_analyzable_declarative_identifier(node): self._scope_tree_builder.handle_new_variable_found(node) return self._scope_tree_builder.handle_referencing_identifier_found(node) def _enter_handler(self, node): # type: (Dict[str, Any]) -> None node_type = NodeType(node['type']) if node_type is NodeType.FUNCTION: return self._handle_function_node(node) elif node_type is NodeType.LAMBDA: return self._handle_lambda_node(node) self._find_variable_like_nodes(node) def _handle_function_node(self, func_node): # type: (Dict[str, Any]) -> None # We should interrupt traversing, because a node of the function # name should be added to the parent scope before the current # scope switched to a new scope of the function. # We approach to it by the following 5 steps. # 1. Add the function to the current scope # 2. Create a new scope of the function # 3. The current scope point to the new scope # 4. Add parameters to the new scope # 5. Add variables in the function body to the new scope # 1. Add the function to the current scope func_name_node = func_node['left'] traverse(func_name_node, on_enter=self._find_variable_like_nodes) # 2. Create a new scope of the function # 3. The current scope point to the new scope self._scope_tree_builder.enter_new_scope(ScopeVisibility.FUNCTION_LOCAL) has_variadic = False # 4. Add parameters to the new scope param_nodes = func_node['rlist'] for param_node in param_nodes: if param_node['value'] == '...': has_variadic = True else: # the param_node type is always NodeType.IDENTIFIER self._scope_tree_builder.handle_new_parameter_found(param_node, is_lambda_argument=False) # We can always access a:0, a:000 self._scope_tree_builder.handle_new_parameters_list_and_length_found() # In a variadic function, we can access a:1 ... a:n # (n = 20 - explicit parameters length). See :help a:0 if has_variadic: # -1 means ignore '...' self._scope_tree_builder.handle_new_index_parameters_found(len(param_nodes) - 1) # We can access "a:firstline" and "a:lastline" if the function is # declared with an attribute "range". See :func-range attr = func_node['attr'] is_declared_with_range = attr['range'] != 0 if is_declared_with_range: self._scope_tree_builder.handle_new_range_parameters_found() # We can access "l:self" is declared with an attribute "dict" or # the function is a member of a dict. See :help self is_declared_with_dict = ( attr["dict"] != 0 or NodeType(func_name_node["type"]) in FunctionNameNodesDeclaringVariableSelf ) if is_declared_with_dict: self._scope_tree_builder.handle_new_dict_parameter_found() # 5. Add variables in the function body to the new scope func_body_nodes = func_node['body'] for func_body_node in func_body_nodes: traverse(func_body_node, on_enter=self._enter_handler, on_leave=self._leave_handler) # Skip child nodes traversing return SKIP_CHILDREN def _handle_lambda_node(self, lambda_node): # type: (Dict[str, Any]) -> Optional[str] # This method do the following 4 steps: # 1. Create a new scope of the lambda # 2. The current scope point to the new scope # 3. Add parameters to the new scope # 4. Add variables in the function body to the new scope # 1. Create a new scope of the function # 2. The current scope point to the new scope self._scope_tree_builder.enter_new_scope(ScopeVisibility.LAMBDA) # 3. Add parameters to the new scope has_variadic_symbol = False param_nodes = lambda_node['rlist'] for param_node in param_nodes: if param_node['value'] == '...': has_variadic_symbol = True else: # the param_node type is always NodeType.IDENTIFIER self._scope_tree_builder.handle_new_parameter_found(param_node, is_lambda_argument=True) # We can access a:0 and a:000 when the number of arguments is less than actual parameters. self._scope_tree_builder.handle_new_parameters_list_and_length_found() # In the context of lambda, we can access a:1 ... a:n when the number of arguments is less than actual parameters. # XXX: We can not know what a:N we can access by static analysis, so we assume it is 20. if has_variadic_symbol: lambda_args_len = len(param_nodes) - 1 else: lambda_args_len = len(param_nodes) self._scope_tree_builder.handle_new_index_parameters_found(lambda_args_len) # 4. Add variables in the function body to the new scope traverse(lambda_node['left'], on_enter=self._enter_handler, on_leave=self._leave_handler) # Skip child nodes traversing return SKIP_CHILDREN def _leave_handler(self, node): # type: (Dict[str, Any]) -> None node_type = NodeType(node['type']) if node_type is NodeType.FUNCTION: self._scope_tree_builder.leave_current_scope() elif node_type is NodeType.LAMBDA: self._scope_tree_builder.leave_current_scope()
class ScopeLinker(object): ''' A class for scope linkers. The class link identifiers in the given AST node and the scopes where the identifier will be declared or referenced. ''' class ScopeTreeBuilder(object): ''' A class for event-driven builders to build a scope tree. The class interest to scope-level events rather than AST-level events. ''' def __init__(self): pass def enter_new_scope(self, scope_visibility): pass def leave_current_scope(self): pass def get_global_scope(self): pass def get_script_local_scope(self): pass def get_current_scope(self): pass def handle_new_parameter_found(self, id_node, is_lambda_argument): pass def handle_new_range_parameters_found(self): pass def handle_new_dict_parameter_found(self): pass def handle_new_parameters_list_and_length_found(self): pass def handle_new_index_parameters_found(self, params_number): pass def handle_new_variable_found(self, id_node): pass def _get_objective_scope(self, node): pass def handle_referencing_identifier_found(self, node): pass def _add_parameter(self, objective_scope, id_node, is_explicit_lambda_argument): pass def _add_self_variable(self, objective_scope): pass def _add_variable(self, objective_scope, id_node, is_function, explicity): pass def _add_builtin_variable(self, id_node, explicity, is_function): pass def _add_symbol_table_variables(self, objective_scope): pass def _register_variable(self, objective_scope, variable_name, node, explicity, is_function, is_builtin, is_explicit_lambda_argument): pass class ScopeLinkRegistry(object): ''' A class for registry services for links between scopes and identifiers. ''' def __init__(self): pass def link_variable_to_declarative_identifier(self, variable, declaring_id_node): pass def get_declarative_identifier_by_variable(self, variable): pass def link_identifier_to_context_scope(self, decl_or_ref_id_node, scope): ''' Link declarative identifier node or reference identifier node to the lexical context scope that the identifier is presented at. ''' pass def get_context_scope_by_identifier(self, decl_or_ref_id_node): ''' Return the lexical context scope that the identifier is presented at by a declarative identifier node or a reference identifier node ''' pass def __init__(self): pass def process(self, ast): ''' Build a scope tree and links between scopes and identifiers by the specified ast. You can access the built scope tree and the built links by .scope_tree and .link_registry. ''' pass def _find_variable_like_nodes(self, node): pass def _enter_handler(self, node): pass def _handle_function_node(self, func_node): pass def _handle_lambda_node(self, lambda_node): pass def _leave_handler(self, node): pass
35
6
11
2
8
3
2
0.42
1
4
4
0
7
3
7
7
445
117
251
98
216
105
183
98
148
7
1
2
55
144,209
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/scope_detector.py
vint.ast.plugin.scope_plugin.scope_detector.ScopeVisibilityHint
class ScopeVisibilityHint: def __init__(self, scope_visibility, explicity): # type: (ScopeVisibility, ExplicityOfScopeVisibility) -> None self.scope_visibility = scope_visibility self.explicity = explicity
class ScopeVisibilityHint: def __init__(self, scope_visibility, explicity): pass
2
0
4
0
3
1
1
0.25
0
0
0
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
0
0
1
144,210
Kuniwak/vint
Kuniwak_vint/vint/linting/formatter/json_formatter.py
vint.linting.formatter.json_formatter.JSONFormatter
class JSONFormatter(AbstractFormatter): def __init__(self): # type: () -> None super(JSONFormatter, self).__init__() pass def format_violations(self, violations): # type: (List[Dict[str, Any]]) -> str return json.dumps(_normalize_violations(violations))
class JSONFormatter(AbstractFormatter): def __init__(self): pass def format_violations(self, violations): pass
3
0
3
0
3
1
1
0.33
1
1
0
0
2
0
2
3
8
2
6
3
3
2
6
3
3
1
2
0
2
144,211
Kuniwak/vint
Kuniwak_vint/vint/linting/formatter/statistic_formatter.py
vint.linting.formatter.statistic_formatter.StatisticFormatter
class StatisticFormatter(Formatter): def format_violations(self, violations): # type: (List[Dict[str, Any]]) -> str violations_count = len(violations) output = super(StatisticFormatter, self).format_violations(violations) + '\n' return output + 'Total violations: {count}'.format(count=violations_count)
class StatisticFormatter(Formatter): def format_violations(self, violations): pass
2
0
5
1
4
1
1
0.2
1
1
0
0
1
0
1
5
6
1
5
4
3
1
5
4
3
1
3
0
1
144,212
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/test/unit/vint/linting/config/test_config_next_line_comment_source.py
test.unit.vint.linting.config.test_config_next_line_comment_source.TestConfigNextLineCommentSource.ProhibitStringPolicy
class ProhibitStringPolicy(AbstractPolicy): def __init__(self): super(TestConfigNextLineCommentSource.ProhibitStringPolicy, self).__init__() self.description = '' self.reference = 'nothing' self.level = Level.ERROR def listen_node_types(self): return [NodeType.STRING] def is_valid(self, node, lint_context): self.description = node['value'] return False
class ProhibitStringPolicy(AbstractPolicy): def __init__(self): pass def listen_node_types(self): pass def is_valid(self, node, lint_context): pass
4
0
3
0
3
0
1
0
1
4
3
0
3
3
3
10
15
4
11
7
7
0
11
7
7
1
2
0
3
144,213
Kuniwak/vint
Kuniwak_vint/vint/ast/traversing.py
vint.ast.traversing.UnknownNodeTypeException
class UnknownNodeTypeException(BaseException): def __init__(self, node_type): self.node_type = node_type def __str__(self): node_type_name = self.node_type return 'Unknown node type: `{node_type}`'.format(node_type=node_type_name)
class UnknownNodeTypeException(BaseException): def __init__(self, node_type): pass def __str__(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
1
2
11
7
1
6
5
3
0
6
5
3
1
2
0
2
144,214
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/identifier_classifier.py
vint.ast.plugin.scope_plugin.identifier_classifier.CollectedIdentifiers
class CollectedIdentifiers: def __init__(self, statically_declared_identifiers, statically_referencing_identifiers): # type: (List[Dict[str, Any]], List[Dict[str, Any]]) -> None self.statically_declared_identifiers = statically_declared_identifiers self.statically_referencing_identifiers = statically_referencing_identifiers
class CollectedIdentifiers: def __init__(self, statically_declared_identifiers, statically_referencing_identifiers): pass
2
0
4
0
3
1
1
0.25
0
0
0
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
0
0
1
144,215
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/__init__.py
vint.ast.plugin.scope_plugin.ScopePlugin
class ScopePlugin(AbstractASTPlugin): def __init__(self): super(ScopePlugin, self).__init__() self._ref_tester = ReferenceReachabilityTester() def process(self, ast): processed_ast = self._ref_tester.process(ast) return processed_ast def _get_link_registry(self): # NOTE: This is a hack for performance. We should build LinkRegistry # by this method if ReferenceReachabilityTester hide the link_registry. return self._ref_tester._scope_linker.link_registry def is_unreachable_reference_identifier(self, node): return _is_reference_identifier(node) \ and not _is_reachable_reference_identifier(node) def is_unused_declarative_identifier(self, node): return _is_declarative_identifier(node) \ and not _is_referenced_declarative_identifier(node) def is_autoload_identifier(self, node): return _is_autoload_identifier(node) def is_function_identifier(self, node): return _is_function_identifier(node) def get_objective_scope_visibility(self, node): scope_visibility_hint = self._ref_tester.get_objective_scope_visibility(node) return scope_visibility_hint.scope_visibility def get_explicity_of_scope_visibility(self, node): scope_visibility_hint = self._ref_tester.get_objective_scope_visibility(node) return scope_visibility_hint.explicity def normalize_variable_name(self, node): return _normalize_variable_name(node, self._ref_tester)
class ScopePlugin(AbstractASTPlugin): def __init__(self): pass def process(self, ast): pass def _get_link_registry(self): pass def is_unreachable_reference_identifier(self, node): pass def is_unused_declarative_identifier(self, node): pass def is_autoload_identifier(self, node): pass def is_function_identifier(self, node): pass def get_objective_scope_visibility(self, node): pass def get_explicity_of_scope_visibility(self, node): pass def normalize_variable_name(self, node): pass
11
0
3
0
3
0
1
0.07
1
2
1
0
10
1
10
11
47
18
27
15
16
2
25
15
14
1
2
0
10
144,216
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/test/unit/vint/linting/test_cli.py
test.unit.vint.linting.test_cli.TestCLI
class TestCLI(unittest.TestCase): @classmethod def setUpClass(cls): # For test_start_with_invalid_file_path. # The test case want to load several policies. import_all_policies() def assertExitWithSuccess(self, argv): with mock.patch('sys.argv', argv): with self.assertRaises(SystemExit) as e: start_cli() self.assertEqual(e.exception.code, 0) def assertExitWithFailure(self, argv): with mock.patch('sys.argv', argv): with self.assertRaises(SystemExit) as e: start_cli() self.assertNotEqual(e.exception.code, 0) def test_start_with_no_arg(self): argv = ['bin/vint'] self.assertExitWithFailure(argv) def test_start_with_unexistent_file_path(self): argv = ['bin/vint', 'path/to/unexistent'] self.assertExitWithFailure(argv) def test_start_with_valid_file_path(self): argv = ['bin/vint', 'test/fixture/cli/valid1.vim'] self.assertExitWithSuccess(argv) def test_start_with_invalid_file_path(self): argv = ['bin/vint', 'test/fixture/cli/invalid1.vim'] self.assertExitWithFailure(argv) def test_start_with_both_calid_invalid_file_paths(self): argv = ['bin/vint', 'test/fixture/cli/valid1.vim', 'test/fixture/cli/invalid1.vim'] self.assertExitWithFailure(argv) @mock.patch('sys.stdin', open('test/fixture/cli/valid1.vim')) def test_passing_code_to_stdin_lints_the_code_from_stdin(self): argv = ['bin/vint', '-'] self.assertExitWithSuccess(argv) @mock.patch('sys.stdin', open('test/fixture/cli/valid1.vim')) def test_multiple_stdin_symbol(self): argv = ['bin/vint', '-', '-'] self.assertExitWithFailure(argv)
class TestCLI(unittest.TestCase): @classmethod def setUpClass(cls): pass def assertExitWithSuccess(self, argv): pass def assertExitWithFailure(self, argv): pass def test_start_with_no_arg(self): pass def test_start_with_unexistent_file_path(self): pass def test_start_with_valid_file_path(self): pass def test_start_with_invalid_file_path(self): pass def test_start_with_both_calid_invalid_file_paths(self): pass @mock.patch('sys.stdin', open('test/fixture/cli/valid1.vim')) def test_passing_code_to_stdin_lints_the_code_from_stdin(self): pass @mock.patch('sys.stdin', open('test/fixture/cli/valid1.vim')) def test_multiple_stdin_symbol(self): pass
14
0
4
0
3
0
1
0.05
1
1
0
0
9
0
10
82
59
20
37
23
23
2
34
18
23
1
2
2
10
144,217
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/vint/ast/plugin/scope_plugin/identifier_classifier.py
vint.ast.plugin.scope_plugin.identifier_classifier.IdentifierClassifier.IdentifierCollector
class IdentifierCollector(object): """ A class for identifier node collectors. Only static and not member nodes will be collected and the nodes will be grouped by 2 types; declaring or referencing. """ def __init__(self): # type: List[Dict[str, Any]] self._static_referencing_identifiers = None # type: List[Dict[str, Any]] self._static_declaring_identifiers = None # type: (Dict[str, Any]) -> CollectedIdentifiers def collect_identifiers(self, ast): self._static_referencing_identifiers = [] self._static_declaring_identifiers = [] # TODO: Make more performance efficiency. traverse(ast, on_enter=self._enter_handler) return CollectedIdentifiers( self._static_declaring_identifiers, self._static_referencing_identifiers ) def _enter_handler(self, node): if not _is_identifier_like_node(node): return # FIXME: Dynamic identifiers should be returned and it should be filtered by the caller. if _is_dynamic_identifier(node) or _is_member_identifier(node) or _is_variadic_symbol(node): return if _is_declarative_identifier(node): self._static_declaring_identifiers.append(node) else: self._static_referencing_identifiers.append(node)
class IdentifierCollector(object): ''' A class for identifier node collectors. Only static and not member nodes will be collected and the nodes will be grouped by 2 types; declaring or referencing. ''' def __init__(self): pass def collect_identifiers(self, ast): pass def _enter_handler(self, node): pass
4
1
9
1
7
2
2
0.43
1
1
1
0
3
2
3
3
36
9
21
6
17
9
17
6
13
4
1
1
6
144,218
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/abstract_ast_plugin.py
vint.ast.plugin.abstract_ast_plugin.AbstractASTPlugin
class AbstractASTPlugin(object): """ An abstract class for AST plugins. AST plugins can add attributes to the AST. But for maintainability reason, overwriting or deleting any attribute is prohibited. """ def process(self, ast): return ast
class AbstractASTPlugin(object): ''' An abstract class for AST plugins. AST plugins can add attributes to the AST. But for maintainability reason, overwriting or deleting any attribute is prohibited. ''' def process(self, ast): pass
2
1
2
0
2
0
1
1.33
1
0
0
1
1
0
1
1
8
1
3
2
1
4
3
2
1
1
1
0
1
144,219
Kuniwak/vint
Kuniwak_vint/vint/ast/parsing.py
vint.ast.parsing.Parser
class Parser(object): def __init__(self, plugins=None, enable_neovim=False): """ Initialize Parser with the specified plugins. The plugins can add attributes to the AST. """ self.plugins = plugins if plugins else [] self._enable_neovim = enable_neovim def parse(self, lint_target): # type: (AbstractLintTarget) -> Dict[str, Any] """ Parse vim script file and return the AST. """ decoder = Decoder(default_decoding_strategy) decoded = decoder.decode(lint_target.read()) decoded_and_lf_normalized = decoded.replace('\r\n', '\n') return self.parse_string(decoded_and_lf_normalized) def parse_string(self, string): # type: (str) -> Dict[str, Any] """ Parse vim script string and return the AST. """ lines = string.split('\n') reader = vimlparser.StringReader(lines) parser = vimlparser.VimLParser(self._enable_neovim) ast = parser.parse(reader) # TOPLEVEL does not have a pos, but we need pos for all nodes ast['pos'] = {'col': 1, 'i': 0, 'lnum': 1} for plugin in self.plugins: plugin.process(ast) return ast def parse_redir(self, redir_cmd): """ Parse a command :redir content. """ redir_cmd_str = redir_cmd['str'] matched = re.match(r'redir?!?\s*(=>>?\s*)(\S+)', redir_cmd_str) if matched: redir_cmd_op = matched.group(1) redir_cmd_body = matched.group(2) arg_pos = redir_cmd['ea']['argpos'] # Position of the "redir_cmd_body" start_pos = { 'col': arg_pos['col'] + len(redir_cmd_op), 'i': arg_pos['i'] + len(redir_cmd_op), 'lnum': arg_pos['lnum'], } # NOTE: This is a hack to parse variable node. raw_ast = self.parse_string('echo ' + redir_cmd_body) # We need the left node of ECHO node redir_cmd_ast = raw_ast['body'][0]['list'][0] def adjust_position(node): pos = node['pos'] # Care 1-based index and the length of "echo ". pos['col'] += start_pos['col'] - 1 - 5 # Care the length of "echo ". pos['i'] += start_pos['i'] - 5 # Care 1-based index pos['lnum'] += start_pos['lnum'] - 1 traverse(redir_cmd_ast, on_enter=adjust_position) return redir_cmd_ast return None def parse_string_expr(self, string_expr_node): """ Parse a string node content. """ string_expr_node_value = string_expr_node['value'] string_expr_str = string_expr_node_value[1:-1] # Care escaped string literals if string_expr_node_value[0] == "'": string_expr_str = string_expr_str.replace("''", "'") else: string_expr_str = string_expr_str.replace('\\"', '"') # NOTE: This is a hack to parse expr1. See :help expr1 raw_ast = self.parse_string('echo ' + string_expr_str) # We need the left node of ECHO node parsed_string_expr_nodes = raw_ast['body'][0]['list'] start_pos = string_expr_node['pos'] def adjust_position(node): pos = node['pos'] # Care 1-based index and the length of "echo ". pos['col'] += start_pos['col'] - 1 - 5 # Care the length of "echo ". pos['i'] += start_pos['i'] - 5 # Care 1-based index pos['lnum'] += start_pos['lnum'] - 1 for parsed_string_expr_node in parsed_string_expr_nodes: traverse(parsed_string_expr_node, on_enter=adjust_position) return parsed_string_expr_nodes
class Parser(object): def __init__(self, plugins=None, enable_neovim=False): ''' Initialize Parser with the specified plugins. The plugins can add attributes to the AST. ''' pass def parse(self, lint_target): ''' Parse vim script file and return the AST. ''' pass def parse_string(self, string): ''' Parse vim script string and return the AST. ''' pass def parse_redir(self, redir_cmd): ''' Parse a command :redir content. ''' pass def adjust_position(node): pass def parse_string_expr(self, string_expr_node): ''' Parse a string node content. ''' pass def adjust_position(node): pass
8
5
18
4
10
4
2
0.38
1
3
3
0
5
2
5
5
112
34
58
34
50
22
53
34
45
3
1
1
12
144,220
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/scope.py
vint.ast.plugin.scope_plugin.scope.VariableDeclaration
class VariableDeclaration: def __init__(self, explicity, is_builtin, is_explicit_lambda_argument): # type: (str, ExplicityOfScopeVisibility, bool, bool) -> None self.explicity = explicity self.is_builtin = is_builtin # NOTE: This property used for determining whether the implicit variable is constrained by lambda or not. self.is_explicit_lambda_argument = is_explicit_lambda_argument
class VariableDeclaration: def __init__(self, explicity, is_builtin, is_explicit_lambda_argument): pass
2
0
7
1
4
2
1
0.4
0
0
0
0
1
3
1
1
8
1
5
5
3
2
5
5
3
1
0
0
1
144,221
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/call_node_parser.py
vint.ast.plugin.scope_plugin.call_node_parser.CallNodeParser
class CallNodeParser(object): """ A class to make string expression in map and filter function parseable. """ def process(self, ast): def enter_handler(node): node_type = NodeType(node['type']) if node_type is not NodeType.CALL: return called_function_identifier = node['left'] # The name node type of "map" or "filter" or "call" are always IDENTIFIER. if NodeType(called_function_identifier['type']) is not NodeType.IDENTIFIER: return called_function_identifier_value = called_function_identifier.get('value') if called_function_identifier_value in ['map', 'filter']: # Analyze second argument of "map" or "filter" if the node type is STRING. self._attach_string_expr_content_to_map_or_func(node) elif called_function_identifier_value in ['call', 'function']: # Analyze first argument of "call" or "function" if the node type is STRING. self._attach_string_expr_content_to_call_or_function(node) traverse(ast, on_enter=enter_handler) return ast def _attach_string_expr_content_to_map_or_func(self, map_or_func_call_node): args = map_or_func_call_node['rlist'] # Prevent crash. See https://github.com/Kuniwak/vint/issues/256. if len(args) < 2: return string_expr_node = args[1] # We can statically analyze only STRING nodes if NodeType(string_expr_node['type']) is not NodeType.STRING: return parser = Parser() string_expr_content_nodes = parser.parse_string_expr(string_expr_node) # Set a flag that means whether the expression is in other string literals. CallNodeParser._set_string_expr_context_flag(string_expr_content_nodes) string_expr_node[LAMBDA_STRING_EXPR_CONTENT] = string_expr_content_nodes @classmethod def _set_string_expr_context_flag(cls, string_expr_content_nodes): def enter_handler(node): # NOTE: We need this flag only string nodes, because this flag is only for # ProhibitUnnecessaryDoubleQuote. if NodeType(node['type']) is NodeType.STRING: node[STRING_EXPR_CONTEXT] = { STRING_EXPR_CONTEXT_FLAG: True, } for string_expr_content_node in string_expr_content_nodes: traverse(string_expr_content_node, on_enter=enter_handler) return string_expr_content_nodes def _attach_string_expr_content_to_call_or_function(self, call_call_node): args = call_call_node['rlist'] if len(args) < 1: return # We can statically analyze only STRING node string_expr_node = args[0] if NodeType(string_expr_node['type']) is not NodeType.STRING: return parser = Parser() string_expr_content_nodes = parser.parse_string_expr(string_expr_node) func_ref_nodes = list(filter( lambda node: NodeType(node['type']) is NodeType.IDENTIFIER, string_expr_content_nodes )) string_expr_node[FUNCTION_REFERENCE_STRING_EXPR_CONTENT] = func_ref_nodes
class CallNodeParser(object): ''' A class to make string expression in map and filter function parseable. ''' def process(self, ast): pass def enter_handler(node): pass def _attach_string_expr_content_to_map_or_func(self, map_or_func_call_node): pass @classmethod def _set_string_expr_context_flag(cls, string_expr_content_nodes): pass def enter_handler(node): pass def _attach_string_expr_content_to_call_or_function(self, call_call_node): pass
8
1
17
4
11
2
3
0.22
1
4
2
0
3
0
4
4
88
26
51
21
43
11
44
20
37
5
1
1
16
144,222
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoder.py
vint.encodings.decoder.Decoder
class Decoder(object): def __init__(self, strategy): # type: (DecodingStrategy) -> None self.strategy = strategy self.debug_hint = dict(version=sys.version) def decode(self, bytes_seq): # type: (bytes) -> str strings = [] for (loc, hunk) in _split_by_scriptencoding(bytes_seq): debug_hint_for_the_loc = dict() self.debug_hint[loc] = debug_hint_for_the_loc string = self.strategy.decode(hunk, debug_hint=debug_hint_for_the_loc) if string is None: raise EncodingDetectionError(self.debug_hint) strings.append(string) return ''.join(strings)
class Decoder(object): def __init__(self, strategy): pass def decode(self, bytes_seq): pass
3
0
10
3
7
1
2
0.14
1
2
1
0
2
2
2
2
23
7
14
9
11
2
14
9
11
3
1
2
4
144,223
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoder.py
vint.encodings.decoder.EncodingDetectionError
class EncodingDetectionError(Exception): def __init__(self, debug_hint): # type: (Dict[str, Any]) -> None self.debug_hint = debug_hint def __str__(self): # type: () -> str return 'Cannot detect encoding (binary file?): {debug_hint}'.format( debug_hint=pformat(self.debug_hint) )
class EncodingDetectionError(Exception): def __init__(self, debug_hint): pass def __str__(self): pass
3
0
4
0
3
1
1
0.29
1
0
0
0
2
1
2
12
11
2
7
4
4
2
5
4
2
1
3
0
2
144,224
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoding_strategy.py
vint.encodings.decoding_strategy.ComposedDecodingStrategy
class ComposedDecodingStrategy(DecodingStrategy): def __init__(self, strategies): # type: ([DecodingStrategy]) -> None self.strategies = strategies def decode(self, bytes_seq, debug_hint): # type: (bytes, Dict[str, Any]) -> Optional[str] debug_hint['composed_strategies'] = [type(strategy).__name__ for strategy in self.strategies] for strategy in self.strategies: string_candidate = strategy.decode(bytes_seq, debug_hint) if string_candidate is None: continue debug_hint['selected_strategy'] = type(strategy).__name__ return string_candidate
class ComposedDecodingStrategy(DecodingStrategy): def __init__(self, strategies): pass def decode(self, bytes_seq, debug_hint): pass
3
0
9
3
5
1
2
0.18
1
1
0
0
2
1
2
3
20
7
11
5
8
2
11
5
8
3
2
2
4
144,225
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoding_strategy.py
vint.encodings.decoding_strategy.DecodingStrategyForEmpty
class DecodingStrategyForEmpty(DecodingStrategy): def decode(self, bytes_seq, debug_hint): # type: (bytes, Dict[str, Any]) -> Optional[str] if len(bytes_seq) <= 0: debug_hint['empty'] = 'true' return '' debug_hint['empty'] = 'false' return None
class DecodingStrategyForEmpty(DecodingStrategy): def decode(self, bytes_seq, debug_hint): pass
2
0
8
1
6
1
2
0.14
1
0
0
0
1
0
1
2
9
1
7
2
5
1
7
2
5
2
2
1
2
144,226
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoding_strategy.py
vint.encodings.decoding_strategy.DecodingStrategyForUTF8
class DecodingStrategyForUTF8(DecodingStrategy): def decode(self, bytes_seq, debug_hint): # type: (bytes, Dict[str, Any]) -> Optional[str] try: string = bytes_seq.decode('utf8') debug_hint['utf-8'] = 'success' return string except Exception as e: debug_hint['utf-8'] = 'failed: {}'.format(str(e)) return None
class DecodingStrategyForUTF8(DecodingStrategy): def decode(self, bytes_seq, debug_hint): pass
2
0
12
3
8
1
2
0.11
1
2
0
0
1
0
1
2
13
3
9
4
7
1
9
3
7
2
2
1
2
144,227
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_cmdargs_source.py
vint.linting.config.config_cmdargs_source.ConfigCmdargsSource
class ConfigCmdargsSource(ConfigSource): def __init__(self, env): self._config_dict = self._build_config_dict(env) def get_config_dict(self): return self._config_dict def _build_config_dict(self, env): config_dict = { 'cmdargs': {}, 'source_name': self.__class__.__name__, } config_dict = self._normalize_color(env, config_dict) config_dict = self._normalize_json(env, config_dict) config_dict = self._normalize_stat(env, config_dict) config_dict = self._normalize_verbose(env, config_dict) config_dict = self._normalize_severity(env, config_dict) config_dict = self._normalize_max_violations(env, config_dict) config_dict = self._normalize_format(env, config_dict) config_dict = self._normalize_env(env, config_dict) config_dict = self._normalize_stdin_filename(env, config_dict) return config_dict def _pass_config_by_key(self, key, env, config_dict): env_cmdargs = env['cmdargs'] config_dict_cmdargs = config_dict['cmdargs'] if key in env_cmdargs and env_cmdargs[key] is not None: config_dict_cmdargs[key] = env_cmdargs[key] return config_dict def _normalize_stat(self, env, config_dict): return self._pass_config_by_key('stat', env, config_dict) def _normalize_json(self, env, config_dict): return self._pass_config_by_key('json', env, config_dict) def _normalize_color(self, env, config_dict): env_cmdargs = env['cmdargs'] should_colorize = 'color' in env_cmdargs and env_cmdargs['color'] is not None should_not_colorize = 'no_color' in env_cmdargs and env_cmdargs['no_color'] is not None if should_colorize and should_not_colorize: raise ConflictedOptionsError(['color', 'no_color']) if should_colorize: config_dict['cmdargs']['color'] = True if should_not_colorize: config_dict['cmdargs']['color'] = False return config_dict def _normalize_verbose(self, env, config_dict): return self._pass_config_by_key('verbose', env, config_dict) def _normalize_max_violations(self, env, config_dict): return self._pass_config_by_key('max-violations', env, config_dict) def _normalize_format(self, env, config_dict): return self._pass_config_by_key('format', env, config_dict) def _normalize_severity(self, env, config_dict): env_cmdargs = env['cmdargs'] config_dict_cmdargs = config_dict['cmdargs'] # Severity option priority is: # 1. error # 2. warning # 3. style problem if env_cmdargs.get('style_problem', False): config_dict_cmdargs['severity'] = Level.STYLE_PROBLEM if env_cmdargs.get('warning', False): config_dict_cmdargs['severity'] = Level.WARNING if env_cmdargs.get('error', False): config_dict_cmdargs['severity'] = Level.ERROR return config_dict def _normalize_env(self, env, config_dict): env_cmdargs = env['cmdargs'] config_dict_cmdargs = config_dict['cmdargs'] if 'enable_neovim' in env_cmdargs and env_cmdargs['enable_neovim'] is True: config_dict_cmdargs['env'] = {'neovim': True} return config_dict def _normalize_stdin_filename(self, env, config_dict): return self._pass_config_by_key('stdin_display_name', env, config_dict)
class ConfigCmdargsSource(ConfigSource): def __init__(self, env): pass def get_config_dict(self): pass def _build_config_dict(self, env): pass def _pass_config_by_key(self, key, env, config_dict): pass def _normalize_stat(self, env, config_dict): pass def _normalize_json(self, env, config_dict): pass def _normalize_color(self, env, config_dict): pass def _normalize_verbose(self, env, config_dict): pass def _normalize_max_violations(self, env, config_dict): pass def _normalize_format(self, env, config_dict): pass def _normalize_severity(self, env, config_dict): pass def _normalize_env(self, env, config_dict): pass def _normalize_stdin_filename(self, env, config_dict): pass
14
0
6
1
5
0
2
0.06
1
2
2
0
13
1
13
14
108
39
65
25
51
4
62
25
48
4
2
1
21
144,228
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_cmdargs_source.py
vint.linting.config.config_cmdargs_source.ConflictedOptionsError
class ConflictedOptionsError(Exception): def __init__(self, conflicted_option_names): self.conflicted_option_names = conflicted_option_names def __str__(self): option_names = ', '.join(self.conflicted_option_names) return 'These options are conflicted: {0}'.format(option_names)
class ConflictedOptionsError(Exception): def __init__(self, conflicted_option_names): pass def __str__(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
1
2
12
7
1
6
5
3
0
6
5
3
1
3
0
2
144,229
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_comment_parser.py
vint.linting.config.config_comment_parser.ConfigComment
class ConfigComment: def __init__(self, config_dict, is_only_next_line): # type: (Dict[str, Any], bool) -> None self.config_dict = config_dict self.is_only_next_line = is_only_next_line
class ConfigComment: def __init__(self, config_dict, is_only_next_line): pass
2
0
4
0
3
1
1
0.25
0
0
0
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
0
0
1
144,230
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_container.py
vint.linting.config.config_container.ConfigContainer
class ConfigContainer(ConfigSource): def __init__(self, *config_sources): self.config_sources = config_sources def get_config_dict(self): config_dicts_ordered_by_prior_asc = [config_source.get_config_dict() for config_source in self.config_sources] result = reduce(merge_dict_deeply, config_dicts_ordered_by_prior_asc, {}) result['source_name'] = self.__class__.__name__ return result
class ConfigContainer(ConfigSource): def __init__(self, *config_sources): pass def get_config_dict(self): pass
3
0
5
1
4
0
1
0
1
0
0
0
2
1
2
3
13
4
9
6
6
0
8
6
5
1
2
0
2
144,231
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_default_source.py
vint.linting.config.config_default_source.ConfigDefaultSource
class ConfigDefaultSource(ConfigFileSource): def get_file_path(self, env): return DEFAULT_CONFIG_PATH
class ConfigDefaultSource(ConfigFileSource): def get_file_path(self, env): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
7
3
0
3
2
1
0
3
2
1
1
3
0
1
144,232
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_dict_source.py
vint.linting.config.config_dict_source.ConfigDictSource
class ConfigDictSource(ConfigSource): def __init__(self, config_dict): # type: (Dict[str, Any]) -> None self._config_dict = config_dict.copy() # For debugging. self._config_dict['source_name'] = self.__class__.__name__ def get_config_dict(self): # type: () -> Dict[str, Any] return self._config_dict
class ConfigDictSource(ConfigSource): def __init__(self, config_dict): pass def get_config_dict(self): pass
3
0
5
1
3
2
1
0.5
1
0
0
0
2
1
2
3
12
3
6
4
3
3
6
4
3
1
2
0
2
144,233
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_global_source.py
vint.linting.config.config_global_source.ConfigGlobalSource
class ConfigGlobalSource(ConfigFileSource): def get_file_path(self, env): global_config_paths = ConfigGlobalSource._get_filenames_candidates(env) for global_config_path in global_config_paths: if global_config_path.is_file(): return global_config_path return VOID_CONFIG_PATH @classmethod def _get_filenames_candidates(cls, env): # type: (Dict[str, str]) -> [Path] global_config_dir_candidates = [ env['xdg_config_home'], env['home_path'], ] return flat_map( lambda directory: ConfigGlobalSource._get_filenames_candidates_from_dir(directory), global_config_dir_candidates ) @classmethod def _get_filenames_candidates_from_dir(cls, config_dir): # type: (str) -> [Path] return [Path(config_dir, filename) for filename in CONFIG_FILENAMES]
class ConfigGlobalSource(ConfigFileSource): def get_file_path(self, env): pass @classmethod def _get_filenames_candidates(cls, env): pass @classmethod def _get_filenames_candidates_from_dir(cls, config_dir): pass
6
0
7
1
6
1
2
0.1
1
1
0
0
1
0
3
9
27
5
20
9
14
2
12
7
8
3
3
2
5
144,234
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_next_line_comment_source.py
vint.linting.config.config_next_line_comment_source.ConfigNextLineCommentSource
class ConfigNextLineCommentSource(ConfigAbstractDynamicSource): """ A class for ConfigLineCommentSources. This class provide to change config by modeline-like config comments as follow: " vint: next-line -PolicyA " vint: next-line +PolicyA " vint: next-line -PolicyA +PolicyB Prefix vint: means that the comment is a config comment. And, +PolicyName means to enable the policy, and -PolicyName means to disable. This class handle the config comment that have before nodes at the line. For example: " vint: next-line -PolicyA echo 'Vint do not check the code after the comment' echo 'Vint check the code' """ def __init__(self, is_debug=False): super(ConfigNextLineCommentSource, self).__init__() self._is_debug = is_debug self._current_lnum = 0 self._empty_config_dict = { 'policies': {}, 'source_name': self.__class__.__name__, } # type: Dict[str, Any] self._config_dict = self._empty_config_dict self._config_dict_for_next_line = self._empty_config_dict def get_config_dict(self): return self._config_dict def update_by_node(self, node): lnum_of_node = node['pos']['lnum'] is_line_changed = lnum_of_node > self._current_lnum if is_line_changed: if lnum_of_node - self._current_lnum == 1: if self._is_debug and self._config_dict != self._config_dict_for_next_line: logging.debug("{cls}: update config to {config_dict} at {lnum}".format( cls=self.__class__.__name__, config_dict=self._config_dict_for_next_line, lnum=lnum_of_node )) self._config_dict = self._config_dict_for_next_line else: if self._is_debug and self._config_dict != self._empty_config_dict: logging.debug("{cls}: update config to {config_dict} at {lnum}".format( cls=self.__class__.__name__, config_dict=self._empty_config_dict, lnum=lnum_of_node )) self._config_dict = self._empty_config_dict # Refresh config_dict for each line. self._current_lnum = lnum_of_node self._config_dict_for_next_line = self._empty_config_dict config_comment = parse_config_comment_node_if_exists(node) if config_comment is None: return if not config_comment.is_only_next_line: # Config comment affects over lines should be handled by an other class. return self._config_dict_for_next_line = config_comment.config_dict self._config_dict_for_next_line['source_name'] = self.__class__.__name__
class ConfigNextLineCommentSource(ConfigAbstractDynamicSource): ''' A class for ConfigLineCommentSources. This class provide to change config by modeline-like config comments as follow: " vint: next-line -PolicyA " vint: next-line +PolicyA " vint: next-line -PolicyA +PolicyB Prefix vint: means that the comment is a config comment. And, +PolicyName means to enable the policy, and -PolicyName means to disable. This class handle the config comment that have before nodes at the line. For example: " vint: next-line -PolicyA echo 'Vint do not check the code after the comment' echo 'Vint check the code' ''' def __init__(self, is_debug=False): pass def get_config_dict(self): pass def update_by_node(self, node): pass
4
1
17
3
14
1
3
0.38
1
1
0
0
3
5
3
7
74
17
42
12
38
16
30
12
26
7
3
3
9
144,235
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_project_source.py
vint.linting.config.config_project_source.ConfigProjectSource
class ConfigProjectSource(ConfigFileSource): def get_file_path(self, env): cwd = Path(env['cwd']) path_list_to_search = [cwd] + list(cwd.parents) for project_path in path_list_to_search: for basename in PROJECT_CONFIG_FILENAMES: proj_conf_path_tmp = project_path / basename if proj_conf_path_tmp.is_file(): return proj_conf_path_tmp return get_asset_path('void_config.yaml')
class ConfigProjectSource(ConfigFileSource): def get_file_path(self, env): pass
2
0
12
3
9
0
4
0
1
2
0
0
1
0
1
7
13
3
10
7
8
0
10
7
8
4
3
3
4
144,236
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoding_strategy.py
vint.encodings.decoding_strategy.DecodingStrategyByScriptencoding
class DecodingStrategyByScriptencoding(DecodingStrategy): def decode(self, bytes_seq, debug_hint): # type: (bytes, Dict[str, Any]) -> Optional[str] encoding_part = DecodingStrategyByScriptencoding.parse_script_encoding(bytes_seq, debug_hint) if encoding_part is None: debug_hint['scriptencoding'] = 'None' return None try: debug_hint['scriptencoding'] = encoding_part return bytes_seq.decode(encoding=encoding_part.decode(encoding='ascii')) except LookupError as e: debug_hint['scriptencoding_error'] = str(e) return None @classmethod def parse_script_encoding(cls, bytes_seq, debug_hint): # type: (bytes, Dict[str, Any]) -> Optional[bytes] try: start_index = bytes_seq.index(SCRIPTENCODING_PREFIX) encoding_part_start_index = start_index + len(SCRIPTENCODING_PREFIX) try: encoding_part_end_index_candidate_by_line_break = bytes_seq.index(LF, encoding_part_start_index) try: encoding_part_end_index_candidate_by_comment = bytes_seq.index( COMMENT_START_TOKEN, encoding_part_start_index) # Case for :scriptencoding foo "foo\n encoding_part_end_index = min( encoding_part_end_index_candidate_by_line_break, encoding_part_end_index_candidate_by_comment ) except ValueError: # Case for :scriptencoding foo\n encoding_part_end_index = encoding_part_end_index_candidate_by_line_break except ValueError: try: # Case for :scriptencoding foo "foo<EOF> encoding_part_end_index_candidate_by_comment = bytes_seq.index( COMMENT_START_TOKEN, encoding_part_start_index) encoding_part_end_index = encoding_part_end_index_candidate_by_comment except ValueError: # Case for :scriptencoding foo<EOF> encoding_part_end_index = len(bytes_seq) - 1 encoding_part_candidate = bytes_seq[encoding_part_start_index:encoding_part_end_index] return encoding_part_candidate.strip() except ValueError: debug_hint['scriptencoding_error'] = '`scriptencoding` is not found' return None
class DecodingStrategyByScriptencoding(DecodingStrategy): def decode(self, bytes_seq, debug_hint): pass @classmethod def parse_script_encoding(cls, bytes_seq, debug_hint): pass
4
0
28
6
19
3
4
0.15
1
3
0
0
1
0
2
3
59
13
40
12
36
6
34
10
31
5
2
3
8
144,237
Kuniwak/vint
Kuniwak_vint/vint/linting/config/config_toggle_comment_source.py
vint.linting.config.config_toggle_comment_source.ConfigToggleCommentSource
class ConfigToggleCommentSource(ConfigAbstractDynamicSource): """ A class for ConfigToggleCommentSources. This class provide to change config by modeline-like config comments as follow: " vint: -PolicyA " vint: +PolicyA " vint: -PolicyA +PolicyB The prefix 'vint:' means that the comment is a config comment. And, +PolicyName means to enable the policy, and -PolicyName means to disable. This class handle the config comment that have no before nodes at the line. For example: " vint: -PolicyA echo 'Vint do not check the code after the above comment' " vint: +PolicyA echo 'Vint check the code after the above comment' """ def __init__(self): super(ConfigToggleCommentSource, self).__init__() self._config_dict = { 'policies': {}, 'source_name': self.__class__.__name__, } # type: Dict[str, Any] def get_config_dict(self): return self._config_dict def update_by_node(self, node): config_comment = parse_config_comment_node_if_exists(node) if config_comment is None: return if config_comment.is_only_next_line: # Config comment only affects to next line should be handled by an other class. return logging.debug("{cls}: update config to {config_dict} at {lnum}".format( cls=self.__class__.__name__, config_dict=config_comment.config_dict, lnum=node['pos']['lnum'] )) self._config_dict = config_comment.config_dict self._config_dict['source_name'] = self.__class__.__name__
class ConfigToggleCommentSource(ConfigAbstractDynamicSource): ''' A class for ConfigToggleCommentSources. This class provide to change config by modeline-like config comments as follow: " vint: -PolicyA " vint: +PolicyA " vint: -PolicyA +PolicyB The prefix 'vint:' means that the comment is a config comment. And, +PolicyName means to enable the policy, and -PolicyName means to disable. This class handle the config comment that have no before nodes at the line. For example: " vint: -PolicyA echo 'Vint do not check the code after the above comment' " vint: +PolicyA echo 'Vint check the code after the above comment' ''' def __init__(self): pass def get_config_dict(self): pass def update_by_node(self, node): pass
4
1
9
2
7
1
2
0.73
1
1
0
0
3
1
3
7
50
13
22
6
18
16
15
6
11
3
3
1
5
144,238
Kuniwak/vint
Kuniwak_vint/vint/linting/formatter/formatter.py
vint.linting.formatter.formatter.Formatter
class Formatter(AbstractFormatter): def __init__(self, config_dict): # type: (Dict[str, Any]) -> None if 'cmdargs' in config_dict: cmdargs = config_dict['cmdargs'] else: cmdargs = {} if 'format' in cmdargs and cmdargs['format'] is not None: self._format = cmdargs['format'] else: self._format = DEFAULT_FORMAT if 'color' in cmdargs and cmdargs['color'] is not None: self._should_be_colorized = cmdargs['color'] else: self._should_be_colorized = False def format_violations(self, violations): # type: (List[Dict[str, Any]]) -> str sorted_violations = _sort_violations(violations) formatted_lines = map(self.format_violation, sorted_violations) return '\n'.join(formatted_lines) def format_violation(self, violation): # type: (Dict[str, Any]) -> str if self._should_be_colorized: formatter_map = _get_colorize_formatter_map(violation) else: formatter_map = _get_formatter_map(violation) formatted_line = self._format.format(**formatter_map) return formatted_line
class Formatter(AbstractFormatter): def __init__(self, config_dict): pass def format_violations(self, violations): pass def format_violations(self, violations): pass
4
0
9
1
8
1
2
0.12
1
1
0
1
3
2
3
4
33
8
25
11
21
3
21
11
17
4
2
1
7
144,239
Kuniwak/vint
Kuniwak_vint/vint/encodings/decoding_strategy.py
vint.encodings.decoding_strategy.DecodingStrategyByChardet
class DecodingStrategyByChardet(DecodingStrategy): def decode(self, bytes_seq, debug_hint): # type: (bytes, Dict[str, Any]) -> Optional[str] encoding_hint = chardet.detect(bytearray(bytes_seq)) encoding = encoding_hint['encoding'] debug_hint['chardet_encoding'] = encoding_hint['encoding'] debug_hint['chardet_confidence'] = encoding_hint['confidence'] try: return bytes_seq.decode(encoding) except Exception as e: debug_hint['chardet_error'] = str(e) return None
class DecodingStrategyByChardet(DecodingStrategy): def decode(self, bytes_seq, debug_hint): pass
2
0
14
3
10
1
2
0.09
1
3
0
0
1
0
1
2
15
3
11
5
9
1
11
4
9
2
2
1
2
144,240
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/vint/ast/plugin/scope_plugin/reference_reachability_tester.py
vint.ast.plugin.scope_plugin.reference_reachability_tester.ReferenceReachabilityTester.TwoWayScopeReferenceAttacher
class TwoWayScopeReferenceAttacher(object): """ A class for AST processor to do attach to way reference between a parent scope and the child scopes. """ @classmethod def attach(cls, root_scope_tree): # type: (Scope) -> Scope root_scope_tree.parent = None return cls._attach_recursively(root_scope_tree) @classmethod def _attach_recursively(cls, scope_tree): # type: (Scope) -> Scope for child_scope in scope_tree.child_scopes: child_scope.parent = scope_tree cls._attach_recursively(child_scope) return scope_tree
class TwoWayScopeReferenceAttacher(object): ''' A class for AST processor to do attach to way reference between a parent scope and the child scopes. ''' @classmethod def attach(cls, root_scope_tree): pass @classmethod def _attach_recursively(cls, scope_tree): pass
5
1
6
1
4
1
2
0.45
1
0
0
0
0
0
2
2
21
5
11
6
6
5
9
4
6
2
1
1
3
144,241
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/vint/ast/plugin/scope_plugin/scope_linker.py
vint.ast.plugin.scope_plugin.scope_linker.ScopeLinker.ScopeLinkRegistry
class ScopeLinkRegistry(object): """ A class for registry services for links between scopes and identifiers. """ def __init__(self): # type: Dict[int, Dict[str, Any]] self._vars_to_declarative_ids_map = {} self._ids_to_scopes_map = {} # type: Dict[int, Scope] def link_variable_to_declarative_identifier(self, variable, declaring_id_node): # type: (VariableDeclaration, Dict[str, Any]) -> None self._vars_to_declarative_ids_map[id(variable)] = declaring_id_node # type: (VariableDeclaration) -> Dict[str, Any] def get_declarative_identifier_by_variable(self, variable): variable_id = id(variable) return self._vars_to_declarative_ids_map.get(variable_id) # type: (Dict[str, Any], Scope) -> None def link_identifier_to_context_scope(self, decl_or_ref_id_node, scope): """ Link declarative identifier node or reference identifier node to the lexical context scope that the identifier is presented at. """ node_id = id(decl_or_ref_id_node) self._ids_to_scopes_map[node_id] = scope # type: (Dict[str, Any]) -> Scope def get_context_scope_by_identifier(self, decl_or_ref_id_node): """ Return the lexical context scope that the identifier is presented at by a declarative identifier node or a reference identifier node """ node_id = id(decl_or_ref_id_node) return self._ids_to_scopes_map.get(node_id)
class ScopeLinkRegistry(object): ''' A class for registry services for links between scopes and identifiers. ''' def __init__(self): pass def link_variable_to_declarative_identifier(self, variable, declaring_id_node): pass def get_declarative_identifier_by_variable(self, variable): pass def link_identifier_to_context_scope(self, decl_or_ref_id_node, scope): ''' Link declarative identifier node or reference identifier node to the lexical context scope that the identifier is presented at. ''' pass def get_context_scope_by_identifier(self, decl_or_ref_id_node): ''' Return the lexical context scope that the identifier is presented at by a declarative identifier node or a reference identifier node ''' pass
6
3
4
0
3
2
1
0.87
1
0
0
0
5
2
5
5
32
9
15
11
9
13
15
11
9
1
1
0
5
144,242
Kuniwak/vint
Kuniwak_vint/vint/ast/plugin/scope_plugin/scope.py
vint.ast.plugin.scope_plugin.scope.ScopeVisibility
class ScopeVisibility(enum.Enum): """ 6 types scope visibility. We interest to analyze the variable scope by checking a single file. So, we do not interest to the strict visibility of the scopes that have a larger visibility than script local. """ GLOBAL_LIKE = 0 BUILTIN = 1 SCRIPT_LOCAL = 2 FUNCTION_LOCAL = 3 UNANALYZABLE = 4 INVALID = 5 LAMBDA = 6
class ScopeVisibility(enum.Enum): ''' 6 types scope visibility. We interest to analyze the variable scope by checking a single file. So, we do not interest to the strict visibility of the scopes that have a larger visibility than script local. ''' pass
1
1
0
0
0
0
0
0.63
1
0
0
0
0
0
0
49
13
0
8
8
7
5
8
8
7
0
4
0
0
144,243
Kuniwak/vint
Kuniwak_vint/vint/ast/node_type.py
vint.ast.node_type.NodeType
class NodeType(Enum): TOPLEVEL = 1 COMMENT = 2 EXCMD = 3 FUNCTION = 4 ENDFUNCTION = 5 DELFUNCTION = 6 RETURN = 7 EXCALL = 8 LET = 9 UNLET = 10 LOCKVAR = 11 UNLOCKVAR = 12 IF = 13 ELSEIF = 14 ELSE = 15 ENDIF = 16 WHILE = 17 ENDWHILE = 18 FOR = 19 ENDFOR = 20 CONTINUE = 21 BREAK = 22 TRY = 23 CATCH = 24 FINALLY = 25 ENDTRY = 26 THROW = 27 ECHO = 28 ECHON = 29 ECHOHL = 30 ECHOMSG = 31 ECHOERR = 32 EXECUTE = 33 TERNARY = 34 OR = 35 AND = 36 EQUAL = 37 EQUALCI = 38 EQUALCS = 39 NEQUAL = 40 NEQUALCI = 41 NEQUALCS = 42 GREATER = 43 GREATERCI = 44 GREATERCS = 45 GEQUAL = 46 GEQUALCI = 47 GEQUALCS = 48 SMALLER = 49 SMALLERCI = 50 SMALLERCS = 51 SEQUAL = 52 SEQUALCI = 53 SEQUALCS = 54 MATCH = 55 MATCHCI = 56 MATCHCS = 57 NOMATCH = 58 NOMATCHCI = 59 NOMATCHCS = 60 IS = 61 ISCI = 62 ISCS = 63 ISNOT = 64 ISNOTCI = 65 ISNOTCS = 66 ADD = 67 SUBTRACT = 68 CONCAT = 69 MULTIPLY = 70 DIVIDE = 71 REMAINDER = 72 NOT = 73 MINUS = 74 PLUS = 75 SUBSCRIPT = 76 SLICE = 77 CALL = 78 DOT = 79 NUMBER = 80 STRING = 81 LIST = 82 DICT = 83 NESTING = 84 OPTION = 85 IDENTIFIER = 86 CURLYNAME = 87 ENV = 88 REG = 89 CURLYNAMEPART = 90 CURLYNAMEEXPR = 91 LAMBDA = 92 BLOB = 93 CONST = 94 EVAL = 95 HEREDOC = 96 METHOD = 97 ECHOCONSOLE = 98
class NodeType(Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
99
0
99
99
98
0
99
99
98
0
4
0
0
144,244
Kuniwak/vint
Kuniwak_vint/vint/_bundles/vimlparser.py
vint._bundles.vimlparser.Compiler
class Compiler: def __init__(self): self.indent = [""] self.lines = [] def out(self, *a000): if viml_len(a000) == 1: if a000[0][0] == ")": self.lines[-1] += a000[0] else: viml_add(self.lines, self.indent[0] + a000[0]) else: viml_add(self.lines, self.indent[0] + viml_printf(*a000)) def incindent(self, s): viml_insert(self.indent, self.indent[0] + s) def decindent(self): viml_remove(self.indent, 0) def compile(self, node): if node.type == NODE_TOPLEVEL: return self.compile_toplevel(node) elif node.type == NODE_COMMENT: self.compile_comment(node) return NIL elif node.type == NODE_EXCMD: self.compile_excmd(node) return NIL elif node.type == NODE_FUNCTION: self.compile_function(node) return NIL elif node.type == NODE_DELFUNCTION: self.compile_delfunction(node) return NIL elif node.type == NODE_RETURN: self.compile_return(node) return NIL elif node.type == NODE_EXCALL: self.compile_excall(node) return NIL elif node.type == NODE_EVAL: self.compile_eval(node) return NIL elif node.type == NODE_LET: self.compile_let(node) return NIL elif node.type == NODE_CONST: self.compile_const(node) return NIL elif node.type == NODE_UNLET: self.compile_unlet(node) return NIL elif node.type == NODE_LOCKVAR: self.compile_lockvar(node) return NIL elif node.type == NODE_UNLOCKVAR: self.compile_unlockvar(node) return NIL elif node.type == NODE_IF: self.compile_if(node) return NIL elif node.type == NODE_WHILE: self.compile_while(node) return NIL elif node.type == NODE_FOR: self.compile_for(node) return NIL elif node.type == NODE_CONTINUE: self.compile_continue(node) return NIL elif node.type == NODE_BREAK: self.compile_break(node) return NIL elif node.type == NODE_TRY: self.compile_try(node) return NIL elif node.type == NODE_THROW: self.compile_throw(node) return NIL elif node.type == NODE_ECHO: self.compile_echo(node) return NIL elif node.type == NODE_ECHON: self.compile_echon(node) return NIL elif node.type == NODE_ECHOHL: self.compile_echohl(node) return NIL elif node.type == NODE_ECHOMSG: self.compile_echomsg(node) return NIL elif node.type == NODE_ECHOERR: self.compile_echoerr(node) return NIL elif node.type == NODE_ECHOCONSOLE: self.compile_echoconsole(node) return NIL elif node.type == NODE_EXECUTE: self.compile_execute(node) return NIL elif node.type == NODE_TERNARY: return self.compile_ternary(node) elif node.type == NODE_OR: return self.compile_or(node) elif node.type == NODE_AND: return self.compile_and(node) elif node.type == NODE_EQUAL: return self.compile_equal(node) elif node.type == NODE_EQUALCI: return self.compile_equalci(node) elif node.type == NODE_EQUALCS: return self.compile_equalcs(node) elif node.type == NODE_NEQUAL: return self.compile_nequal(node) elif node.type == NODE_NEQUALCI: return self.compile_nequalci(node) elif node.type == NODE_NEQUALCS: return self.compile_nequalcs(node) elif node.type == NODE_GREATER: return self.compile_greater(node) elif node.type == NODE_GREATERCI: return self.compile_greaterci(node) elif node.type == NODE_GREATERCS: return self.compile_greatercs(node) elif node.type == NODE_GEQUAL: return self.compile_gequal(node) elif node.type == NODE_GEQUALCI: return self.compile_gequalci(node) elif node.type == NODE_GEQUALCS: return self.compile_gequalcs(node) elif node.type == NODE_SMALLER: return self.compile_smaller(node) elif node.type == NODE_SMALLERCI: return self.compile_smallerci(node) elif node.type == NODE_SMALLERCS: return self.compile_smallercs(node) elif node.type == NODE_SEQUAL: return self.compile_sequal(node) elif node.type == NODE_SEQUALCI: return self.compile_sequalci(node) elif node.type == NODE_SEQUALCS: return self.compile_sequalcs(node) elif node.type == NODE_MATCH: return self.compile_match(node) elif node.type == NODE_MATCHCI: return self.compile_matchci(node) elif node.type == NODE_MATCHCS: return self.compile_matchcs(node) elif node.type == NODE_NOMATCH: return self.compile_nomatch(node) elif node.type == NODE_NOMATCHCI: return self.compile_nomatchci(node) elif node.type == NODE_NOMATCHCS: return self.compile_nomatchcs(node) elif node.type == NODE_IS: return self.compile_is(node) elif node.type == NODE_ISCI: return self.compile_isci(node) elif node.type == NODE_ISCS: return self.compile_iscs(node) elif node.type == NODE_ISNOT: return self.compile_isnot(node) elif node.type == NODE_ISNOTCI: return self.compile_isnotci(node) elif node.type == NODE_ISNOTCS: return self.compile_isnotcs(node) elif node.type == NODE_ADD: return self.compile_add(node) elif node.type == NODE_SUBTRACT: return self.compile_subtract(node) elif node.type == NODE_CONCAT: return self.compile_concat(node) elif node.type == NODE_MULTIPLY: return self.compile_multiply(node) elif node.type == NODE_DIVIDE: return self.compile_divide(node) elif node.type == NODE_REMAINDER: return self.compile_remainder(node) elif node.type == NODE_NOT: return self.compile_not(node) elif node.type == NODE_PLUS: return self.compile_plus(node) elif node.type == NODE_MINUS: return self.compile_minus(node) elif node.type == NODE_SUBSCRIPT: return self.compile_subscript(node) elif node.type == NODE_SLICE: return self.compile_slice(node) elif node.type == NODE_DOT: return self.compile_dot(node) elif node.type == NODE_METHOD: return self.compile_method(node) elif node.type == NODE_CALL: return self.compile_call(node) elif node.type == NODE_NUMBER: return self.compile_number(node) elif node.type == NODE_BLOB: return self.compile_blob(node) elif node.type == NODE_STRING: return self.compile_string(node) elif node.type == NODE_LIST: return self.compile_list(node) elif node.type == NODE_DICT: return self.compile_dict(node) elif node.type == NODE_OPTION: return self.compile_option(node) elif node.type == NODE_IDENTIFIER: return self.compile_identifier(node) elif node.type == NODE_CURLYNAME: return self.compile_curlyname(node) elif node.type == NODE_ENV: return self.compile_env(node) elif node.type == NODE_REG: return self.compile_reg(node) elif node.type == NODE_CURLYNAMEPART: return self.compile_curlynamepart(node) elif node.type == NODE_CURLYNAMEEXPR: return self.compile_curlynameexpr(node) elif node.type == NODE_LAMBDA: return self.compile_lambda(node) elif node.type == NODE_HEREDOC: return self.compile_heredoc(node) else: raise VimLParserException(viml_printf("Compiler: unknown node: %s", viml_string(node))) return NIL def compile_body(self, body): for node in body: self.compile(node) def compile_toplevel(self, node): self.compile_body(node.body) return self.lines def compile_comment(self, node): self.out(";%s", node.str) def compile_excmd(self, node): self.out("(excmd \"%s\")", viml_escape(node.str, "\\\"")) def compile_function(self, node): left = self.compile(node.left) rlist = [self.compile(vval) for vval in node.rlist] default_args = [self.compile(vval) for vval in node.default_args] if not viml_empty(rlist): remaining = FALSE if rlist[-1] == "...": viml_remove(rlist, -1) remaining = TRUE for i in viml_range(viml_len(rlist)): if i < viml_len(rlist) - viml_len(default_args): left += viml_printf(" %s", rlist[i]) else: left += viml_printf(" (%s %s)", rlist[i], default_args[i + viml_len(default_args) - viml_len(rlist)]) if remaining: left += " . ..." self.out("(function (%s)", left) self.incindent(" ") self.compile_body(node.body) self.out(")") self.decindent() def compile_delfunction(self, node): self.out("(delfunction %s)", self.compile(node.left)) def compile_return(self, node): if node.left is NIL: self.out("(return)") else: self.out("(return %s)", self.compile(node.left)) def compile_excall(self, node): self.out("(call %s)", self.compile(node.left)) def compile_eval(self, node): self.out("(eval %s)", self.compile(node.left)) def compile_let(self, node): left = "" if node.left is not NIL: left = self.compile(node.left) else: left = viml_join([self.compile(vval) for vval in node.list], " ") if node.rest is not NIL: left += " . " + self.compile(node.rest) left = "(" + left + ")" right = self.compile(node.right) self.out("(let %s %s %s)", node.op, left, right) # TODO: merge with s:Compiler.compile_let() ? def compile_const(self, node): left = "" if node.left is not NIL: left = self.compile(node.left) else: left = viml_join([self.compile(vval) for vval in node.list], " ") if node.rest is not NIL: left += " . " + self.compile(node.rest) left = "(" + left + ")" right = self.compile(node.right) self.out("(const %s %s %s)", node.op, left, right) def compile_unlet(self, node): list = [self.compile(vval) for vval in node.list] self.out("(unlet %s)", viml_join(list, " ")) def compile_lockvar(self, node): list = [self.compile(vval) for vval in node.list] if node.depth is NIL: self.out("(lockvar %s)", viml_join(list, " ")) else: self.out("(lockvar %d %s)", node.depth, viml_join(list, " ")) def compile_unlockvar(self, node): list = [self.compile(vval) for vval in node.list] if node.depth is NIL: self.out("(unlockvar %s)", viml_join(list, " ")) else: self.out("(unlockvar %d %s)", node.depth, viml_join(list, " ")) def compile_if(self, node): self.out("(if %s", self.compile(node.cond)) self.incindent(" ") self.compile_body(node.body) self.decindent() for enode in node.elseif: self.out(" elseif %s", self.compile(enode.cond)) self.incindent(" ") self.compile_body(enode.body) self.decindent() if node.else_ is not NIL: self.out(" else") self.incindent(" ") self.compile_body(node.else_.body) self.decindent() self.incindent(" ") self.out(")") self.decindent() def compile_while(self, node): self.out("(while %s", self.compile(node.cond)) self.incindent(" ") self.compile_body(node.body) self.out(")") self.decindent() def compile_for(self, node): left = "" if node.left is not NIL: left = self.compile(node.left) else: left = viml_join([self.compile(vval) for vval in node.list], " ") if node.rest is not NIL: left += " . " + self.compile(node.rest) left = "(" + left + ")" right = self.compile(node.right) self.out("(for %s %s", left, right) self.incindent(" ") self.compile_body(node.body) self.out(")") self.decindent() def compile_continue(self, node): self.out("(continue)") def compile_break(self, node): self.out("(break)") def compile_try(self, node): self.out("(try") self.incindent(" ") self.compile_body(node.body) for cnode in node.catch: if cnode.pattern is not NIL: self.decindent() self.out(" catch /%s/", cnode.pattern) self.incindent(" ") self.compile_body(cnode.body) else: self.decindent() self.out(" catch") self.incindent(" ") self.compile_body(cnode.body) if node.finally_ is not NIL: self.decindent() self.out(" finally") self.incindent(" ") self.compile_body(node.finally_.body) self.out(")") self.decindent() def compile_throw(self, node): self.out("(throw %s)", self.compile(node.left)) def compile_echo(self, node): list = [self.compile(vval) for vval in node.list] self.out("(echo %s)", viml_join(list, " ")) def compile_echon(self, node): list = [self.compile(vval) for vval in node.list] self.out("(echon %s)", viml_join(list, " ")) def compile_echohl(self, node): self.out("(echohl \"%s\")", viml_escape(node.str, "\\\"")) def compile_echomsg(self, node): list = [self.compile(vval) for vval in node.list] self.out("(echomsg %s)", viml_join(list, " ")) def compile_echoerr(self, node): list = [self.compile(vval) for vval in node.list] self.out("(echoerr %s)", viml_join(list, " ")) def compile_echoconsole(self, node): list = [self.compile(vval) for vval in node.list] self.out("(echoconsole %s)", viml_join(list, " ")) def compile_execute(self, node): list = [self.compile(vval) for vval in node.list] self.out("(execute %s)", viml_join(list, " ")) def compile_ternary(self, node): return viml_printf("(?: %s %s %s)", self.compile(node.cond), self.compile(node.left), self.compile(node.right)) def compile_or(self, node): return viml_printf("(|| %s %s)", self.compile(node.left), self.compile(node.right)) def compile_and(self, node): return viml_printf("(&& %s %s)", self.compile(node.left), self.compile(node.right)) def compile_equal(self, node): return viml_printf("(== %s %s)", self.compile(node.left), self.compile(node.right)) def compile_equalci(self, node): return viml_printf("(==? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_equalcs(self, node): return viml_printf("(==# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_nequal(self, node): return viml_printf("(!= %s %s)", self.compile(node.left), self.compile(node.right)) def compile_nequalci(self, node): return viml_printf("(!=? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_nequalcs(self, node): return viml_printf("(!=# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_greater(self, node): return viml_printf("(> %s %s)", self.compile(node.left), self.compile(node.right)) def compile_greaterci(self, node): return viml_printf("(>? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_greatercs(self, node): return viml_printf("(># %s %s)", self.compile(node.left), self.compile(node.right)) def compile_gequal(self, node): return viml_printf("(>= %s %s)", self.compile(node.left), self.compile(node.right)) def compile_gequalci(self, node): return viml_printf("(>=? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_gequalcs(self, node): return viml_printf("(>=# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_smaller(self, node): return viml_printf("(< %s %s)", self.compile(node.left), self.compile(node.right)) def compile_smallerci(self, node): return viml_printf("(<? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_smallercs(self, node): return viml_printf("(<# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_sequal(self, node): return viml_printf("(<= %s %s)", self.compile(node.left), self.compile(node.right)) def compile_sequalci(self, node): return viml_printf("(<=? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_sequalcs(self, node): return viml_printf("(<=# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_match(self, node): return viml_printf("(=~ %s %s)", self.compile(node.left), self.compile(node.right)) def compile_matchci(self, node): return viml_printf("(=~? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_matchcs(self, node): return viml_printf("(=~# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_nomatch(self, node): return viml_printf("(!~ %s %s)", self.compile(node.left), self.compile(node.right)) def compile_nomatchci(self, node): return viml_printf("(!~? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_nomatchcs(self, node): return viml_printf("(!~# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_is(self, node): return viml_printf("(is %s %s)", self.compile(node.left), self.compile(node.right)) def compile_isci(self, node): return viml_printf("(is? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_iscs(self, node): return viml_printf("(is# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_isnot(self, node): return viml_printf("(isnot %s %s)", self.compile(node.left), self.compile(node.right)) def compile_isnotci(self, node): return viml_printf("(isnot? %s %s)", self.compile(node.left), self.compile(node.right)) def compile_isnotcs(self, node): return viml_printf("(isnot# %s %s)", self.compile(node.left), self.compile(node.right)) def compile_add(self, node): return viml_printf("(+ %s %s)", self.compile(node.left), self.compile(node.right)) def compile_subtract(self, node): return viml_printf("(- %s %s)", self.compile(node.left), self.compile(node.right)) def compile_concat(self, node): return viml_printf("(concat %s %s)", self.compile(node.left), self.compile(node.right)) def compile_multiply(self, node): return viml_printf("(* %s %s)", self.compile(node.left), self.compile(node.right)) def compile_divide(self, node): return viml_printf("(/ %s %s)", self.compile(node.left), self.compile(node.right)) def compile_remainder(self, node): return viml_printf("(%% %s %s)", self.compile(node.left), self.compile(node.right)) def compile_not(self, node): return viml_printf("(! %s)", self.compile(node.left)) def compile_plus(self, node): return viml_printf("(+ %s)", self.compile(node.left)) def compile_minus(self, node): return viml_printf("(- %s)", self.compile(node.left)) def compile_subscript(self, node): return viml_printf("(subscript %s %s)", self.compile(node.left), self.compile(node.right)) def compile_slice(self, node): r0 = "nil" if node.rlist[0] is NIL else self.compile(node.rlist[0]) r1 = "nil" if node.rlist[1] is NIL else self.compile(node.rlist[1]) return viml_printf("(slice %s %s %s)", self.compile(node.left), r0, r1) def compile_dot(self, node): return viml_printf("(dot %s %s)", self.compile(node.left), self.compile(node.right)) def compile_method(self, node): return viml_printf("(method %s %s)", self.compile(node.left), self.compile(node.right)) def compile_call(self, node): rlist = [self.compile(vval) for vval in node.rlist] if viml_empty(rlist): return viml_printf("(%s)", self.compile(node.left)) else: return viml_printf("(%s %s)", self.compile(node.left), viml_join(rlist, " ")) def compile_number(self, node): return node.value def compile_blob(self, node): return node.value def compile_string(self, node): return node.value def compile_list(self, node): value = [self.compile(vval) for vval in node.value] if viml_empty(value): return "(list)" else: return viml_printf("(list %s)", viml_join(value, " ")) def compile_dict(self, node): value = ["(" + self.compile(vval[0]) + " " + self.compile(vval[1]) + ")" for vval in node.value] if viml_empty(value): return "(dict)" else: return viml_printf("(dict %s)", viml_join(value, " ")) def compile_option(self, node): return node.value def compile_identifier(self, node): return node.value def compile_curlyname(self, node): return viml_join([self.compile(vval) for vval in node.value], "") def compile_env(self, node): return node.value def compile_reg(self, node): return node.value def compile_curlynamepart(self, node): return node.value def compile_curlynameexpr(self, node): return "{" + self.compile(node.value) + "}" def escape_string(self, str): m = AttributeDict({"\n": "\\n", "\t": "\\t", "\r": "\\r"}) out = "\"" for i in viml_range(viml_len(str)): c = str[i] if viml_has_key(m, c): out += m[c] else: out += c out += "\"" return out def compile_lambda(self, node): rlist = [self.compile(vval) for vval in node.rlist] return viml_printf("(lambda (%s) %s)", viml_join(rlist, " "), self.compile(node.left)) def compile_heredoc(self, node): if viml_empty(node.rlist): rlist = "(list)" else: rlist = "(list " + viml_join([self.escape_string(vval.value) for vval in node.rlist], " ") + ")" if viml_empty(node.body): body = "(list)" else: body = "(list " + viml_join([self.escape_string(vval.value) for vval in node.body], " ") + ")" op = self.escape_string(node.op) return viml_printf("(heredoc %s %s %s)", rlist, op, body)
class Compiler: def __init__(self): pass def out(self, *a000): pass def incindent(self, s): pass def decindent(self): pass def compile(self, node): pass def compile_body(self, body): pass def compile_toplevel(self, node): pass def compile_comment(self, node): pass def compile_excmd(self, node): pass def compile_function(self, node): pass def compile_delfunction(self, node): pass def compile_return(self, node): pass def compile_excall(self, node): pass def compile_eval(self, node): pass def compile_let(self, node): pass def compile_const(self, node): pass def compile_unlet(self, node): pass def compile_lockvar(self, node): pass def compile_unlockvar(self, node): pass def compile_if(self, node): pass def compile_while(self, node): pass def compile_for(self, node): pass def compile_continue(self, node): pass def compile_break(self, node): pass def compile_try(self, node): pass def compile_throw(self, node): pass def compile_echo(self, node): pass def compile_echon(self, node): pass def compile_echohl(self, node): pass def compile_echomsg(self, node): pass def compile_echoerr(self, node): pass def compile_echoconsole(self, node): pass def compile_execute(self, node): pass def compile_ternary(self, node): pass def compile_or(self, node): pass def compile_and(self, node): pass def compile_equal(self, node): pass def compile_equalci(self, node): pass def compile_equalcs(self, node): pass def compile_nequal(self, node): pass def compile_nequalci(self, node): pass def compile_nequalcs(self, node): pass def compile_greater(self, node): pass def compile_greaterci(self, node): pass def compile_greatercs(self, node): pass def compile_gequal(self, node): pass def compile_gequalci(self, node): pass def compile_gequalcs(self, node): pass def compile_smaller(self, node): pass def compile_smallerci(self, node): pass def compile_smallercs(self, node): pass def compile_sequal(self, node): pass def compile_sequalci(self, node): pass def compile_sequalcs(self, node): pass def compile_match(self, node): pass def compile_matchci(self, node): pass def compile_matchcs(self, node): pass def compile_nomatch(self, node): pass def compile_nomatchci(self, node): pass def compile_nomatchcs(self, node): pass def compile_is(self, node): pass def compile_isci(self, node): pass def compile_iscs(self, node): pass def compile_isnot(self, node): pass def compile_isnotci(self, node): pass def compile_isnotcs(self, node): pass def compile_add(self, node): pass def compile_subtract(self, node): pass def compile_concat(self, node): pass def compile_multiply(self, node): pass def compile_divide(self, node): pass def compile_remainder(self, node): pass def compile_not(self, node): pass def compile_plus(self, node): pass def compile_minus(self, node): pass def compile_subscript(self, node): pass def compile_slice(self, node): pass def compile_dot(self, node): pass def compile_method(self, node): pass def compile_call(self, node): pass def compile_number(self, node): pass def compile_blob(self, node): pass def compile_string(self, node): pass def compile_list(self, node): pass def compile_dict(self, node): pass def compile_option(self, node): pass def compile_identifier(self, node): pass def compile_curlyname(self, node): pass def compile_env(self, node): pass def compile_reg(self, node): pass def compile_curlynamepart(self, node): pass def compile_curlynameexpr(self, node): pass def escape_string(self, str): pass def compile_lambda(self, node): pass def compile_heredoc(self, node): pass
96
0
6
0
6
0
2
0.02
0
2
2
0
95
2
95
95
641
95
545
134
449
11
441
134
345
89
0
3
214
144,245
Kuniwak/vint
Kuniwak_vint/vint/_bundles/vimlparser.py
vint._bundles.vimlparser.AttributeDict
class AttributeDict(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
class AttributeDict(dict): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
4
0
4
4
3
0
4
4
3
0
2
0
0
144,246
Kuniwak/vint
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kuniwak_vint/test/unit/vint/linting/config/test_config_container.py
test.unit.vint.linting.config.test_config_container.TestConfigContainer.StubConfigSource
class StubConfigSource(ConfigSource): def __init__(self, config_dict): self.return_value = config_dict def get_config_dict(self): return self.return_value
class StubConfigSource(ConfigSource): def __init__(self, config_dict): pass def get_config_dict(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
1
2
3
7
2
5
4
2
0
5
4
2
1
2
0
2
144,247
Kuniwak/vint
Kuniwak_vint/test/unit/vint/linting/test_policy_set.py
test.unit.vint.linting.test_policy_set.TestPolicySet
class TestPolicySet(TestCase): def test_get_enabled_policies_when_no_updated(self): policy_set = PolicySet([PolicyFixture1, PolicyFixture2]) expected_no_policies = policy_set.get_enabled_policies() self.assertEqual(expected_no_policies, [], 'Expect all policies to be disabled') def assertEnabledPolicies(self, expected_enabled_policy_classes, actual_enabled_policies): actual_enabled_policy_classes = {enabled_policy_class: False for enabled_policy_class in expected_enabled_policy_classes} for actual_enabled_policy in actual_enabled_policies: actual_enabled_policy_classes[actual_enabled_policy.__class__] = True pprint(actual_enabled_policy_classes) assert all(actual_enabled_policy_classes.values()) def test_get_enabled_policies_with_a_disabled_option(self): config_dict = { 'cmdargs': { 'severity': Level.WARNING, }, 'policies': { 'PolicyFixture1': { 'enabled': True, }, 'PolicyFixture2': { 'enabled': False, }, } } policy_set = PolicySet([PolicyFixture1, PolicyFixture2]) policy_set.update_by_config(config_dict) actual_enabled_policies = policy_set.get_enabled_policies() expected_enabled_policy_classes = [ PolicyFixture1, ] self.assertEnabledPolicies(expected_enabled_policy_classes, actual_enabled_policies) def test_get_enabled_policies_with_severity_warning(self): config_dict = { 'cmdargs': { 'severity': Level.WARNING, }, 'policies': {} } policy_set = PolicySet([PolicyFixture1, PolicyFixture2]) policy_set.update_by_config(config_dict) actual_enabled_policies = policy_set.get_enabled_policies() expected_enabled_policy_classes = [ PolicyFixture1, ] self.assertEnabledPolicies(expected_enabled_policy_classes, actual_enabled_policies) def test_get_enabled_policies_with_severity_style_problem(self): config_dict = { 'cmdargs': { 'severity': Level.STYLE_PROBLEM, }, 'policies': {} } policy_set = PolicySet([PolicyFixture1, PolicyFixture2]) policy_set.update_by_config(config_dict) actual_enabled_policies = policy_set.get_enabled_policies() expected_enabled_policy_classes = [ PolicyFixture1, PolicyFixture2, ] self.assertEnabledPolicies(expected_enabled_policy_classes, actual_enabled_policies)
class TestPolicySet(TestCase): def test_get_enabled_policies_when_no_updated(self): pass def assertEnabledPolicies(self, expected_enabled_policy_classes, actual_enabled_policies): pass def test_get_enabled_policies_with_a_disabled_option(self): pass def test_get_enabled_policies_with_severity_warning(self): pass def test_get_enabled_policies_with_severity_style_problem(self): pass
6
0
16
3
13
0
1
0
1
4
4
0
5
0
5
77
87
23
64
22
58
0
32
22
26
2
2
1
6