summaryrefslogtreecommitdiff
path: root/platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMapDecoder.java
blob: c033a6979f09b7fc7a9c9ef063affe1a7cc8a931 (plain)
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
package org.jetbrains.debugger.sourcemap;

import com.google.gson.stream.JsonToken;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.PathUtil;
import com.intellij.util.SmartList;
import com.intellij.util.text.CharSequenceSubSequence;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.JsonReaderEx;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static org.jetbrains.debugger.sourcemap.Base64VLQ.CharIterator;

// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US
public final class SourceMapDecoder {
  public static final int UNMAPPED = -1;

  private static final Comparator<MappingEntry> MAPPING_COMPARATOR_BY_SOURCE_POSITION = new Comparator<MappingEntry>() {
    @Override
    public int compare(MappingEntry o1, MappingEntry o2) {
      if (o1.getSourceLine() == o2.getSourceLine()) {
        return o1.getSourceColumn() - o2.getSourceColumn();
      }
      else {
        return o1.getSourceLine() - o2.getSourceLine();
      }
    }
  };

  public static final Comparator<MappingEntry> MAPPING_COMPARATOR_BY_GENERATED_POSITION = new Comparator<MappingEntry>() {
    @Override
    public int compare(MappingEntry o1, MappingEntry o2) {
      if (o1.getGeneratedLine() == o2.getGeneratedLine()) {
        return o1.getGeneratedColumn() - o2.getGeneratedColumn();
      }
      else {
        return o1.getGeneratedLine() - o2.getGeneratedLine();
      }
    }
  };

  public static SourceMap decode(@NotNull String contents, @NotNull Function<List<String>, SourceResolver> sourceResolverFactory) throws IOException {
    if (contents.isEmpty()) {
      throw new IOException("source map contents cannot be empty");
    }

    CharSequence in = contents;
    if (contents.startsWith(")]}")) {
      in = new CharSequenceSubSequence(contents, contents.indexOf('\n') + 1, contents.length());
    }
    return decode(in, sourceResolverFactory);
  }

  @Nullable
  public static SourceMap decode(@NotNull CharSequence in, @NotNull Function<List<String>, SourceResolver> sourceResolverFactory) throws IOException {
    JsonReaderEx reader = new JsonReaderEx(in);
    List<MappingEntry> mappings = new ArrayList<MappingEntry>();
    return parseMap(reader, 0, 0, mappings, sourceResolverFactory);
  }

  @Nullable
  private static SourceMap parseMap(JsonReaderEx reader,
                                    int line,
                                    int column,
                                    List<MappingEntry> mappings,
                                    @NotNull Function<List<String>, SourceResolver> sourceResolverFactory) throws IOException {
    reader.beginObject();
    String sourceRoot = null;
    JsonReaderEx sourcesReader = null;
    List<String> names = null;
    String encodedMappings = null;
    String file = null;
    int version = -1;
    while (reader.hasNext()) {
      String propertyName = reader.nextName();
      if (propertyName.equals("sections")) {
        throw new IOException("sections is not supported yet");
      }
      else if (propertyName.equals("version")) {
        version = reader.nextInt();
      }
      else if (propertyName.equals("sourceRoot")) {
        sourceRoot = readSourcePath(reader);
      }
      else if (propertyName.equals("sources")) {
        sourcesReader = reader.subReader();
        reader.skipValue();
      }
      else if (propertyName.equals("names")) {
        reader.beginArray();
        if (reader.hasNext()) {
          names = new ArrayList<String>();
          do {
            names.add(reader.nextString(true));
          }
          while (reader.hasNext());
        }
        else {
          names = Collections.emptyList();
        }
        reader.endArray();
      }
      else if (propertyName.equals("mappings")) {
        encodedMappings = reader.nextString();
      }
      else if (propertyName.equals("file")) {
        file = reader.nextString();
      }
      else {
        // skip file or extensions
        reader.skipValue();
      }
    }
    reader.close();

    // check it before other checks, probably it is not sourcemap file
    if (StringUtil.isEmpty(encodedMappings)) {
      // empty map
      return null;
    }

    if (version != 3) {
      throw new IOException("Unsupported sourcemap version: " + version);
    }

    if (sourcesReader == null) {
      throw new IOException("sources is not specified");
    }

    List<String> sources = readSources(sourcesReader, sourceRoot);
    if (sources.isEmpty()) {
      // empty map, meteor can report such ugly maps
      return null;
    }

    @SuppressWarnings("unchecked")
    List<MappingEntry>[] reverseMappingsBySourceUrl = new List[sources.size()];
    readMappings(encodedMappings, line, column, mappings, reverseMappingsBySourceUrl, names);

    MappingList[] sourceToEntries = new MappingList[reverseMappingsBySourceUrl.length];
    for (int i = 0; i < reverseMappingsBySourceUrl.length; i++) {
      List<MappingEntry> entries = reverseMappingsBySourceUrl[i];
      if (entries != null) {
        Collections.sort(entries, MAPPING_COMPARATOR_BY_SOURCE_POSITION);
        sourceToEntries[i] = new SourceMappingList(entries);
      }
    }
    return new SourceMap(file, new GeneratedMappingList(mappings), sourceToEntries, sourceResolverFactory.fun(sources));
  }

