match-graph.cjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. 'use strict';
  2. const parse = require('../definition-syntax/parse.cjs');
  3. const MATCH = { type: 'Match' };
  4. const MISMATCH = { type: 'Mismatch' };
  5. const DISALLOW_EMPTY = { type: 'DisallowEmpty' };
  6. const LEFTPARENTHESIS = 40; // (
  7. const RIGHTPARENTHESIS = 41; // )
  8. function createCondition(match, thenBranch, elseBranch) {
  9. // reduce node count
  10. if (thenBranch === MATCH && elseBranch === MISMATCH) {
  11. return match;
  12. }
  13. if (match === MATCH && thenBranch === MATCH && elseBranch === MATCH) {
  14. return match;
  15. }
  16. if (match.type === 'If' && match.else === MISMATCH && thenBranch === MATCH) {
  17. thenBranch = match.then;
  18. match = match.match;
  19. }
  20. return {
  21. type: 'If',
  22. match,
  23. then: thenBranch,
  24. else: elseBranch
  25. };
  26. }
  27. function isFunctionType(name) {
  28. return (
  29. name.length > 2 &&
  30. name.charCodeAt(name.length - 2) === LEFTPARENTHESIS &&
  31. name.charCodeAt(name.length - 1) === RIGHTPARENTHESIS
  32. );
  33. }
  34. function isEnumCapatible(term) {
  35. return (
  36. term.type === 'Keyword' ||
  37. term.type === 'AtKeyword' ||
  38. term.type === 'Function' ||
  39. term.type === 'Type' && isFunctionType(term.name)
  40. );
  41. }
  42. function groupNode(terms, combinator = ' ', explicit = false) {
  43. return {
  44. type: 'Group',
  45. terms,
  46. combinator,
  47. disallowEmpty: false,
  48. explicit
  49. };
  50. }
  51. function replaceTypeInGraph(node, replacements, visited = new Set()) {
  52. if (!visited.has(node)) {
  53. visited.add(node);
  54. switch (node.type) {
  55. case 'If':
  56. node.match = replaceTypeInGraph(node.match, replacements, visited);
  57. node.then = replaceTypeInGraph(node.then, replacements, visited);
  58. node.else = replaceTypeInGraph(node.else, replacements, visited);
  59. break;
  60. case 'Type':
  61. return replacements[node.name] || node;
  62. }
  63. }
  64. return node;
  65. }
  66. function buildGroupMatchGraph(combinator, terms, atLeastOneTermMatched) {
  67. switch (combinator) {
  68. case ' ': {
  69. // Juxtaposing components means that all of them must occur, in the given order.
  70. //
  71. // a b c
  72. // =
  73. // match a
  74. // then match b
  75. // then match c
  76. // then MATCH
  77. // else MISMATCH
  78. // else MISMATCH
  79. // else MISMATCH
  80. let result = MATCH;
  81. for (let i = terms.length - 1; i >= 0; i--) {
  82. const term = terms[i];
  83. result = createCondition(
  84. term,
  85. result,
  86. MISMATCH
  87. );
  88. }
  89. return result;
  90. }
  91. case '|': {
  92. // A bar (|) separates two or more alternatives: exactly one of them must occur.
  93. //
  94. // a | b | c
  95. // =
  96. // match a
  97. // then MATCH
  98. // else match b
  99. // then MATCH
  100. // else match c
  101. // then MATCH
  102. // else MISMATCH
  103. let result = MISMATCH;
  104. let map = null;
  105. for (let i = terms.length - 1; i >= 0; i--) {
  106. let term = terms[i];
  107. // reduce sequence of keywords into a Enum
  108. if (isEnumCapatible(term)) {
  109. if (map === null && i > 0 && isEnumCapatible(terms[i - 1])) {
  110. map = Object.create(null);
  111. result = createCondition(
  112. {
  113. type: 'Enum',
  114. map
  115. },
  116. MATCH,
  117. result
  118. );
  119. }
  120. if (map !== null) {
  121. const key = (isFunctionType(term.name) ? term.name.slice(0, -1) : term.name).toLowerCase();
  122. if (key in map === false) {
  123. map[key] = term;
  124. continue;
  125. }
  126. }
  127. }
  128. map = null;
  129. // create a new conditonal node
  130. result = createCondition(
  131. term,
  132. MATCH,
  133. result
  134. );
  135. }
  136. return result;
  137. }
  138. case '&&': {
  139. // A double ampersand (&&) separates two or more components,
  140. // all of which must occur, in any order.
  141. // Use MatchOnce for groups with a large number of terms,
  142. // since &&-groups produces at least N!-node trees
  143. if (terms.length > 5) {
  144. return {
  145. type: 'MatchOnce',
  146. terms,
  147. all: true
  148. };
  149. }
  150. // Use a combination tree for groups with small number of terms
  151. //
  152. // a && b && c
  153. // =
  154. // match a
  155. // then [b && c]
  156. // else match b
  157. // then [a && c]
  158. // else match c
  159. // then [a && b]
  160. // else MISMATCH
  161. //
  162. // a && b
  163. // =
  164. // match a
  165. // then match b
  166. // then MATCH
  167. // else MISMATCH
  168. // else match b
  169. // then match a
  170. // then MATCH
  171. // else MISMATCH
  172. // else MISMATCH
  173. let result = MISMATCH;
  174. for (let i = terms.length - 1; i >= 0; i--) {
  175. const term = terms[i];
  176. let thenClause;
  177. if (terms.length > 1) {
  178. thenClause = buildGroupMatchGraph(
  179. combinator,
  180. terms.filter(function(newGroupTerm) {
  181. return newGroupTerm !== term;
  182. }),
  183. false
  184. );
  185. } else {
  186. thenClause = MATCH;
  187. }
  188. result = createCondition(
  189. term,
  190. thenClause,
  191. result
  192. );
  193. }
  194. return result;
  195. }
  196. case '||': {
  197. // A double bar (||) separates two or more options:
  198. // one or more of them must occur, in any order.
  199. // Use MatchOnce for groups with a large number of terms,
  200. // since ||-groups produces at least N!-node trees
  201. if (terms.length > 5) {
  202. return {
  203. type: 'MatchOnce',
  204. terms,
  205. all: false
  206. };
  207. }
  208. // Use a combination tree for groups with small number of terms
  209. //
  210. // a || b || c
  211. // =
  212. // match a
  213. // then [b || c]
  214. // else match b
  215. // then [a || c]
  216. // else match c
  217. // then [a || b]
  218. // else MISMATCH
  219. //
  220. // a || b
  221. // =
  222. // match a
  223. // then match b
  224. // then MATCH
  225. // else MATCH
  226. // else match b
  227. // then match a
  228. // then MATCH
  229. // else MATCH
  230. // else MISMATCH
  231. let result = atLeastOneTermMatched ? MATCH : MISMATCH;
  232. for (let i = terms.length - 1; i >= 0; i--) {
  233. const term = terms[i];
  234. let thenClause;
  235. if (terms.length > 1) {
  236. thenClause = buildGroupMatchGraph(
  237. combinator,
  238. terms.filter(function(newGroupTerm) {
  239. return newGroupTerm !== term;
  240. }),
  241. true
  242. );
  243. } else {
  244. thenClause = MATCH;
  245. }
  246. result = createCondition(
  247. term,
  248. thenClause,
  249. result
  250. );
  251. }
  252. return result;
  253. }
  254. }
  255. }
  256. function buildMultiplierMatchGraph(node) {
  257. let result = MATCH;
  258. let matchTerm = buildMatchGraphInternal(node.term);
  259. if (node.max === 0) {
  260. // disable repeating of empty match to prevent infinite loop
  261. matchTerm = createCondition(
  262. matchTerm,
  263. DISALLOW_EMPTY,
  264. MISMATCH
  265. );
  266. // an occurrence count is not limited, make a cycle;
  267. // to collect more terms on each following matching mismatch
  268. result = createCondition(
  269. matchTerm,
  270. null, // will be a loop
  271. MISMATCH
  272. );
  273. result.then = createCondition(
  274. MATCH,
  275. MATCH,
  276. result // make a loop
  277. );
  278. if (node.comma) {
  279. result.then.else = createCondition(
  280. { type: 'Comma', syntax: node },
  281. result,
  282. MISMATCH
  283. );
  284. }
  285. } else {
  286. // create a match node chain for [min .. max] interval with optional matches
  287. for (let i = node.min || 1; i <= node.max; i++) {
  288. if (node.comma && result !== MATCH) {
  289. result = createCondition(
  290. { type: 'Comma', syntax: node },
  291. result,
  292. MISMATCH
  293. );
  294. }
  295. result = createCondition(
  296. matchTerm,
  297. createCondition(
  298. MATCH,
  299. MATCH,
  300. result
  301. ),
  302. MISMATCH
  303. );
  304. }
  305. }
  306. if (node.min === 0) {
  307. // allow zero match
  308. result = createCondition(
  309. MATCH,
  310. MATCH,
  311. result
  312. );
  313. } else {
  314. // create a match node chain to collect [0 ... min - 1] required matches
  315. for (let i = 0; i < node.min - 1; i++) {
  316. if (node.comma && result !== MATCH) {
  317. result = createCondition(
  318. { type: 'Comma', syntax: node },
  319. result,
  320. MISMATCH
  321. );
  322. }
  323. result = createCondition(
  324. matchTerm,
  325. result,
  326. MISMATCH
  327. );
  328. }
  329. }
  330. return result;
  331. }
  332. function buildMatchGraphInternal(node) {
  333. if (typeof node === 'function') {
  334. return {
  335. type: 'Generic',
  336. fn: node
  337. };
  338. }
  339. switch (node.type) {
  340. case 'Group': {
  341. let result = buildGroupMatchGraph(
  342. node.combinator,
  343. node.terms.map(buildMatchGraphInternal),
  344. false
  345. );
  346. if (node.disallowEmpty) {
  347. result = createCondition(
  348. result,
  349. DISALLOW_EMPTY,
  350. MISMATCH
  351. );
  352. }
  353. return result;
  354. }
  355. case 'Multiplier':
  356. return buildMultiplierMatchGraph(node);
  357. // https://drafts.csswg.org/css-values-5/#boolean
  358. case 'Boolean': {
  359. const term = buildMatchGraphInternal(node.term);
  360. // <boolean-expr[ <test> ]> = not <boolean-expr-group> | <boolean-expr-group> [ [ and <boolean-expr-group> ]* | [ or <boolean-expr-group> ]* ]
  361. const matchNode = buildMatchGraphInternal(groupNode([
  362. groupNode([
  363. { type: 'Keyword', name: 'not' },
  364. { type: 'Type', name: '!boolean-group' }
  365. ]),
  366. groupNode([
  367. { type: 'Type', name: '!boolean-group' },
  368. groupNode([
  369. { type: 'Multiplier', comma: false, min: 0, max: 0, term: groupNode([
  370. { type: 'Keyword', name: 'and' },
  371. { type: 'Type', name: '!boolean-group' }
  372. ]) },
  373. { type: 'Multiplier', comma: false, min: 0, max: 0, term: groupNode([
  374. { type: 'Keyword', name: 'or' },
  375. { type: 'Type', name: '!boolean-group' }
  376. ]) }
  377. ], '|')
  378. ])
  379. ], '|'));
  380. // <boolean-expr-group> = <test> | ( <boolean-expr[ <test> ]> ) | <general-enclosed>
  381. const booleanGroup = buildMatchGraphInternal(
  382. groupNode([
  383. { type: 'Type', name: '!term' },
  384. groupNode([
  385. { type: 'Token', value: '(' },
  386. { type: 'Type', name: '!self' },
  387. { type: 'Token', value: ')' }
  388. ]),
  389. { type: 'Type', name: 'general-enclosed' }
  390. ], '|')
  391. );
  392. replaceTypeInGraph(booleanGroup, { '!term': term, '!self': matchNode });
  393. replaceTypeInGraph(matchNode, { '!boolean-group': booleanGroup });
  394. return matchNode;
  395. }
  396. case 'Type':
  397. case 'Property':
  398. return {
  399. type: node.type,
  400. name: node.name,
  401. syntax: node
  402. };
  403. case 'Keyword':
  404. return {
  405. type: node.type,
  406. name: node.name.toLowerCase(),
  407. syntax: node
  408. };
  409. case 'AtKeyword':
  410. return {
  411. type: node.type,
  412. name: '@' + node.name.toLowerCase(),
  413. syntax: node
  414. };
  415. case 'Function':
  416. return {
  417. type: node.type,
  418. name: node.name.toLowerCase() + '(',
  419. syntax: node
  420. };
  421. case 'String':
  422. // convert a one char length String to a Token
  423. if (node.value.length === 3) {
  424. return {
  425. type: 'Token',
  426. value: node.value.charAt(1),
  427. syntax: node
  428. };
  429. }
  430. // otherwise use it as is
  431. return {
  432. type: node.type,
  433. value: node.value.substr(1, node.value.length - 2).replace(/\\'/g, '\''),
  434. syntax: node
  435. };
  436. case 'Token':
  437. return {
  438. type: node.type,
  439. value: node.value,
  440. syntax: node
  441. };
  442. case 'Comma':
  443. return {
  444. type: node.type,
  445. syntax: node
  446. };
  447. default:
  448. throw new Error('Unknown node type:', node.type);
  449. }
  450. }
  451. function buildMatchGraph(syntaxTree, ref) {
  452. if (typeof syntaxTree === 'string') {
  453. syntaxTree = parse.parse(syntaxTree);
  454. }
  455. return {
  456. type: 'MatchGraph',
  457. match: buildMatchGraphInternal(syntaxTree),
  458. syntax: ref || null,
  459. source: syntaxTree
  460. };
  461. }
  462. exports.DISALLOW_EMPTY = DISALLOW_EMPTY;
  463. exports.MATCH = MATCH;
  464. exports.MISMATCH = MISMATCH;
  465. exports.buildMatchGraph = buildMatchGraph;