contrib: intro header_keeper, a cog in the toolchains to generate FFI bindings
[nit.git] / contrib / header_keeper / src / header_keeper.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Filters preprocessed C-like header files to remove included files
16 #
17 # This tool is used in the process of parsing header files to extract
18 # information on the declared services (the functions and structures).
19 # This information is then used to generate bindings for Nit code
20 # to access these services.
21 #
22 # The C preprocessor extends macros, inline files marked with `#include`,
23 # and more. This tool acts after the C preprocessor, in a way to keep
24 # everything but the included files. It searches for line pragmas
25 # to identify the source of each line. The result is printed to stdout.
26 #
27 # Typical usage on the output of `gcc -E` (it would be the same with `clang`):
28 #
29 # ~~~sh
30 # gcc -E /usr/include/SDL/SDL_image.h | header_keeper SDL_image.h > preprocessed_header.h
31 # ~~~
32 #
33 # This module can also be used as a library.
34 # The main service is the method `header_keeper`.
35 module header_keeper
36
37 # Filters the preprocessed `input` to keep only files from `target` and write to the `output`
38 fun header_keeper(input: Reader, output: Writer, target: String)
39 do
40 var in_target = false
41 while not input.eof do
42 var line = input.read_line
43 if not line.is_empty and line[0] == '#' then
44 in_target = line.has(target)
45 continue
46 end
47
48 if in_target then output.write line + "\n"
49 end
50 end
51
52 if args.length != 1 then
53 print "Usage: header_keeper header_name.h"
54 exit 1
55 end
56
57 header_keeper(sys.stdin, sys.stdout, args.first)