|
| 1 | +#![feature(specialization)] |
| 2 | + |
| 3 | +extern crate pyo3; |
| 4 | +extern crate source_map_mappings; |
| 5 | + |
| 6 | +use std::fs::File; |
| 7 | +use std::io::{BufReader, Read}; |
| 8 | + |
| 9 | +use pyo3::prelude::*; |
| 10 | +use source_map_mappings::{Bias, Mappings, parse_mappings}; |
| 11 | + |
| 12 | +#[pyclass] |
| 13 | +struct SourcemapParser { |
| 14 | + parsed_map: Mappings<()> |
| 15 | +} |
| 16 | + |
| 17 | +#[pymethods] |
| 18 | +impl SourcemapParser { |
| 19 | + #[new] |
| 20 | + fn __new__(obj: &PyRawObject, path: &str) -> PyResult<()> { |
| 21 | + let file = File::open(path).map_err(PyErr::from)?; |
| 22 | + let mut buffers = vec![]; |
| 23 | + let mut reader = BufReader::new(file); |
| 24 | + reader.read_to_end(&mut buffers).map_err(PyErr::from)?; |
| 25 | + let mappings = parse_mappings(&buffers).map_err(|_| PyErr::new::<exc::TypeError, _>(format!("Parse Sourcemap failed: {}", path)))?; |
| 26 | + obj.init(|_| SourcemapParser { |
| 27 | + parsed_map: mappings, |
| 28 | + }) |
| 29 | + } |
| 30 | + |
| 31 | + fn original_location_for(&self, generated_line: u32, generated_column: u32) -> PyResult<(u32, u32)> { |
| 32 | + if let Some(mapping) = self.parsed_map.original_location_for(generated_line, generated_column, Bias::LeastUpperBound) { |
| 33 | + return Ok((mapping.generated_line, mapping.generated_column)) |
| 34 | + } |
| 35 | + Err(PyErr::new::<exc::TypeError, _>("No sources found")) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +#[pymodinit] |
| 40 | +fn py_sourcemap(_py: Python, m: &PyModule) -> PyResult<()> { |
| 41 | + m.add_class::<SourcemapParser>()?; |
| 42 | + Ok(()) |
| 43 | +} |
0 commit comments