Skip to content

Commit 52058dc

Browse files
committed
Tweak C type name sanitizer
This should remove some gnarly-looking underscores.
1 parent 3f25fc1 commit 52058dc

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/c.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,11 @@ const ctypes = Dict{String, String}(
106106

107107
function sanitize_for_c(str::AbstractString)
108108
# Replace any non alphanumeric characters with '_'
109-
return replace(str, r"[^a-zA-Z0-9_]" => "_")
109+
str = replace(str, r"[^a-zA-Z0-9_]" => "_")
110+
# Strip any leading / trailing underscores
111+
str = strip(str, Char['_'])
112+
# Merge any repeated underscores to just one
113+
return replace(str, r"_+" => "_")
110114
end
111115

112116
function mangle_c!(typedict::Dict{Int, String}, type_id::Int, typeinfo::OrderedDict{Int,TypeDesc})
@@ -125,6 +129,9 @@ function mangle_c!(typedict::Dict{Int, String}, type_id::Int, typeinfo::OrderedD
125129
elseif type isa StructDesc
126130
mangled = sanitize_for_c(type.name)
127131
end
132+
# FIXME: this function should check for name collisions at this stage (which can happen due to
133+
# sanitization or name ambiguity in the printing from Julia) and gensym a unique suffix
134+
# if necessary
128135
typedict[type_id] = mangled
129136
return mangled
130137
end

test/runtests.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,12 +85,12 @@ end
8585
@test occursin("#include <stddef.h>", content)
8686
@test occursin("#include <stdint.h>", content)
8787
@test occursin("#include <stdbool.h>", content)
88-
@test occursin("typedef struct CVector_Float32_ {", content)
88+
@test occursin("typedef struct CVector_Float32 {", content)
8989
@test occursin(" int32_t length;", content)
9090
@test occursin(" float* data;", content)
91-
@test occursin("CVector_Float32_ from;", content)
92-
@test occursin("CVector_Float32_ to;", content)
93-
@test occursin("float copyto_and_sum(CVectorPair_Float32_ fromto);", content)
91+
@test occursin("CVector_Float32 from;", content)
92+
@test occursin("CVector_Float32 to;", content)
93+
@test occursin("float copyto_and_sum(CVectorPair_Float32 fromto);", content)
9494
@test occursin("int32_t countsame(MyTwoVec* list, int32_t n);", content)
9595
end
9696
end

0 commit comments

Comments
 (0)