  @Nullable
  private static String readSourcePath(JsonReaderEx reader) {
    return PathUtil.toSystemIndependentName(StringUtil.nullize(reader.nextString().trim()));
  }

  private static void readMappings(@NotNull String value,
                                   int line,
                                   int column,
                                   @NotNull List<MappingEntry> mappings,
                                   @NotNull List<MappingEntry>[] reverseMappingsBySourceUrl,
                                   @Nullable List<String> names) {
    if (StringUtil.isEmpty(value)) {
      return;
    }

    CharSequenceIterator charIterator = new CharSequenceIterator(value);
    int sourceIndex = 0;
    List<MappingEntry> reverseMappings = getMapping(reverseMappingsBySourceUrl, sourceIndex);
    int sourceLine = 0;
    int sourceColumn = 0;
    int nameIndex = 0;
    while (charIterator.hasNext()) {
      if (charIterator.peek() == ',') {
        charIterator.next();
      }
      else {
        while (charIterator.peek() == ';') {
          line++;
          column = 0;
          charIterator.next();
          if (!charIterator.hasNext()) {
            return;
          }
        }
      }

      column += Base64VLQ.decode(charIterator);
      if (isSeparator(charIterator)) {
        mappings.add(new UnmappedEntry(line, column));
        continue;
      }

      int sourceIndexDelta = Base64VLQ.decode(charIterator);
      if (sourceIndexDelta != 0) {
        sourceIndex += sourceIndexDelta;
        reverseMappings = getMapping(reverseMappingsBySourceUrl, sourceIndex);
      }
      sourceLine += Base64VLQ.decode(charIterator);
      sourceColumn += Base64VLQ.decode(charIterator);

      MappingEntry entry;
      if (isSeparator(charIterator)) {
        entry = new UnnamedEntry(line, column, sourceIndex, sourceLine, sourceColumn);
      }
      else {
        nameIndex += Base64VLQ.decode(charIterator);
        assert names != null;
        entry = new NamedEntry(names.get(nameIndex), line, column, sourceIndex, sourceLine, sourceColumn);
      }
      reverseMappings.add(entry);
      mappings.add(entry);
    }
  }

  private static List<String> readSources(@NotNull JsonReaderEx reader, @Nullable String sourceRootUrl) {
    reader.beginArray();
    List<String> sources;
    if (reader.peek() == JsonToken.END_ARRAY) {
      sources = Collections.emptyList();
    }
    else {
      sources = new SmartList<String>();
      do {
        String sourceUrl = readSourcePath(reader);
        sourceUrl = StringUtil.isEmpty(sourceRootUrl) ? sourceUrl : (sourceRootUrl + '/' + sourceUrl);
        sources.add(sourceUrl);
      }
      while (reader.hasNext());
    }
    reader.endArray();
    return sources;
  }

