parser.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = void 0;
  4. var _root = _interopRequireDefault(require("./selectors/root"));
  5. var _selector = _interopRequireDefault(require("./selectors/selector"));
  6. var _className = _interopRequireDefault(require("./selectors/className"));
  7. var _comment = _interopRequireDefault(require("./selectors/comment"));
  8. var _id = _interopRequireDefault(require("./selectors/id"));
  9. var _tag = _interopRequireDefault(require("./selectors/tag"));
  10. var _string = _interopRequireDefault(require("./selectors/string"));
  11. var _pseudo = _interopRequireDefault(require("./selectors/pseudo"));
  12. var _attribute = _interopRequireWildcard(require("./selectors/attribute"));
  13. var _universal = _interopRequireDefault(require("./selectors/universal"));
  14. var _combinator = _interopRequireDefault(require("./selectors/combinator"));
  15. var _nesting = _interopRequireDefault(require("./selectors/nesting"));
  16. var _sortAscending = _interopRequireDefault(require("./sortAscending"));
  17. var _tokenize = _interopRequireWildcard(require("./tokenize"));
  18. var tokens = _interopRequireWildcard(require("./tokenTypes"));
  19. var types = _interopRequireWildcard(require("./selectors/types"));
  20. var _util = require("./util");
  21. var _WHITESPACE_TOKENS, _Object$assign;
  22. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  23. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  24. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  25. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  26. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  27. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  28. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  29. function tokenStart(token) {
  30. return {
  31. line: token[_tokenize.FIELDS.START_LINE],
  32. column: token[_tokenize.FIELDS.START_COL]
  33. };
  34. }
  35. function tokenEnd(token) {
  36. return {
  37. line: token[_tokenize.FIELDS.END_LINE],
  38. column: token[_tokenize.FIELDS.END_COL]
  39. };
  40. }
  41. function getSource(startLine, startColumn, endLine, endColumn) {
  42. return {
  43. start: {
  44. line: startLine,
  45. column: startColumn
  46. },
  47. end: {
  48. line: endLine,
  49. column: endColumn
  50. }
  51. };
  52. }
  53. function getTokenSource(token) {
  54. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  55. }
  56. function getTokenSourceSpan(startToken, endToken) {
  57. if (!startToken) {
  58. return undefined;
  59. }
  60. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  61. }
  62. function unescapeProp(node, prop) {
  63. var value = node[prop];
  64. if (typeof value !== "string") {
  65. return;
  66. }
  67. if (value.indexOf("\\") !== -1) {
  68. (0, _util.ensureObject)(node, 'raws');
  69. node[prop] = (0, _util.unesc)(value);
  70. if (node.raws[prop] === undefined) {
  71. node.raws[prop] = value;
  72. }
  73. }
  74. return node;
  75. }
  76. function indexesOf(array, item) {
  77. var i = -1;
  78. var indexes = [];
  79. while ((i = array.indexOf(item, i + 1)) !== -1) {
  80. indexes.push(i);
  81. }
  82. return indexes;
  83. }
  84. function uniqs() {
  85. var list = Array.prototype.concat.apply([], arguments);
  86. return list.filter(function (item, i) {
  87. return i === list.indexOf(item);
  88. });
  89. }
  90. var Parser = /*#__PURE__*/function () {
  91. function Parser(rule, options) {
  92. if (options === void 0) {
  93. options = {};
  94. }
  95. this.rule = rule;
  96. this.options = Object.assign({
  97. lossy: false,
  98. safe: false
  99. }, options);
  100. this.position = 0;
  101. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  102. this.tokens = (0, _tokenize["default"])({
  103. css: this.css,
  104. error: this._errorGenerator(),
  105. safe: this.options.safe
  106. });
  107. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  108. this.root = new _root["default"]({
  109. source: rootSource
  110. });
  111. this.root.errorGenerator = this._errorGenerator();
  112. var selector = new _selector["default"]({
  113. source: {
  114. start: {
  115. line: 1,
  116. column: 1
  117. }
  118. }
  119. });
  120. this.root.append(selector);
  121. this.current = selector;
  122. this.loop();
  123. }
  124. var _proto = Parser.prototype;
  125. _proto._errorGenerator = function _errorGenerator() {
  126. var _this = this;
  127. return function (message, errorOptions) {
  128. if (typeof _this.rule === 'string') {
  129. return new Error(message);
  130. }
  131. return _this.rule.error(message, errorOptions);
  132. };
  133. };
  134. _proto.attribute = function attribute() {
  135. var attr = [];
  136. var startingToken = this.currToken;
  137. this.position++;
  138. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  139. attr.push(this.currToken);
  140. this.position++;
  141. }
  142. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  143. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  144. }
  145. var len = attr.length;
  146. var node = {
  147. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  148. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  149. };
  150. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  151. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  152. }
  153. var pos = 0;
  154. var spaceBefore = '';
  155. var commentBefore = '';
  156. var lastAdded = null;
  157. var spaceAfterMeaningfulToken = false;
  158. while (pos < len) {
  159. var token = attr[pos];
  160. var content = this.content(token);
  161. var next = attr[pos + 1];
  162. switch (token[_tokenize.FIELDS.TYPE]) {
  163. case tokens.space:
  164. // if (
  165. // len === 1 ||
  166. // pos === 0 && this.content(next) === '|'
  167. // ) {
  168. // return this.expected('attribute', token[TOKEN.START_POS], content);
  169. // }
  170. spaceAfterMeaningfulToken = true;
  171. if (this.options.lossy) {
  172. break;
  173. }
  174. if (lastAdded) {
  175. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  176. var prevContent = node.spaces[lastAdded].after || '';
  177. node.spaces[lastAdded].after = prevContent + content;
  178. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  179. if (existingComment) {
  180. node.raws.spaces[lastAdded].after = existingComment + content;
  181. }
  182. } else {
  183. spaceBefore = spaceBefore + content;
  184. commentBefore = commentBefore + content;
  185. }
  186. break;
  187. case tokens.asterisk:
  188. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  189. node.operator = content;
  190. lastAdded = 'operator';
  191. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  192. if (spaceBefore) {
  193. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  194. node.spaces.attribute.before = spaceBefore;
  195. spaceBefore = '';
  196. }
  197. if (commentBefore) {
  198. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  199. node.raws.spaces.attribute.before = spaceBefore;
  200. commentBefore = '';
  201. }
  202. node.namespace = (node.namespace || "") + content;
  203. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  204. if (rawValue) {
  205. node.raws.namespace += content;
  206. }
  207. lastAdded = 'namespace';
  208. }
  209. spaceAfterMeaningfulToken = false;
  210. break;
  211. case tokens.dollar:
  212. if (lastAdded === "value") {
  213. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  214. node.value += "$";
  215. if (oldRawValue) {
  216. node.raws.value = oldRawValue + "$";
  217. }
  218. break;
  219. }
  220. // Falls through
  221. case tokens.caret:
  222. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  223. node.operator = content;
  224. lastAdded = 'operator';
  225. }
  226. spaceAfterMeaningfulToken = false;
  227. break;
  228. case tokens.combinator:
  229. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  230. node.operator = content;
  231. lastAdded = 'operator';
  232. }
  233. if (content !== '|') {
  234. spaceAfterMeaningfulToken = false;
  235. break;
  236. }
  237. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  238. node.operator = content;
  239. lastAdded = 'operator';
  240. } else if (!node.namespace && !node.attribute) {
  241. node.namespace = true;
  242. }
  243. spaceAfterMeaningfulToken = false;
  244. break;
  245. case tokens.word:
  246. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  247. // this look-ahead probably fails with comment nodes involved.
  248. !node.operator && !node.namespace) {
  249. node.namespace = content;
  250. lastAdded = 'namespace';
  251. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  252. if (spaceBefore) {
  253. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  254. node.spaces.attribute.before = spaceBefore;
  255. spaceBefore = '';
  256. }
  257. if (commentBefore) {
  258. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  259. node.raws.spaces.attribute.before = commentBefore;
  260. commentBefore = '';
  261. }
  262. node.attribute = (node.attribute || "") + content;
  263. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  264. if (_rawValue) {
  265. node.raws.attribute += content;
  266. }
  267. lastAdded = 'attribute';
  268. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  269. var _unescaped = (0, _util.unesc)(content);
  270. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  271. var oldValue = node.value || '';
  272. node.value = oldValue + _unescaped;
  273. node.quoteMark = null;
  274. if (_unescaped !== content || _oldRawValue) {
  275. (0, _util.ensureObject)(node, 'raws');
  276. node.raws.value = (_oldRawValue || oldValue) + content;
  277. }
  278. lastAdded = 'value';
  279. } else {
  280. var insensitive = content === 'i' || content === "I";
  281. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  282. node.insensitive = insensitive;
  283. if (!insensitive || content === "I") {
  284. (0, _util.ensureObject)(node, 'raws');
  285. node.raws.insensitiveFlag = content;
  286. }
  287. lastAdded = 'insensitive';
  288. if (spaceBefore) {
  289. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  290. node.spaces.insensitive.before = spaceBefore;
  291. spaceBefore = '';
  292. }
  293. if (commentBefore) {
  294. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  295. node.raws.spaces.insensitive.before = commentBefore;
  296. commentBefore = '';
  297. }
  298. } else if (node.value || node.value === '') {
  299. lastAdded = 'value';
  300. node.value += content;
  301. if (node.raws.value) {
  302. node.raws.value += content;
  303. }
  304. }
  305. }
  306. spaceAfterMeaningfulToken = false;
  307. break;
  308. case tokens.str:
  309. if (!node.attribute || !node.operator) {
  310. return this.error("Expected an attribute followed by an operator preceding the string.", {
  311. index: token[_tokenize.FIELDS.START_POS]
  312. });
  313. }
  314. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  315. unescaped = _unescapeValue.unescaped,
  316. quoteMark = _unescapeValue.quoteMark;
  317. node.value = unescaped;
  318. node.quoteMark = quoteMark;
  319. lastAdded = 'value';
  320. (0, _util.ensureObject)(node, 'raws');
  321. node.raws.value = content;
  322. spaceAfterMeaningfulToken = false;
  323. break;
  324. case tokens.equals:
  325. if (!node.attribute) {
  326. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  327. }
  328. if (node.value) {
  329. return this.error('Unexpected "=" found; an operator was already defined.', {
  330. index: token[_tokenize.FIELDS.START_POS]
  331. });
  332. }
  333. node.operator = node.operator ? node.operator + content : content;
  334. lastAdded = 'operator';
  335. spaceAfterMeaningfulToken = false;
  336. break;
  337. case tokens.comment:
  338. if (lastAdded) {
  339. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  340. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  341. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  342. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  343. node.raws.spaces[lastAdded].after = rawLastComment + content;
  344. } else {
  345. var lastValue = node[lastAdded] || '';
  346. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  347. (0, _util.ensureObject)(node, 'raws');
  348. node.raws[lastAdded] = rawLastValue + content;
  349. }
  350. } else {
  351. commentBefore = commentBefore + content;
  352. }
  353. break;
  354. default:
  355. return this.error("Unexpected \"" + content + "\" found.", {
  356. index: token[_tokenize.FIELDS.START_POS]
  357. });
  358. }
  359. pos++;
  360. }
  361. unescapeProp(node, "attribute");
  362. unescapeProp(node, "namespace");
  363. this.newNode(new _attribute["default"](node));
  364. this.position++;
  365. }
  366. /**
  367. * return a node containing meaningless garbage up to (but not including) the specified token position.
  368. * if the token position is negative, all remaining tokens are consumed.
  369. *
  370. * This returns an array containing a single string node if all whitespace,
  371. * otherwise an array of comment nodes with space before and after.
  372. *
  373. * These tokens are not added to the current selector, the caller can add them or use them to amend
  374. * a previous node's space metadata.
  375. *
  376. * In lossy mode, this returns only comments.
  377. */;
  378. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  379. if (stopPosition < 0) {
  380. stopPosition = this.tokens.length;
  381. }
  382. var startPosition = this.position;
  383. var nodes = [];
  384. var space = "";
  385. var lastComment = undefined;
  386. do {
  387. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  388. if (!this.options.lossy) {
  389. space += this.content();
  390. }
  391. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  392. var spaces = {};
  393. if (space) {
  394. spaces.before = space;
  395. space = "";
  396. }
  397. lastComment = new _comment["default"]({
  398. value: this.content(),
  399. source: getTokenSource(this.currToken),
  400. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  401. spaces: spaces
  402. });
  403. nodes.push(lastComment);
  404. }
  405. } while (++this.position < stopPosition);
  406. if (space) {
  407. if (lastComment) {
  408. lastComment.spaces.after = space;
  409. } else if (!this.options.lossy) {
  410. var firstToken = this.tokens[startPosition];
  411. var lastToken = this.tokens[this.position - 1];
  412. nodes.push(new _string["default"]({
  413. value: '',
  414. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  415. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  416. spaces: {
  417. before: space,
  418. after: ''
  419. }
  420. }));
  421. }
  422. }
  423. return nodes;
  424. }
  425. /**
  426. *
  427. * @param {*} nodes
  428. */;
  429. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  430. var _this2 = this;
  431. if (requiredSpace === void 0) {
  432. requiredSpace = false;
  433. }
  434. var space = "";
  435. var rawSpace = "";
  436. nodes.forEach(function (n) {
  437. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  438. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  439. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  440. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  441. });
  442. if (rawSpace === space) {
  443. rawSpace = undefined;
  444. }
  445. var result = {
  446. space: space,
  447. rawSpace: rawSpace
  448. };
  449. return result;
  450. };
  451. _proto.isNamedCombinator = function isNamedCombinator(position) {
  452. if (position === void 0) {
  453. position = this.position;
  454. }
  455. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  456. };
  457. _proto.namedCombinator = function namedCombinator() {
  458. if (this.isNamedCombinator()) {
  459. var nameRaw = this.content(this.tokens[this.position + 1]);
  460. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  461. var raws = {};
  462. if (name !== nameRaw) {
  463. raws.value = "/" + nameRaw + "/";
  464. }
  465. var node = new _combinator["default"]({
  466. value: "/" + name + "/",
  467. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  468. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  469. raws: raws
  470. });
  471. this.position = this.position + 3;
  472. return node;
  473. } else {
  474. this.unexpected();
  475. }
  476. };
  477. _proto.combinator = function combinator() {
  478. var _this3 = this;
  479. if (this.content() === '|') {
  480. return this.namespace();
  481. }
  482. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  483. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  484. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  485. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  486. if (nodes.length > 0) {
  487. var last = this.current.last;
  488. if (last) {
  489. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  490. space = _this$convertWhitespa.space,
  491. rawSpace = _this$convertWhitespa.rawSpace;
  492. if (rawSpace !== undefined) {
  493. last.rawSpaceAfter += rawSpace;
  494. }
  495. last.spaces.after += space;
  496. } else {
  497. nodes.forEach(function (n) {
  498. return _this3.newNode(n);
  499. });
  500. }
  501. }
  502. return;
  503. }
  504. var firstToken = this.currToken;
  505. var spaceOrDescendantSelectorNodes = undefined;
  506. if (nextSigTokenPos > this.position) {
  507. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  508. }
  509. var node;
  510. if (this.isNamedCombinator()) {
  511. node = this.namedCombinator();
  512. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  513. node = new _combinator["default"]({
  514. value: this.content(),
  515. source: getTokenSource(this.currToken),
  516. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  517. });
  518. this.position++;
  519. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  520. // pass
  521. } else if (!spaceOrDescendantSelectorNodes) {
  522. this.unexpected();
  523. }
  524. if (node) {
  525. if (spaceOrDescendantSelectorNodes) {
  526. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  527. _space = _this$convertWhitespa2.space,
  528. _rawSpace = _this$convertWhitespa2.rawSpace;
  529. node.spaces.before = _space;
  530. node.rawSpaceBefore = _rawSpace;
  531. }
  532. } else {
  533. // descendant combinator
  534. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  535. _space2 = _this$convertWhitespa3.space,
  536. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  537. if (!_rawSpace2) {
  538. _rawSpace2 = _space2;
  539. }
  540. var spaces = {};
  541. var raws = {
  542. spaces: {}
  543. };
  544. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  545. spaces.before = _space2.slice(0, _space2.length - 1);
  546. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  547. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  548. spaces.after = _space2.slice(1);
  549. raws.spaces.after = _rawSpace2.slice(1);
  550. } else {
  551. raws.value = _rawSpace2;
  552. }
  553. node = new _combinator["default"]({
  554. value: ' ',
  555. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  556. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  557. spaces: spaces,
  558. raws: raws
  559. });
  560. }
  561. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  562. node.spaces.after = this.optionalSpace(this.content());
  563. this.position++;
  564. }
  565. return this.newNode(node);
  566. };
  567. _proto.comma = function comma() {
  568. if (this.position === this.tokens.length - 1) {
  569. this.root.trailingComma = true;
  570. this.position++;
  571. return;
  572. }
  573. this.current._inferEndPosition();
  574. var selector = new _selector["default"]({
  575. source: {
  576. start: tokenStart(this.tokens[this.position + 1])
  577. }
  578. });
  579. this.current.parent.append(selector);
  580. this.current = selector;
  581. this.position++;
  582. };
  583. _proto.comment = function comment() {
  584. var current = this.currToken;
  585. this.newNode(new _comment["default"]({
  586. value: this.content(),
  587. source: getTokenSource(current),
  588. sourceIndex: current[_tokenize.FIELDS.START_POS]
  589. }));
  590. this.position++;
  591. };
  592. _proto.error = function error(message, opts) {
  593. throw this.root.error(message, opts);
  594. };
  595. _proto.missingBackslash = function missingBackslash() {
  596. return this.error('Expected a backslash preceding the semicolon.', {
  597. index: this.currToken[_tokenize.FIELDS.START_POS]
  598. });
  599. };
  600. _proto.missingParenthesis = function missingParenthesis() {
  601. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  602. };
  603. _proto.missingSquareBracket = function missingSquareBracket() {
  604. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  605. };
  606. _proto.unexpected = function unexpected() {
  607. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  608. };
  609. _proto.unexpectedPipe = function unexpectedPipe() {
  610. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  611. };
  612. _proto.namespace = function namespace() {
  613. var before = this.prevToken && this.content(this.prevToken) || true;
  614. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  615. this.position++;
  616. return this.word(before);
  617. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  618. this.position++;
  619. return this.universal(before);
  620. }
  621. this.unexpectedPipe();
  622. };
  623. _proto.nesting = function nesting() {
  624. if (this.nextToken) {
  625. var nextContent = this.content(this.nextToken);
  626. if (nextContent === "|") {
  627. this.position++;
  628. return;
  629. }
  630. }
  631. var current = this.currToken;
  632. this.newNode(new _nesting["default"]({
  633. value: this.content(),
  634. source: getTokenSource(current),
  635. sourceIndex: current[_tokenize.FIELDS.START_POS]
  636. }));
  637. this.position++;
  638. };
  639. _proto.parentheses = function parentheses() {
  640. var last = this.current.last;
  641. var unbalanced = 1;
  642. this.position++;
  643. if (last && last.type === types.PSEUDO) {
  644. var selector = new _selector["default"]({
  645. source: {
  646. start: tokenStart(this.tokens[this.position - 1])
  647. }
  648. });
  649. var cache = this.current;
  650. last.append(selector);
  651. this.current = selector;
  652. while (this.position < this.tokens.length && unbalanced) {
  653. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  654. unbalanced++;
  655. }
  656. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  657. unbalanced--;
  658. }
  659. if (unbalanced) {
  660. this.parse();
  661. } else {
  662. this.current.source.end = tokenEnd(this.currToken);
  663. this.current.parent.source.end = tokenEnd(this.currToken);
  664. this.position++;
  665. }
  666. }
  667. this.current = cache;
  668. } else {
  669. // I think this case should be an error. It's used to implement a basic parse of media queries
  670. // but I don't think it's a good idea.
  671. var parenStart = this.currToken;
  672. var parenValue = "(";
  673. var parenEnd;
  674. while (this.position < this.tokens.length && unbalanced) {
  675. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  676. unbalanced++;
  677. }
  678. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  679. unbalanced--;
  680. }
  681. parenEnd = this.currToken;
  682. parenValue += this.parseParenthesisToken(this.currToken);
  683. this.position++;
  684. }
  685. if (last) {
  686. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  687. } else {
  688. this.newNode(new _string["default"]({
  689. value: parenValue,
  690. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  691. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  692. }));
  693. }
  694. }
  695. if (unbalanced) {
  696. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  697. }
  698. };
  699. _proto.pseudo = function pseudo() {
  700. var _this4 = this;
  701. var pseudoStr = '';
  702. var startingToken = this.currToken;
  703. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  704. pseudoStr += this.content();
  705. this.position++;
  706. }
  707. if (!this.currToken) {
  708. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  709. }
  710. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  711. this.splitWord(false, function (first, length) {
  712. pseudoStr += first;
  713. _this4.newNode(new _pseudo["default"]({
  714. value: pseudoStr,
  715. source: getTokenSourceSpan(startingToken, _this4.currToken),
  716. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  717. }));
  718. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  719. _this4.error('Misplaced parenthesis.', {
  720. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  721. });
  722. }
  723. });
  724. } else {
  725. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  726. }
  727. };
  728. _proto.space = function space() {
  729. var content = this.content();
  730. // Handle space before and after the selector
  731. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  732. return node.type === 'comment';
  733. })) {
  734. this.spaces = this.optionalSpace(content);
  735. this.position++;
  736. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  737. this.current.last.spaces.after = this.optionalSpace(content);
  738. this.position++;
  739. } else {
  740. this.combinator();
  741. }
  742. };
  743. _proto.string = function string() {
  744. var current = this.currToken;
  745. this.newNode(new _string["default"]({
  746. value: this.content(),
  747. source: getTokenSource(current),
  748. sourceIndex: current[_tokenize.FIELDS.START_POS]
  749. }));
  750. this.position++;
  751. };
  752. _proto.universal = function universal(namespace) {
  753. var nextToken = this.nextToken;
  754. if (nextToken && this.content(nextToken) === '|') {
  755. this.position++;
  756. return this.namespace();
  757. }
  758. var current = this.currToken;
  759. this.newNode(new _universal["default"]({
  760. value: this.content(),
  761. source: getTokenSource(current),
  762. sourceIndex: current[_tokenize.FIELDS.START_POS]
  763. }), namespace);
  764. this.position++;
  765. };
  766. _proto.splitWord = function splitWord(namespace, firstCallback) {
  767. var _this5 = this;
  768. var nextToken = this.nextToken;
  769. var word = this.content();
  770. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  771. this.position++;
  772. var current = this.content();
  773. word += current;
  774. if (current.lastIndexOf('\\') === current.length - 1) {
  775. var next = this.nextToken;
  776. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  777. word += this.requiredSpace(this.content(next));
  778. this.position++;
  779. }
  780. }
  781. nextToken = this.nextToken;
  782. }
  783. var hasClass = indexesOf(word, '.').filter(function (i) {
  784. // Allow escaped dot within class name
  785. var escapedDot = word[i - 1] === '\\';
  786. // Allow decimal numbers percent in @keyframes
  787. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  788. return !escapedDot && !isKeyframesPercent;
  789. });
  790. var hasId = indexesOf(word, '#').filter(function (i) {
  791. return word[i - 1] !== '\\';
  792. });
  793. // Eliminate Sass interpolations from the list of id indexes
  794. var interpolations = indexesOf(word, '#{');
  795. if (interpolations.length) {
  796. hasId = hasId.filter(function (hashIndex) {
  797. return !~interpolations.indexOf(hashIndex);
  798. });
  799. }
  800. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  801. indices.forEach(function (ind, i) {
  802. var index = indices[i + 1] || word.length;
  803. var value = word.slice(ind, index);
  804. if (i === 0 && firstCallback) {
  805. return firstCallback.call(_this5, value, indices.length);
  806. }
  807. var node;
  808. var current = _this5.currToken;
  809. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  810. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  811. if (~hasClass.indexOf(ind)) {
  812. var classNameOpts = {
  813. value: value.slice(1),
  814. source: source,
  815. sourceIndex: sourceIndex
  816. };
  817. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  818. } else if (~hasId.indexOf(ind)) {
  819. var idOpts = {
  820. value: value.slice(1),
  821. source: source,
  822. sourceIndex: sourceIndex
  823. };
  824. node = new _id["default"](unescapeProp(idOpts, "value"));
  825. } else {
  826. var tagOpts = {
  827. value: value,
  828. source: source,
  829. sourceIndex: sourceIndex
  830. };
  831. unescapeProp(tagOpts, "value");
  832. node = new _tag["default"](tagOpts);
  833. }
  834. _this5.newNode(node, namespace);
  835. // Ensure that the namespace is used only once
  836. namespace = null;
  837. });
  838. this.position++;
  839. };
  840. _proto.word = function word(namespace) {
  841. var nextToken = this.nextToken;
  842. if (nextToken && this.content(nextToken) === '|') {
  843. this.position++;
  844. return this.namespace();
  845. }
  846. return this.splitWord(namespace);
  847. };
  848. _proto.loop = function loop() {
  849. while (this.position < this.tokens.length) {
  850. this.parse(true);
  851. }
  852. this.current._inferEndPosition();
  853. return this.root;
  854. };
  855. _proto.parse = function parse(throwOnParenthesis) {
  856. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  857. case tokens.space:
  858. this.space();
  859. break;
  860. case tokens.comment:
  861. this.comment();
  862. break;
  863. case tokens.openParenthesis:
  864. this.parentheses();
  865. break;
  866. case tokens.closeParenthesis:
  867. if (throwOnParenthesis) {
  868. this.missingParenthesis();
  869. }
  870. break;
  871. case tokens.openSquare:
  872. this.attribute();
  873. break;
  874. case tokens.dollar:
  875. case tokens.caret:
  876. case tokens.equals:
  877. case tokens.word:
  878. this.word();
  879. break;
  880. case tokens.colon:
  881. this.pseudo();
  882. break;
  883. case tokens.comma:
  884. this.comma();
  885. break;
  886. case tokens.asterisk:
  887. this.universal();
  888. break;
  889. case tokens.ampersand:
  890. this.nesting();
  891. break;
  892. case tokens.slash:
  893. case tokens.combinator:
  894. this.combinator();
  895. break;
  896. case tokens.str:
  897. this.string();
  898. break;
  899. // These cases throw; no break needed.
  900. case tokens.closeSquare:
  901. this.missingSquareBracket();
  902. case tokens.semicolon:
  903. this.missingBackslash();
  904. default:
  905. this.unexpected();
  906. }
  907. }
  908. /**
  909. * Helpers
  910. */;
  911. _proto.expected = function expected(description, index, found) {
  912. if (Array.isArray(description)) {
  913. var last = description.pop();
  914. description = description.join(', ') + " or " + last;
  915. }
  916. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  917. if (!found) {
  918. return this.error("Expected " + an + " " + description + ".", {
  919. index: index
  920. });
  921. }
  922. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  923. index: index
  924. });
  925. };
  926. _proto.requiredSpace = function requiredSpace(space) {
  927. return this.options.lossy ? ' ' : space;
  928. };
  929. _proto.optionalSpace = function optionalSpace(space) {
  930. return this.options.lossy ? '' : space;
  931. };
  932. _proto.lossySpace = function lossySpace(space, required) {
  933. if (this.options.lossy) {
  934. return required ? ' ' : '';
  935. } else {
  936. return space;
  937. }
  938. };
  939. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  940. var content = this.content(token);
  941. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  942. return this.requiredSpace(content);
  943. } else {
  944. return content;
  945. }
  946. };
  947. _proto.newNode = function newNode(node, namespace) {
  948. if (namespace) {
  949. if (/^ +$/.test(namespace)) {
  950. if (!this.options.lossy) {
  951. this.spaces = (this.spaces || '') + namespace;
  952. }
  953. namespace = true;
  954. }
  955. node.namespace = namespace;
  956. unescapeProp(node, "namespace");
  957. }
  958. if (this.spaces) {
  959. node.spaces.before = this.spaces;
  960. this.spaces = '';
  961. }
  962. return this.current.append(node);
  963. };
  964. _proto.content = function content(token) {
  965. if (token === void 0) {
  966. token = this.currToken;
  967. }
  968. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  969. };
  970. /**
  971. * returns the index of the next non-whitespace, non-comment token.
  972. * returns -1 if no meaningful token is found.
  973. */
  974. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  975. if (startPosition === void 0) {
  976. startPosition = this.position + 1;
  977. }
  978. var searchPosition = startPosition;
  979. while (searchPosition < this.tokens.length) {
  980. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  981. searchPosition++;
  982. continue;
  983. } else {
  984. return searchPosition;
  985. }
  986. }
  987. return -1;
  988. };
  989. _createClass(Parser, [{
  990. key: "currToken",
  991. get: function get() {
  992. return this.tokens[this.position];
  993. }
  994. }, {
  995. key: "nextToken",
  996. get: function get() {
  997. return this.tokens[this.position + 1];
  998. }
  999. }, {
  1000. key: "prevToken",
  1001. get: function get() {
  1002. return this.tokens[this.position - 1];
  1003. }
  1004. }]);
  1005. return Parser;
  1006. }();
  1007. exports["default"] = Parser;
  1008. module.exports = exports.default;