diff options
Diffstat (limited to 'stdlib/buffer.ml')
-rw-r--r-- | stdlib/buffer.ml | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/stdlib/buffer.ml b/stdlib/buffer.ml index e31b7b80a..ce9b5c1f1 100644 --- a/stdlib/buffer.ml +++ b/stdlib/buffer.ml @@ -80,3 +80,71 @@ let add_channel b ic len = let output_buffer oc b = output oc b.buffer 0 b.position + +let closing = function + | '(' -> ')' + | '{' -> '}' + | _ -> assert false;; + +(* opening and closing: open and close characters, typically ( and ) + k balance of opening and closing chars + s the string where we are searching + p the index where we start the search *) +let advance_to_closing opening closing k s start = + let rec advance k i lim = + if i >= lim then raise Not_found else + if s.[i] = opening then advance (k + 1) (i + 1) lim else + if s.[i] = closing then + if k = 0 then i else advance (k - 1) (i + 1) lim + else advance k (i + 1) lim in + advance k start (String.length s);; + +let advance_to_non_alpha s start = + let rec advance i lim = + if i >= lim then lim else + match s.[i] with + | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | + 'é'|'à'|'á'|'è'|'ù'|'â'|'ê'|'î'|'ô'|'û'|'ë'|'ï'|'ü'|'ç'| + 'É'|'À'|'Á'|'È'|'Ù'|'Â'|'Ê'|'Î'|'Ô'|'Û'|'Ë'|'Ï'|'Ü'|'Ç' -> + advance (i + 1) lim + | _ -> i in + advance start (String.length s);; + +(* We are just at the beginning of an ident in s, starting at p *) +let find_ident s start = + match s.[start] with + (* Parenthesized ident ? *) + | '(' | '{' as c -> + let new_start = start + 1 in + let stop = advance_to_closing c (closing c) 0 s new_start in + String.sub s new_start (stop - start - 1), stop + 1 + (* Regular ident *) + | _ -> + let stop = advance_to_non_alpha s (start + 1) in + String.sub s start (stop - start), stop;; + +(* Substitute $ident (or $(ident)) in s, + according to the function f. *) +let add_substitute b f s = + let lim = String.length s in + let rec subst previous i = + if i < lim then begin + match s.[i] with + | '$' as current when previous = '\\' -> + add_char b current; + subst current (i + 1) + | '$' -> + let ident, next_i = find_ident s (i + 1) in + add_string b (f ident); + subst ' ' next_i + | current when previous == '\\' -> + add_char b '\\'; + add_char b current; + subst current (i + 1) + | '\\' as current -> + subst current (i + 1) + | current -> + add_char b current; + subst current (i + 1) + end in + subst ' ' 0;; |