orakuda / pa / lexrex.mll

  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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
{
open Lexing

type token =
  | MetaChar of char
  | Group of string option * token list
  | Escaped of string
  | Quoted of string
  | Quantifier of bool (* greedieness *) * int * int * token
  | Char of char
  | CharClass of bool (* pos/neg *) * charclass list
  | Comment of string
  | Modifier of string
  | Cluster of string * token list
  | LookAhead of bool (* pos/neg *) * token list
  | LookBehind of bool (* pos/neg *) * token list
  | Independent of token list
  | PBackRef of string
  | Recursive of string option (* None = entire *)
  | CallOut of int
  | CallOutByName of string

and charclass = 
  | ClassChar of token
  | ClassPOSIX of bool (* pos/neg *) * string
  | ClassRange of token * token
  | ClassQuoted of string

let char_lexeme lexbuf = (lexeme lexbuf).[0]

exception Error of int * int * string

let error lexbuf s =
  raise (Error (lexeme_start lexbuf, lexeme_end lexbuf, s))

let posix_character_classes = [
  "alpha"; "alnum"; "ascii"; "blank"; "cntrl"; "digit"; "graph";
  "lower"; "print"; "punct"; "space"; "upper"; "word"; "xdigit"
]

let get_class_name start lexbuf =
  let lxm = lexeme lexbuf in
  let classname = String.sub lxm start (String.length lxm - (start + 2)) in
  if not (List.mem classname posix_character_classes) then
    error lexbuf "unknown POSIX class"
  else classname
}

let digit = ['0'-'9']
let hex = ['0'-'9' 'A'-'F' 'a'-'f']

(* 
   not yet:
   - Comment by # ... \n in PCRE_EXTENDED mode
   - \x{hhhh} is special even not in UTF-8 mmode
   - various PCRE_... mode
   - (?(condition)yes-pattern|no-pattern)
   - (?(condition)yes-pattern)
   - UTF8
   
   not supported by PCRE:

   (?{ code })
   (??{ code })
   
*)

