we have to check the cls_node without changing it.
        There are two possiblities:
          1)  clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
          2)  clsdef => simple_stmt => expr_stmt => Leaf('__meta')
549077
def has_metaclass(parent):
    
    for node in parent.children:
        if node.type == syms.suite:
            return has_metaclass(node)
        elif node.type == syms.simple_stmt and node.children:
            expr_node = node.children[0]
            if expr_node.type == syms.expr_stmt and expr_node.children:
                left_side = expr_node.children[0]
                if isinstance(left_side, Leaf) and \
                        left_side.value == '__metaclass__':
                    return True
    return False
1017395
function checkMetaMessages(context, exportsNode) {
    if (exportsNode.type !== "ObjectExpression") {

        // if the exported node is not the correct format, "internal-no-invalid-meta" will already report this.
        return;
    }

    const metaProperty = getPropertyFromObject("meta", exportsNode);
    const messages = metaProperty && getPropertyFromObject("messages", metaProperty.value);

    if (!messages) {
        context.report({
            node: metaProperty,
            messageId: "expectedMessages"
        });
    }
}
512140
function detect_ext_define(cls, ast) {
  // defaults
  cls["extends"] = "Ext.Base";
  cls["requires"] = [];
  cls["uses"] = [];
  cls["alternateClassNames"] = [];
  cls["mixins"] = [];
  cls["aliases"] = [];
  cls["members"] = [];
  cls["code_type"] = "ext_define";
  
  each_pair_in_object_expression(ast["arguments"][1], function(key, value, pair) {
    switch (key) {
     case "extend":
        cls["extends"] = make_string(value);
        break;
     case "override":
        cls["override"] = make_string(value);
        break;
     case "requires":
        cls["requires"] = make_string_list(value);
        break;
     case "uses":
        cls["uses"] = make_string_list(value);
        break;
     case "alternateClassName":
        cls["alternateClassNames"] = make_string_list(value);
        break;
     case "mixins":
        cls["mixins"] = make_mixins(value);
        break;
     case "singleton":
        cls["singleton"] = make_singleton(value);
        break;
     case "alias":
        cls["aliases"] += make_string_list(value);
        break;
     case "see":
        cls["see"] += make_string_list(value);
        break;
     case "xtype":
        cls["aliases"] += _.map(make_string_list(value), function(xtype) { return "widget."+xtype });
        break;
     case "config":
        cls["members"] += make_configs(value, {"accessor": true});
        break;
     case "cachedConfig":
        cls["members"] += make_configs(value, {"accessor": true});
        break;
     case "eventedConfig":
        cls["members"] += make_configs(value, {"accessor": true, "evented": true});
        break;
     case "statics":
        cls["members"] += make_statics(value);
        break;
     case "inheritableStatics":
        cls["members"] += make_statics(value, {"inheritable": true});
        break;
     default:
        detect_method_or_property(cls, key, value, pair);
        break;
    }
  });
}
566844
function(context) {
        /*
        if a key is a node type, ESLint calls that visitor function while going down the tree
        if a key is a node type plus :exit, ESLint calls that visitor function while going up the tree
        if a key is an event name, ESLint calls that handler function for code path analysis
        */

        'use strict';
        var defaultOptions = {
            comments: true,
            strings: true,
            identifiers: true,
            templates: true,
            skipWords: [],
            skipIfMatch: [],
            skipWordIfMatch: [],
            minLength: 1
        },
        options = lodash.assign(defaultOptions, context.options[0]),
        lang = options.lang || 'en_US';


        if (dictionaryLang !== lang) { //Dictionary will only be initialized if changed
            dictionaryLang = lang;
            initializeDictionary(lang);
        }

        options.skipWords = new Set(lodash.union(options.skipWords, skipWords)
            .map(function (string) {
                return string.toLowerCase();
            }));

        function initializeDictionary(language) {
            dictionary = spell.parse({
                aff: fs.readFileSync(__dirname + '/utils/dicts/' + language + '.aff'),
                dic: fs.readFileSync(__dirname + '/utils/dicts/' + language + '.dic')
            });

            spell.use(dictionary);
        }

        function isSpellingError(aWord) {
            return !options.skipWords.has(aWord) && !spell.check(aWord);
        }

        function checkSpelling(aNode, value, spellingType) {
            if(!hasToSkip(value)) {
                // Regular expression matches regexp metacharacters, and any special char
                var regexp = /(\\[sSwdDB0nfrtv])|\\[0-7][0-7][0-7]|\\x[0-9A-F][0-9A-F]|\\u[0-9A-F][0-9A-F][0-9A-F][0-9A-F]|[^0-9a-zA-Z ']/g,
                    nodeWords = value.replace(regexp, ' ')
                        .replace(/([A-Z])/g, ' $1').split(' '),
                    errors;
                errors = nodeWords
                    .filter(hasToSkipWord)
                    .filter(isSpellingError)
                    .filter(function(aWord) {
                      // Split words by numbers for special cases such as test12anything78variable and to include 2nd and 3rd ordinals
                      // also for Proper names we convert to lower case in second pass.
                        var splitByNumberWords = aWord.replace(/[0-9']/g, ' ').replace(/([A-Z])/g, ' $1').toLowerCase().split(' ');
                        return splitByNumberWords.some(isSpellingError);
                    })
                    .forEach(function(aWord) {
                        context.report(
                            aNode,
                            'You have a misspelled word: {{word}} on {{spellingType}}', {
                              word: aWord,
                              spellingType: spellingType
                        });
                    });
                }
            }

        function checkComment(aNode) {
            if(options.comments) {
                checkSpelling(aNode, aNode.value, 'Comment');
            }
        }

        function checkLiteral(aNode){
            if(options.strings && typeof aNode.value === 'string') {
                checkSpelling(aNode, aNode.value, 'String');
            }
        }
        function checkTemplateElement(aNode){
            if(options.templates && typeof aNode.value.raw === 'string') {
                checkSpelling(aNode, aNode.value.raw, 'Template');
            }
        }

        function checkIdentifier(aNode) {
            if(options.identifiers) {
                checkSpelling(aNode, aNode.name, 'Identifier');
            }
        }
        /* Returns true if the string in value has to be skipped for spell checking */
        function hasToSkip(value) {
            return options.skipWords.has(value) ||
                lodash.find(options.skipIfMatch, function (aPattern) {
                    return value.match(aPattern);
                });
        }


        /**
         * returns false if the word has to be skipped
         * @param  {string}  word
         * @return {Boolean} false if skip; true if not
         */
        function hasToSkipWord(word) {
            if(word.length < options.minLength) return false;
            if(lodash.find(options.skipWordIfMatch, function (aPattern) {
                return word.match(aPattern);
            })){
                return false;
            }
            return true;
        }

        // Coverage exclusion only needed for ESLint<4
        /* istanbul ignore next */
        if (isEslint4OrAbove(context)) {
          context
            .getSourceCode()
            .getAllComments()
            .forEach(function (commentNode) {
              checkComment(commentNode);
            });
        }

        return {
            // Noop in ESLint 4+
            'BlockComment': checkComment,
            // Noop in ESLint 4+
            'LineComment': checkComment,
            'Literal': checkLiteral,
            'TemplateElement': checkTemplateElement,
            'Identifier': checkIdentifier
        };
    }
18549
function checkMetaDocsDescription(context, exportsNode) {
    if (exportsNode.type !== "ObjectExpression") {

        // if the exported node is not the correct format, "internal-no-invalid-meta" will already report this.
        return;
    }

    const metaProperty = getPropertyFromObject("meta", exportsNode);
    const metaDocs = metaProperty && getPropertyFromObject("docs", metaProperty.value);
    const metaDocsDescription = metaDocs && getPropertyFromObject("description", metaDocs.value);

    if (!metaDocsDescription) {

        // if there is no `meta.docs.description` property, "internal-no-invalid-meta" will already report this.
        return;
    }

    const description = metaDocsDescription.value.value;

    if (typeof description !== "string") {
        context.report({
            node: metaDocsDescription.value,
            message: "`meta.docs.description` should be a string."
        });
        return;
    }

    if (description === "") {
        context.report({
            node: metaDocsDescription.value,
            message: "`meta.docs.description` should not be empty."
        });
        return;
    }

    if (description.indexOf(" ") === 0) {
        context.report({
            node: metaDocsDescription.value,
            message: "`meta.docs.description` should not start with whitespace."
        });
        return;
    }

    const firstWord = description.split(" ")[0];

    if (ALLOWED_FIRST_WORDS.indexOf(firstWord) === -1) {
        context.report({
            node: metaDocsDescription.value,
            message: "`meta.docs.description` should start with one of the following words: {{ allowedWords }}. Started with \"{{ firstWord }}\" instead.",
            data: {
                allowedWords: ALLOWED_FIRST_WORDS.join(", "),
                firstWord
            }
        });
    }
}
255910
static void visitTemplateLiteral(NodeTraversal t, Node n, boolean addTypes) {
    JSTypeRegistry registry = t.getCompiler().getTypeRegistry();
    JSType stringType = createType(addTypes, registry, JSTypeNative.STRING_TYPE);
    int length = n.getChildCount();
    if (length == 0) {
      n.replaceWith(withType(IR.string("\"\""), stringType));
    } else {
      Node first = n.removeFirstChild();
      checkState(first.isTemplateLitString() && first.getCookedString() != null);
      Node firstStr = withType(IR.string(first.getCookedString()), stringType);
      if (length == 1) {
        n.replaceWith(firstStr);
      } else {
        // Add the first string with the first substitution expression
        Node add =
            withType(IR.add(firstStr, n.removeFirstChild().removeFirstChild()), n.getJSType());
        // Process the rest of the template literal
        for (int i = 2; i < length; i++) {
          Node child = n.removeFirstChild();
          if (child.isTemplateLitString()) {
            checkState(child.getCookedString() != null);
            if (child.getCookedString().isEmpty()) {
              continue;
            } else if (i == 2 && first.getCookedString().isEmpty()) {
              // So that `${hello} world` gets translated into (hello + " world")
              // instead of ("" + hello + " world").
              add = add.getSecondChild().detach();
            }
          }
          add =
              withType(
                  IR.add(
                      add,
                      child.isTemplateLitString()
                          ? withType(IR.string(child.getCookedString()), stringType)
                          : child.removeFirstChild()),
                  n.getJSType());
        }
        n.replaceWith(add.useSourceInfoIfMissingFromForTree(n));
      }
    }
    t.reportCodeChange();
  }
370478
function(class_data, source_object, is_root) {

		var name,
			skeleton = {},
			value,
			type,
			skeleton_value;

		for (name in source_object) {

			if (is_root && (this._reserved_members.indexOf(name) != -1 || (name in class_data.shared))) {

				continue;

			}

			value = source_object[name];
			type = Firestorm.getType(value);

			switch (type) {
				case 'null':
				case 'boolean':
				case 'number':
					skeleton_value = {type: this.MEMBER_TYPES.PRIMITIVE, value: value};
					break;
				case 'string':
					skeleton_value = {type: this.MEMBER_TYPES.STRING, value: value};
					break;
				case 'function':
					skeleton_value = {type: this.MEMBER_TYPES.FUNCTION, index: class_data.references.length};
					class_data.references.push(value);
					break;
				case 'regexp':
					skeleton_value = {type: this.MEMBER_TYPES.REGEXP, index: class_data.references.length};
					class_data.references.push(value);
					break;
				case 'object':
					skeleton_value = {
						type: this.MEMBER_TYPES.OBJECT,
						skeleton: this._disassemble(class_data, value, false)
					};
					break;
				case 'array':
					if (value.length == 0) {
						skeleton_value = {type: this.MEMBER_TYPES.EMPTY_ARRAY};
					} else if (this.inline_simple_arrays && this.isInlineArray(value)) {
						skeleton_value = {type: this.MEMBER_TYPES.INLINE_ARRAY, value: value};
					} else {
						skeleton_value = {type: this.MEMBER_TYPES.SLICE_ARRAY, index: class_data.references.length};
						class_data.references.push(value);
					}
					break;
				case 'undefined':
					Lava.t("[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: " + name);
					break;
				default:
					Lava.t("[ClassManager] Unsupported property type in source object: " + type);
					break;
			}

			skeleton[name] = skeleton_value;

		}

		return skeleton;

	}
1338372
function define(name, expr, global){
  utils.assertType(name, 'string', 'name');
  expr = utils.unwrap(expr);
  var scope = this.currentScope;
  if (global && global.toBoolean().isTrue) {
    scope = this.global.scope;
  }
  var node = new nodes.Ident(name.val, expr);
  scope.add(node);
  return nodes.null;
}
847816
def visit_functiondef(self, node):
        
        if not node.is_method():
            # We only check methods.
            return

        name = node.name

        if isTestModule(node.root().name):
            if name.startswith('test'):
                if not name.startswith('test_'):
                    self.add_message('C9303', node=node)
                    return
                else:
                    # Test names start with 'test_NAME' and can be like
                    # test_SOME_NAME or test_render_SomeCondition.
                    return

        if name[0].isupper():
            self.add_message('C9302', node=node)
            return

        if name.startswith('___'):
            self.add_message('C9302', node=node)
            return

        if name.endswith('___'):
            self.add_message('C9302', node=node)
            return

        if name.startswith('__'):
            if name.endswith('___'):
                # To many trailing underscores.
                self.add_message('C9302', node=node)
                return
            if name.endswith('_') and not name.endswith('__'):
                # To few trailing underscored
                self.add_message('C9302', node=node)
                return
            if name.endswith('__'):
                # This is a reserved name and we don't do any checks on it.
                return
            name = name[2:-2]

        if name.startswith('_'):
            name = name[1:]

        if name.endswith('_'):
            self.add_message('C9302', node=node)
            return

        if '_' in name:
            # This has a underscore in the main name.
            prefix = self._getMethodNamePrefix(node)
            if prefix:
                # There are other names with same prefix so this should be
                # a dispatched method.
                return

            self.add_message('C9302', node=node)
            return


        if isTestModule(node.name) and self.moduleContainsTestCase(node):
            self._checkTestMethodName(node)
670651
Map<String, DefineInfo> collectDefines(Node externs, Node root) {
    GlobalNamespace namespace = null;
    if (namespaceSupplier != null) {
      namespace = namespaceSupplier.get();
    }
    if (namespace == null) {
      namespace = new GlobalNamespace(compiler, externs, root);
    }

    // namespace =
    //     namespaceSupplier != nul
    //         ? namespaceSupplier.get()
    //         : new GlobalNamespace(compiler, externs, root);

    // Find all the global names with a @define annotation
    List<Name> listOfDefines = new ArrayList<>();
    for (Name name : namespace.getNameIndex().values()) {
      Ref decl = name.getDeclaration();
      if (name.getJSDocInfo() != null && name.getJSDocInfo().isDefine()) {
        // Process defines should not depend on check types being enabled,
        // so we look for the JSDoc instead of the inferred type.
        if (isValidDefineType(name.getJSDocInfo().getType())) {
          listOfDefines.add(name);
        } else {
          JSError error = JSError.make(decl.getNode(), INVALID_DEFINE_TYPE_ERROR);
          compiler.report(error);
        }
      } else {
        for (Ref ref : name.getRefs()) {
          if (ref == decl) {
            // Declarations were handled above.
            continue;
          }

          Node n = ref.getNode();
          Node parent = ref.getNode().getParent();
          JSDocInfo info = n.getJSDocInfo();
          if (info == null && parent.isVar() && parent.hasOneChild()) {
            info = parent.getJSDocInfo();
          }

          if (info != null && info.isDefine()) {
            listOfDefines.add(name);
            break;
          }
        }
      }
    }

    CollectDefines pass = new CollectDefines(namespace, listOfDefines);
    NodeTraversal.traverseRoots(compiler, pass, externs, root);
    return pass.allDefines;
  }
414154
def is_probably_builtin(node):
    
    prev = node.prev_sibling
    if prev is not None and prev.type == token.DOT:
        # Attribute lookup.
        return False
    parent = node.parent
    if parent.type in (syms.funcdef, syms.classdef):
        return False
    if parent.type == syms.expr_stmt and parent.children[0] is node:
        # Assignment.
        return False
    if parent.type == syms.parameters or \
            (parent.type == syms.typedargslist and (
            (prev is not None and prev.type == token.COMMA) or
            parent.children[0] is node
            )):
        # The name of an argument.
        return False
    return True
738097
def visit_classdef(self, node):
        """"""
        decorate = node.decorators.accept(self) if node.decorators else ""
        bases = ", ".join(n.accept(self) for n in node.bases)
        metaclass = node.metaclass()
        if metaclass and not node.has_metaclass_hack():
            if bases:
                bases = "(%s, metaclass=%s)" % (bases, metaclass.name)
            else:
                bases = "(metaclass=%s)" % metaclass.name
        else:
            bases = "(%s)" % bases if bases else ""
        docs = self._docs_dedent(node.doc) if node.doc else ""
        return "\n\n%sclass %s%s:%s\n%s\n" % (
            decorate,
            node.name,
            bases,
            docs,
            self._stmt_list(node.body),
        )
1324839
def v_reference_leaf_leafref(ctx, stmt):
    """"""

    if (hasattr(stmt, 'i_leafref') and
        stmt.i_leafref is not None and
        stmt.i_leafref_expanded is False):
        path_type_spec = stmt.i_leafref
        not_req_inst = not(path_type_spec.require_instance)
        x = validate_leafref_path(ctx, stmt,
                                  path_type_spec.path_spec,
                                  path_type_spec.path_,
                                  accept_non_config_target=not_req_inst
        )
        if x is None:
            return
        ptr, expanded_path, path_list = x
        path_type_spec.i_target_node = ptr
        path_type_spec.i_expanded_path = expanded_path
        path_type_spec.i_path_list = path_list
        stmt.i_leafref_expanded = True
        if ptr is not None:
            chk_status(ctx, stmt, ptr)
            stmt.i_leafref_ptr = (ptr, path_type_spec.pos)
62589
def literal_eval(node_or_string):
    
    _safe_names = {
        'None': None,
        'True': True,
        'False': False,
        'dict': dict,
        'list': list,
        'sorted': sorted
    }
    
    if isinstance(node_or_string, basestring):
        node_or_string = parse(node_or_string, mode='eval')
        
    if isinstance(node_or_string, ast.Expression):
        node_or_string = node_or_string.body
        
    def _convert(node):
        
        if isinstance(node, ast.Str):
            return node.s
        
        elif isinstance(node, ast.Num):
            return node.n
        
        elif isinstance(node, ast.Tuple):
            return tuple(map(_convert, node.elts))
        
        elif isinstance(node, ast.List):
            return list(map(_convert, node.elts))
        
        elif isinstance(node, ast.Dict):
            return dict((_convert(k), _convert(v)) for k, v
                        in zip(node.keys, node.values))
        
        elif isinstance(node, ast.Name):
            if node.id in _safe_names:
                return _safe_names[node.id]
        
        elif isinstance(node, ast.BinOp):
            left = _convert(node.left)
            right = _convert(node.right)
            op = {
                ast.Add: operator.add,
                ast.Sub: operator.sub,
                ast.Mult: operator.mul,
                ast.Div: operator.div,
                ast.Mod: operator.mod
            }.get(type(node.op), None)
            if op:
                return op(left, right)
        
        elif isinstance(node, ast.Call):
            func = _convert(node.func)
            args = map(_convert, node.args)
            kwargs = dict((kw.arg, _convert(kw.value)) for kw in node.keywords)
            if node.starargs:
                args.extend(_convert(node.starargs))
            if node.kwargs:
                kwargs.update(_convert(node.kwargs))
            return func(*args, **kwargs)
        
        elif isinstance(node, ast.Attribute):
            if not node.attr.startswith('_'):
                return getattr(_convert(node.value), node.attr)
        
        raise ValueError('malformed string: %r' % node)
    return _convert(node_or_string)
494714
def check_static_member_vars(class_, fpath=None, only_init=True):
    
    #import ast
    #import astor
    import utool as ut

    if isinstance(class_, six.string_types):
        classname = class_
        if fpath is None:
            raise Exception('must specify fpath')
    else:
        # We were given a live object
        if not isinstance(class_, type):
            # We were given the class instance not the class
            class_instance = class_
            class_ = class_instance.__class__
        classname = class_.__name__
        if fpath is None:
            module = ut.get_module_from_class(class_)
            fpath = ut.get_modpath(module)

    sourcecode = ut.readfrom(fpath)

    import redbaron
    # Pares a FULL syntax tree that keeps blockcomments
    baron = redbaron.RedBaron(sourcecode)

    for node in baron:
        if node.type == 'class' and node.name == classname:
            classnode = node
            break

    def find_parent_method(node):
        par = node.parent_find('def')
        if par is not None and par.parent is not None:
            if par.parent.type == 'class':
                return par
            else:
                return find_parent_method(par)

    # TODO: Find inherited attrs
    #classnode.inherit_from
    # inhertied_attrs = ['parent']
    # inhertied_attrs = []

    class_methods = []
    for node in classnode:
        if node.type == 'def':
            if only_init:
                if node.name == '__init__':
                    class_methods.append(node)
            else:
                class_methods.append(node)

    class_vars = []
    self_vars = []
    for method_node in class_methods:
        self_var = method_node.arguments[0].dumps()
        self_vars.append(self_var)
        for assign in method_node.find_all('assignment'):
            # method_node = find_parent_method(assign)
            if assign.target.dumps().startswith(self_var + '.'):
                class_vars.append(assign.target.value[1].dumps())
    static_attrs = ut.unique(class_vars)
    return static_attrs

    # class_members = ut.unique(class_vars + class_methods + inhertied_attrs)
    if False:
        self_var = self_vars[0]

        # Find everything that is used
        complex_cases = []
        simple_cases = []
        all_self_ref = classnode.find_all(
            'name_', value=re.compile('.*' + self_var + '\\.*'))
        for x in all_self_ref:
            if x.parent.type == 'def_argument':
                continue
            if x.parent.type == 'atomtrailers':
                atom = x.parent
                if ut.depth(atom.fst()) <= 3:
                    simple_cases.append(atom)
                else:
                    complex_cases.append(atom)
                #print(ut.depth(atom.value.data))
                #print(atom.value)
                #print(atom.dumps())
                #if len(atom.dumps()) > 200:
                #    break

        accessed_attrs = []
        for x in simple_cases:
            if x.value[0].dumps() == self_var:
                attr = x.value[1].dumps()
                accessed_attrs.append(attr)
        accessed_attrs = ut.unique(accessed_attrs)

        ut.setdiff(accessed_attrs, class_vars)
141076
def do_memberdef(self, node):
        
        prot = node.attributes['prot'].value
        id = node.attributes['id'].value
        kind = node.attributes['kind'].value
        tmp = node.parentNode.parentNode.parentNode
        compdef = tmp.getElementsByTagName('compounddef')[0]
        cdef_kind = compdef.attributes['kind'].value
        if cdef_kind in ('file', 'namespace', 'class', 'struct'):
            # These cases are now handled by `handle_typical_memberdefs`
            return
        if prot != 'public':
            return
        first = self.get_specific_nodes(node, ('definition', 'name'))
        name = self.extract_text(first['name'])
        if name[:8] == 'operator':  # Don't handle operators yet.
            return
        if not 'definition' in first or kind in ['variable', 'typedef']:
            return

        data = self.extract_text(first['definition'])
        self.add_text('\n')
        self.add_text(['/* where did this entry come from??? */', '\n'])
        self.add_text('%feature("docstring") %s "\n%s' % (data, data))

        for n in node.childNodes:
            if n not in first.values():
                self.parse(n)
        self.add_text(['";', '\n'])
1310750
def matchImpObjStrs(fdefs,imp_obj_strs,cdefs):
    ''''''
    imp_funcs=dict()
    imp_classes=dict()
    for source in imp_obj_strs:
        if not imp_obj_strs[source]:
            continue
        imp_funcs[source]=[]
        imp_classes[source]=[]
        for (mod,func) in imp_obj_strs[source]:
            if mod not in fdefs:
                #print(mod+" is not part of the project.")
                continue
            if func=='*':
                all_fns = [x for x in fdefs[mod] if x.name!='body']
                imp_funcs[source] += all_fns
                all_cls = [x for x in cdefs[mod]]
                imp_classes[source] += all_cls
            else:
                fn_node = [x for x in fdefs[mod] if x.name==func]
                cls_node = [x for x in cdefs[mod] if x.name==func]
                #assert len(fn_node) in [1,0]
                #assert len(cls_node) in [1,0]
                if cls_node:
                    imp_classes[source] += cls_node
                if fn_node:
                    imp_funcs[source] += fn_node
                if not fn_node and not cls_node:
                    pass
                    #print(func+' not found in function and class definitions.')
    return imp_funcs,imp_classes