Initial commit

This commit is contained in:
Alexandre 2024-10-19 12:11:00 +02:00
commit 7ea6b0dc1c
4 changed files with 54 additions and 0 deletions

BIN
ctoh Executable file

Binary file not shown.

BIN
generator.cmi Normal file

Binary file not shown.

BIN
generator.cmo Normal file

Binary file not shown.

54
generator.ml Normal file
View File

@ -0,0 +1,54 @@
let capify str =
String.init (String.length str) (fun i -> if Char.code str.[i] >= 97 && Char.code str.[i] < 122 then Char.chr (Char.code str.[i] - 32) else str.[i]) ;;
let count_brackets str =
String.fold_left (fun acc ch -> if ch = '{' then acc+1 else if ch = '}' then acc-1 else acc) 0 str ;;
let ban_line str =
try
(Char.code str.[0] < 65) || (Char.code str.[0] > 122) || (Char.code str.[0] >= 91 && Char.code str.[0] <= 96) ||
((String.fold_left (
fun acc ch -> match acc with
| 0 -> if ch = '(' then 1 else 0
| 1 -> if ch = ')' then 2 else 1
| 2 -> if ch = '=' then 3 else 2
| k -> k
) 0 str) <> 2) ||
(str.[0] = '/' && str.[1] = '/')
with
| Invalid_argument _ -> true ;;
let parse_the_whole_thing filename =
let ptr = open_in filename in
let res = ref "" in
let bracket = ref 0 in
try
while true do
let line = input_line ptr in
if !bracket = 0 && not (ban_line line) then
res := (!res)^line^"\n\n" ;
bracket := !bracket + count_brackets line ;
done;
"0 factorielle"
with
| End_of_file ->
close_in ptr;
String.map (fun ch -> if ch = '{' then ';' else ch) !res ;;
let convert filename =
let whole = parse_the_whole_thing (filename^".c")
and ptr_out = open_out (filename^".h") in
let capped = ((capify filename)^"_H") in
Printf.fprintf ptr_out "#ifndef %s\n#define %s\n\n" capped capped ;
Printf.fprintf ptr_out "%s" whole ;
Printf.fprintf ptr_out "#endif" ;
close_out ptr_out ;;
let main () =
if Array.length Sys.argv <> 2 then begin
Printf.fprintf stderr "Usage : ./a.out <c_filename>\nNote : filename should not include the .c extension (e.g. enter 'main' and not 'main.c')\n" ;
assert false ;
end else
convert ((Sys.argv).(1)) ;;
main () ;;