1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 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
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! The public JS API to the `source-map-mappings` crate.
//!
//! ## Usage
//!
//! 1. Instantiate the WebAssembly module, supplying a JS implementation of
//! `mapping_callback`.
//!
//! 2. Allocate space for the mappings string with `allocate_mappings`.
//!
//! 3. Initialize the mappings string by copying the JS `String`'s data into it.
//!
//! 4. Parse the mappings with `parse_mappings`. Handle errors, if any.
//!
//! 5. Query the resulting `Mappings` structure as needed with
//! `by_generated_location`, `by_original_location`, `compute_column_spans`,
//! `original_location_for`, `generated_location_for`, and
//! `all_generated_locations_for` as needed.
//!
//! 6. When finished with `Mappings` structure, dispose of it with
//! `free_mappings`.

// NB: every exported function must be `#[no_mangle]` and `pub extern "C"`.

#![deny(missing_docs)]

extern crate source_map_mappings;

use source_map_mappings::{Bias, Error, Mapping, Mappings};
use std::mem;
use std::ptr;
use std::process;
use std::slice;

#[cfg(feature = "profiling")]
mod observer {
    use source_map_mappings;

    macro_rules! define_raii_observer {
        ( $name:ident , $ctor:ident , $dtor:ident ) => {
            #[derive(Debug)]
            pub struct $name;

            impl Default for $name {
                #[inline]
                fn default() -> $name {
                    extern "C" {
                        fn $ctor();
                    }
                    unsafe {
                        $ctor();
                    }
                    $name
                }
            }

            impl Drop for $name {
                #[inline]
                fn drop(&mut self) {
                    extern "C" {
                        fn $dtor();
                    }
                    unsafe {
                        $dtor();
                    }
                }
            }
        }
    }

    define_raii_observer!(ParseMappings, start_parse_mappings, end_parse_mappings);
    define_raii_observer!(
        SortByOriginalLocation,
        start_sort_by_original_location,
        end_sort_by_original_location
    );
    define_raii_observer!(
        SortByGeneratedLocation,
        start_sort_by_generated_location,
        end_sort_by_generated_location
    );
    define_raii_observer!(
        ComputeColumnSpans,
        start_compute_column_spans,
        end_compute_column_spans
    );
    define_raii_observer!(
        OriginalLocationFor,
        start_original_location_for,
        end_original_location_for
    );
    define_raii_observer!(
        GeneratedLocationFor,
        start_generated_location_for,
        end_generated_location_for
    );
    define_raii_observer!(
        AllGeneratedLocationsFor,
        start_all_generated_locations_for,
        end_all_generated_locations_for
    );

    #[derive(Debug, Default)]
    pub struct Observer;

    impl source_map_mappings::Observer for Observer {
        type ParseMappings = ParseMappings;
        type SortByOriginalLocation = SortByOriginalLocation;
        type SortByGeneratedLocation = SortByGeneratedLocation;
        type ComputeColumnSpans = ComputeColumnSpans;
        type OriginalLocationFor = OriginalLocationFor;
        type GeneratedLocationFor = GeneratedLocationFor;
        type AllGeneratedLocationsFor = AllGeneratedLocationsFor;
    }
}

#[cfg(not(feature = "profiling"))]
mod observer {
    pub type Observer = ();
}

use observer::Observer;

static mut LAST_ERROR: Option<Error> = None;

/// Get the last error's error code, or 0 if there was none.
///
/// See `source_map_mappings::Error` for the error code definitions.
#[no_mangle]
pub extern "C" fn get_last_error() -> u32 {
    unsafe {
        match LAST_ERROR {
            None => 0,
            Some(e) => e as u32,
        }
    }
}

#[inline]
fn assert_pointer_is_word_aligned(p: *mut u8) {
    debug_assert_eq!(p as usize & (mem::size_of::<usize>() - 1), 0);
}

