Struct sourcemap::SourceMap

source ·
pub struct SourceMap { /* private fields */ }
Expand description

Represents a sourcemap in memory

This is always represents a regular “non-indexed” sourcemap. Particularly in case the from_reader method is used an index sourcemap will be rejected with an error on reading.

Implementations§

source§

impl SourceMap

source

pub fn from_reader<R: Read>(rdr: R) -> Result<SourceMap>

Creates a sourcemap from a reader over a JSON stream in UTF-8 format. Optionally a “garbage header” as defined by the sourcemap draft specification is supported. In case an indexed sourcemap is encountered an error is returned.

use sourcemap::SourceMap;
let input: &[_] = b"{
    \"version\":3,
    \"sources\":[\"coolstuff.js\"],
    \"names\":[\"x\",\"alert\"],
    \"mappings\":\"AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM\"
}";
let sm = SourceMap::from_reader(input).unwrap();

While sourcemaps objects permit some modifications, it’s generally not possible to modify tokens after they have been added. For creating sourcemaps from scratch or for general operations for modifying a sourcemap have a look at the SourceMapBuilder.

source

pub fn to_writer<W: Write>(&self, w: W) -> Result<()>

Writes a sourcemap into a writer.

Note that this operation will generate an equivalent sourcemap to the one that was generated on load however there might be small differences in the generated JSON and layout. For instance sourceRoot will not be set as upon parsing of the sourcemap the sources will already be expanded.

let sm = SourceMap::from_reader(input).unwrap();
let mut output : Vec<u8> = vec![];
sm.to_writer(&mut output).unwrap();
Examples found in repository?
examples/rewrite.rs (line 46)
37
38
39
40
41
42
43
44
45
46
47
48
49
fn main() {
    let args: Vec<_> = env::args().collect();
    let mut f = fs::File::open(&args[1]).unwrap();
    let sm = load_from_reader(&mut f);
    println!("before dump");
    test(&sm);

    println!("after dump");
    let mut json: Vec<u8> = vec![];
    sm.to_writer(&mut json).unwrap();
    let sm = load_from_reader(json.as_slice());
    test(&sm);
}
More examples
Hide additional examples
examples/split_ram_bundle.rs (line 56)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<_> = env::args().collect();
    if args.len() < 4 {
        println!("{USAGE}");
        std::process::exit(1);
    }

    let bundle_path = Path::new(&args[1]);
    let ram_bundle = RamBundle::parse_indexed_from_path(bundle_path)
        .or_else(|_| RamBundle::parse_unbundle_from_path(bundle_path))?;

    match ram_bundle.bundle_type() {
        RamBundleType::Indexed => println!("Indexed RAM Bundle detected"),
        RamBundleType::Unbundle => println!("File RAM Bundle detected"),
    }

    let sourcemap_file = File::open(&args[2])?;
    let ism = SourceMapIndex::from_reader(sourcemap_file).unwrap();

    let output_directory = Path::new(&args[3]);
    if !output_directory.exists() {
        panic!("Directory {} does not exist!", output_directory.display());
    }

    println!(
        "Ouput directory: {}",
        output_directory.canonicalize()?.display()
    );
    let ram_bundle_iter = split_ram_bundle(&ram_bundle, &ism).unwrap();
    for result in ram_bundle_iter {
        let (name, sv, sm) = result.unwrap();
        println!("Writing down source: {name}");
        fs::write(output_directory.join(name.clone()), sv.source())?;

        let sourcemap_name = format!("{name}.map");
        println!("Writing down sourcemap: {sourcemap_name}");
        let out_sm = File::create(output_directory.join(sourcemap_name))?;
        sm.to_writer(out_sm)?;
    }
    println!("Done.");

    Ok(())
}
source

pub fn from_slice(slice: &[u8]) -> Result<SourceMap>

Creates a sourcemap from a reader over a JSON byte slice in UTF-8 format. Optionally a “garbage header” as defined by the sourcemap draft specification is supported. In case an indexed sourcemap is encountered an error is returned.

use sourcemap::SourceMap;
let input: &[_] = b"{
    \"version\":3,
    \"sources\":[\"coolstuff.js\"],
    \"names\":[\"x\",\"alert\"],
    \"mappings\":\"AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM\"
}";
let sm = SourceMap::from_slice(input).unwrap();
source

pub fn new( file: Option<String>, tokens: Vec<RawToken>, names: Vec<String>, sources: Vec<String>, sources_content: Option<Vec<Option<String>>> ) -> SourceMap

Constructs a new sourcemap from raw components.

  • file: an optional filename of the sourcemap
  • tokens: a list of raw tokens
  • names: a vector of names
  • sources a vector of source filenames
  • sources_content optional source contents
source

pub fn get_debug_id(&self) -> Option<DebugId>

Returns the embedded debug id.

source

pub fn set_debug_id(&mut self, debug_id: Option<DebugId>)

Sets a new value for the debug id.

source

pub fn get_file(&self) -> Option<&str>

