Mercurial > python-compiler.rs
diff src/ast_convert.rs @ 18:51ef651266b1
Fix expr_contexts.
Do not always use Load, get the real context from the node.
author | Bastien Orivel <eijebong@bananium.fr> |
---|---|
date | Fri, 03 Jun 2016 00:10:41 +0200 |
parents | f1c77634a2eb |
children | 0cb53a31ac12 |
line wrap: on
line diff
--- a/src/ast_convert.rs +++ b/src/ast_convert.rs @@ -9,6 +9,28 @@ fn get_str(py: Python, object: PyObject) string.to_mut().to_string() } +fn get_ctx(py: Python, object: PyObject) -> expr_context { + let builtins_module = py.import("builtins").unwrap(); + let isinstance = builtins_module.get(py, "isinstance").unwrap(); + + let is_instance = |object: &PyObject, type_: &PyObject| { + return isinstance.call(py, (object, type_), None).unwrap().is_true(py).unwrap(); + }; + + let ast_module = py.import("ast").unwrap(); + let store_type = ast_module.get(py, "Store").unwrap(); + let load_type = ast_module.get(py, "Load").unwrap(); + + let ctx = object.getattr(py, "ctx").unwrap(); + if is_instance(&ctx, &store_type) { + expr_context::Store + } else if is_instance(&ctx, &load_type) { + expr_context::Load + } else{ + unreachable!(); + } +} + fn parse_expr_vec(py: Python, ast: PyObject) -> Vec<String> { let builtins_module = py.import("builtins").unwrap(); let isinstance = builtins_module.get(py, "isinstance").unwrap(); @@ -224,7 +246,7 @@ fn parse_expr(py: Python, ast: PyObject) if is_instance(&ast, &arg_type) { let arg = ast.getattr(py, "arg").unwrap(); let arg = get_str(py, arg); - expr::Name(arg, expr_context::Load) + expr::Name(arg, get_ctx(py, ast)) } else if is_instance(&ast, &attribute_type) { let value = ast.getattr(py, "value").unwrap(); let attr = ast.getattr(py, "attr").unwrap(); @@ -232,11 +254,11 @@ fn parse_expr(py: Python, ast: PyObject) let value = parse_expr(py, value); let attr = get_str(py, attr); - expr::Attribute(Box::new(value), attr, expr_context::Load) + expr::Attribute(Box::new(value), attr, get_ctx(py, ast)) } else if is_instance(&ast, &name_type) { let id = ast.getattr(py, "id").unwrap(); let id = get_str(py, id); - expr::Name(id, expr_context::Load) + expr::Name(id, get_ctx(py, ast)) } else if is_instance(&ast, &name_constant_type) { let value = ast.getattr(py, "value").unwrap(); let value = get_str(py, value); @@ -258,7 +280,7 @@ fn parse_expr(py: Python, ast: PyObject) elements.push(parse_expr(py, elt)); } - expr::List(elements, expr_context::Load) + expr::List(elements, get_ctx(py, ast)) } else if is_instance(&ast, &unary_op_type) { let op = ast.getattr(py, "op").unwrap(); let operand = ast.getattr(py, "operand").unwrap(); @@ -363,7 +385,7 @@ fn parse_expr(py: Python, ast: PyObject) let elt = parse_expr(py, elt); new_elts.push(elt); } - expr::Tuple(new_elts, expr_context::Load) + expr::Tuple(new_elts, get_ctx(py, ast)) } else { println!("expr {}", ast); unreachable!()