/// Allocate space for a mappings string of the given size (in bytes).
///
/// It is the JS callers responsibility to initialize the resulting buffer by
/// copying the JS `String` holding the source map's "mappings" into it (encoded
/// in ascii).
#[no_mangle]
pub extern "C" fn allocate_mappings(size: usize) -> *mut u8 {
    // Make sure that we don't lose any bytes from size in the remainder.
    let size_in_units_of_usize = (size + mem::size_of::<usize>() - 1) / mem::size_of::<usize>();

    // Make room for two additional `usize`s: we'll stuff capacity and length in
    // there.
    let mut vec: Vec<usize> = Vec::with_capacity(size_in_units_of_usize + 2);

    // And do the stuffing.
    let capacity = vec.capacity();
    vec.push(capacity);
    vec.push(size);

    // Leak the vec's elements and get a pointer to them.
    let ptr = vec.as_mut_ptr();
    debug_assert!(!ptr.is_null());
    mem::forget(vec);

    // Advance the pointer past our stuffed data and return it to JS, so that JS
    // can write the mappings string into it.
    let ptr = ptr.wrapping_offset(2) as *mut u8;
    assert_pointer_is_word_aligned(ptr);
    ptr
}

#[inline]
fn constrain<'a, T>(_scope: &'a (), reference: &'a T) -> &'a T
where
    T: ?Sized,
{
    reference
}

/// Parse the given initialized mappings string into a `Mappings` structure.
///
/// Returns `NULL` on failure, or a pointer to the parsed `Mappings` structure
/// on success.
///
/// In the case of failure, the error can be retrieved with `get_last_error`.
///
/// In the case of success, the caller takes ownership of the result, and must
/// call `free_mappings` to destroy it when finished.
///
/// In both the success or failure cases, the caller gives up ownership of the
/// input mappings string and must not use it again.
#[no_mangle]
pub extern "C" fn parse_mappings(mappings: *mut u8) -> *mut Mappings<Observer> {
    assert_pointer_is_word_aligned(mappings);
    let mappings = mappings as *mut usize;

    // Unstuff the data we put just before the pointer to the mappings
    // string.
    let capacity_ptr = mappings.wrapping_offset(-2);
    debug_assert!(!capacity_ptr.is_null());
    let capacity = unsafe { *capacity_ptr };

    let size_ptr = mappings.wrapping_offset(-1);
    debug_assert!(!size_ptr.is_null());
    let size = unsafe { *size_ptr };

    // Construct the input slice from the pointer and parse the mappings.
    let result = unsafe {
        let input = slice::from_raw_parts(mappings as *const u8, size);
        let this_scope = ();
        let input = constrain(&this_scope, input);
        source_map_mappings::parse_mappings(input)
    };

    // Deallocate the mappings string and its two prefix words.
    let size_in_usizes = (size + mem::size_of::<usize>() - 1) / mem::size_of::<usize>();
    unsafe {
        Vec::<usize>::from_raw_parts(capacity_ptr, size_in_usizes + 2, capacity);
    }

    // Return the result, saving any errors on the side for later inspection by
    // JS if required.
    match result {
        Ok(mappings) => Box::into_raw(Box::new(mappings)),
        Err(e) => {
            unsafe {
                LAST_ERROR = Some(e);
            }
            ptr::null_mut()
        }
    }
}

/// Destroy the given `Mappings` structure.
///
/// The caller gives up ownership of the mappings and must not use them again.
#[no_mangle]
pub extern "C" fn free_mappings(mappings: *mut Mappings<Observer>) {
    unsafe {
        Box::from_raw(mappings);
    }
}

#[inline]
unsafe fn mappings_mut<'a>(
    _scope: &'a (),
    mappings: *mut Mappings<Observer>,
) -> &'a mut Mappings<Observer> {
    mappings.as_mut().unwrap()
}

extern "C" {
    fn mapping_callback(
        // These two parameters are always valid.
        generated_line: u32,
        generated_column: u32,

        // The `last_generated_column` parameter is only valid if
        // `has_last_generated_column` is `true`.
        has_last_generated_column: bool,
        last_generated_column: u32,

        // The `source`, `original_line`, and `original_column` parameters are
        // only valid if `has_original` is `true`.
        has_original: bool,
        source: u32,
        original_line: u32,
        original_column: u32,

        // The `name` parameter is only valid if `has_name` is `true`.
        has_name: bool,
        name: u32,
    );
}

#[inline]
unsafe fn invoke_mapping_callback(mapping: &Mapping) {
    let generated_line = mapping.generated_line;
    let generated_column = mapping.generated_column;

    let (has_last_generated_column, last_generated_column) =
        if let Some(last_generated_column) = mapping.last_generated_column {
            (true, last_generated_column)
        } else {
            (false, 0)
        };

    let (has_original, source, original_line, original_column, has_name, name) =
        if let Some(original) = mapping.original.as_ref() {
            let (has_name, name) = if let Some(name) = original.name {
                (true, name)
            } else {
                (false, 0)
            };

            (
                true,
                original.source,
                original.original_line,
                original.original_column,
                has_name,
                name,
            )
        } else {
            (false, 0, 0, 0, false, 0)
        };

    mapping_callback(
        generated_line,
        generated_column,
        has_last_generated_column,
        last_generated_column,
        has_original,
        source,
        original_line,
        original_column,
        has_name,
        name,
    );
}

