|
| 1 | +using Clang.Generators |
| 2 | +using Clang |
| 3 | +using MacroTools |
| 4 | +using libxlsxwriter_jll |
| 5 | +using JuliaFormatter: format |
| 6 | + |
| 7 | +function return_type_is_const_char(cursor::Clang.CLFunctionDecl) |
| 8 | + result_type = Clang.getCanonicalType(Clang.getCursorResultType(cursor)) |
| 9 | + if result_type isa CLPointer |
| 10 | + destination = Clang.getPointeeType(result_type) |
| 11 | + return destination isa CLChar_S && Clang.isConstQualifiedType(destination) |
| 12 | + end |
| 13 | + return false |
| 14 | +end |
| 15 | + |
| 16 | +"Functions that return a Cstring are wrapped in unsafe_string to return a String" |
| 17 | +function rewrite(ex::Expr, cursor::Clang.CLFunctionDecl) |
| 18 | + if @capture(ex, function fname_(fargs__) |
| 19 | + @ccall lib_.cname_(cargs__)::rettype_ |
| 20 | + end) |
| 21 | + # bind the ccall such that we can easily wrap it |
| 22 | + cc = :(@ccall $lib.$cname($(cargs...))::$rettype) |
| 23 | + |
| 24 | + cc′ = if rettype == :Cstring |
| 25 | + # do not try to free a const char * |
| 26 | + if return_type_is_const_char(cursor) |
| 27 | + :(unsafe_string($cc)) |
| 28 | + else |
| 29 | + if endswith(string(cname), "_r") |
| 30 | + :(string_copy_free($cc, handle)) |
| 31 | + else |
| 32 | + :(string_copy_free($cc)) |
| 33 | + end |
| 34 | + end |
| 35 | + else |
| 36 | + cc |
| 37 | + end |
| 38 | + |
| 39 | + # stitch the modified function expression back together |
| 40 | + f = :(function $fname($(fargs...)) |
| 41 | + $cc′ |
| 42 | + end) |> prettify |
| 43 | + |
| 44 | + return f |
| 45 | + end |
| 46 | + return ex |
| 47 | +end |
| 48 | + |
| 49 | +function rewrite!(dag::ExprDAG) |
| 50 | + for n in dag.nodes |
| 51 | + if !isa(n.cursor, Clang.CLFunctionDecl) |
| 52 | + continue |
| 53 | + end |
| 54 | + map!(e -> rewrite(e, n.cursor), n.exprs, n.exprs) |
| 55 | + end |
| 56 | +end |
| 57 | + |
| 58 | +cd(@__DIR__) |
| 59 | + |
| 60 | +include_dir = joinpath(libxlsxwriter_jll.artifact_dir, "include") |> normpath |
| 61 | + |
| 62 | +# wrapper generator options |
| 63 | +options = load_options(joinpath(@__DIR__, "generator.toml")) |
| 64 | + |
| 65 | +args = get_default_args() |
| 66 | +push!(args, "-I$include_dir") |
| 67 | + |
| 68 | +header_dir = include_dir |
| 69 | +headers = [joinpath(header_dir, "xlsxwriter.h")] |
| 70 | + |
| 71 | +# create context |
| 72 | +ctx = create_context(headers, args, options) |
| 73 | + |
| 74 | +# run generator |
| 75 | +build!(ctx, BUILDSTAGE_NO_PRINTING) |
| 76 | +rewrite!(ctx.dag) |
| 77 | +build!(ctx, BUILDSTAGE_PRINTING_ONLY) |
| 78 | + |
| 79 | +# run JuliaFormatter on the whole package |
| 80 | +format(joinpath(@__DIR__, "..")) |
0 commit comments