Skip to content

Commit ee22d40

Browse files
committed
utils: source map generator
1 parent b4cfedf commit ee22d40

File tree

1 file changed

+77
-9
lines changed

1 file changed

+77
-9
lines changed

src/utils/source_map_generator.cr

Lines changed: 77 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,89 @@ module MoonScript
2525

2626
getter sources_content = [] of String
2727

28-
getter sources_names = [] of String
28+
getter source_names = [] of String
2929

3030
getter sources = [] of String
3131

32-
def initialize(unsorted: Deque(Mapping), @generated)
33-
unsorted.each do |item|
34-
(mappings[item[1][0]] ||= [] of Mapping) << item
35-
end
32+
getter generated : String
33+
34+
def initialize(unsorted : Deque(Mapping), @generated)
35+
unsorted.each do |item|
36+
(mappings[item[1][0]] ||= [] of Mapping) << item
37+
end
3638
end
3739

3840
def get_source_index(file)
39-
sources.index(file.path) || begin
40-
sources_content << file.contents
41-
sources << file.path
42-
sources.size - 1
41+
sources.index(file.path) || begin
42+
sources_content << file.contents
43+
sources << file.path
44+
sources.size - 1
45+
end
46+
end
47+
48+
def get_source_name_index(value)
49+
source_names.index(value) || begin
50+
source_names << value
51+
source_names.size - 1
52+
end
53+
end
54+
55+
def generate : String
56+
last_name_index = 0
57+
last_column = 0
58+
last_index = 0
59+
last_line = 0
60+
61+
generated_mappings =
62+
(0..generated.lines.size).map do |line_index|
63+
next "" unless items = mappings[line_index]?
64+
65+
items.reduce({[] of String, 0}) do |(memo, last), item|
66+
column =
67+
item[1][1]
68+
69+
segment =
70+
VLQ.encode(column - last)
71+
72+
if node = item[0]
73+
source_line =
74+
node.from.line - 1
75+
76+
source_column =
77+
node.from.column
78+
79+
source_index =
80+
get_source_index(node.file)
81+
82+
segment += VLQ.encode(source_index - last_index)
83+
segment += VLQ.encode(source_line - last_line)
84+
segment += VLQ.encode(source_column - last_column)
85+
86+
if name = item[2]
87+
source_name_index =
88+
get_source_name_index(name)
89+
90+
segment += VLQ.encode(source_name_index - last_name_index)
91+
last_name_index = source_name_index
92+
end
93+
94+
last_column = source_column
95+
last_index = source_index
96+
last_line = source_line
97+
end
98+
99+
memo << segment
100+
{memo, column}
101+
end.first.join(",")
102+
end.join(";")
103+
104+
{
105+
mappings: generated_mappings,
106+
sourcesContent: sources_content,
107+
names: source_names,
108+
sources: sources,
109+
version: 3,
110+
}.to_json
43111
end
44112
end
45113
end

0 commit comments

Comments
 (0)