parser.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. 'use strict';
  2. const Root = require('./root');
  3. const Value = require('./value');
  4. const AtWord = require('./atword');
  5. const Colon = require('./colon');
  6. const Comma = require('./comma');
  7. const Comment = require('./comment');
  8. const Func = require('./function');
  9. const Numbr = require('./number');
  10. const Operator = require('./operator');
  11. const Paren = require('./paren');
  12. const Str = require('./string');
  13. const Word = require('./word');
  14. const UnicodeRange = require('./unicode-range');
  15. const tokenize = require('./tokenize');
  16. const flatten = require('flatten');
  17. const indexesOf = require('indexes-of');
  18. const uniq = require('uniq');
  19. const ParserError = require('./errors/ParserError');
  20. function sortAscending (list) {
  21. return list.sort((a, b) => a - b);
  22. }
  23. module.exports = class Parser {
  24. constructor (input, options) {
  25. const defaults = { loose: false };
  26. // cache needs to be an array for values with more than 1 level of function nesting
  27. this.cache = [];
  28. this.input = input;
  29. this.options = Object.assign({}, defaults, options);
  30. this.position = 0;
  31. // we'll use this to keep track of the paren balance
  32. this.unbalanced = 0;
  33. this.root = new Root();
  34. let value = new Value();
  35. this.root.append(value);
  36. this.current = value;
  37. this.tokens = tokenize(input, this.options);
  38. }
  39. parse () {
  40. return this.loop();
  41. }
  42. colon () {
  43. let token = this.currToken;
  44. this.newNode(new Colon({
  45. value: token[1],
  46. source: {
  47. start: {
  48. line: token[2],
  49. column: token[3]
  50. },
  51. end: {
  52. line: token[4],
  53. column: token[5]
  54. }
  55. },
  56. sourceIndex: token[6]
  57. }));
  58. this.position ++;
  59. }
  60. comma () {
  61. let token = this.currToken;
  62. this.newNode(new Comma({
  63. value: token[1],
  64. source: {
  65. start: {
  66. line: token[2],
  67. column: token[3]
  68. },
  69. end: {
  70. line: token[4],
  71. column: token[5]
  72. }
  73. },
  74. sourceIndex: token[6]
  75. }));
  76. this.position ++;
  77. }
  78. comment () {
  79. let inline = false,
  80. value = this.currToken[1].replace(/\/\*|\*\//g, ''),
  81. node;
  82. if (this.options.loose && value.startsWith("//")) {
  83. value = value.substring(2);
  84. inline = true;
  85. }
  86. node = new Comment({
  87. value: value,
  88. inline: inline,
  89. source: {
  90. start: {
  91. line: this.currToken[2],
  92. column: this.currToken[3]
  93. },
  94. end: {
  95. line: this.currToken[4],
  96. column: this.currToken[5]
  97. }
  98. },
  99. sourceIndex: this.currToken[6]
  100. });
  101. this.newNode(node);
  102. this.position++;
  103. }
  104. error (message, token) {
  105. throw new ParserError(message + ` at line: ${token[2]}, column ${token[3]}`);
  106. }
  107. loop () {
  108. while (this.position < this.tokens.length) {
  109. this.parseTokens();
  110. }
  111. if (!this.current.last && this.spaces) {
  112. this.current.raws.before += this.spaces;
  113. }
  114. else if (this.spaces) {
  115. this.current.last.raws.after += this.spaces;
  116. }
  117. this.spaces = '';
  118. return this.root;
  119. }
  120. operator () {
  121. // if a +|- operator is followed by a non-word character (. is allowed) and
  122. // is preceded by a non-word character. (5+5)
  123. let char = this.currToken[1],
  124. node;
  125. if (char === '+' || char === '-') {
  126. // only inspect if the operator is not the first token, and we're only
  127. // within a calc() function: the only spec-valid place for math expressions
  128. if (!this.options.loose) {
  129. if (this.position > 0) {
  130. if (this.current.type === 'func' && this.current.value === 'calc') {
  131. // allow operators to be proceeded by spaces and opening parens
  132. if (this.prevToken[0] !== 'space' && this.prevToken[0] !== '(') {
  133. this.error('Syntax Error', this.currToken);
  134. }
  135. // valid: calc(1 - +2)
  136. // invalid: calc(1 -+2)
  137. else if (this.nextToken[0] !== 'space' && this.nextToken[0] !== 'word') {
  138. this.error('Syntax Error', this.currToken);
  139. }
  140. // valid: calc(1 - +2)
  141. // valid: calc(-0.5 + 2)
  142. // invalid: calc(1 -2)
  143. else if (this.nextToken[0] === 'word' && this.current.last.type !== 'operator' &&
  144. this.current.last.value !== '(') {
  145. this.error('Syntax Error', this.currToken);
  146. }
  147. }
  148. // if we're not in a function and someone has doubled up on operators,
  149. // or they're trying to perform a calc outside of a calc
  150. // eg. +-4px or 5+ 5, throw an error
  151. else if (this.nextToken[0] === 'space'
  152. || this.nextToken[0] === 'operator'
  153. || this.prevToken[0] === 'operator') {
  154. this.error('Syntax Error', this.currToken);
  155. }
  156. }
  157. }
  158. if (!this.options.loose) {
  159. if (this.nextToken[0] === 'word') {
  160. return this.word();
  161. }
  162. }
  163. else {
  164. if ((!this.current.nodes.length || (this.current.last && this.current.last.type === 'operator')) && this.nextToken[0] === 'word') {
  165. return this.word();
  166. }
  167. }
  168. }
  169. node = new Operator({
  170. value: this.currToken[1],
  171. source: {
  172. start: {
  173. line: this.currToken[2],
  174. column: this.currToken[3]
  175. },
  176. end: {
  177. line: this.currToken[2],
  178. column: this.currToken[3]
  179. }
  180. },
  181. sourceIndex: this.currToken[4]
  182. });
  183. this.position ++;
  184. return this.newNode(node);
  185. }
  186. parseTokens () {
  187. switch (this.currToken[0]) {
  188. case 'space':
  189. this.space();
  190. break;
  191. case 'colon':
  192. this.colon();
  193. break;
  194. case 'comma':
  195. this.comma();
  196. break;
  197. case 'comment':
  198. this.comment();
  199. break;
  200. case '(':
  201. this.parenOpen();
  202. break;
  203. case ')':
  204. this.parenClose();
  205. break;
  206. case 'atword':
  207. case 'word':
  208. this.word();
  209. break;
  210. case 'operator':
  211. this.operator();
  212. break;
  213. case 'string':
  214. this.string();
  215. break;
  216. case 'unicoderange':
  217. this.unicodeRange();
  218. break;
  219. default:
  220. this.word();
  221. break;
  222. }
  223. }
  224. parenOpen () {
  225. let unbalanced = 1,
  226. pos = this.position + 1,
  227. token = this.currToken,
  228. last;
  229. // check for balanced parens
  230. while (pos < this.tokens.length && unbalanced) {
  231. let tkn = this.tokens[pos];
  232. if (tkn[0] === '(') {
  233. unbalanced++;
  234. }
  235. if (tkn[0] === ')') {
  236. unbalanced--;
  237. }
  238. pos ++;
  239. }
  240. if (unbalanced) {
  241. this.error('Expected closing parenthesis', token);
  242. }
  243. // ok, all parens are balanced. continue on
  244. last = this.current.last;
  245. if (last && last.type === 'func' && last.unbalanced < 0) {
  246. last.unbalanced = 0; // ok we're ready to add parens now
  247. this.current = last;
  248. }
  249. this.current.unbalanced ++;
  250. this.newNode(new Paren({
  251. value: token[1],
  252. source: {
  253. start: {
  254. line: token[2],
  255. column: token[3]
  256. },
  257. end: {
  258. line: token[4],
  259. column: token[5]
  260. }
  261. },
  262. sourceIndex: token[6]
  263. }));
  264. this.position ++;
  265. // url functions get special treatment, and anything between the function
  266. // parens get treated as one word, if the contents aren't not a string.
  267. if (this.current.type === 'func' && this.current.unbalanced &&
  268. this.current.value === 'url' && this.currToken[0] !== 'string' &&
  269. this.currToken[0] !== ')' && !this.options.loose) {
  270. let nextToken = this.nextToken,
  271. value = this.currToken[1],
  272. start = {
  273. line: this.currToken[2],
  274. column: this.currToken[3]
  275. };
  276. while (nextToken && nextToken[0] !== ')' && this.current.unbalanced) {
  277. this.position ++;
  278. value += this.currToken[1];
  279. nextToken = this.nextToken;
  280. }
  281. if (this.position !== this.tokens.length - 1) {
  282. // skip the following word definition, or it'll be a duplicate
  283. this.position ++;
  284. this.newNode(new Word({
  285. value,
  286. source: {
  287. start,
  288. end: {
  289. line: this.currToken[4],
  290. column: this.currToken[5]
  291. }
  292. },
  293. sourceIndex: this.currToken[6]
  294. }));
  295. }
  296. }
  297. }
  298. parenClose () {
  299. let token = this.currToken;
  300. this.newNode(new Paren({
  301. value: token[1],
  302. source: {
  303. start: {
  304. line: token[2],
  305. column: token[3]
  306. },
  307. end: {
  308. line: token[4],
  309. column: token[5]
  310. }
  311. },
  312. sourceIndex: token[6]
  313. }));
  314. this.position ++;
  315. if (this.position >= this.tokens.length - 1 && !this.current.unbalanced) {
  316. return;
  317. }
  318. this.current.unbalanced --;
  319. if (this.current.unbalanced < 0) {
  320. this.error('Expected opening parenthesis', token);
  321. }
  322. if (!this.current.unbalanced && this.cache.length) {
  323. this.current = this.cache.pop();
  324. }
  325. }
  326. space () {
  327. let token = this.currToken;
  328. // Handle space before and after the selector
  329. if (this.position === (this.tokens.length - 1) || this.nextToken[0] === ',' || this.nextToken[0] === ')') {
  330. this.current.last.raws.after += token[1];
  331. this.position ++;
  332. }
  333. else {
  334. this.spaces = token[1];
  335. this.position ++;
  336. }
  337. }
  338. unicodeRange () {
  339. let token = this.currToken;
  340. this.newNode(new UnicodeRange({
  341. value: token[1],
  342. source: {
  343. start: {
  344. line: token[2],
  345. column: token[3]
  346. },
  347. end: {
  348. line: token[4],
  349. column: token[5]
  350. }
  351. },
  352. sourceIndex: token[6]
  353. }));
  354. this.position ++;
  355. }
  356. splitWord () {
  357. let nextToken = this.nextToken,
  358. word = this.currToken[1],
  359. rNumber = /^[\+\-]?((\d+(\.\d*)?)|(\.\d+))([eE][\+\-]?\d+)?/,
  360. // treat css-like groupings differently so they can be inspected,
  361. // but don't address them as anything but a word, but allow hex values
  362. // to pass through.
  363. rNoFollow = /^(?!\#([a-z0-9]+))[\#\{\}]/gi,
  364. hasAt, indices;
  365. if (!rNoFollow.test(word)) {
  366. while (nextToken && nextToken[0] === 'word') {
  367. this.position ++;
  368. let current = this.currToken[1];
  369. word += current;
  370. nextToken = this.nextToken;
  371. }
  372. }
  373. hasAt = indexesOf(word, '@');
  374. indices = sortAscending(uniq(flatten([[0], hasAt])));
  375. indices.forEach((ind, i) => {
  376. let index = indices[i + 1] || word.length,
  377. value = word.slice(ind, index),
  378. node;
  379. if (~hasAt.indexOf(ind)) {
  380. node = new AtWord({
  381. value: value.slice(1),
  382. source: {
  383. start: {
  384. line: this.currToken[2],
  385. column: this.currToken[3] + ind
  386. },
  387. end: {
  388. line: this.currToken[4],
  389. column: this.currToken[3] + (index - 1)
  390. }
  391. },
  392. sourceIndex: this.currToken[6] + indices[i]
  393. });
  394. }
  395. else if (rNumber.test(this.currToken[1])) {
  396. let unit = value.replace(rNumber, '');
  397. node = new Numbr({
  398. value: value.replace(unit, ''),
  399. source: {
  400. start: {
  401. line: this.currToken[2],
  402. column: this.currToken[3] + ind
  403. },
  404. end: {
  405. line: this.currToken[4],
  406. column: this.currToken[3] + (index - 1)
  407. }
  408. },
  409. sourceIndex: this.currToken[6] + indices[i],
  410. unit
  411. });
  412. }
  413. else {
  414. node = new (nextToken && nextToken[0] === '(' ? Func : Word)({
  415. value,
  416. source: {
  417. start: {
  418. line: this.currToken[2],
  419. column: this.currToken[3] + ind
  420. },
  421. end: {
  422. line: this.currToken[4],
  423. column: this.currToken[3] + (index - 1)
  424. }
  425. },
  426. sourceIndex: this.currToken[6] + indices[i]
  427. });
  428. if (node.constructor.name === 'Word') {
  429. node.isHex = /^#(.+)/.test(value);
  430. node.isColor = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value);
  431. }
  432. else {
  433. this.cache.push(this.current);
  434. }
  435. }
  436. this.newNode(node);
  437. });
  438. this.position ++;
  439. }
  440. string () {
  441. let token = this.currToken,
  442. value = this.currToken[1],
  443. rQuote = /^(\"|\')/,
  444. quoted = rQuote.test(value),
  445. quote = '',
  446. node;
  447. if (quoted) {
  448. quote = value.match(rQuote)[0];
  449. // set value to the string within the quotes
  450. // quotes are stored in raws
  451. value = value.slice(1, value.length - 1);
  452. }
  453. node = new Str({
  454. value,
  455. source: {
  456. start: {
  457. line: token[2],
  458. column: token[3]
  459. },
  460. end: {
  461. line: token[4],
  462. column: token[5]
  463. }
  464. },
  465. sourceIndex: token[6],
  466. quoted
  467. });
  468. node.raws.quote = quote;
  469. this.newNode(node);
  470. this.position++;
  471. }
  472. word () {
  473. return this.splitWord();
  474. }
  475. newNode (node) {
  476. if (this.spaces) {
  477. node.raws.before += this.spaces;
  478. this.spaces = '';
  479. }
  480. return this.current.append(node);
  481. }
  482. get currToken () {
  483. return this.tokens[this.position];
  484. }
  485. get nextToken () {
  486. return this.tokens[this.position + 1];
  487. }
  488. get prevToken () {
  489. return this.tokens[this.position - 1];
  490. }
  491. };