1ba9a6027dca2bff30b6feb61b9965fef43f2569db53f1532342fc495f02dde8451eb6cbf7afa01490a19b71b3372eb59914d6d61d01fe0584390c09a340c5 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens)
  2. ========
  3. A regex that tokenizes JavaScript.
  4. ```js
  5. var jsTokens = require("js-tokens").default
  6. var jsString = "var foo=opts.foo;\n..."
  7. jsString.match(jsTokens)
  8. // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...]
  9. ```
  10. Installation
  11. ============
  12. `npm install js-tokens`
  13. ```js
  14. import jsTokens from "js-tokens"
  15. // or:
  16. var jsTokens = require("js-tokens").default
  17. ```
  18. Usage
  19. =====
  20. ### `jsTokens` ###
  21. A regex with the `g` flag that matches JavaScript tokens.
  22. The regex _always_ matches, even invalid JavaScript and the empty string.
  23. The next match is always directly after the previous.
  24. ### `var token = matchToToken(match)` ###
  25. ```js
  26. import {matchToToken} from "js-tokens"
  27. // or:
  28. var matchToToken = require("js-tokens").matchToToken
  29. ```
  30. Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type:
  31. String, value: String}` object. The following types are available:
  32. - string
  33. - comment
  34. - regex
  35. - number
  36. - name
  37. - punctuator
  38. - whitespace
  39. - invalid
  40. Multi-line comments and strings also have a `closed` property indicating if the
  41. token was closed or not (see below).
  42. Comments and strings both come in several flavors. To distinguish them, check if
  43. the token starts with `//`, `/*`, `'`, `"` or `` ` ``.
  44. Names are ECMAScript IdentifierNames, that is, including both identifiers and
  45. keywords. You may use [is-keyword-js] to tell them apart.
  46. Whitespace includes both line terminators and other whitespace.
  47. [is-keyword-js]: https://github.com/crissdev/is-keyword-js
  48. ECMAScript support
  49. ==================
  50. The intention is to always support the latest stable ECMAScript version.
  51. If adding support for a newer version requires changes, a new version with a
  52. major verion bump will be released.
  53. Currently, [ECMAScript 2017] is supported.
  54. [ECMAScript 2017]: https://www.ecma-international.org/ecma-262/8.0/index.html
  55. Invalid code handling
  56. =====================
  57. Unterminated strings are still matched as strings. JavaScript strings cannot
  58. contain (unescaped) newlines, so unterminated strings simply end at the end of
  59. the line. Unterminated template strings can contain unescaped newlines, though,
  60. so they go on to the end of input.
  61. Unterminated multi-line comments are also still matched as comments. They
  62. simply go on to the end of the input.
  63. Unterminated regex literals are likely matched as division and whatever is
  64. inside the regex.
  65. Invalid ASCII characters have their own capturing group.
  66. Invalid non-ASCII characters are treated as names, to simplify the matching of
  67. names (except unicode spaces which are treated as whitespace).
  68. Regex literals may contain invalid regex syntax. They are still matched as
  69. regex literals. They may also contain repeated regex flags, to keep the regex
  70. simple.
  71. Strings may contain invalid escape sequences.
  72. Limitations
  73. ===========
  74. Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be
  75. perfect. But that’s not the point either.
  76. You may compare jsTokens with [esprima] by using `esprima-compare.js`.
  77. See `npm run esprima-compare`!
  78. [esprima]: http://esprima.org/
  79. ### Template string interpolation ###
  80. Template strings are matched as single tokens, from the starting `` ` `` to the
  81. ending `` ` ``, including interpolations (whose tokens are not matched
  82. individually).
  83. Matching template string interpolations requires recursive balancing of `{` and
  84. `}`—something that JavaScript regexes cannot do. Only one level of nesting is
  85. supported.
  86. ### Division and regex literals collision ###
  87. Consider this example:
  88. ```js
  89. var g = 9.82
  90. var number = bar / 2/g
  91. var regex = / 2/g
  92. ```
  93. A human can easily understand that in the `number` line we’re dealing with
  94. division, and in the `regex` line we’re dealing with a regex literal. How come?
  95. Because humans can look at the whole code to put the `/` characters in context.
  96. A JavaScript regex cannot. It only sees forwards.
  97. When the `jsTokens` regex scans throught the above, it will see the following
  98. at the end of both the `number` and `regex` rows:
  99. ```js
  100. / 2/g
  101. ```
  102. It is then impossible to know if that is a regex literal, or part of an
  103. expression dealing with division.
  104. Here is a similar case:
  105. ```js
  106. foo /= 2/g
  107. foo(/= 2/g)
  108. ```
  109. The first line divides the `foo` variable with `2/g`. The second line calls the
  110. `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only
  111. sees forwards, it cannot tell the two cases apart.
  112. There are some cases where we _can_ tell division and regex literals apart,
  113. though.
  114. First off, we have the simple cases where there’s only one slash in the line:
  115. ```js
  116. var foo = 2/g
  117. foo /= 2
  118. ```
  119. Regex literals cannot contain newlines, so the above cases are correctly
  120. identified as division. Things are only problematic when there are more than
  121. one non-comment slash in a single line.
  122. Secondly, not every character is a valid regex flag.
  123. ```js
  124. var number = bar / 2/e
  125. ```
  126. The above example is also correctly identified as division, because `e` is not a
  127. valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*`
  128. (any letter) as flags, but it is not worth it since it increases the amount of
  129. ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are
  130. allowed. This means that the above example will be identified as division as
  131. long as you don’t rename the `e` variable to some permutation of `gmiyu` 1 to 5
  132. characters long.
  133. Lastly, we can look _forward_ for information.
  134. - If the token following what looks like a regex literal is not valid after a
  135. regex literal, but is valid in a division expression, then the regex literal
  136. is treated as division instead. For example, a flagless regex cannot be
  137. followed by a string, number or name, but all of those three can be the
  138. denominator of a division.
  139. - Generally, if what looks like a regex literal is followed by an operator, the
  140. regex literal is treated as division instead. This is because regexes are
  141. seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division
  142. could likely be part of such an expression.
  143. Please consult the regex source and the test cases for precise information on
  144. when regex or division is matched (should you need to know). In short, you
  145. could sum it up as:
  146. If the end of a statement looks like a regex literal (even if it isn’t), it
  147. will be treated as one. Otherwise it should work as expected (if you write sane
  148. code).
  149. License
  150. =======
  151. [MIT](LICENSE).