Debian Codegraph @

src/com/google/javascript/jscomp/JsMessage.java

raw symbols SCIP
1 /*
2 * Copyright 2006 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Sets;
22
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import javax.annotation.Nullable;
30
31 /**
32 * A representation of a translatable message in JavaScript source code.
33 *
34 * <p>Instances are created using a {@link JsMessage.Builder},
35 * like this:
36 * <pre>
37 * JsMessage m = new JsMessage.Builder(key)
38 * .appendPart("Hi ")
39 * .appendPlaceholderReference("firstName")
40 * .appendPart("!")
41 * .setDesc("A welcome message")
42 * .build();
43 * </pre>
44 *
45 */
46 public class JsMessage {
47
48 /**
49 * Message style that could be used for JS code parsing.
50 * The enum order is from most relaxed to most restricted.
51 */
52 public enum Style {
53 LEGACY, // All legacy code is completely OK
54 RELAX, // You allowed to use legacy code but it would be reported as warn
55 CLOSURE; // Any legacy code is prohibited
56
57 /**
58 * Calculates current messages {@link Style} based on the given arguments.
59 *
60 * @param useClosure if true then use closure style, otherwise not
61 * @param allowLegacyMessages if true then allow legacy messages otherwise
62 * not
63 * @return the message style based on the given arguments
64 */
65 static Style getFromParams(boolean useClosure,
66 boolean allowLegacyMessages) {
67 if (useClosure) {
68 return allowLegacyMessages ? RELAX : CLOSURE;
69 } else {
70 return LEGACY;
71 }
72 }
73 }
74
75 private static final String MESSAGE_REPRESENTATION_FORMAT = "{$%s}";
76
77 private final String key;
78 private final String id;
79 private final List<CharSequence> parts;
80 private final Set<String> placeholders;
81 private final String desc;
82 private final boolean hidden;
83 private final String meaning;
84
85 private final String sourceName;
86 private final boolean isAnonymous;
87 private final boolean isExternal;
88
89 /**
90 * Creates an instance. Client code should use a {@link JsMessage.Builder}.
91 *
92 * @param key a key that should identify this message in sources; typically
93 * it is the message's name (e.g. {@code "MSG_HELLO"}).
94 * @param id an id that *uniquely* identifies the message in the bundle.
95 * It could be either the message name or id generated from the message
96 * content.
97 * @param meaning The user-specified meaning of the message. May be null if
98 * the user did not specify an explicit meaning.
99 */
100 private JsMessage(String sourceName, String key,
101 boolean isAnonymous, boolean isExternal,
102 String id, List<CharSequence> parts, Set<String> placeholders,
103 String desc, boolean hidden, String meaning) {
104
105 Preconditions.checkState(key != null);
106 Preconditions.checkState(id != null);
107
108 this.key = key;
109 this.id = id;
110 this.parts = Collections.unmodifiableList(parts);
111 this.placeholders = Collections.unmodifiableSet(placeholders);
112 this.desc = desc;
113 this.hidden = hidden;
114 this.meaning = meaning;
115
116 this.sourceName = sourceName;
117 this.isAnonymous = isAnonymous;
118 this.isExternal = isExternal;
119 }
120
121 /**
122 * Gets the message's sourceName.
123 */
124 public String getSourceName() {
125 return sourceName;
126 }
127
128 /**
129 * Gets the message's key, or name (e.g. {@code "MSG_HELLO"}).
130 */
131 public String getKey() {
132 return key;
133 }
134
135 public boolean isAnonymous() {
136 return isAnonymous;
137 }
138
139 public boolean isExternal() {
140 return isExternal;
141 }
142
143 /**
144 * Gets the message's id, or name (e.g. {@code "92430284230902938293"}).
145 */
146 public String getId() {
147 return id;
148 }
149
150 /**
151 * Gets the description associated with this message, intended to help
152 * translators, or null if this message has no description.
153 */
154 public String getDesc() {
155 return desc;
156 }
157
158 /**
159 * Gets the meaning annotated to the message, intended to force different
160 * translations.
161 */
162 String getMeaning() {
163 return meaning;
164 }
165
166 /**
167 * Gets whether this message should be hidden from volunteer translators (to
168 * reduce the chances of a new feature leak).
169 */
170 public boolean isHidden() {
171 return hidden;
172 }
173
174 /**
175 * Gets a read-only list of the parts of this message. Each part is either a
176 * {@link String} or a {@link PlaceholderReference}.
177 */
178 public List<CharSequence> parts() {
179 return parts;
180 }
181
182 /** Gets a read-only set of the registered placeholders in this message. */
183 public Set<String> placeholders() {
184 return placeholders;
185 }
186
187 @Override
188 public String toString() {
189 StringBuilder sb = new StringBuilder();
190 for (CharSequence p : parts) {
191 sb.append(p.toString());
192 }
193 return sb.toString();
194 }
195
196 /** @return false iff the message is represented by empty string. */
197 public boolean isEmpty() {
198 for (CharSequence part : parts) {
199 if (part.length() > 0) {
200 return false;
201 }
202 }
203
204 return true;
205 }
206
207 @Override
208 public boolean equals(Object o) {
209 if (o == this) return true;
210 if (!(o instanceof JsMessage)) return false;
211
212 JsMessage m = (JsMessage) o;
213 return id.equals(m.id) &&
214 key.equals(m.key) &&
215 isAnonymous == m.isAnonymous &&
216 parts.equals(m.parts) &&
217 (meaning == null ? m.meaning == null : meaning.equals(m.meaning)) &&
218 placeholders.equals(m.placeholders) &&
219 (desc == null ? m.desc == null : desc.equals(m.desc)) &&
220 (sourceName == null
221 ? m.sourceName == null
222 : sourceName.equals(m.sourceName)) &&
223 hidden == m.hidden;
224 }
225
226 @Override
227 public int hashCode() {
228 int hash = key.hashCode();
229 hash = 31 * hash + (isAnonymous ? 1 : 0);
230 hash = 31 * hash + id.hashCode();
231 hash = 31 * hash + parts.hashCode();
232 hash = 31 * hash + (desc != null ? desc.hashCode() : 0);
233 hash = 31 * hash + (hidden ? 1 : 0);
234 hash = 31 * hash + (sourceName != null ? sourceName.hashCode() : 0);
235 return hash;
236 }
237
238 /** A reference to a placeholder in a translatable message. */
239 public static class PlaceholderReference implements CharSequence {
240
241 private final String name;
242
243 PlaceholderReference(String name) {
244 this.name = name;
245 }
246
247 @Override
248 public int length() {
249 return name.length();
250 }
251
252 @Override
253 public char charAt(int index) {
254 return name.charAt(index);
255 }
256
257 @Override
258 public CharSequence subSequence(int start, int end) {
259 return name.subSequence(start, end);
260 }
261
262 public String getName() {
263 return name;
264 }
265
266 @Override
267 public String toString() {
268 return String.format(MESSAGE_REPRESENTATION_FORMAT, name);
269 }
270
271 @Override
272 public boolean equals(Object o) {
273 return o == this ||
274 o instanceof PlaceholderReference &&
275 name.equals(((PlaceholderReference) o).name);
276 }
277
278 @Override
279 public int hashCode() {
280 return 31 * name.hashCode();
281 }
282 }
283
284 /**
285 * Contains functionality for creating JS messages. Generates authoritative
286 * keys and fingerprints for a message that must stay constant over time.
287 *
288 * This implementation correctly processes unnamed messages and creates a key
289 * for them that looks like MSG_<fingerprint value>.
290 */
291 public static class Builder {
292
293 private static final Pattern MSG_EXTERNAL_PATTERN =
294 Pattern.compile("MSG_EXTERNAL_(\\d+)");
295
296 /**
297 * @return an external message id or null if this is not an
298 * external message identifier
299 */
300 private static String getExternalMessageId(String identifier) {
301 Matcher m = MSG_EXTERNAL_PATTERN.matcher(identifier);
302 return m.matches() ? m.group(1) : null;
303 }
304
305 private String key;
306
307 private String meaning;
308
309 private String desc;
310 private boolean hidden;
311
312 private List<CharSequence> parts = Lists.newLinkedList();
313 private Set<String> placeholders = Sets.newHashSet();
314
315 private String sourceName;
316
317 public Builder() {
318 this(null);
319 }
320
321 /** Creates an instance. */
322 public Builder(String key) {
323 this.key = key;
324 }
325
326 /** Gets the message's key (e.g. {@code "MSG_HELLO"}). */
327 public String getKey() {
328 return key;
329 }
330
331 /**
332 * @param key a key that should uniquely identify this message; typically
333 * it is the message's name (e.g. {@code "MSG_HELLO"}).
334 */
335 public Builder setKey(String key) {
336 this.key = key;
337 return this;
338 }
339
340 /**
341 * @param sourceName The message's sourceName.
342 */
343 public Builder setSourceName(String sourceName) {
344 this.sourceName = sourceName;
345 return this;
346 }
347
348 /**
349 * Appends a placeholder reference to the message
350 */
351 public Builder appendPlaceholderReference(String name) {
352 Preconditions.checkNotNull(name, "Placeholder name could not be null");
353 parts.add(new PlaceholderReference(name));
354 placeholders.add(name);
355 return this;
356 }
357
358 /** Appends a translatable string literal to the message. */
359 public Builder appendStringPart(String part) {
360 Preconditions.checkNotNull(part,
361 "String part of the message could not be null");
362 parts.add(part);
363 return this;
364 }
365
366 /** Returns the message registered placeholders */
367 public Set<String> getPlaceholders() {
368 return placeholders;
369 }
370
371 /** Sets the description of the message, which helps translators. */
372 public Builder setDesc(String desc) {
373 this.desc = desc;
374 return this;
375 }
376
377 /**
378 * Sets the programmer-specified meaning of this message, which
379 * forces this message to translate differently.
380 */
381 public Builder setMeaning(String meaning) {
382 this.meaning = meaning;
383 return this;
384 }
385
386 /** Sets whether the message should be hidden from volunteer translators. */
387 public Builder setIsHidden(boolean hidden) {
388 this.hidden = hidden;
389 return this;
390 }
391
392 /** Gets whether at least one part has been appended. */
393 public boolean hasParts() {
394 return !parts.isEmpty();
395 }
396
397 public List<CharSequence> getParts() {
398 return parts;
399 }
400
401 public JsMessage build() {
402 return build(null);
403 }
404
405 public JsMessage build(IdGenerator idGenerator) {
406 boolean isAnonymous = false;
407 boolean isExternal = false;
408 String id = null;
409
410 if (getKey() == null) {
411 // Before constructing a message we need to change unnamed messages name
412 // to the unique one.
413 key = JsMessageVisitor.MSG_PREFIX + fingerprint(getParts());
414 isAnonymous = true;
415 }
416
417 if (!isAnonymous) {
418 String externalId = getExternalMessageId(key);
419 if (externalId != null) {
420 isExternal = true;
421 id = externalId;
422 }
423 }
424
425 if (!isExternal) {
426 String defactoMeaning = meaning != null ? meaning : key;
427 id = idGenerator == null ? defactoMeaning :
428 idGenerator.generateId(defactoMeaning, parts);
429 }
430
431 return new JsMessage(sourceName, key, isAnonymous, isExternal, id, parts,
432 placeholders, desc, hidden, meaning);
433 }
434
435 /**
436 * Generates a compact uppercase alphanumeric text representation of a
437 * 63-bit fingerprint of the content parts of a message.
438 */
439 private static String fingerprint(List<CharSequence> messageParts) {
440 StringBuilder sb = new StringBuilder();
441 for (CharSequence part : messageParts) {
442 if (part instanceof JsMessage.PlaceholderReference) {
443 sb.append(part.toString());
444 } else {
445 sb.append(part);
446 }
447 }
448 long nonnegativeHash = Long.MAX_VALUE & Hash.hash64(sb.toString());
449 return Long.toString(nonnegativeHash, 36).toUpperCase();
450 }
451 }
452
453 /**
454 * This class contains routines for hashing.
455 *
456 * <p>The hash takes a byte array representing arbitrary data (a
457 * number, String, or Object) and turns it into a small, hopefully
458 * unique, number. There are additional convenience functions which
459 * hash int, long, and String types.
460 *
461 * <p><b>Note</b>: this hash has weaknesses in the two
462 * most-significant key bits and in the three least-significant seed
463 * bits. The weaknesses are small and practically speaking, will not
464 * affect the distribution of hash values. Still, it would be good
465 * practice not to choose seeds 0, 1, 2, 3, ..., n to yield n,
466 * independent hash functions. Use pseudo-random seeds instead.
467 *
468 * <p>This code is based on the work of Craig Silverstein and Sanjay
469 * Ghemawat in, then forked from com.google.common.
470 *
471 * <p>The original code for the hash function is courtesy
472 * <a href="http://burtleburtle.net/bob/hash/evahash.html">Bob Jenkins</a>.
473 *
474 * <p>TODO: Add stream hashing functionality.
475 */
476 final static class Hash {
477 private Hash() {}
478
479 /** Default hash seed (64 bit) */
480 private static final long SEED64 =
481 0x2b992ddfa23249d6L; // part of pi, arbitrary
482
483 /** Hash constant (64 bit) */
484 private static final long CONSTANT64 =
485 0xe08c1d668b756f82L; // part of golden ratio, arbitrary
486
487
488 /******************
489 * STRING HASHING *
490 ******************/
491
492 /**
493 * Hash a string to a 64 bit value. The digits of pi are used for
494 * the hash seed.
495 *
496 * @param value the string to hash
497 * @return 64 bit hash value
498 */
499 static long hash64(@Nullable String value) {
500 return hash64(value, SEED64);
501 }
502
503 /**
504 * Hash a string to a 64 bit value using the supplied seed.
505 *
506 * @param value the string to hash
507 * @param seed the seed
508 * @return 64 bit hash value
509 */
510 private static long hash64(@Nullable String value, long seed) {
511 if (value == null) {
512 return hash64(null, 0, 0, seed);
513 }
514 return hash64(value.getBytes(), seed);
515 }
516
517 /**
518 * Hash byte array to a 64 bit value using the supplied seed.
519 *
520 * @param value the bytes to hash
521 * @param seed the seed
522 * @return 64 bit hash value
523 */
524 private static long hash64(byte[] value, long seed) {
525 return hash64(value, 0, value == null ? 0 : value.length, seed);
526 }
527
528 /**
529 * Hash byte array to a 64 bit value using the supplied seed.
530 *
531 * @param value the bytes to hash
532 * @param offset the starting position of value where bytes are
533 * used for the hash computation
534 * @param length number of bytes of value that are used for the
535 * hash computation
536 * @param seed the seed
537 * @return 64 bit hash value
538 */
539 @SuppressWarnings("fallthrough")
540 private static long hash64(
541 byte[] value, int offset, int length, long seed) {
542 long a = CONSTANT64;
543 long b = a;
544 long c = seed;
545 int keylen;
546
547 for (keylen = length; keylen >= 24; keylen -= 24, offset += 24) {
548 a += word64At(value, offset);
549 b += word64At(value, offset + 8);
550 c += word64At(value, offset + 16);
551
552 // Mix
553 a -= b; a -= c; a ^= c >>> 43;
554 b -= c; b -= a; b ^= a << 9;
555 c -= a; c -= b; c ^= b >>> 8;
556 a -= b; a -= c; a ^= c >>> 38;
557 b -= c; b -= a; b ^= a << 23;
558 c -= a; c -= b; c ^= b >>> 5;
559 a -= b; a -= c; a ^= c >>> 35;
560 b -= c; b -= a; b ^= a << 49;
561 c -= a; c -= b; c ^= b >>> 11;
562 a -= b; a -= c; a ^= c >>> 12;
563 b -= c; b -= a; b ^= a << 18;
564 c -= a; c -= b; c ^= b >>> 22;
565 }
566
567 c += length;
568 switch (keylen) { // deal with rest. Cases fall through
569 case 23:
570 c += ((long) value[offset + 22]) << 56;
571 case 22:
572 c += (value[offset + 21] & 0xffL) << 48;
573 case 21:
574 c += (value[offset + 20] & 0xffL) << 40;
575 case 20:
576 c += (value[offset + 19] & 0xffL) << 32;
577 case 19:
578 c += (value[offset + 18] & 0xffL) << 24;
579 case 18:
580 c += (value[offset + 17] & 0xffL) << 16;
581 case 17:
582 c += (value[offset + 16] & 0xffL) << 8;
583 // the first byte of c is reserved for the length
584 case 16:
585 b += word64At(value, offset + 8);
586 a += word64At(value, offset);
587 break;
588 case 15:
589 b += (value[offset + 14] & 0xffL) << 48;
590 case 14:
591 b += (value[offset + 13] & 0xffL) << 40;
592 case 13:
593 b += (value[offset + 12] & 0xffL) << 32;
594 case 12:
595 b += (value[offset + 11] & 0xffL) << 24;
596 case 11:
597 b += (value[offset + 10] & 0xffL) << 16;
598 case 10:
599 b += (value[offset + 9] & 0xffL) << 8;
600 case 9:
601 b += (value[offset + 8] & 0xffL);
602 case 8:
603 a += word64At(value, offset);
604 break;
605 case 7:
606 a += (value[offset + 6] & 0xffL) << 48;
607 case 6:
608 a += (value[offset + 5] & 0xffL) << 40;
609 case 5:
610 a += (value[offset + 4] & 0xffL) << 32;
611 case 4:
612 a += (value[offset + 3] & 0xffL) << 24;
613 case 3:
614 a += (value[offset + 2] & 0xffL) << 16;
615 case 2:
616 a += (value[offset + 1] & 0xffL) << 8;
617 case 1:
618 a += (value[offset + 0] & 0xffL);
619 // case 0: nothing left to add
620 }
621 return mix64(a, b, c);
622 }
623
624 private static long word64At(byte[] bytes, int offset) {
625 return (bytes[offset + 0] & 0xffL)
626 + ((bytes[offset + 1] & 0xffL) << 8)
627 + ((bytes[offset + 2] & 0xffL) << 16)
628 + ((bytes[offset + 3] & 0xffL) << 24)
629 + ((bytes[offset + 4] & 0xffL) << 32)
630 + ((bytes[offset + 5] & 0xffL) << 40)
631 + ((bytes[offset + 6] & 0xffL) << 48)
632 + ((bytes[offset + 7] & 0xffL) << 56);
633 }
634
635 /**
636 * Mixes longs a, b, and c, and returns the final value of c.
637 */
638 private static long mix64(long a, long b, long c) {
639 a -= b; a -= c; a ^= c >>> 43;
640 b -= c; b -= a; b ^= a << 9;
641 c -= a; c -= b; c ^= b >>> 8;
642 a -= b; a -= c; a ^= c >>> 38;
643 b -= c; b -= a; b ^= a << 23;
644 c -= a; c -= b; c ^= b >>> 5;
645 a -= b; a -= c; a ^= c >>> 35;
646 b -= c; b -= a; b ^= a << 49;
647 c -= a; c -= b; c ^= b >>> 11;
648 a -= b; a -= c; a ^= c >>> 12;
649 b -= c; b -= a; b ^= a << 18;
650 c -= a; c -= b; c ^= b >>> 22;
651 return c;
652 }
653 }
654
655 public interface IdGenerator {
656 /**
657 * Generate the ID for the message. Messages with the same messageParts
658 * and meaning will get the same id. Messages with the same id
659 * will get the same translation.
660 *
661 * @param meaning The programmer-specified meaning. If no {@code @meaning}
662 * annotation appears, we will use the name of the variable it's
663 * assigned to. If the variable is unnamed, then we will just
664 * use a fingerprint of the message.
665 * @param messageParts The parts of the message, including the main
666 * message text.
667 */
668 String generateId(String meaning, List<CharSequence> messageParts);
669 }
670 }