match-graph.js 15 KB

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