Debian Codegraph @

internal/gen/unicode.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Package unicode handles parsing of Unicode data files for string width calculation
2 package main
3
4 import (
5 "bufio"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "unicode"
13 )
14
15 // UnicodeData contains all the parsed Unicode character properties
16 type UnicodeData struct {
17 EastAsianWidth map[rune]string // From EastAsianWidth.txt
18 ExtendedPictographic map[rune]bool // From emoji-data.txt (Extended_Pictographic property)
19 EmojiPresentation map[rune]bool // From emoji-data.txt (Emoji_Presentation property)
20 RegionalIndicator map[rune]bool // From emoji-data.txt (Regional Indicator symbols, range 1F1E6..1F1FF)
21 ControlChars map[rune]bool // From Go stdlib
22 CombiningMarks map[rune]bool // From Go stdlib (Mn, Me only - Mc excluded for proper width)
23 ZeroWidthChars map[rune]bool // Special zero-width characters
24 }
25
26 // property represents the properties of a character
27 type property uint8
28
29 // PropertyDefinition describes a single character property flag
30 type PropertyDefinition struct {
31 Name string
32 Comment string
33 }
34
35 // PropertyDefinitions is the single source of truth for all character properties.
36 // The order matters - it defines the bit positions (via iota).
37 var PropertyDefinitions = []PropertyDefinition{
38 {"Zero_Width", "Always 0 width, includes combining marks, control characters, non-printable, etc"},
39 {"Wide", "Always 2 wide (East Asian Wide F/W, Emoji, Regional Indicator)"},
40 {"East_Asian_Ambiguous", "Width depends on EastAsianWidth option"},
41 }
42
43 // these constants are used to build the property bitmap, internally.
44 // the external properties are above. Keep them in the same order!
45 const (
46 // ZWSP, ZWJ, ZWNJ, etc.
47 zero_Width property = iota + 1
48 // F, W (East Asian Wide), Emoji, Regional Indicator
49 wide
50 // A (East Asian Ambiguous)
51 east_Asian_Ambiguous
52 )
53
54 // ParseUnicodeData downloads and parses all required Unicode data files
55 func ParseUnicodeData() (*UnicodeData, error) {
56 data := &UnicodeData{
57 EastAsianWidth: make(map[rune]string),
58 ExtendedPictographic: make(map[rune]bool),
59 EmojiPresentation: make(map[rune]bool),
60 RegionalIndicator: make(map[rune]bool),
61 ControlChars: make(map[rune]bool),
62 CombiningMarks: make(map[rune]bool),
63 ZeroWidthChars: make(map[rune]bool),
64 }
65
66 // Create data directory
•67 dataDir := "data"
68 if err := os.MkdirAll(dataDir, 0755); err != nil {
69 return nil, fmt.Errorf("failed to create data directory: %v", err)
70 }
71
72 eawFile := filepath.Join(dataDir, "EastAsianWidth.txt")
•73 if err := downloadFile("/usr/share/unicode/EastAsianWidth.txt", eawFile); err != nil {
74 return nil, fmt.Errorf("failed to download EastAsianWidth.txt: %v", err)
75 }
76 if err := parseEastAsianWidth(eawFile, data); err != nil {
77 return nil, fmt.Errorf("failed to parse EastAsianWidth.txt: %v", err)
78 }
79
80 emojiFile := filepath.Join(dataDir, "emoji-data.txt")
•81 if err := downloadFile("/usr/share/unicode/emoji/emoji-data.txt", emojiFile); err != nil {
82 fmt.Printf("Warning: failed to download emoji-data.txt: %v\n", err)
83 fmt.Println("Continuing with basic emoji detection from Go stdlib...")
84 } else {
85 if err := parseEmojiData(emojiFile, data); err != nil {
86 fmt.Printf("Warning: failed to parse emoji-data.txt: %v\n", err)
87 fmt.Println("Continuing with basic emoji detection from Go stdlib...")
88 }
89 }
90
91 extractStdlibData(data)
92
93 return data, nil
94 }
95
96 // downloadFile downloads a file from URL to local path
97 func downloadFile(url, filepath string) error {
98 // Check if file already exists
99 if _, err := os.Stat(filepath); err == nil {
100 fmt.Printf("File %s already exists, skipping download\n", filepath)
101 return nil
102 }
103
104 fmt.Printf("Downloading %s...\n", url)
•105 file, err := os.Open(url)
106 if err != nil {
107 return err
108 }
•109 defer file.Close()
110
111 out, err := os.Create(filepath)
112 if err != nil {
113 return err
114 }
115 defer out.Close()
116
•117 _, err = io.Copy(out, file)
118 if err != nil {
119 return err
120 }
121
122 fmt.Printf("Downloaded %s\n", filepath)
123 return nil
124 }
125
126 // parseEastAsianWidth parses the EastAsianWidth.txt file
127 func parseEastAsianWidth(filename string, data *UnicodeData) error {
128 file, err := os.Open(filename)
129 if err != nil {
130 return err
131 }
132 defer file.Close()
133
134 scanner := bufio.NewScanner(file)
135 for scanner.Scan() {
136 line := strings.TrimSpace(scanner.Text())
137 if line == "" || strings.HasPrefix(line, "#") {
138 continue
139 }
140
141 parts := strings.Split(line, ";")
142 if len(parts) < 2 {
143 continue
144 }
145
146 rangeStr := strings.TrimSpace(parts[0])
147 widthStr := strings.TrimSpace(parts[1])
148
149 // Remove comments from width string
150 if commentIndex := strings.Index(widthStr, "#"); commentIndex != -1 {
151 widthStr = strings.TrimSpace(widthStr[:commentIndex])
152 }
153
154 // Parse range
155 if strings.Contains(rangeStr, "..") {
156 // Range of codepoints
157 rangeParts := strings.Split(rangeStr, "..")
158 if len(rangeParts) != 2 {
159 continue
160 }
161 start, err1 := strconv.ParseInt(rangeParts[0], 16, 32)
162 end, err2 := strconv.ParseInt(rangeParts[1], 16, 32)
163 if err1 != nil || err2 != nil {
164 continue
165 }
166 for r := rune(start); r <= rune(end); r++ {
167 data.EastAsianWidth[r] = widthStr
168 }
169 } else {
170 // Single codepoint
171 codepoint, err := strconv.ParseInt(rangeStr, 16, 32)
172 if err != nil {
173 continue
174 }
175 data.EastAsianWidth[rune(codepoint)] = widthStr
176 }
177 }
178
179 return scanner.Err()
180 }
181
182 // parseEmojiData parses the emoji-data.txt file for Extended_Pictographic and Emoji_Presentation
183 func parseEmojiData(filename string, data *UnicodeData) error {
184 file, err := os.Open(filename)
185 if err != nil {
186 return err
187 }
188 defer file.Close()
189
190 scanner := bufio.NewScanner(file)
191
192 for scanner.Scan() {
193 line := strings.TrimSpace(scanner.Text())
194 if line == "" || strings.HasPrefix(line, "#") {
195 continue
196 }
197
198 // Parse line format: <codepoint(s)> ; <property> # <comments>
199 parts := strings.Split(line, ";")
200 if len(parts) < 2 {
201 continue
202 }
203
204 rangeStr := strings.TrimSpace(parts[0])
205 propertyStr := strings.TrimSpace(parts[1])
206
207 // Remove comments from property string
208 if commentIndex := strings.Index(propertyStr, "#"); commentIndex != -1 {
209 propertyStr = strings.TrimSpace(propertyStr[:commentIndex])
210 }
211
212 var r1, r2 rune
213
214 // Parse range
215 if strings.Contains(rangeStr, "..") {
216 // Range of codepoints
217 rangeParts := strings.Split(rangeStr, "..")
218 if len(rangeParts) != 2 {
219 continue
220 }
221 start, err1 := strconv.ParseInt(rangeParts[0], 16, 32)
222 end, err2 := strconv.ParseInt(rangeParts[1], 16, 32)
223 if err1 != nil || err2 != nil {
224 continue
225 }
226 r1, r2 = rune(start), rune(end)
227 } else {
228 // Single codepoint
229 codepoint, err := strconv.ParseInt(rangeStr, 16, 32)
230 if err != nil {
231 continue
232 }
233 r1, r2 = rune(codepoint), rune(codepoint)
234 }
235
236 // Skip characters below 0xFF (ASCII range is handled specially)
237 if r2 < 0xFF {
238 continue
239 }
240
241 // Check if this is a Regional Indicator character (range 1F1E6..1F1FF)
242 // Regional Indicator characters can appear with any property, but we identify them by range
243 const regionalIndicatorStart = 0x1F1E6
244 const regionalIndicatorEnd = 0x1F1FF
245 if r1 >= regionalIndicatorStart && r2 <= regionalIndicatorEnd {
246 // Add all Regional Indicator characters to the RegionalIndicator map
247 for r := r1; r <= r2; r++ {
248 data.RegionalIndicator[r] = true
249 }
250 // Don't add them to ExtendedPictographic or EmojiPresentation maps
251 continue
252 }
253
254 // We're only interested in Extended_Pictographic and Emoji_Presentation for non-Regional Indicator characters
255 if propertyStr != "Extended_Pictographic" && propertyStr != "Emoji_Presentation" {
256 continue
257 }
258
259 // Add to the appropriate map
260 for r := r1; r <= r2; r++ {
261 switch propertyStr {
262 case "Extended_Pictographic":
263 data.ExtendedPictographic[r] = true
264 case "Emoji_Presentation":
265 data.EmojiPresentation[r] = true
266 }
267 }
268 }
269
270 return scanner.Err()
271 }
272
273 // extractStdlibData extracts character properties from Go's unicode package
274 func extractStdlibData(data *UnicodeData) {
275 // Extract control characters
276 // Skip 0x00-0x1F and 0x7F as they're handled by the fast path in width.go
277 // Only add C1 controls (0x80-0x9F) which are multi-byte in UTF-8
278 for r := rune(0x80); r <= 0x9F; r++ {
279 data.ControlChars[r] = true // C1 controls
280 }
281
282 // Extract combining marks using range tables for efficiency
283 // Mn: Nonspacing_Mark, Me: Enclosing_Mark
284 // Note: Mc (Spacing Mark) characters are excluded so they get default width 1
285 extractRunesFromRangeTable(unicode.Mn, data.CombiningMarks)
286 extractRunesFromRangeTable(unicode.Me, data.CombiningMarks)
287
288 // Cf (Other, format) is the official Unicode category for format characters
289 // which are generally invisible and have zero width.
290 extractRunesFromRangeTable(unicode.Cf, data.ZeroWidthChars)
291
292 // Zl (Other, line separator) is the official Unicode category for line separator characters
293 // which are generally invisible and have zero width.
294 extractRunesFromRangeTable(unicode.Zl, data.ZeroWidthChars)
295
296 // Zp (Other, paragraph separator) is the official Unicode category for paragraph separator characters
297 // which are generally invisible and have zero width.
298 extractRunesFromRangeTable(unicode.Zp, data.ZeroWidthChars)
299
300 // Noncharacters (U+nFFFE and U+nFFFF)
301 data.ZeroWidthChars[0xFFFE] = true
302 data.ZeroWidthChars[0xFFFF] = true
303 }
304
305 // extractRunesFromRangeTable efficiently extracts all runes from a Unicode range table
306 func extractRunesFromRangeTable(table *unicode.RangeTable, target map[rune]bool) {
307 // Iterate over 16-bit ranges
308 for _, r16 := range table.R16 {
309 for r := rune(r16.Lo); r <= rune(r16.Hi); r += rune(r16.Stride) {
310 target[r] = true
311 }
312 }
313
314 // Iterate over 32-bit ranges
315 for _, r32 := range table.R32 {
316 for r := rune(r32.Lo); r <= rune(r32.Hi); r += rune(r32.Stride) {
317 target[r] = true
318 }
319 }
320 }
321
322 func buildPropertyBitmap(r rune, data *UnicodeData) property {
323 if data.CombiningMarks[r] {
324 return zero_Width
325 }
326 if data.ControlChars[r] {
327 return zero_Width
328 }
329 if data.ZeroWidthChars[r] {
330 return zero_Width
331 }
332
333 // As a practical matter, we probably don't need separate properties for
334 // Emoji and East Asian Wide, as I believe they lead to the same
335 // result. I made this distinction for VS15 handling. However,
336 // eventually I came to the conclusion that VS15 is a no-op for width
337 // calculation. Keeping the distinction for now.
338
339 // Check for Regional Indicator before emoji
340 if data.RegionalIndicator[r] {
341 return wide
342 }
343
344 if data.ExtendedPictographic[r] && data.EmojiPresentation[r] {
345 return wide
346 }
347
348 if eaw, exists := data.EastAsianWidth[r]; exists {
349 switch eaw {
350 case "F", "W":
351 return wide
352 case "A":
353 return east_Asian_Ambiguous
354 // H (Halfwidth), Na (Narrow), and N (Neutral) are not stored
355 // as they all result in width 1 (default behavior)
356 }
357 }
358
359 return 0
360 }