Returns the embedded filename in case there is one.

source

pub fn set_file<T: Into<String>>(&mut self, value: Option<T>)

Sets a new value for the file.

source

pub fn get_source_root(&self) -> Option<&str>

Returns the embedded source_root in case there is one.

source

pub fn set_source_root<T: Into<String>>(&mut self, value: Option<T>)

Sets a new value for the source_root.

source

pub fn get_token(&self, idx: u32) -> Option<Token<'_>>

Looks up a token by its index.

source

pub fn get_token_count(&self) -> u32

Returns the number of tokens in the sourcemap.

source

pub fn tokens(&self) -> TokenIter<'_>

Returns an iterator over the tokens.

source

pub fn lookup_token(&self, line: u32, col: u32) -> Option<Token<'_>>

Looks up the closest token to a given 0-indexed line and column.

Examples found in repository?
examples/read.rs (line 36)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn main() {
    let args: Vec<_> = env::args().collect();
    let mut f = fs::File::open(&args[1]).unwrap();
    let sm = load_from_reader(&mut f);

    let line = if args.len() > 2 {
        args[2].parse::<u32>().unwrap()
    } else {
        0
    };
    let column = if args.len() > 3 {
        args[3].parse::<u32>().unwrap()
    } else {
        0
    };

    let token = sm.lookup_token(line, column).unwrap(); // line-number and column
    println!("token: {token}");
}
source

pub fn get_original_function_name<'a>( &self, line: u32, col: u32, minified_name: &str, sv: &'a SourceView<'a> ) -> Option<&str>

Given a location, name and minified source file resolve a minified name to an original function name.

This invokes some guesswork and requires access to the original minified source. This will not yield proper results for anonymous functions or functions that do not have clear function names. (For instance it’s recommended that dotted function names are not passed to this function).

source

pub fn get_source_count(&self) -> u32

Returns the number of sources in the sourcemap.

source

pub fn get_source(&self, idx: u32) -> Option<&str>

Looks up a source for a specific index.

source

pub fn set_source(&mut self, idx: u32, value: &str)

Sets a new source value for an index. This cannot add new sources.

This panics if a source is set that does not exist.

source

pub fn sources(&self) -> SourceIter<'_>

Iterates over all sources

Examples found in repository?
examples/rewrite.rs (line 9)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn test(sm: &SourceMap) {
    for (src_id, source) in sm.sources().enumerate() {
        let path = Path::new(source);
        if path.is_file() {
            let mut f = fs::File::open(path).unwrap();
            let mut contents = String::new();
            if f.read_to_string(&mut contents).ok().is_none() {
                continue;
            }
            if Some(contents.as_str()) != sm.get_source_contents(src_id as u32) {
                println!("  !!! {source}");
            }
        }
    }
}
source

pub fn get_source_view(&self, idx: u32) -> Option<&SourceView<'_>>

Returns the sources content as source view.

source

pub fn get_source_contents(&self, idx: u32) -> Option<&str>

Looks up the content for a source.

Examples found in repository?
examples/rewrite.rs (line 17)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn test(sm: &SourceMap) {
    for (src_id, source) in sm.sources().enumerate() {
        let path = Path::new(source);
        if path.is_file() {
            let mut f = fs::File::open(path).unwrap();
            let mut contents = String::new();
            if f.read_to_string(&mut contents).ok().is_none() {
                continue;
            }
            if Some(contents.as_str()) != sm.get_source_contents(src_id as u32) {
                println!("  !!! {source}");
            }
        }
    }
}
source

pub fn set_source_contents(&mut self, idx: u32, value: Option<&str>)

Sets source contents for a source.

source

pub fn source_contents(&self) -> SourceContentsIter<'_>

Iterates over all source contents

source

pub fn names(&self) -> NameIter<'_>

Returns an iterator over the names.

source

pub fn get_name_count(&self) -> u32

Returns the number of names in the sourcemap.

source

pub fn has_names(&self) -> bool

Returns true if there are any names in the map.

source

pub fn get_name(&self, idx: u32) -> Option<&str>

Looks up a name for a specific index.

source

pub fn remove_names(&mut self)

Removes all names from the sourcemap.

source

pub fn get_index_size(&self) -> usize

Returns the number of items in the index

source

pub fn index_iter(&self) -> IndexIter<'_>

Returns the number of items in the index

source

pub fn rewrite(self, options: &RewriteOptions<'_>) -> Result<SourceMap>

This rewrites the sourcemap according to the provided rewrite options.

The default behavior is to just deduplicate the sourcemap, something that automatically takes place. This for instance can be used to slightly compress sourcemaps if certain data is not wanted.

use sourcemap::{SourceMap, RewriteOptions};
let sm = SourceMap::from_slice(input).unwrap();
let new_sm = sm.rewrite(&RewriteOptions {
    with_names: false,
    ..Default::default()
});

Trait Implementations§

source§

impl Clone for SourceMap

source§

fn clone(&self) -> SourceMap

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for SourceMap

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.