aboutsummaryrefslogtreecommitdiff
path: root/src/eval/index.ts
blob: b1d55b999b393df8b600959d0e67754e0d5303f1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import { identity, pipe } from 'fp-ts/function'
import { filter, takeLeftWhile, zip, zipWith } from 'fp-ts/Array'
import * as Option from 'fp-ts/Option'
import { index, Expr, ListExpr, Literal } from '../types'
import { jlog, match } from '../utils'

export interface MatchGroupIndexed<T = any> {
  value: T
  index: number
}

export interface MatchGroupResult {
  groups: MatchGroupIndexed[]
}

const group = <T>(value: T, index: number): MatchGroupIndexed<T> => ({
  value,
  index,
})

const indexed = <T>(ls: T[]): Array<[number, T]> => ls.map((x, i) => [i, x])

const accumulateSkip = () => {
  const skipIndexes = [] as index[]
  return {
    localSkip:
      (i: index) =>
        <T>(x: T): T => (skipIndexes.push(i), x),
    getSkips: () => skipIndexes,
  }
}

const checkExpr = <T>(
  expr: Expr,
  item: T,
  list: T[],
  index: number,
  skip: (
    n: index,
  ) => (m: MatchGroupIndexed<any>[]) => MatchGroupIndexed<any>[] = _ =>
      identity,
): MatchGroupIndexed<any>[] => {
  return pipe(
    expr,
    match<MatchGroupIndexed<any>[], Expr>({
      AnyItem: _ => pipe([group(item, index)], skip(1)),
      AnyNumber: _ =>
        pipe(typeof item === 'number' ? [group(item, index)] : [], skip(1)),
      AnyString: _ =>
        pipe(typeof item === 'string' ? [group(item, index)] : [], skip(1)),
      AnyBool: _ =>
        pipe(typeof item === 'boolean' ? [group(item, index)] : [], skip(1)),
      Truthy: _ => pipe(!!item ? [group(item, index)] : [], skip(1)),
      Falsey: _ => pipe(!item ? [group(item, index)] : [], skip(1)),
      Literal: literal =>
        pipe(
          literal,
          match<boolean, Literal>({
            RegExp: regex =>
              regex && typeof item === 'string' && regex.test(item),
            _: () => (literal.value as any) === item,
          }),
          passed => (passed ? [group(item, index)] : []),
          skip(1),
        ),

      Group: ({ exprs }) => {
        const [head, ...tail] = exprs
        const { getSkips, localSkip } = accumulateSkip()
        const matches = tail.reduce(
          (acc, exp) =>
            pipe(
              acc,
              Option.chain(ac =>
                pipe(
                  checkExpr(exp, item, list, index, localSkip),
                  zip(ac),
                  z => z.map(([res, _cur]) => res),
                  z => (z.length === 0 ? Option.none : Option.some(z)),
                ),
              ),
            ),
          Option.some(checkExpr(head, item, list, index, localSkip)),
        )
        return pipe(
          matches,
          Option.getOrElseW(() => []),
          skip(Math.max(...getSkips()) || 1),
        )
      },

      Or: ({ exprs }) => {
        const match = exprs.find(
          expr => checkExpr(expr, item, list, index).length > 0,
        )
        return pipe(match ? [group(item, index)] : [], skip(1))
      },

      PropertyMatch: ({ name, expr }) =>
        pipe(
          Object.prototype.hasOwnProperty.call(item ?? {}, name)
            ? checkExpr(expr, item[name], list, index)
            : [],
          res => (res.length > 0 ? [group(item, index)] : []), // TODO: doesn't allow nested matching
          skip(1),
        ),

      OneOrMore: ({ expr }) => {
        const { localSkip, getSkips } = accumulateSkip()
        const result = checkExpr(
          Expr.ZeroOrMore({ expr }),
          item,
          list,
          index,
          localSkip,
        )
        return pipe(
          result[0].value.length > 0 ? result : [],
          skip(getSkips().reduce((a, b) => a + b, 0)),
        )
      },

      MinMax: ({ expr, min, max }) => {
        const { localSkip, getSkips } = accumulateSkip()
        const result = checkExpr(
          Expr.ZeroOrMore({ expr }),
          item,
          list,
          index,
          localSkip,
        )
        // TODO: Use nested skips

        const matches = result[0].value.length
        const capturedMatchCount = matches < min ? 0 : Math.min(matches, max)
        // const skipCount = getSkips().reduce((a, b) => a + b, 0)

        return pipe(
          result
            .map(r => ({ ...r, value: r.value.slice(0, capturedMatchCount) }))
            .filter(r => r.value.length > 0),
          skip(capturedMatchCount || 1),
        )
      },

      ZeroOrMore: ({ expr }) => {
        const matches = pipe(
          list,
          takeLeftWhile(a => checkExpr(expr, a, list, index).length > 0),
        )
        return pipe([group(matches, index)], skip(matches.length || 1))
      },

      Sequence: ({ exprs }) => {
        const { getSkips, localSkip } = accumulateSkip()
        const getGroups = () => {
          if (exprs.length > list.length) return []
          const result = pipe(
            zipWith(exprs, indexed(list), (expr, [i, val]) =>
              checkExpr(expr, val, list.slice(i), index + i, localSkip),
            ),
            filter(matches => !!matches.length),
          )
          if (result.length !== exprs.length) return []

          return [group(result, index)]
        }

        const groups = getGroups()
        const skips = groups.length === 0 ? 1 : Math.max(
          1,
          getSkips().reduce((a, b) => a + b, 0),
        )

        return pipe(groups, skip(skips))
      },

      _: _ => {
        throw new Error(`TODO: ${expr.tag} not implemented for match`)
      },
    }),
  )
}

export const matchAll = <T>(
  [startO, expr, endO]: ListExpr,
  list: T[],
): MatchGroupResult => {
  const check = (index: number, ls: T[], expr: Expr): MatchGroupIndexed[] => {
    if (ls.length === 0) return []

    const [item] = ls

    const next =
      (i: number = 1) =>
        (curMatch: MatchGroupIndexed[]) =>
          [...curMatch, ...check(index + i, ls.slice(i), expr)]

    return checkExpr(expr, item, ls, index, next)
  }

  return {
    groups: check(0, list, expr),
  }
}

export const replaceAll = <T>(
  [startO, expr, endO]: ListExpr,
  replacer: (v: T, match: MatchGroupIndexed<T>, i: index) => T[],
  list: T[],
): T[] => {
  const check = (index: number, ls: T[], expr: Expr): T[] => {
    if (ls.length === 0) return []

    const [item] = ls

    const next =
      (skip: number = 1) =>
        (curMatch: MatchGroupIndexed[]): MatchGroupIndexed<T>[] => {
          const [match] = curMatch
          const vals = match ? replacer(item, match, index) : ls.slice(0, skip)
          // console.log(i, curMatch, vals)
          return [...vals, ...check(index + skip, ls.slice(skip), expr)] as any
        }

    return checkExpr(expr, item, ls, index, next) as any
  }

  return check(0, list, expr)
}