Recursively parse out an AST value.  This makes no attempt to load
    modules or reconstruct functions on purpose.  We do not want to
    inadvertently call destructive code.
515667
def ast_value(val, scope, return_name=False):
    '''
    '''
    # :TODO: refactor the hell out of this
    try:
        if isinstance(val, (ast.Assign, ast.Delete)):
            if hasattr(val, 'value'):
                value = ast_value(val.value, scope)
            else:
                value = None
            for t in val.targets:
                name = ast_value(t, scope, return_name=True)
                if isinstance(t.ctx, ast.Del):
                    if name in scope:
                        scope.pop(name)
                elif isinstance(t.ctx, ast.Store):
                    scope[name] = value
            return
        elif isinstance(val, ast.Expr) and isinstance(val.value, ast.Name):
            return ast_value(val.value)

        if isinstance(val, ast.Name):
            if isinstance(val.ctx, ast.Load):
                if val.id == 'None':
                    return None
                elif val.id == 'True':
                    return True
                elif val.id == 'False':
                    return False

                if val.id in scope:
                    return scope[val.id]

                if return_name:
                    return val.id
            elif isinstance(val.ctx, ast.Store):
                if return_name:
                    return val.id
            return None

        if isinstance(val, ast.Subscript):
            toslice = ast_value(val.value, scope)
            theslice = ast_value(val.slice, scope)
            return toslice[theslice]
        elif isinstance(val, ast.Index):
            return ast_value(val.value, scope)
        elif isinstance(val, ast.Slice):
            lower = ast_value(val.lower)
            upper = ast_value(val.upper)
            step = ast_value(val.step)
            return slice(lower, upper, step)

        if isinstance(val, list):
            return [ast_value(x, scope) for x in val]
        elif isinstance(val, tuple):
            return tuple(ast_value(x, scope) for x in val)

        if isinstance(val, ast.Attribute):
            name = ast_value(val.value, scope, return_name=True)
            if isinstance(val.ctx, ast.Load):
                return '.'.join((name, val.attr))
            if return_name:
                return name
        elif isinstance(val, ast.keyword):
            return {val.arg: ast_value(val.value, scope)}
        elif isinstance(val, ast.List):
            return [ast_value(x, scope) for x in val.elts]
        elif isinstance(val, ast.Tuple):
            return tuple(ast_value(x, scope) for x in val.elts)
        elif isinstance(val, ast.Dict):
            return dict(zip([ast_value(x, scope) for x in val.keys],
                            [ast_value(x, scope) for x in val.values]))
        elif isinstance(val, ast.Num):
            return val.n
        elif isinstance(val, ast.Str):
            return val.s
        elif hasattr(ast, 'Bytes') and isinstance(val, ast.Bytes):
            return bytes(val.s)
    except Exception:
        # Don't care, just return None
        pass

    return None
1327467
protected AstNode value() throws ScanException, ParseException {
		boolean lvalue = true;
		AstNode v = nonliteral();
		if (v == null) {
			v = literal();
			if (v == null) {
				return null;
			}
			lvalue = false;
		}
		while (true) {
			switch (token.getSymbol()) {
				case DOT:
					consumeToken();
					String name = consumeToken(IDENTIFIER).getImage();
					AstDot dot = createAstDot(v, name, lvalue);
					if (token.getSymbol() == LPAREN && context.isEnabled(METHOD_INVOCATIONS)) {
						v = createAstMethod(dot, params());
					} else {
						v = dot;
					}
					break;
				case LBRACK:
					consumeToken();
					AstNode property = expr(true);
					boolean strict = !context.isEnabled(NULL_PROPERTIES);
					consumeToken(RBRACK);
					AstBracket bracket = createAstBracket(v, property, lvalue, strict);
					if (token.getSymbol() == LPAREN && context.isEnabled(METHOD_INVOCATIONS)) {
						v = createAstMethod(bracket, params());
					} else {
						v = bracket;
					}
					break;
				default:
					return v;
			}
		}
	}
