pico_lint

Functions to lint a cart - reporting potential issues in it

  1"""Functions to lint a cart - reporting potential issues in it"""
  2
  3from utils import *
  4from pico_srcdefs import Error
  5from pico_tokenize import CommentHint, is_identifier
  6from pico_parse import VarKind, NodeType
  7from pico_parse import is_assign_target, is_function_target, is_any_assign_target, is_root_global_or_builtin_local
  8
  9def lint_code(ctxt, root, lint_opts):
 10    """lint `root`, returning a list of 'errors'"""
 11
 12    errors = []
 13    builtin_globals = ctxt.builtins
 14
 15    lint_undefined = lint_opts.get("undefined", True)
 16    lint_unused = lint_opts.get("unused", True)
 17    lint_unused_global = lint_opts.get("unused-global", True)
 18    lint_duplicate = lint_opts.get("duplicate", True)
 19    lint_duplicate_global = lint_opts.get("duplicate-global", True)
 20    custom_globals = set(lint_opts.get("globals", ()))
 21
 22    def add_error(msg, node):
 23        errors.append(Error(msg, node))
 24
 25    # find global assignment, and check for uses
 26
 27    used_globals = set()
 28    used_locals = set()
 29    used_labels = set()
 30    assigned_globals = set()
 31    assigned_locals = set()
 32    # (builtin locals will end up both as used globals and used locals)
 33
 34    def preprocess_tokens(token):
 35        if token.children:
 36            for comment in token.children:
 37                if comment.hint == CommentHint.lint:
 38                    for value in comment.hintdata:
 39                        if "::" not in value:
 40                            custom_globals.add(value)
 41                        elif value.startswith("used::"):
 42                            used_globals.add(str_after_first(value, "::"))
 43
 44    def preprocess_vars(node):
 45        if node.type == NodeType.var:
 46            if is_root_global_or_builtin_local(node):
 47                if node.name not in custom_globals:
 48                    assign = False
 49                    if is_assign_target(node):
 50                        func = node.find_parent(NodeType.function)
 51                        assign = True
 52                    elif is_function_target(node):
 53                        func = node.parent.find_parent(NodeType.function)
 54                        assign = True
 55
 56                    if assign and (func == None or func.kind == "_init" or (func.kind is None and func.name == "_init" and func.find_parent(NodeType.function) == None)):
 57                        custom_globals.add(node.name)
 58
 59                if is_any_assign_target(node):
 60                    assigned_globals.add(node.name)
 61                else:
 62                    used_globals.add(node.name)
 63
 64            if node.kind == VarKind.local and not node.new:
 65                if is_any_assign_target(node):
 66                    assigned_locals.add(node.var)
 67                else:
 68                    used_locals.add(node.var)
 69            
 70            if node.kind == VarKind.label and not node.new:
 71                used_labels.add(node.var)
 72
 73        elif node.type == NodeType.sublang:
 74            for glob in node.sublang.get_defined_globals():
 75                if glob not in custom_globals and is_identifier(glob, ctxt.lang):
 76                    custom_globals.add(glob)
 77                assigned_globals.add(glob)
 78            
 79            for glob in node.sublang.get_used_globals():
 80                used_globals.add(glob)
 81
 82    root.traverse_nodes(preprocess_vars, tokens=preprocess_tokens, extra=True)
 83
 84    # check for issues
 85
 86    def lint_pre(node):
 87        if node.type == NodeType.var:
 88            if node.kind == VarKind.local and node.new:
 89                if lint_duplicate and node.name not in ('_', '_ENV'):
 90                    prev_var = node.scope.parent.find(node.name)
 91                    if prev_var is None or prev_var.builtin:
 92                        if lint_duplicate_global:
 93                            if node.name in custom_globals:
 94                                add_error(f"Local '{node.name}' has the same name as a global", node)
 95                            elif node.name in used_globals or node.name in assigned_globals:
 96                                add_error(f"Local '{node.name}' has the same name as a built-in global used elsewhere in the cart", node)
 97                    elif prev_var.scope.funcdepth < node.var.scope.funcdepth:
 98                        if prev_var.scope.funcdepth < 0:
 99                            pass # local builtin
