|
6 | 6 |
|
7 | 7 | /// <reference types="tree-sitter-cli/dsl" /> |
8 | 8 | // @ts-check |
| 9 | +function generatePermutations($) { |
| 10 | + const required = $.run_definition; |
| 11 | + const optionalNames = ['desc_definition', 'needs_definition', 'alias_definition']; |
| 12 | + |
| 13 | + // Generate power set (all combinations) of optionals |
| 14 | + function combinations(arr) { |
| 15 | + const result = [[]]; |
| 16 | + for (const value of arr) { |
| 17 | + const copy = [...result]; |
| 18 | + for (const prefix of copy) { |
| 19 | + result.push([...prefix, value]); |
| 20 | + } |
| 21 | + } |
| 22 | + return result; |
| 23 | + } |
| 24 | + |
| 25 | + // Generate all permutations of an array |
| 26 | + function permute(arr) { |
| 27 | + if (arr.length <= 1) return [arr]; |
| 28 | + const result = []; |
| 29 | + for (let i = 0; i < arr.length; i++) { |
| 30 | + const rest = permute([...arr.slice(0, i), ...arr.slice(i + 1)]); |
| 31 | + for (const r of rest) { |
| 32 | + result.push([arr[i], ...r]); |
| 33 | + } |
| 34 | + } |
| 35 | + return result; |
| 36 | + } |
| 37 | + |
| 38 | + const allSequences = []; |
| 39 | + |
| 40 | + // All combinations of optional fields (including empty) |
| 41 | + const combos = combinations(optionalNames); |
| 42 | + |
| 43 | + for (const combo of combos) { |
| 44 | + const permutedOptionals = permute(combo); |
| 45 | + for (const p of permutedOptionals) { |
| 46 | + // Insert `required` at every position in the permutation |
| 47 | + for (let i = 0; i <= p.length; i++) { |
| 48 | + const names = [...p.slice(0, i), 'run_definition', ...p.slice(i)]; |
| 49 | + const fields = names.map(name => $[name]); |
| 50 | + allSequences.push(seq(...fields)); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return choice(...allSequences); |
| 56 | +} |
9 | 57 |
|
10 | 58 | module.exports = grammar({ |
11 | 59 | name: "taskr", |
@@ -62,13 +110,8 @@ module.exports = grammar({ |
62 | 110 | $.kw_task, |
63 | 111 | $.identifier, |
64 | 112 | $._colon, |
65 | | - repeat1( |
66 | | - choice( |
67 | | - $.run_definition, |
68 | | - $.desc_definition, |
69 | | - $.needs_definition, |
70 | | - $.alias_definition |
71 | | - ) |
| 113 | + choice( |
| 114 | + generatePermutations($) |
72 | 115 | ) |
73 | 116 | ), |
74 | 117 |
|
|
0 commit comments