string-literals.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // string literal characters cannot contain control codes
  2. var CONTROL_CODES = [0, // null
  3. 7, // bell
  4. 8, // backspace
  5. 9, // horizontal
  6. 10, // line feed
  7. 11, // vertical tab
  8. 12, // form feed
  9. 13, // carriage return
  10. 26, // Control-Z
  11. 27, // escape
  12. 127 // delete
  13. ]; // escaped sequences can either be a two character hex value, or one of the
  14. // following single character codes
  15. function decodeControlCharacter(char) {
  16. switch (char) {
  17. case "t":
  18. return 0x09;
  19. case "n":
  20. return 0x0a;
  21. case "r":
  22. return 0x0d;
  23. case '"':
  24. return 0x22;
  25. case "′":
  26. return 0x27;
  27. case "\\":
  28. return 0x5c;
  29. }
  30. return -1;
  31. }
  32. var ESCAPE_CHAR = 92; // backslash
  33. var QUOTE_CHAR = 34; // backslash
  34. // parse string as per the spec:
  35. // https://webassembly.github.io/spec/core/multipage/text/values.html#text-string
  36. export function parseString(value) {
  37. var byteArray = [];
  38. var index = 0;
  39. while (index < value.length) {
  40. var charCode = value.charCodeAt(index);
  41. if (CONTROL_CODES.indexOf(charCode) !== -1) {
  42. throw new Error("ASCII control characters are not permitted within string literals");
  43. }
  44. if (charCode === QUOTE_CHAR) {
  45. throw new Error("quotes are not permitted within string literals");
  46. }
  47. if (charCode === ESCAPE_CHAR) {
  48. var firstChar = value.substr(index + 1, 1);
  49. var decodedControlChar = decodeControlCharacter(firstChar);
  50. if (decodedControlChar !== -1) {
  51. // single character escaped values, e.g. \r
  52. byteArray.push(decodedControlChar);
  53. index += 2;
  54. } else {
  55. // hex escaped values, e.g. \2a
  56. var hexValue = value.substr(index + 1, 2);
  57. if (!/^[0-9A-F]{2}$/i.test(hexValue)) {
  58. throw new Error("invalid character encoding");
  59. }
  60. byteArray.push(parseInt(hexValue, 16));
  61. index += 3;
  62. }
  63. } else {
  64. // ASCII encoded values
  65. byteArray.push(charCode);
  66. index++;
  67. }
  68. }
  69. return byteArray;
  70. }