  private static List<MappingEntry> getMapping(@NotNull List<MappingEntry>[] reverseMappingsBySourceUrl, int sourceIndex) {
    List<MappingEntry> reverseMappings = reverseMappingsBySourceUrl[sourceIndex];
    if (reverseMappings == null) {
      reverseMappings = new ArrayList<MappingEntry>();
      reverseMappingsBySourceUrl[sourceIndex] = reverseMappings;
    }
    return reverseMappings;
  }

  private static boolean isSeparator(CharSequenceIterator charIterator) {
    if (!charIterator.hasNext()) {
      return true;
    }

    char current = charIterator.peek();
    return current == ',' || current == ';';
  }

  /**
   * Not mapped to a section in the original source.
   */
  private static class UnmappedEntry extends MappingEntry {
    private final int line;
    private final int column;

    UnmappedEntry(int line, int column) {
      this.line = line;
      this.column = column;
    }

    @Override
    public int getGeneratedColumn() {
      return column;
    }

    @Override
    public int getGeneratedLine() {
      return line;
    }

    @Override
    public int getSourceLine() {
      return UNMAPPED;
    }

    @Override
    public int getSourceColumn() {
      return UNMAPPED;
    }
  }

  /**
   * Mapped to a section in the original source.
   */
  private static class UnnamedEntry extends UnmappedEntry {
    private final int source;
    private final int sourceLine;
    private final int sourceColumn;

    UnnamedEntry(int line, int column, int source, int sourceLine, int sourceColumn) {
      super(line, column);

      this.source = source;
      this.sourceLine = sourceLine;
      this.sourceColumn = sourceColumn;
    }

    @Override
    public int getSource() {
      return source;
    }

    @Override
    public int getSourceLine() {
      return sourceLine;
    }

    @Override
    public int getSourceColumn() {
      return sourceColumn;
    }
  }

  /**
   * Mapped to a section in the original source, and is associated with a name.
   */
  private static class NamedEntry extends UnnamedEntry {
    private final String name;

    NamedEntry(String name, int line, int column, int source, int sourceLine, int sourceColumn) {
      super(line, column, source, sourceLine, sourceColumn);
      this.name = name;
    }

    @Override
    public String getName() {
      return name;
    }
  }

  // java CharacterIterator is ugly, next() impl, so, we reinvent
  private static class CharSequenceIterator implements CharIterator {
    private final CharSequence content;
    private final int length;
    private int current = 0;

    CharSequenceIterator(CharSequence content) {
      this.content = content;
      length = content.length();
    }

    @Override
    public char next() {
      return content.charAt(current++);
    }

    char peek() {
      return content.charAt(current);
    }

    @Override
    public boolean hasNext() {
      return current < length;
    }
  }

  private static final class SourceMappingList extends MappingList {
    public SourceMappingList(@NotNull List<MappingEntry> mappings) {
      super(mappings);
    }

    @Override
    public int getLine(@NotNull MappingEntry mapping) {
      return mapping.getSourceLine();
    }

    @Override
    public int getColumn(@NotNull MappingEntry mapping) {
      return mapping.getSourceColumn();
    }

    @Override
    protected Comparator<MappingEntry> getComparator() {
      return MAPPING_COMPARATOR_BY_SOURCE_POSITION;
    }
  }

  private static final class GeneratedMappingList extends MappingList {
    public GeneratedMappingList(List<MappingEntry> mappings) {
      super(mappings);
    }

    @Override
    public int getLine(@NotNull MappingEntry mapping) {
      return mapping.getGeneratedLine();
    }

    @Override
    public int getColumn(@NotNull MappingEntry mapping) {
      return mapping.getGeneratedColumn();
    }

    @Override
    protected Comparator<MappingEntry> getComparator() {
      return MAPPING_COMPARATOR_BY_GENERATED_POSITION;
    }
  }
}