100                        elif prev_var.scope.funcdepth == 0:
101                            add_error(f"Local '{node.name}' has the same name as a local declared at the top level", node)
102                        else:
103                            add_error(f"Local '{node.name}' has the same name as a local declared in a parent function", node)
104                    elif prev_var.scope.depth < node.var.scope.depth:
105                        add_error(f"Local '{node.name}' has the same name as a local declared in a parent scope", node)
106                    else:
107                        add_error(f"Local '{node.name}' has the same name as a local declared in the same scope", node)
108                
109                if lint_unused and node.var not in used_locals and not node.name.startswith("_"):
110                    if node.var in assigned_locals:
111                        add_error(f"Local '{node.name}' is only ever assigned to, never used", node)
112                    elif not (node.parent.type == NodeType.function and node in node.parent.params and 
113                              (node != node.parent.params[-1] or node not in node.parent.children)): # don't warn for non-last or implicit params
114                        add_error(f"Local '{node.name}' isn't used", node)
115
116            elif node.kind == VarKind.label and node.new:
117                if lint_duplicate and node.name != '_':
118                    prev_var = node.scope.parent.find(node.name, crossfunc=True)
119                    if prev_var != None:
120                        if prev_var.scope.funcdepth < node.var.scope.funcdepth:
121                            if prev_var.scope.funcdepth <= 0:
122                                add_error(f"Label '{node.name}' has the same name as a label declared at the top level", node)
123                            else:
124                                add_error(f"Label '{node.name}' has the same name as a label declared in a parent function", node)
125                        else:
126                            add_error(f"Label '{node.name}' has the same name as a label declared in a parent scope", node)
127                
128                if lint_unused and node.var not in used_labels and not node.name.startswith("_"):
129                    add_error(f"Label '{node.name}' isn't used", node)
130
131            elif is_root_global_or_builtin_local(node):
132                if lint_undefined and node.name not in custom_globals:
133                    if node.name in builtin_globals:
134                        if is_assign_target(node):
135                            add_error(f"Built-in global '{node.name}' assigned outside _init - did you mean to use 'local'?", node)
136                        elif is_function_target(node):
137                            add_error(f"Built-in global '{node.name}' assigned outside _init - did you mean to use 'local function'?", node)
138                    else:
139                        if is_assign_target(node):
140                            add_error(f"Identifier '{node.name}' not found - did you mean to use 'local' to define it?", node)
141                        elif is_function_target(node):
142                            add_error(f"Identifier '{node.name}' not found - did you mean to use 'local function' to define it?", node)
143                        else:
144                            add_error(f"Identifier '{node.name}' not found", node)
145                            
146                if lint_unused and lint_unused_global and node.name not in used_globals and not node.name.startswith("_"):
147                    if node.name in assigned_globals:
148                        add_error(f"Global '{node.name}' is only ever assigned to, never used", node)
149                    else:
150                        add_error(f"Global '{node.name}' isn't used", node)
151                            
152        elif node.type == NodeType.sublang:
153            add_lang_error = lambda msg: add_error(f"{node.name}: {msg}", node)
154            node.sublang.lint(on_error=add_lang_error, builtins=builtin_globals, globals=custom_globals)
155
156    root.traverse_nodes(lint_pre, extra=True)
157    return errors
def lint_code(ctxt, root, lint_opts):
 10def lint_code(ctxt, root, lint_opts):
 11    """lint `root`, returning a list of 'errors'"""
 12
 13    errors = []
 14    builtin_globals = ctxt.builtins
 15
 16    lint_undefined = lint_opts.get("undefined", True)
 17    lint_unused = lint_opts.get("unused", True)
 18    lint_unused_global = lint_opts.get("unused-global", True)
 19    lint_duplicate = lint_opts.get("duplicate", True)
 20    lint_duplicate_global = lint_opts.get("duplicate-global", True)
 21    custom_globals = set(lint_opts.get("globals", ()))
 22
 23    def add_error(msg, node):
 24        errors.append(Error(msg, node))
 25
 26    # find global assignment, and check for uses
 27
 28    used_globals = set()
 29    used_locals = set()
 30    used_labels = set()
 31    assigned_globals = set()
 32    assigned_locals = set()
 33    # (builtin locals will end up both as used globals and used locals)
 34
 35    def preprocess_tokens(token):
 36        if token.children:
 37            for comment in token.children:
 38                if comment.hint == CommentHint.lint:
 39                    for value in comment.hintdata:
 40                        if "::" not in value:
 41                            custom_globals.add(value)
 42                        elif value.startswith("used::"):
 43                            used_globals.add(str_after_first(value, "::"))
 44
 45    def preprocess_vars(node):
 46        if node.type == NodeType.var:
 47            if is_root_global_or_builtin_local(node):
 48                if node.name not in custom_globals:
 49                    assign = False
 50                    if is_assign_target(node):
 51                        func = node.find_parent(NodeType.function)
 52                        assign = True
 53                    elif is_function_target(node):
 54                        func = node.parent.find_parent(NodeType.function)
 55                        assign = True
 56
 57                    if assign and (func == None or func.kind == "_init" or (func.kind is None and func.name == "_init" and func.find_parent(NodeType.function) == None)):
 58                        custom_globals.add(node.name)
 59
 60                if is_any_assign_target(node):
 61                    assigned_globals.add(node.name)
 62                else:
 63                    used_globals.add(node.name)
 64
 65            if node.kind == VarKind.local and not node.new:
 66                if is_any_assign_target(node):
 67                    assigned_locals.add(node.var)
 68                else:
 69                    used_locals.add(node.var)
 70            
 71            if node.kind == VarKind.label and not node.new:
 72                used_labels.add(node.var)
 73
 74        elif node.type == NodeType.sublang:
 75            for glob in node.sublang.get_defined_globals():
 76                if glob not in custom_globals and is_identifier(glob, ctxt.lang):
 77                    custom_globals.add(glob)
 78                assigned_globals.add(glob)
 79            
 80            for glob in node.sublang.get_used_globals():
 81                used_globals.add(glob)
 82
 83    root.traverse_nodes(preprocess_vars, tokens=preprocess_tokens, extra=True)
 84
 85    # check for issues
 86
 87    def lint_pre(node):
 88        if node.type == NodeType.var:
 89            if node.kind == VarKind.local and node.new:
 90                if lint_duplicate and node.name not in ('_', '_ENV'):
 91                    prev_var = node.scope.parent.find(node.name)
 92                    if prev_var is None or prev_var.builtin:
 93                        if lint_duplicate_global:
 94                            if node.name in custom_globals:
 95                                add_error(f"Local '{node.name}' has the same name as a global", node)
 96                            elif node.name in used_globals or node.name in assigned_globals:
 97                                add_error(f"Local '{node.name}' has the same name as a built-in global used elsewhere in the cart", node)
 98                    elif prev_var.scope.funcdepth < node.var.scope.funcdepth:
 99                        if prev_var.scope.funcdepth < 0:
