1
+ //! Sourcemap generation utils
2
+ //!
3
+ //! # What are sourcemaps ?
4
+ //!
5
+ //! Sourcemaps are a tool of web development that helps debugging when working
6
+ //! with code that is generated from other code.
7
+ //!
8
+ //! A sourcemap is essentially a list of positions in a target file (the
9
+ //! code generated by the tool - in our case JavaScript) linked to a location
10
+ //! in the source code (Gleam) that is responsible for its presence.
11
+
1
12
use sourcemap:: SourceMapBuilder ;
2
13
3
14
use crate :: line_numbers:: LineColumn ;
4
15
16
+ /// Tells whether or not the codegen should emit sourcemaps for all Gleam
17
+ /// modules
5
18
#[ derive( Debug , Clone , Copy ) ]
6
19
pub enum SourceMapSupport {
7
20
Emit ,
8
21
None ,
9
22
}
10
23
24
+ /// An utility that handles the emission of an associated sourcemap
25
+ /// for a given Gleam module.
11
26
pub enum SourceMapEmitter {
12
27
Null ,
13
28
Emit ( Box < SourceMapBuilder > ) ,
@@ -24,6 +39,8 @@ impl std::fmt::Debug for SourceMapEmitter {
24
39
}
25
40
26
41
impl SourceMapEmitter {
42
+ /// Adds one mapping on the generated (javascript) file
43
+ /// referring to the given Gleam source location
27
44
pub fn add_mapping (
28
45
& mut self ,
29
46
generated_code_line : u32 ,
@@ -47,6 +64,32 @@ impl SourceMapEmitter {
47
64
}
48
65
}
49
66
67
+ /// Consumes the SourceMapEmitter to get the content of the sourcemap as a
68
+ /// String
69
+ pub fn maybe_emit_sourcemap_content ( self ) -> Option < String > {
70
+ match self {
71
+ SourceMapEmitter :: Null => None ,
72
+ SourceMapEmitter :: Emit ( builder) => {
73
+ let sourcemap = builder. into_sourcemap ( ) ;
74
+ let mut output = Vec :: new ( ) ;
75
+ // We first write to a vector then build a string, hoping that
76
+ // the `sourcemap` crate generated a valid sourcemap. If it
77
+ // did not, it is a bug that should be reported.
78
+ //
79
+ // SourceMap currently does not support being written directly
80
+ // to a string.
81
+ sourcemap
82
+ . to_writer ( & mut output)
83
+ . expect ( "Failed to write sourcemap to memory." ) ;
84
+ let content =
85
+ String :: from_utf8 ( output) . expect ( "Sourcemap did not generate valid UTF-8." ) ;
86
+ Some ( content)
87
+ }
88
+ }
89
+ }
90
+
91
+ /// Creates a null SourceMapEmitter.
92
+ /// Any operation on this SourceMapEmitter will be no-ops
50
93
pub fn null ( ) -> Self {
51
94
SourceMapEmitter :: Null
52
95
}
0 commit comments