summary refs log tree commit diff stats
path: root/atlas/compiledpatterns.nim
blob: 69751d82bf940b0dab2ca1a6d1f834738ffb2b0a (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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#
#           Atlas Package Cloner
#        (c) Copyright 2021 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

##[

Syntax taken from strscans.nim:

=================   ========================================================
``$$``              Matches a single dollar sign.
``$*``              Matches until the token following the ``$*`` was found.
                    The match is allowed to be of 0 length.
``$+``              Matches until the token following the ``$+`` was found.
                    The match must consist of at least one char.
``$s``              Skips optional whitespace.
=================   ========================================================

]##

import tables
from strutils import continuesWith, Whitespace

type
  Opcode = enum
    MatchVerbatim # needs verbatim match
    Capture0Until
    Capture1Until
    Capture0UntilEnd
    Capture1UntilEnd
    SkipWhitespace

  Instr = object
    opc: Opcode
    arg1: uint8
    arg2: uint16

  Pattern* = object
    code: seq[Instr]
    usedMatches: int
    error: string

# A rewrite rule looks like:
#
# foo$*bar -> https://gitlab.cross.de/$1

proc compile*(pattern: string; strings: var seq[string]): Pattern =
  proc parseSuffix(s: string; start: int): int =
    result = start
    while result < s.len and s[result] != '$':
      inc result

  result = Pattern(code: @[], usedMatches: 0, error: "")
  var p = 0
  while p < pattern.len:
    if pattern[p] == '$' and p+1 < pattern.len:
      case pattern[p+1]
      of '$':
        if result.code.len > 0 and result.code[^1].opc in {
              MatchVerbatim, Capture0Until, Capture1Until, Capture0UntilEnd, Capture1UntilEnd}:
          # merge with previous opcode
          let key = strings[result.code[^1].arg2] & "$"
          var idx = find(strings, key)
          if idx < 0:
            idx = strings.len
            strings.add key
          result.code[^1].arg2 = uint16(idx)
        else:
          var idx = find(strings, "$")
          if idx < 0:
            idx = strings.len
            strings.add "$"
          result.code.add Instr(opc: MatchVerbatim,
                                arg1: uint8(0), arg2: uint16(idx))
        inc p, 2
      of '+', '*':
        let isPlus = pattern[p+1] == '+'

        let pEnd = parseSuffix(pattern, p+2)
        let suffix = pattern.substr(p+2, pEnd-1)
        p = pEnd
        if suffix.len == 0:
          result.code.add Instr(opc: if isPlus: Capture1UntilEnd else: Capture0UntilEnd,
                                arg1: uint8(result.usedMatches), arg2: uint16(0))
        else:
          var idx = find(strings, suffix)
          if idx < 0:
            idx = strings.len
            strings.add suffix
          result.code.add Instr(opc: if isPlus: Capture1Until else: Capture0Until,
                                arg1: uint8(result.usedMatches), arg2: uint16(idx))
        inc result.usedMatches

      of 's':
        result.code.add Instr(opc: SkipWhitespace)
        inc p, 2
      else:
        result.error = "unknown syntax '$" & pattern[p+1] & "'"
        break
    elif pattern[p] == '$':
      result.error = "unescaped '$'"
      break
    else:
      let pEnd = parseSuffix(pattern, p)
      let suffix = pattern.substr(p, pEnd-1)
      var idx = find(strings, suffix)
      if idx < 0:
        idx = strings.len
        strings.add suffix
      result.code.add Instr(opc: MatchVerbatim,
                            arg1: uint8(0), arg2: uint16(idx))
      p = pEnd

type
  MatchObj = object
    m: int
    a: array[20, (int, int)]

proc matches(s: Pattern; strings: seq[string]; input: string): MatchObj =
  template failed =
    result.m = -1
    return result

  var i = 0
  for instr in s.code:
    case instr.opc
    of MatchVerbatim:
      if continuesWith(input, strings[instr.arg2], i):
        inc i, strings[instr.arg2].len
      else:
        failed()
    of Capture0Until, Capture1Until:
      block searchLoop:
        let start = i
        while i < input.len:
          if continuesWith(input, strings[instr.arg2], i):
            if instr.opc == Capture1Until and i == start:
              failed()
            result.a[result.m] = (start, i-1)
            inc result.m
            inc i, strings[instr.arg2].len
            break searchLoop
          inc i
        failed()

    of Capture0UntilEnd, Capture1UntilEnd:
      if instr.opc == Capture1UntilEnd and i >= input.len:
        failed()
      result.a[result.m] = (i, input.len-1)
      inc result.m
      i = input.len
    of SkipWhitespace:
      while i < input.len and input[i] in Whitespace: inc i
  if i < input.len:
    # still unmatched stuff was left:
    failed()

proc translate(m: MatchObj; outputPattern, input: string): string =
  result = newStringOfCap(outputPattern.len)
  var i = 0
  var patternCount = 0
  while i < outputPattern.len:
    if i+1 < outputPattern.len and outputPattern[i] == '$':
      if outputPattern[i+1] == '#':
        inc i, 2
        if patternCount < m.a.len:
          let (a, b) = m.a[patternCount]
          for j in a..b: result.add input[j]
        inc patternCount
      elif outputPattern[i+1] in {'1'..'9'}:
        var n = ord(outputPattern[i+1]) - ord('0')
        inc i, 2
        while i < outputPattern.len and outputPattern[i] in {'0'..'9'}:
          n = n * 10 + (ord(outputPattern[i]) - ord('0'))
          inc i
        patternCount = n
        if n-1 < m.a.len:
          let (a, b) = m.a[n-1]
          for j in a..b: result.add input[j]
      else:
        # just ignore the wrong pattern:
        inc i
    else:
      result.add outputPattern[i]
      inc i

proc replace*(s: Pattern; outputPattern, input: string): string =
  var strings: seq[string] = @[]
  let m = s.matches(strings, input)
  if m.m < 0:
    result = ""
  else:
    result = translate(m, outputPattern, input)


type
  Patterns* = object
    s: seq[(Pattern, string)]
    t: Table[string, string]
    strings: seq[string]

proc initPatterns*(): Patterns =
  Patterns(s: @[], t: initTable[string, string](), strings: @[])

proc addPattern*(p: var Patterns; inputPattern, outputPattern: string): string =
  if '$' notin inputPattern and '$' notin outputPattern:
    p.t[inputPattern] = outputPattern
    result = ""
  else:
    let code = compile(inputPattern, p.strings)
    if code.error.len > 0:
      result = code.error
    else:
      p.s.add (code, outputPattern)
      result = ""

proc substitute*(p: Patterns; input: string): string =
  result = p.t.getOrDefault(input)
  if result.len == 0:
    for i in 0..<p.s.len:
      let m = p.s[i][0].matches(p.strings, input)
      if m.m >= 0:
        return translate(m, p.s[i][1], input)

proc replacePattern*(inputPattern, outputPattern, input: string): string =
  var strings: seq[string] = @[]
  let code = compile(inputPattern, strings)
  result = replace(code, outputPattern, input)

when isMainModule:
  # foo$*bar -> https://gitlab.cross.de/$1
  const realInput = "$fooXXbar$z00end"
  var strings: seq[string] = @[]
  let code = compile("$$foo$*bar$$$*z00$*", strings)
  echo code

  let m = code.matches(strings, realInput)
  echo m.m

  echo translate(m, "$1--$#-$#-", realInput)

  echo translate(m, "https://gitlab.cross.de/$1", realInput)