477990
function rpnToTree(values) {
    let ii, len, op, stack, slice, count;

    stack = [];
    // result = [];
    for (ii = 0, len = values.length; ii < len; ii++) {
        op = values[ii];

        if (op === LEFT_PAREN) {
            // cut out this sub and convert it to a tree
            slice = findMatchingRightParam(values, ii);

            if (!slice || slice.length === 0) {
                throw new Error('mismatch parentheses');
            }

            ii += slice.length + 1;

            // evaluate this sub command before pushing it to the stack
            slice = rpnToTree(slice);

            stack.push(slice);
        } else {
            if (Array.isArray(op)) {
                stack.push(op);
            } else {
                // figure out how many arguments to take from the stack
                count = argCount(op);

                slice = stack.splice(stack.length - count, count);

                if (Array.isArray(slice) && slice.length === 1) {
                    slice = arrayFlatten(slice, true);
                }

                // TODO: ugh, occasionally args will get flattened too much
                if (slice[0] === VALUE) {
                    // note only happens with ALIAS_GET
                    // log.debug('overly flat ' + JSON.stringify([op].concat(slice)));
                    slice = [slice];
                }
                stack.push([op].concat(slice));
            }
        }
    }

    return stack;
}
185341
def on_subscript(self, node):    # ('value', 'slice', 'ctx')
        """"""
        val = self.run(node.value)
        nslice = self.run(node.slice)
        ctx = node.ctx.__class__
        if ctx in (ast.Load, ast.Store):
            if isinstance(node.slice, (ast.Index, ast.Slice, ast.Ellipsis)):
                return val.__getitem__(nslice)
            elif isinstance(node.slice, ast.ExtSlice):
                return val[nslice]
        else:
            msg = "subscript with unknown context"
            self.raise_exception(node, msg=msg)
650355
function parse(obj, objType, stack) {
  			stack = stack || [];
  			var res,
  			    parser,
  			    parserType,
  			    objIndex = stack.indexOf(obj);

  			if (objIndex !== -1) {
  				return "recursion(" + (objIndex - stack.length) + ")";
  			}

  			objType = objType || this.typeOf(obj);
  			parser = this.parsers[objType];
  			parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser);

  			if (parserType === "function") {
  				stack.push(obj);
  				res = parser.call(this, obj, stack);
  				stack.pop();
  				return res;
  			}
  			return parserType === "string" ? parser : this.parsers.error;
  		}
811968
def parse_expr(expr, local_dict=None):
    
    if local_dict is None:
        local_dict = {}
    if expr["type"] == "Add":
        return add([parse_expr(arg, local_dict) for arg in expr["args"]])
    elif expr["type"] == "Mul":
        return mul([parse_expr(arg, local_dict) for arg in expr["args"]])
    elif expr["type"] == "Pow":
        return Pow(parse_expr(arg, local_dict) for arg in expr["args"])
    elif expr["type"] == "Symbol":
        try:
            return local_dict[expr["name"]]
        except KeyError:
            return symbolics.Symbol(expr["name"])
    elif expr["type"] == "Number":
        return symbolics.sympify(expr["value"])
    else:
        raise NotImplementedError(expr["type"] + " is not implemented")
846769
def parse(code, mode='exec', **exception_kwargs):
    """"""

    try:
        return _ast_util.parse(code, '<unknown>', mode)
    except Exception:
        raise exceptions.SyntaxException(
                    "(%s) %s (%r)" % (
                        compat.exception_as().__class__.__name__,
                        compat.exception_as(),
                        code[0:50]
                    ), **exception_kwargs)
521291
def parse_value(cls, value, cast):
        
        if cast is None:
            return value
        elif cast is bool:
            try:
                value = int(value) != 0
            except ValueError:
                value = value.lower() in cls.BOOLEAN_TRUE_STRINGS
        elif isinstance(cast, list):
            value = list(map(cast[0], [x for x in value.split(',') if x]))
        elif isinstance(cast, tuple):
            val = value.strip('(').strip(')').split(',')
            value = tuple(map(cast[0], [x for x in val if x]))
        elif isinstance(cast, dict):
            key_cast = cast.get('key', str)
            value_cast = cast.get('value', str)
            value_cast_by_key = cast.get('cast', dict())
            value = dict(map(
                lambda kv: (
                    key_cast(kv[0]),
                    cls.parse_value(kv[1], value_cast_by_key.get(kv[0], value_cast))
                ),
                [val.split('=') for val in value.split(';') if val]
            ))
        elif cast is dict:
            value = dict([val.split('=') for val in value.split(',') if val])
        elif cast is list:
            value = [x for x in value.split(',') if x]
        elif cast is tuple:
            val = value.strip('(').strip(')').split(',')
            value = tuple([x for x in val if x])
        elif cast is float:
            # clean string
            float_str = re.sub(r'[^\d,\.]', '', value)
            # split for avoid thousand separator and different locale comma/dot symbol
            parts = re.split(r'[,\.]', float_str)
            if len(parts) == 1:
                float_str = parts[0]
            else:
                float_str = "{0}.{1}".format(''.join(parts[0:-1]), parts[-1])
            value = float(float_str)
        else:
            value = cast(value)
        return value
