File: SourceMapTestCase.java

package info (click to toggle)
closure-compiler 20130227%2Bdfsg1-10.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,792 kB
  • sloc: java: 175,338; javascript: 20,728; xml: 371; makefile: 19; sh: 6
file content (320 lines) | stat: -rw-r--r-- 9,626 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright 2011 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.debugging.sourcemap;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.SourceFile;
import com.google.javascript.jscomp.SourceMap;
import com.google.javascript.jscomp.SourceMap.DetailLevel;

import junit.framework.TestCase;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author johnlenz@google.com (John Lenz)
 */
public abstract class SourceMapTestCase extends TestCase {

  private boolean validateColumns = true;

  public SourceMapTestCase() {
  }

  void disableColumnValidation() {
    validateColumns = false;
  }


  static final List<SourceFile> EXTERNS = ImmutableList.of(
      SourceFile.fromCode("externs", ""));

  protected DetailLevel detailLevel = SourceMap.DetailLevel.ALL;

  protected static class RunResult {
      String generatedSource;
      SourceMap sourceMap;
      public String sourceMapFileContent;
    }

  protected static class Token {
      final String tokenName;
      final String inputName;
      final FilePosition position;
      Token(String tokenName, String inputName, FilePosition position) {
        this.tokenName = tokenName;
        this.inputName = inputName;
        this.position = position;
      }
    }

  @Override
  public void setUp() {
    detailLevel = SourceMap.DetailLevel.ALL;
  }

  /**
   * Creates a source map for the given JS code and asserts it is
   * equal to the expected golden map.
   */
  protected void checkSourceMap(String js, String expectedMap)
      throws IOException {
    checkSourceMap("testcode", js, expectedMap);
  }

  protected String getSourceMap(RunResult result) throws IOException {
    StringBuilder sb = new StringBuilder();
    result.sourceMap.appendTo(sb, "testcode");
    return sb.toString();
  }

  protected void checkSourceMap(String fileName, String js, String expectedMap)
      throws IOException {
    RunResult result = compile(js, fileName);
    assertEquals(expectedMap, result.sourceMapFileContent);
    assertEquals(result.sourceMapFileContent, getSourceMap(result));
  }

  /**
   * Finds the all the __XX__ tokens in the given JavaScript
   * string.
   */
  private Map<String, Token> findTokens(Map<String, String> inputs) {
    Map<String, Token> tokens = Maps.newLinkedHashMap();

    for (Entry<String, String> entry : inputs.entrySet()) {
      findTokens(tokens, entry.getKey(), entry.getValue());
    }

    return tokens;
  }

  /**
   * Finds the all the __XX__ tokens in the given JavaScript
   * string.
   */
  private Map<String, Token> findTokens(String src) {
    Map<String, Token> tokens = Maps.newLinkedHashMap();

    findTokens(tokens, "", src);

    return tokens;
  }

  /**
   * Finds the all the __XX__ tokens in the given JavaScript
   * string.
   */
  private Map<String, Token> findTokens(
    Map<String, Token> tokens, String inputName, String js) {

    int currentLine = 0;
    int positionOffset = 0;

    for (int i = 0; i < js.length(); ++i) {
      char current = js.charAt(i);

      if (current == '\n') {
        positionOffset = i + 1;
        currentLine++;
        continue;
      }

      if (current == '_' && (i < js.length() - 5)) {
        // Check for the _ token.
        if (js.charAt(i + 1) != '_') {
          continue;
        }

        // Loop until we have another _ token.
        String tokenName = "";

        int j = i + 2;
        for (; j < js.length(); ++j) {
          if (js.charAt(j) == '_') {
            break;
          }

          tokenName += js.charAt(j);
        }

        if (tokenName.length() > 0) {
          int currentPosition = i - positionOffset;
          Token token = new Token(
              tokenName, inputName,
              new FilePosition(currentLine, currentPosition));
          tokens.put(tokenName, token);
        }

        i = j;
      }
    }

    return tokens;
  }

  abstract protected SourceMap.Format getSourceMapFormat();

  abstract protected SourceMapConsumer getSourceMapConsumer();

  protected void compileAndCheck(String js) {
    String inputName = "testcode";
    RunResult result = compile(js, inputName);
    check(inputName, js, result.generatedSource, result.sourceMapFileContent);
  }

