parser.js 43 KB

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