rule tokens = parse
  | "\\Q"
      {
        let re = Quoted (quoted lexbuf (Buffer.create 16)) in
	let res = tokens lexbuf in
	re :: res
      }
      (* do not consider about \E not paired with \Q.
	 it is treated as a Escaped "E". *)
      
  | '\\' 
      { 
	let re = quantifier lexbuf (escaped lexbuf) in
	let res = tokens lexbuf in
	re :: res
      }

  | '.' 
      {
        let re = quantifier lexbuf (MetaChar '.') in
	let res = tokens lexbuf in
	re :: res
      }
  | ['^' '$' '|']  (* CR jfuruse: $var is not supported *)
      {
        let re = MetaChar (char_lexeme lexbuf) in
	let res = tokens lexbuf in
	re :: res
     }
  | '(' 
      {
        let re = quantifier lexbuf (Group (None, group lexbuf)) in
	let res = tokens lexbuf in
	re :: res 
      }
  | "(?P<" (['A'-'Z' 'a'-'z'] (digit | ['A'-'Z' 'a'-'z' '_'])*) ">" 
      {
         (* python style named pattern *)
         let lxm = lexeme lexbuf in
	 let name = String.sub lxm 4 (String.length lxm - 5) in
	 let re = Group (Some name, group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?P=" (['A'-'Z' 'a'-'z'] (digit | ['A'-'Z' 'a'-'z' '_'])*) ")" 
      {
         (* python style back reference *)
         let lxm = lexeme lexbuf in
	 let name = String.sub lxm 4 (String.length lxm - 5) in
	 let re = PBackRef name in
	 let res = tokens lexbuf in
	 re :: res
      }

(* Recursive *)
  | "(?P" digit+ ")"
      {
         let lxm = lexeme lexbuf in
	 let name = String.sub lxm 3 (String.length lxm - 4) in
	 let re = Recursive (Some name) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?R)" 
      {
	 let re = Recursive None in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?P>" (['A'-'Z' 'a'-'z'] (digit | ['A'-'Z' 'a'-'z' '_'])*) ")" 
      {
         let lxm = lexeme lexbuf in
	 let name = String.sub lxm 4 (String.length lxm - 5) in
	 let re = Recursive (Some name) in
	 let res = tokens lexbuf in
	 re :: res
      }

  (* Call-out *)
  | "(?C" ['1'-'9'] digit* ")" (* callout id must be positive *)
      {
         let lxm = lexeme lexbuf in
	 let name = String.sub lxm 3 (String.length lxm - 4) in
	 let pos = 
	   match name with
	   | "" -> 0
	   | _ -> int_of_string name
	 in
	 let re = CallOut pos in
	 let res = tokens lexbuf in
	 re :: res
      }

  (* Call-out-by-name: Caml extension *)
  | "(?C" ['a'-'z' '_'] ['A'-'Z' 'a'-'z' '_' '0'-'9']* ")"
      {
         let lxm = lexeme lexbuf in
	 let name = String.sub lxm 3 (String.length lxm - 4) in
	 let re = CallOutByName name in
	 let res = tokens lexbuf in
	 re :: res
      }

  (* Comment *)
  | "(?#" [^ ')']* ')'
      {
         let lxm = lexeme lexbuf in
	 let re = Comment (String.sub lxm 3 (String.length lxm - 4)) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?" ['i' 'm' 's' 'x']* ("-" ['i' 'm' 's' 'x']*)? ")"
      {
         let lxm = lexeme lexbuf in
	 let re = Modifier (String.sub lxm 2 (String.length lxm - 3)) in
	 let res = tokens lexbuf in
	 re :: res
      }
 
  | "(?" ['i' 'm' 's' 'x']* ("-" ['i' 'm' 's' 'x']*)? ":"
      {
         let lxm = lexeme lexbuf in
	 let pos = String.index lxm ':' in
	 let md = String.sub lxm 2 (pos - 2) in
	 let re = Cluster(md, group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?="
      {
	 let re = LookAhead(true, group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?!"
      {
	 let re = LookAhead(false, group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?<="
      {
	 let re = LookBehind(true, group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?<!"
      {
	 let re = LookBehind(false, group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
  | "(?>"
      {
	 let re = Independent (group lexbuf) in
	 let res = tokens lexbuf in
	 re :: res
      }
 
  | '[' 
      {
       let re = quantifier lexbuf (CharClass (true, charclass lexbuf)) in
	let res = tokens lexbuf in
	re :: res 
      }
  | "[^"
      {
       let re = quantifier lexbuf (CharClass (false, charclass lexbuf)) in
	let res = tokens lexbuf in
	re :: res 
      }
  | ['*' '+' '?']
      {
        (* quantifiers cannot go here *)
        error lexbuf "Quantifier follows nothing in regex"
      }
  | _ # ['\\' '.' '^' '$' '|' '(' ')' '[' '*' '+' '?' '/' ] 
      (* '{' is a metachar, but maybe parsed as a literal, too *) 
      (* '/' is reserved for pcre syntax i.e. /blahblah/ *)
      {
        let re = quantifier lexbuf (Char (char_lexeme lexbuf)) in
	let res = tokens lexbuf in
	re :: res
      }
  | "" { [] }
      
and quantifier = parse
  | '*' {(fun tk -> Quantifier (true, 0, -1, tk))}
  | '+' {(fun tk -> Quantifier (true, 1, -1, tk))}
  | '?' {(fun tk -> Quantifier (true, 0, 1, tk))}
  | "*?" {(fun tk -> Quantifier (false, 0, -1, tk))}
  | "+?" {(fun tk -> Quantifier (false, 1, -1, tk))}
  | "??" {(fun tk -> Quantifier (false, 0, 1, tk))}
  | '{' digit+ '}' 
      {
        fun tk ->
          let lxm = lexeme lexbuf in
	  let d = int_of_string (String.sub lxm 1 (String.length lxm - 2)) in
	  Quantifier (true, d, d, tk)
      }
  | '{' digit+ ",}"
      {
        fun tk ->
          let lxm = lexeme lexbuf in
	  let d = int_of_string (String.sub lxm 1 (String.length lxm - 3)) in
	  Quantifier (true, d, -1, tk)
      }
  | '{' digit+ ',' digit+ '}'
      {
        fun tk ->
          let lxm = lexeme lexbuf in
	  let pos = String.index lxm ',' in
	  let d1 = 
	    int_of_string (String.sub lxm 1 (pos - 1)) 
	  in
	  let d2 = 
	    int_of_string 
	      (String.sub lxm (pos + 1) (String.length lxm - pos - 2)) 
	  in
	  Quantifier (true, d1, d2, tk)
      }
  | '{' digit+ "}?"
      {
        fun tk ->
          let lxm = lexeme lexbuf in
	  let d = int_of_string (String.sub lxm 1 (String.length lxm - 3)) in
	  Quantifier (false, d, d, tk)
      }
  | '{' digit+ ",}?"
      {
        fun tk ->
          let lxm = lexeme lexbuf in
	  let d = int_of_string (String.sub lxm 1 (String.length lxm - 4)) in
	  Quantifier (false, d, -1, tk)
      }
  | '{' digit+ ',' digit+ "}?"
      {
        fun tk ->
          let lxm = lexeme lexbuf in
	  let pos = String.index lxm ',' in
	  let d1 = 
	    int_of_string (String.sub lxm 1 (pos - 1)) 
	  in
	  let d2 = 
	    int_of_string 
	      (String.sub lxm (pos + 1) (String.length lxm - pos - 3)) 
	  in
	  Quantifier (false, d1, d2, tk)
      }
  | "" {(fun tk -> tk)}

and group = parse
  | ')' { [] }
  | "" 
      {
        let res = tokens lexbuf in
	let res' = group lexbuf in
	res @ res' 
      }
  | eof { error lexbuf "Unbalanced group" }

and quoted = parse
  | "" | "\\E" { fun buf -> Buffer.contents buf }
  | "\\" 
  | [^ '\\']*
      { 
	fun buf -> 
	  Buffer.add_string buf (lexeme lexbuf);
	  quoted lexbuf buf
      }

and charclass = parse
  | ']' { [] }
  | "[:" [^ ':']+ ":]" 
      { 
	let cls = ClassPOSIX (true, get_class_name 2 lexbuf) in
	cls :: charclass lexbuf
      }
  | "[:^" [^ ':']+ ":]" 
      { 
	let cls = ClassPOSIX (false, get_class_name 3 lexbuf) in
	cls :: charclass lexbuf
      }
  | "\\Q"
      {
       let cls = ClassQuoted (quoted lexbuf (Buffer.create 16)) in
	cls :: charclass lexbuf
      }
  | '\\' 
      {
        let e = escaped lexbuf in
	let clses = range lexbuf e in
	clses @ charclass lexbuf 
      }
  | [^ '[' '\\' ']']
      {
        let s = char_lexeme lexbuf in
	let clses =  range lexbuf (Char s) in
	clses @ charclass lexbuf
      }
  | "" { error lexbuf "Unmatched [ in regex" }
          
and range = parse
  | "-[:" [^ ':']+ ":]"
  | "-[:^" [^ ':']+ ":]"
  | '-' ("\\w" | "\\W" | "\\s" | "\\S" | "\\d" | "\\D")
      {
        (* not a range *)
        fun c ->
	  ClassChar c :: 
	  charclass (from_string (lexeme lexbuf ^ "]" (* to finish *)))
      }
      
  | "-\\" 
      {
        fun c ->
	  let e = escaped lexbuf in
	  [ClassRange (c, e)]
      }

  | '-' [^ '[' '\\' ']']
      {
        fun c ->
	  let c' = Char (lexeme lexbuf).[1] in
	  [ClassRange (c, c')]
      }
  | "" { fun c -> [ClassChar c] }
      

and escaped = parse
  | digit (* backreference *)
  | digit digit (* backreference or \0dd *)
  | digit digit digit (* same, same *)
  | "x" 
  | "x" hex
  | "x" hex hex
  | "x{" hex* "}"
  | "c" [^ '\\' '/'] | "\\c\\" _
  | "N{" [^ '}']* "}"
  | ['p' 'P'] [^ '\\' '/' '{'] | "\\" ['p' 'P'] "\\" _
  | ['p' 'P'] "{" [^ '}']+ "}"
  | _
      { 
	let lxm = lexeme lexbuf in
	if lxm = "Q" then assert false; (* must be treated differently *)
	Escaped lxm
      }
  | "" { error lexbuf "Search pattern not terminated" }



{
let from_string_gen s =
  let lexbuf = Lexing.from_string s in
  let regexp = tokens lexbuf in
  let endpos = lexeme_end lexbuf in
  let len = String.length s in
  if endpos < len then
    regexp, endpos, String.sub s endpos (len - endpos)
  else regexp, endpos, "" (* s may be "" *)

let from_string s =
  match from_string_gen s with
  | regexp, _, "" -> s, regexp, ""
  | regexp, endpos, rem when rem.[0] = '/' -> (* flags *)
      String.sub s 0 endpos, regexp, String.sub rem 1 (String.length rem - 1)
  | _, endpos, rem -> 
      raise (Error (endpos, endpos + 1,
		    Printf.sprintf "unknown regexp character %C" rem.[0]))

let replace_from_string s =
  match from_string_gen s with
  | _regexp, endpos, "" -> 
      raise (Error (endpos, endpos + 1, "missing a replace string"))
  | regexp, endpos, rem ->
      if rem.[0] <> '/' then
	raise (Error (endpos, endpos + 1, 
		     Printf.sprintf "unknown regexp character %C" rem.[0]))
      else 
        let rex = String.sub s 0 endpos in
	let rem = String.sub rem 1 (String.length rem - 1) in
        rex, regexp, rem

type typ = {
    num_of_groups : int;
    named_groups : (string * int) list;
    callouts : int list; (* 255 : default, not in the list *)
    named_callouts : (string * int) list; (* caml extension *)
  }

exception Double_defined_group of string
exception Too_many_callouts 

let type_regexp re =

  let pos = ref 0 in
  let named_groups = ref [] in
  let callouts = ref [] in
  let named_callouts = ref [] in

  let rec regexp re = List.iter token re
  and token = function
    | Group (Some n, re) -> 
	if List.mem_assoc n !named_groups then 
	  raise (Double_defined_group n);
	incr pos;
	named_groups := (n, !pos) :: !named_groups;
	regexp re
    | Group (None, re) -> 
	incr pos;
	regexp re
    | Quantifier (_, _, _, tkn) -> token tkn
    | Cluster (_, re)
    | LookAhead (_, re)
    | LookBehind (_, re)
    | Independent re -> regexp re
    | CallOut n -> callouts := n :: !callouts
    | CallOutByName s -> named_callouts := s :: !named_callouts
    | Char _
    | MetaChar _
    | Escaped _
    | Quoted _
    | Comment _
    | CharClass _
    | Modifier _
    | PBackRef _
    | Recursive _ -> ()
  in

  let give_numbers_for_named_callouts = 
    let pos = ref 1 in
    let rec f = function
      | [] -> []
      | s::ss ->
	  while List.mem !pos !callouts do incr pos done;
	  if !pos = 255 then raise Too_many_callouts;
	  (s, !pos) :: f ss
    in
    f 
  in

  regexp re;
  { num_of_groups= !pos;
    named_groups= !named_groups;
    callouts= !callouts;
    named_callouts= give_numbers_for_named_callouts !named_callouts }

let string_of_tokens typ tkns =
  let buf = Buffer.create 16 in
  let char c = Buffer.add_char buf c in
  let string s = Buffer.add_string buf s in
  let greedy = function
    | true -> char '?'
    | false -> ()
  in

  let rec token = function
    | MetaChar c -> char c
    | Group (None, tkns) -> 
	char '(';
	List.iter token tkns;
	char ')'
    | Group (Some s, tkns) -> 
	string "(?P<";
	string s;
	char '>';
	List.iter token tkns;
	char ')'
    | Escaped s ->
	char '\\';
	string s
    | Quoted s ->
	string "\\Q";
	string s;
	string "\\E"
    | Quantifier (b, 0, -1, tk) ->
	token tk;
	char '*';
	greedy b
    | Quantifier (b, 1, -1, tk) ->
	token tk;
	char '+';
	greedy b
    | Quantifier (b, 0, 1, tk) ->
	token tk;
	char '?';
	greedy b
    | Quantifier (b, n, -1, tk) ->
	token tk;
	char '{';
	string (string_of_int n);
	char ',';
	char '}';
	greedy b
    | Quantifier (b, n, m, tk) when n = m ->
	token tk;
	char '{';
	string (string_of_int n);
	char '}';
	greedy b
    | Quantifier (b, n, m, tk) ->
	token tk;
	char '{';
	string (string_of_int n);
	char ',';
	string (string_of_int m);
	char '}';
	greedy b
    | Char c -> char c
    | CharClass (b, clses) ->
	char '[';
	if not b then char '^';
	List.iter cls clses;
	char ']'
    | Comment s ->
	(* FIXME: extended mode *)
	string "(?#";
	string s;
	char ')'
    | Modifier s ->
	string "(?";
	string s;
	char ')'
    | Cluster (md, tkns) ->
	string "(?";
	string md;
	char ':';
	List.iter token tkns;
	char ')'
    | LookAhead (true, tkns) ->
	string "(?=";
	List.iter token tkns;
	char ')'
    | LookAhead (false, tkns) ->
	string "(?!";
	List.iter token tkns;
	char ')'
    | LookBehind (true, tkns) ->
	string "(?<=";
	List.iter token tkns;
	char ')'
    | LookBehind (false, tkns) ->
	string "(?<!";
	List.iter token tkns;
	char ')'
    | Independent tkns ->
	string "(?>";
	List.iter token tkns;
	char ')'
    | PBackRef s ->
	string "(?P=";
	string s;
	char ')'
    | Recursive None -> 
	string "(?R)"
    | Recursive (Some n) ->
	string "(?P";
	string n;
	char ')'
    | CallOut n ->
	string "(?C";
	string (string_of_int n);
	char ')'
    | CallOutByName s ->
	let n = List.assq s typ.named_callouts in
	string "(?C";
	string (string_of_int n);
	char ')'
  
  and cls = function 
    | ClassChar tkn -> token tkn
    | ClassPOSIX (true, s) ->
	string "[:";
	string s;
	string ":]"
    | ClassPOSIX (false, s) ->
	string "[:^";
	string s;
	string ":]"
    | ClassRange (t1, t2) ->
	token t1;
	char '-';
	token t2
    | ClassQuoted s ->
	string "\\Q";
	string s;
	string "\\E"
  in
  
  List.iter token tkns;
  Buffer.contents buf
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.