Skip to main content

rust_css_parser/parser/
source.rs

1//! Port of `src/parser/source.ts`.
2
3use crate::parser::linesmap::LineMap;
4use crate::printer::sourcemap::SourceMap;
5use std::cell::{Cell, RefCell};
6use std::rc::Rc;
7
8thread_local! {
9    static SOURCE_ID: Cell<u32> = const { Cell::new(0) };
10}
11
12/// source file
13#[derive(Debug)]
14pub struct SourceFile {
15    pub id: u32,
16    pub file: Option<Rc<str>>,
17    pub line_starts: RefCell<LineMap>,
18    /// content: shared with the tokenizer (no copy). appended by the stream tokenizer
19    pub content: RefCell<Rc<str>>,
20    input_source_map: RefCell<Option<Rc<SourceMap>>>,
21}
22
23impl SourceFile {
24    pub fn new(content: Rc<str>, lines: Vec<u32>, file: Option<Rc<str>>) -> Rc<Self> {
25        let id = SOURCE_ID.with(|s| {
26            let id = s.get();
27            s.set(id + 1);
28            id
29        });
30        Rc::new(Self {
31            id,
32            file,
33            line_starts: RefCell::new(LineMap::new(lines)),
34            content: RefCell::new(content),
35            input_source_map: RefCell::new(None),
36        })
37    }
38
39    /// append content
40    pub fn append(&self, content: &str) {
41        let mut current = self.content.borrow_mut();
42        let mut s = String::with_capacity(current.len() + content.len());
43        s.push_str(&current);
44        s.push_str(content);
45        *current = Rc::from(s);
46    }
47
48    /// set the input source map (a source map object as json, or a data url / json string)
49    pub fn set_input_source_map(&self, input_source_map: Option<&str>) {
50        *self.input_source_map.borrow_mut() = input_source_map.and_then(|s| SourceMap::parse(s).ok()).map(Rc::new);
51    }
52
53    pub fn set_input_source_map_object(&self, map: Option<SourceMap>) {
54        *self.input_source_map.borrow_mut() = map.map(Rc::new);
55    }
56
57    pub fn get_input_source_map(&self) -> Option<Rc<SourceMap>> {
58        self.input_source_map.borrow().clone()
59    }
60}