|
| 1 | +use crate::obj::objiter; |
| 2 | +use crate::obj::objstr::PyStringRef; |
| 3 | +use crate::obj::{objbool, objtype::PyClassRef}; |
| 4 | +use crate::pyobject::{IdProtocol, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue}; |
| 5 | +use crate::VirtualMachine; |
| 6 | + |
| 7 | +use num_bigint::BigInt; |
| 8 | +use std::str::FromStr; |
| 9 | + |
| 10 | +#[pyclass(name = "Scanner")] |
| 11 | +#[derive(Debug)] |
| 12 | +struct JsonScanner { |
| 13 | + strict: bool, |
| 14 | + object_hook: Option<PyObjectRef>, |
| 15 | + object_pairs_hook: Option<PyObjectRef>, |
| 16 | + parse_float: Option<PyObjectRef>, |
| 17 | + parse_int: Option<PyObjectRef>, |
| 18 | + parse_constant: PyObjectRef, |
| 19 | + ctx: PyObjectRef, |
| 20 | +} |
| 21 | + |
| 22 | +impl PyValue for JsonScanner { |
| 23 | + fn class(vm: &VirtualMachine) -> PyClassRef { |
| 24 | + vm.class("_json", "make_scanner") |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +#[pyimpl] |
| 29 | +impl JsonScanner { |
| 30 | + #[pyslot] |
| 31 | + fn tp_new(cls: PyClassRef, ctx: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { |
| 32 | + let strict = objbool::boolval(vm, vm.get_attribute(ctx.clone(), "strict")?)?; |
| 33 | + let object_hook = vm.option_if_none(vm.get_attribute(ctx.clone(), "object_hook")?); |
| 34 | + let object_pairs_hook = |
| 35 | + vm.option_if_none(vm.get_attribute(ctx.clone(), "object_pairs_hook")?); |
| 36 | + let parse_float = vm.get_attribute(ctx.clone(), "parse_float")?; |
| 37 | + let parse_float = if vm.is_none(&parse_float) || parse_float.is(&vm.ctx.types.float_type) { |
| 38 | + None |
| 39 | + } else { |
| 40 | + Some(parse_float) |
| 41 | + }; |
| 42 | + let parse_int = vm.get_attribute(ctx.clone(), "parse_int")?; |
| 43 | + let parse_int = if vm.is_none(&parse_int) || parse_int.is(&vm.ctx.types.int_type) { |
| 44 | + None |
| 45 | + } else { |
| 46 | + Some(parse_int) |
| 47 | + }; |
| 48 | + let parse_constant = vm.get_attribute(ctx.clone(), "parse_constant")?; |
| 49 | + |
| 50 | + Self { |
| 51 | + strict, |
| 52 | + object_hook, |
| 53 | + object_pairs_hook, |
| 54 | + parse_float, |
| 55 | + parse_int, |
| 56 | + parse_constant, |
| 57 | + ctx, |
| 58 | + } |
| 59 | + .into_ref_with_type(vm, cls) |
| 60 | + } |
| 61 | + |
| 62 | + fn parse( |
| 63 | + &self, |
| 64 | + s: &str, |
| 65 | + pystr: PyStringRef, |
| 66 | + idx: usize, |
| 67 | + scan_once: PyObjectRef, |
| 68 | + vm: &VirtualMachine, |
| 69 | + ) -> PyResult { |
| 70 | + let c = s |
| 71 | + .chars() |
| 72 | + .next() |
| 73 | + .ok_or_else(|| objiter::stop_iter_with_value(vm.new_int(idx), vm))?; |
| 74 | + let next_idx = idx + c.len_utf8(); |
| 75 | + match c { |
| 76 | + '"' => { |
| 77 | + // TODO: parse the string in rust |
| 78 | + let parse_str = vm.get_attribute(self.ctx.clone(), "parse_string")?; |
| 79 | + return vm.invoke( |
| 80 | + &parse_str, |
| 81 | + vec![ |
| 82 | + pystr.into_object(), |
| 83 | + vm.new_int(next_idx), |
| 84 | + vm.new_bool(self.strict), |
| 85 | + ], |
| 86 | + ); |
| 87 | + } |
| 88 | + '{' => { |
| 89 | + // TODO: parse the object in rust |
| 90 | + let parse_obj = vm.get_attribute(self.ctx.clone(), "parse_object")?; |
| 91 | + return vm.invoke( |
| 92 | + &parse_obj, |
| 93 | + vec![ |
| 94 | + vm.ctx |
| 95 | + .new_tuple(vec![pystr.into_object(), vm.new_int(next_idx)]), |
| 96 | + vm.new_bool(self.strict), |
| 97 | + scan_once, |
| 98 | + self.object_hook.clone().unwrap_or_else(|| vm.get_none()), |
| 99 | + self.object_pairs_hook |
| 100 | + .clone() |
| 101 | + .unwrap_or_else(|| vm.get_none()), |
| 102 | + ], |
| 103 | + ); |
| 104 | + } |
| 105 | + '[' => { |
| 106 | + // TODO: parse the array in rust |
| 107 | + let parse_array = vm.get_attribute(self.ctx.clone(), "parse_array")?; |
| 108 | + return vm.invoke( |
| 109 | + &parse_array, |
| 110 | + vec![ |
| 111 | + vm.ctx |
| 112 | + .new_tuple(vec![pystr.into_object(), vm.new_int(next_idx)]), |
| 113 | + scan_once, |
| 114 | + ], |
| 115 | + ); |
| 116 | + } |
| 117 | + _ => {} |
| 118 | + } |
| 119 | + |
| 120 | + macro_rules! parse_const { |
| 121 | + ($s:literal, $val:expr) => { |
| 122 | + if s.starts_with($s) { |
| 123 | + return Ok(vm.ctx.new_tuple(vec![$val, vm.new_int(idx + $s.len())])); |
| 124 | + } |
| 125 | + }; |
| 126 | + } |
| 127 | + |
| 128 | + parse_const!("null", vm.get_none()); |
| 129 | + parse_const!("true", vm.new_bool(true)); |
| 130 | + parse_const!("false", vm.new_bool(false)); |
| 131 | + |
| 132 | + if let Some((res, len)) = self.parse_number(s, vm) { |
| 133 | + return Ok(vm.ctx.new_tuple(vec![res?, vm.new_int(idx + len)])); |
| 134 | + } |
| 135 | + |
| 136 | + macro_rules! parse_constant { |
| 137 | + ($s:literal) => { |
| 138 | + if s.starts_with($s) { |
| 139 | + return Ok(vm.ctx.new_tuple(vec![ |
| 140 | + vm.invoke(&self.parse_constant, vec![vm.new_str($s.to_owned())])?, |
| 141 | + vm.new_int(idx + $s.len()), |
| 142 | + ])); |
| 143 | + } |
| 144 | + }; |
| 145 | + } |
| 146 | + |
| 147 | + parse_constant!("NaN"); |
| 148 | + parse_constant!("Infinity"); |
| 149 | + parse_constant!("-Infinity"); |
| 150 | + |
| 151 | + Err(objiter::stop_iter_with_value(vm.new_int(idx), vm)) |
| 152 | + } |
| 153 | + |
| 154 | + fn parse_number(&self, s: &str, vm: &VirtualMachine) -> Option<(PyResult, usize)> { |
| 155 | + let mut has_neg = false; |
| 156 | + let mut has_decimal = false; |
| 157 | + let mut has_exponent = false; |
| 158 | + let mut has_e_sign = false; |
| 159 | + let mut i = 0; |
| 160 | + for c in s.chars() { |
| 161 | + match c { |
| 162 | + '-' if i == 0 => has_neg = true, |
| 163 | + n if n.is_ascii_digit() => {} |
| 164 | + '.' if !has_decimal => has_decimal = true, |
| 165 | + 'e' | 'E' if !has_exponent => has_exponent = true, |
| 166 | + '+' | '-' if !has_e_sign => has_e_sign = true, |
| 167 | + _ => break, |
| 168 | + } |
| 169 | + i += 1; |
| 170 | + } |
| 171 | + if i == 0 || (i == 1 && has_neg) { |
| 172 | + return None; |
| 173 | + } |
| 174 | + let buf = &s[..i]; |
| 175 | + let ret = if has_decimal || has_exponent { |
| 176 | + // float |
| 177 | + if let Some(ref parse_float) = self.parse_float { |
| 178 | + vm.invoke(parse_float, vec![vm.new_str(buf.to_owned())]) |
| 179 | + } else { |
| 180 | + Ok(vm.ctx.new_float(f64::from_str(buf).unwrap())) |
| 181 | + } |
| 182 | + } else if let Some(ref parse_int) = self.parse_int { |
| 183 | + vm.invoke(parse_int, vec![vm.new_str(buf.to_owned())]) |
| 184 | + } else { |
| 185 | + Ok(vm.new_int(BigInt::from_str(buf).unwrap())) |
| 186 | + }; |
| 187 | + Some((ret, buf.len())) |
| 188 | + } |
| 189 | + |
| 190 | + #[pyslot] |
| 191 | + fn call(zelf: PyRef<Self>, pystr: PyStringRef, idx: isize, vm: &VirtualMachine) -> PyResult { |
| 192 | + if idx < 0 { |
| 193 | + return Err(vm.new_value_error("idx cannot be negative".to_owned())); |
| 194 | + } |
| 195 | + let idx = idx as usize; |
| 196 | + let mut chars = pystr.as_str().chars(); |
| 197 | + if idx > 0 { |
| 198 | + chars |
| 199 | + .nth(idx - 1) |
| 200 | + .ok_or_else(|| objiter::stop_iter_with_value(vm.new_int(idx), vm))?; |
| 201 | + } |
| 202 | + zelf.parse( |
| 203 | + chars.as_str(), |
| 204 | + pystr.clone(), |
| 205 | + idx, |
| 206 | + zelf.clone().into_object(), |
| 207 | + vm, |
| 208 | + ) |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { |
| 213 | + let ctx = &vm.ctx; |
| 214 | + let scanner_cls = JsonScanner::make_class(ctx); |
| 215 | + scanner_cls.set_str_attr("__module__", vm.new_str("_json".to_owned())); |
| 216 | + py_module!(vm, "_json", { |
| 217 | + "make_scanner" => scanner_cls, |
| 218 | + }) |
| 219 | +} |
0 commit comments