100                            pass # local builtin
101                        elif prev_var.scope.funcdepth == 0:
102                            add_error(f"Local '{node.name}' has the same name as a local declared at the top level", node)
103                        else:
104                            add_error(f"Local '{node.name}' has the same name as a local declared in a parent function", node)
105                    elif prev_var.scope.depth < node.var.scope.depth:
106                        add_error(f"Local '{node.name}' has the same name as a local declared in a parent scope", node)
107                    else:
108                        add_error(f"Local '{node.name}' has the same name as a local declared in the same scope", node)
109                
110                if lint_unused and node.var not in used_locals and not node.name.startswith("_"):
111                    if node.var in assigned_locals:
112                        add_error(f"Local '{node.name}' is only ever assigned to, never used", node)
113                    elif not (node.parent.type == NodeType.function and node in node.parent.params and 
114                              (node != node.parent.params[-1] or node not in node.parent.children)): # don't warn for non-last or implicit params
115                        add_error(f"Local '{node.name}' isn't used", node)
116
117            elif node.kind == VarKind.label and node.new:
118                if lint_duplicate and node.name != '_':
119                    prev_var = node.scope.parent.find(node.name, crossfunc=True)
120                    if prev_var != None:
121                        if prev_var.scope.funcdepth < node.var.scope.funcdepth:
122                            if prev_var.scope.funcdepth <= 0:
123                                add_error(f"Label '{node.name}' has the same name as a label declared at the top level", node)
124                            else:
125                                add_error(f"Label '{node.name}' has the same name as a label declared in a parent function", node)
126                        else:
127                            add_error(f"Label '{node.name}' has the same name as a label declared in a parent scope", node)
128                
129                if lint_unused and node.var not in used_labels and not node.name.startswith("_"):
130                    add_error(f"Label '{node.name}' isn't used", node)
131
132            elif is_root_global_or_builtin_local(node):
133                if lint_undefined and node.name not in custom_globals:
134                    if node.name in builtin_globals:
135                        if is_assign_target(node):
136                            add_error(f"Built-in global '{node.name}' assigned outside _init - did you mean to use 'local'?", node)
137                        elif is_function_target(node):
138                            add_error(f"Built-in global '{node.name}' assigned outside _init - did you mean to use 'local function'?", node)
139                    else:
140                        if is_assign_target(node):
141                            add_error(f"Identifier '{node.name}' not found - did you mean to use 'local' to define it?", node)
142                        elif is_function_target(node):
143                            add_error(f"Identifier '{node.name}' not found - did you mean to use 'local function' to define it?", node)
144                        else:
145                            add_error(f"Identifier '{node.name}' not found", node)
146                            
147                if lint_unused and lint_unused_global and node.name not in used_globals and not node.name.startswith("_"):
148                    if node.name in assigned_globals:
149                        add_error(f"Global '{node.name}' is only ever assigned to, never used", node)
150                    else:
151                        add_error(f"Global '{node.name}' isn't used", node)
152                            
153        elif node.type == NodeType.sublang:
154            add_lang_error = lambda msg: add_error(f"{node.name}: {msg}", node)
155            node.sublang.lint(on_error=add_lang_error, builtins=builtin_globals, globals=custom_globals)
156
157    root.traverse_nodes(lint_pre, extra=True)
158    return errors

lint root, returning a list of 'errors'