  protected void check(
      String inputName, String input, String output,
      String sourceMapFileContent) {
    Map<String, String> inputMap = new LinkedHashMap<String, String>();
    inputMap.put(inputName, input);
    check(inputMap, output, sourceMapFileContent);
  }

  protected void check(
      Map<String, String> originalInputs, String generatedSource,
      String sourceMapFileContent) {
    check(originalInputs, generatedSource, sourceMapFileContent, null);
  }

  protected void check(
      Map<String, String> originalInputs, String generatedSource,
      String sourceMapFileContent, SourceMapSupplier supplier) {
    // Find all instances of the __XXX__ pattern in the original
    // source code.
    Map<String, Token> originalTokens = findTokens(originalInputs);

    // Find all instances of the __XXX__ pattern in the generated
    // source code.
    Map<String, Token> resultTokens = findTokens(generatedSource);

    // Ensure that the generated instances match via the source map
    // to the original source code.

    // Ensure the token counts match.
    assertEquals(originalTokens.size(), resultTokens.size());

    SourceMapping reader;
    try {
      reader = SourceMapConsumerFactory.parse(sourceMapFileContent, supplier);
    } catch (SourceMapParseException e) {
      throw new RuntimeException("unexpected exception", e);
    }

    // Map the tokens from the generated source back to the
    // input source and ensure that the map is correct.
    for (Token token : resultTokens.values()) {
      OriginalMapping mapping = reader.getMappingForLine(
          token.position.getLine() + 1,
          token.position.getColumn() + 1);

      assertNotNull(mapping);

      // Find the associated token in the input source.
      Token inputToken = originalTokens.get(token.tokenName);
      assertNotNull(inputToken);
      assertEquals(mapping.getOriginalFile(), inputToken.inputName);

      // Ensure that the map correctly points to the token (we add 1
      // to normalize versus the Rhino line number indexing scheme).
      assertEquals(mapping.getLineNumber(),
                   inputToken.position.getLine() + 1);

      int start = inputToken.position.getColumn() + 1;
      if (inputToken.tokenName.startsWith("STR")) {
        // include the preceding quote.
        start--;
      }

      if (validateColumns) {
        assertEquals(start, mapping.getColumnPosition());
      }

      // Ensure that if the token name does not being with an 'STR' (meaning a
      // string) it has an original name.
      if (!inputToken.tokenName.startsWith("STR")) {
        assertTrue("missing name for " + inputToken.tokenName,
            !mapping.getIdentifier().isEmpty());
      }

      // Ensure that if the mapping has a name, it matches the token.
      if (!mapping.getIdentifier().isEmpty()) {
        assertEquals(mapping.getIdentifier(),
            "__" + inputToken.tokenName + "__");
      }
    }
  }

  protected RunResult compile(String js, String fileName) {
    return compile(js, fileName, null, null);
  }

  protected CompilerOptions getCompilerOptions() {
    CompilerOptions options = new CompilerOptions();
    options.sourceMapOutputPath = "testcode_source_map.out";
    options.sourceMapFormat = getSourceMapFormat();
    options.sourceMapDetailLevel = detailLevel;
    return options;
  }

  protected RunResult compile(
      String js1, String fileName1, String js2, String fileName2) {
    Compiler compiler = new Compiler();
    CompilerOptions options = getCompilerOptions();

    // Turn on IDE mode to get rid of optimizations.
    options.ideMode = true;

    List<SourceFile> inputs =
        ImmutableList.of(SourceFile.fromCode(fileName1, js1));

    if (js2 != null && fileName2 != null) {
      inputs = ImmutableList.of(
          SourceFile.fromCode(fileName1, js1),
          SourceFile.fromCode(fileName2, js2));
    }

    Result result = compiler.compile(EXTERNS, inputs, options);

    assertTrue("compilation failed", result.success);
    String source = compiler.toSource();

    StringBuilder sb = new StringBuilder();
    try {
      result.sourceMap.validate(true);
      result.sourceMap.appendTo(sb, "testcode");
    } catch (IOException e) {
      throw new RuntimeException("unexpected exception", e);
    }

    RunResult rr = new RunResult();
    rr.generatedSource = source;
    rr.sourceMap = result.sourceMap;
    rr.sourceMapFileContent = sb.toString();
    return rr;
  }

}