759200
def parse_namevalue(nameval, sep: ':', default: nil, symbolize: true)
			name,*val=nameval.split(sep)
			if val.empty?
				value=default
				if default == true
					#special case where if name begins by no- we return false
					name.to_s.match(/^no-(.*)$/) do |m| 
						name=m[1]
						value=false
					end
				end
			else
				value=val.join(sep)
			end
			name=name.to_sym if symbolize
			return name,value
		end
1016499
def parse_args(string):
    
    import ast
    is_quoted = False
    result_parts = []
    current_str = ""
    while len(string) > 0:
        if string[0] == "\"":
            is_quoted = not is_quoted
            current_str += string[0]
        elif string[0].isspace():
            if is_quoted:
                current_str += string[0]
            else:
                result_parts.append(current_str)
                current_str = ""
            # end if
        else:
            current_str += string[0]
        # end if
        string = string[1:]
    # end while
    if current_str:  # last part of the array
        result_parts.append(current_str)
    # end if
    for i in range(len(result_parts)):
        # Will try for each element if it is something pythonic. Parsed type will replace original list element.
        try:
            part = ast.literal_eval(result_parts[i])
            result_parts[i] = part  # write it back.
        except ValueError:
            # could not parse -> is string
            pass  # because already is str.
        # end try
    # end for
    return result_parts
298246
def p_value_paren(self, tree):
        ''' '''
        tree.value = convertstr(tree[1].value)
        tree.svalue = "(%s)"%str(tree[1].value)
37018
def parse():
    
    from fortpy.code import CodeParser
    c = CodeParser()
    
    if args["verbose"]:
        c.verbose = True

    f90files = {}
    c.scan_path(args["source"], f90files)
    for fname, fpath in f90files.items():
        if fname not in c._modulefiles:
            c._modulefiles[fname] = []
        c._parse_from_file(fpath, fname, args["recursive"], args["recursive"], False)

    return c
109464
function(ast) {
        var self = this;

        var found;
        var meta = ast;
        var values = {};

        jsstana.traverse(ast, function(node) {
            if (!found) {
                var match = jsstana.match('(ident META)', node);

                if (match) {
                    jsstana.traverse(meta, function(node) {
                        if (!found) {
                            match = jsstana.match('(return)', node) || jsstana.match('(object)', node);

                            if (match) {
                                values = self._extractObjectValues(['path', 'fullPath', 'condition', 'group'], node);

                                found = true;
                            }
                        }
                    });

                } else {
                    meta = node;
                }
            }
        });

        return values;
    }
628378
def deparse_code2str(code, out=sys.stdout, version=None,
                     debug_opts=DEFAULT_DEBUG_OPTS,
                     code_objects={}, compile_mode='exec',
                     is_pypy=IS_PYPY, walker=SourceWalker):
    
    return deparse_code(version, code, out, showasm=debug_opts.get('asm', None),
                        showast=debug_opts.get('tree', None),
                        showgrammar=debug_opts.get('grammar', None), code_objects=code_objects,
                        compile_mode=compile_mode, is_pypy=is_pypy, walker=walker).text