/// Invoke the `mapping_callback` on each mapping in the given `Mappings`
/// structure, in order of generated location.
#[no_mangle]
pub extern "C" fn by_generated_location(mappings: *mut Mappings<Observer>) {
    let this_scope = ();
    let mappings = unsafe { mappings_mut(&this_scope, mappings) };

    mappings
        .by_generated_location()
        .iter()
        .for_each(|m| unsafe {
            invoke_mapping_callback(m);
        });
}

/// Compute column spans for the given mappings.
#[no_mangle]
pub extern "C" fn compute_column_spans(mappings: *mut Mappings<Observer>) {
    let this_scope = ();
    let mappings = unsafe { mappings_mut(&this_scope, mappings) };

    mappings.compute_column_spans();
}

/// Invoke the `mapping_callback` on each mapping in the given `Mappings`
/// structure that has original location information, in order of original
/// location.
#[no_mangle]
pub extern "C" fn by_original_location(mappings: *mut Mappings<Observer>) {
    let this_scope = ();
    let mappings = unsafe { mappings_mut(&this_scope, mappings) };

    mappings.by_original_location().for_each(|m| unsafe {
        invoke_mapping_callback(m);
    });
}

#[inline]
fn u32_to_bias(bias: u32) -> Bias {
    match bias {
        1 => Bias::GreatestLowerBound,
        2 => Bias::LeastUpperBound,
        otherwise => if cfg!(debug_assertions) {
            panic!(
                "Invalid `Bias = {}`; must be `Bias::GreatestLowerBound = {}` or \
                 `Bias::LeastUpperBound = {}`",
                otherwise,
                Bias::GreatestLowerBound as u32,
                Bias::LeastUpperBound as u32,
            )
        } else {
            process::abort()
        },
    }
}

/// Find the mapping for the given generated location, if any exists.
///
/// If a mapping is found, the `mapping_callback` is invoked with it
/// once. Otherwise, the `mapping_callback` is not invoked at all.
#[no_mangle]
pub extern "C" fn original_location_for(
    mappings: *mut Mappings<Observer>,
    generated_line: u32,
    generated_column: u32,
    bias: u32,
) {
    let this_scope = ();
    let mappings = unsafe { mappings_mut(&this_scope, mappings) };
    let bias = u32_to_bias(bias);

    if let Some(m) = mappings.original_location_for(generated_line, generated_column, bias) {
        unsafe {
            invoke_mapping_callback(m);
        }
    }
}

/// Find the mapping for the given original location, if any exists.
///
/// If a mapping is found, the `mapping_callback` is invoked with it
/// once. Otherwise, the `mapping_callback` is not invoked at all.
#[no_mangle]
pub extern "C" fn generated_location_for(
    mappings: *mut Mappings<Observer>,
    source: u32,
    original_line: u32,
    original_column: u32,
    bias: u32,
) {
    let this_scope = ();
    let mappings = unsafe { mappings_mut(&this_scope, mappings) };
    let bias = u32_to_bias(bias);

    if let Some(m) = mappings.generated_location_for(source, original_line, original_column, bias) {
        unsafe {
            invoke_mapping_callback(m);
        }
    }
}

/// Find all mappings for the given original location, and invoke the
/// `mapping_callback` on each of them.
///
/// If `has_original_column` is `true`, then the `mapping_callback` is only
/// invoked with mappings with matching source and original line **and**
/// original column is equal to `original_column`. If `has_original_column` is
/// `false`, then the `original_column` argument is ignored, and the
/// `mapping_callback` is invoked on all mappings with matching source and
/// original line.
#[no_mangle]
pub extern "C" fn all_generated_locations_for(
    mappings: *mut Mappings<Observer>,
    source: u32,
    original_line: u32,
    has_original_column: bool,
    original_column: u32,
) {
    let this_scope = ();
    let mappings = unsafe { mappings_mut(&this_scope, mappings) };

    let original_column = if has_original_column {
        Some(original_column)
    } else {
        None
    };

    for m in mappings.all_generated_locations_for(source, original_line, original_column) {
        unsafe {
            invoke_mapping_callback(m);
        }
    }
}