685342
def restore__ast(_ast):
    
    if hasattr(_ast, 'AST'):
        return
    _ast.PyCF_ONLY_AST = 2 << 9
    m = compile("""\
def foo(): pass
class Bar(object): pass
if False: pass
baz = 'mako'
1 + 2 - 3 * 4 / 5
6 // 7 % 8 << 9 >> 10
11 & 12 ^ 13 | 14
15 and 16 or 17
-baz + (not +18) - ~17
baz and 'foo' or 'bar'
(mako is baz == baz) is not baz != mako
mako > baz < mako >= baz <= mako
mako in baz not in mako""", '<unknown>', 'exec', _ast.PyCF_ONLY_AST)
    _ast.Module = type(m)

    for cls in _ast.Module.__mro__:
        if cls.__name__ == 'mod':
            _ast.mod = cls
        elif cls.__name__ == 'AST':
            _ast.AST = cls

    _ast.FunctionDef = type(m.body[0])
    _ast.ClassDef = type(m.body[1])
    _ast.If = type(m.body[2])

    _ast.Name = type(m.body[3].targets[0])
    _ast.Store = type(m.body[3].targets[0].ctx)
    _ast.Str = type(m.body[3].value)

    _ast.Sub = type(m.body[4].value.op)
    _ast.Add = type(m.body[4].value.left.op)
    _ast.Div = type(m.body[4].value.right.op)
    _ast.Mult = type(m.body[4].value.right.left.op)

    _ast.RShift = type(m.body[5].value.op)
    _ast.LShift = type(m.body[5].value.left.op)
    _ast.Mod = type(m.body[5].value.left.left.op)
    _ast.FloorDiv = type(m.body[5].value.left.left.left.op)

    _ast.BitOr = type(m.body[6].value.op)
    _ast.BitXor = type(m.body[6].value.left.op)
    _ast.BitAnd = type(m.body[6].value.left.left.op)

    _ast.Or = type(m.body[7].value.op)
    _ast.And = type(m.body[7].value.values[0].op)

    _ast.Invert = type(m.body[8].value.right.op)
    _ast.Not = type(m.body[8].value.left.right.op)
    _ast.UAdd = type(m.body[8].value.left.right.operand.op)
    _ast.USub = type(m.body[8].value.left.left.op)

    _ast.Or = type(m.body[9].value.op)
    _ast.And = type(m.body[9].value.values[0].op)

    _ast.IsNot = type(m.body[10].value.ops[0])
    _ast.NotEq = type(m.body[10].value.ops[1])
    _ast.Is = type(m.body[10].value.left.ops[0])
    _ast.Eq = type(m.body[10].value.left.ops[1])

    _ast.Gt = type(m.body[11].value.ops[0])
    _ast.Lt = type(m.body[11].value.ops[1])
    _ast.GtE = type(m.body[11].value.ops[2])
    _ast.LtE = type(m.body[11].value.ops[3])

    _ast.In = type(m.body[12].value.ops[0])
    _ast.NotIn = type(m.body[12].value.ops[1])
9278
def from_str(cls, s):
        """"""
        ast_obj = ast.parse(s).body[0]
        if not isinstance(ast_obj, cls._expected_ast_type):
            raise AssertionError(
                'Expected ast of type {!r} but got {!r}'.format(
                    cls._expected_ast_type,
                    ast_obj
                )
            )
        return cls(ast_obj)
618591
def parse_value_reference(parser, event, node): #pylint: disable=unused-argument

    

    (next_event, next_node) = six.next(parser)

    # TODO 2/16 KS: Functions below do not exist: i.e. class stuff broken:
    #               parse_classpath, parse_localclasspath, parse_classname.

    if _is_start(next_event, next_node, 'CLASSPATH'):
        result = parse_classpath(parser, next_event, next_node)

    elif _is_start(next_event, next_node, 'LOCALCLASSPATH'):
        result = parse_localclasspath(parser, next_event, next_node)

    elif _is_start(next_event, next_node, 'CLASSNAME'):
        result = parse_classname(parser, next_event, next_node)

    elif _is_start(next_event, next_node, 'INSTANCEPATH'):
        result = parse_instancepath(parser, next_event, next_node)

    elif _is_start(next_event, next_node, 'LOCALINSTANCEPATH'):
        result = parse_localinstancepath(parser, next_event, next_node)

    elif _is_start(next_event, next_node, 'INSTANCENAME'):
        result = parse_instancename(parser, next_event, next_node)

    else:
        raise ParseError('Expecting (CLASSPATH | LOCALCLASSPATH | CLASSNAME '
                         '| INSTANCEPATH | LOCALINSTANCEPATH | INSTANCENAME)')

    _get_end_event(parser, 'VALUE.REFERENCE')

    return result