| 1 |
// =========================================================================== |
| 2 |
// |
| 3 |
// PUBLIC DOMAIN NOTICE |
| 4 |
// National Center for Biotechnology Information (NCBI) |
| 5 |
// |
| 6 |
// This software/database is a "United States Government Work" under the |
| 7 |
// terms of the United States Copyright Act. It was written as part of |
| 8 |
// the author's official duties as a United States Government employee and |
| 9 |
// thus cannot be copyrighted. This software/database is freely available |
| 10 |
// to the public for use. The National Library of Medicine and the U.S. |
| 11 |
// Government do not place any restriction on its use or reproduction. |
| 12 |
// We would, however, appreciate having the NCBI and the author cited in |
| 13 |
// any work or product based on this material. |
| 14 |
// |
| 15 |
// Although all reasonable efforts have been taken to ensure the accuracy |
| 16 |
// and reliability of the software and data, the NLM and the U.S. |
| 17 |
// Government do not and cannot warrant the performance or results that |
| 18 |
// may be obtained by using this software or data. The NLM and the U.S. |
| 19 |
// Government disclaim all warranties, express or implied, including |
| 20 |
// warranties of performance, merchantability or fitness for any particular |
| 21 |
// purpose. |
| 22 |
// |
| 23 |
// =========================================================================== |
| 24 |
// |
| 25 |
// File Name: xml.go |
| 26 |
// |
| 27 |
// Author: Jonathan Kans |
| 28 |
// |
| 29 |
// ========================================================================== |
| 30 |
|
| 31 |
package eutils |
| 32 |
|
| 33 |
import ( |
| 34 |
"bufio" |
| 35 |
"bytes" |
| 36 |
"container/heap" |
| 37 |
"html" |
| 38 |
"io" |
| 39 |
"maps" |
| 40 |
"os" |
| 41 |
"runtime" |
| 42 |
"runtime/debug" |
| 43 |
"slices" |
| 44 |
"strconv" |
| 45 |
"strings" |
| 46 |
"sync" |
| 47 |
"time" |
| 48 |
) |
| 49 |
|
| 50 |
// READ XML INPUT FILE INTO CHANNEL OF TRIMMED BLOCKS |
| 51 |
|
| 52 |
// XMLBlock is a string that begins with a left angle bracket and is trimmed back to |
| 53 |
// end with a right angle bracket. The excluded characters are saved and prepended |
| 54 |
// to the next buffer. Providing complete object tags simplifies subsequent parsing. |
| 55 |
type XMLBlock string |
| 56 |
|
| 57 |
// CreateXMLStreamer reads XML input into a channel of trimmed strings that are |
| 58 |
// then split by PartitionXML into individual records (which can be processed |
| 59 |
// concurrently), or parsed directly into a channel of tokens by CreateTokenizer. |
| 60 |
func CreateXMLStreamer(in io.Reader, inp <-chan string) <-chan XMLBlock { |
| 61 |
|
| 62 |
if inp != nil { |
| 63 |
|
| 64 |
out := make(chan XMLBlock, chanDepth) |
| 65 |
if out == nil { |
| 66 |
DisplayError("Unable to create XML block reader channel") |
| 67 |
os.Exit(1) |
| 68 |
} |
| 69 |
|
| 70 |
bufferXMLChannel := func(inp <-chan string, out chan<- XMLBlock) { |
| 71 |
|
| 72 |
// close channel when all records have been processed |
| 73 |
defer close(out) |
| 74 |
|
| 75 |
remainder := "" |
| 76 |
|
| 77 |
for str := range inp { |
| 78 |
|
| 79 |
idx := strings.LastIndex(str, ">") |
| 80 |
// still need to check doStrict and call local version of htmlBehind |
| 81 |
if idx >= 0 { |
| 82 |
idx++ |
| 83 |
prev := remainder |
| 84 |
remainder = str[idx:] |
| 85 |
str = str[:idx] |
| 86 |
rslt := prev + str |
| 87 |
rslt = strings.TrimSpace(rslt) |
| 88 |
rslt = CompressRunsOfSpaces(rslt) |
| 89 |
rslt = strings.TrimPrefix(rslt, " ") |
| 90 |
rslt = strings.TrimSuffix(rslt, " ") |
| 91 |
out <- XMLBlock(rslt) |
| 92 |
} else { |
| 93 |
remainder += str |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
if remainder != "" { |
| 98 |
remainder = strings.TrimSpace(remainder) |
| 99 |
remainder = CompressRunsOfSpaces(remainder) |
| 100 |
remainder = strings.TrimPrefix(remainder, " ") |
| 101 |
remainder = strings.TrimSuffix(remainder, " ") |
| 102 |
out <- XMLBlock(remainder) |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
// launch single buffering goroutine |
| 107 |
go bufferXMLChannel(inp, out) |
| 108 |
|
| 109 |
return out |
| 110 |
} |
| 111 |
|
| 112 |
if in == nil { |
| 113 |
return nil |
| 114 |
} |
| 115 |
|
| 116 |
out := make(chan XMLBlock, chanDepth) |
| 117 |
if out == nil { |
| 118 |
DisplayError("Unable to create XML block reader channel") |
| 119 |
os.Exit(1) |
| 120 |
} |
| 121 |
|
| 122 |
// xmlReader sends trimmed XML blocks through the output channel. |
| 123 |
xmlReader := func(in io.Reader, out chan<- XMLBlock) { |
| 124 |
|
| 125 |
// close channel when all blocks have been processed |
| 126 |
defer close(out) |
| 127 |
|
| 128 |
// 65536 appears to be the maximum number of characters presented to io.Reader |
| 129 |
// when input is piped from stdin. Increasing the buffer size when input is from |
| 130 |
// a file does not improve program performance. An additional 16384 bytes are |
| 131 |
// reserved for copying the previous remainder to the beginning of the buffer |
| 132 |
// before the next read. |
| 133 |
const XMLBUFSIZE = 65536 + 16384 |
| 134 |
|
| 135 |
buffer := make([]byte, XMLBUFSIZE) |
| 136 |
remainder := "" |
| 137 |
position := int64(0) |
| 138 |
delta := 0 |
| 139 |
isClosed := false |
| 140 |
|
| 141 |
// htmlBehind is used in strict mode to trim back further when a lower-case tag |
| 142 |
// is encountered. This may be a formatting decoration, such as <i> or </i> for |
| 143 |
// italics. Processing HTML, which may have embedded mixed content, requires use |
| 144 |
// of mixed mode. |
| 145 |
htmlBehind := func(bufr []byte, pos, txtlen int) bool { |
| 146 |
|
| 147 |
for pos >= 0 { |
| 148 |
if bufr[pos] == '<' { |
| 149 |
// detect lower-case markup tags, or DispFormula in PubMed |
| 150 |
return HTMLAhead(string(bufr), pos, txtlen) != 0 |
| 151 |
} |
| 152 |
pos-- |
| 153 |
} |
| 154 |
|
| 155 |
return false |
| 156 |
} |
| 157 |
|
| 158 |
// nextBuffer reads one buffer, trims back to the right-most > character, and |
| 159 |
// retains the remainder for prepending in the next call. It also signals if |
| 160 |
// there was no > character, resulting in subsequent calls to nextBuffer to |
| 161 |
// continue reading a large content string. |
| 162 |
nextBuffer := func() ([]byte, bool, bool) { |
| 163 |
|
| 164 |
if isClosed { |
| 165 |
return nil, false, true |
| 166 |
} |
| 167 |
|
| 168 |
// prepend previous remainder to beginning of buffer |
| 169 |
m := copy(buffer, remainder) |
| 170 |
remainder = "" |
| 171 |
if m > 16384 { |
| 172 |
// previous remainder is larger than reserved section, |
| 173 |
// write and signal the need to continue reading. |
| 174 |
return buffer[:m], true, false |
| 175 |
} |
| 176 |
|
| 177 |
// read next block, append behind copied remainder from previous read |
| 178 |
n, err := in.Read(buffer[m:]) |
| 179 |
// with data piped through stdin, read function may not always return the |
| 180 |
// same number of bytes each time |
| 181 |
if err != nil { |
| 182 |
if err != io.EOF { |
| 183 |
// real error. |
| 184 |
DisplayError("%s", err.Error()) |
| 185 |
// ignore bytes - non-conforming implementations of io.Reader may |
| 186 |
// return mangled data on non-EOF errors |
| 187 |
isClosed = true |
| 188 |
return nil, false, true |
| 189 |
} |
| 190 |
// end of file. |
| 191 |
isClosed = true |
| 192 |
if n == 0 { |
| 193 |
// if EOF and no more data, do not send final remainder (not terminated |
| 194 |
// by right angle bracket that is used as a sentinel) |
| 195 |
return nil, false, true |
| 196 |
} |
| 197 |
} |
| 198 |
if n < 0 { |
| 199 |
// reality check - non-conforming implementations of io.Reader may return -1 |
| 200 |
DisplayError("io.Reader returned negative count %d", n) |
| 201 |
// treat as n == 0 in order to update file offset and avoid losing previous remainder |
| 202 |
n = 0 |
| 203 |
} |
| 204 |
|
| 205 |
// keep track of file offset |
| 206 |
position += int64(delta) |
| 207 |
delta = n |
| 208 |
|
| 209 |
// slice of actual characters read |
| 210 |
bufr := buffer[:n+m] |
| 211 |
|
| 212 |
// Look for last > character. It is safe to back up on UTF-8 rune array when looking |
| 213 |
// for a 7-bit ASCII character. |
| 214 |
pos := -1 |
| 215 |
for pos = len(bufr) - 1; pos >= 0; pos-- { |
| 216 |
if bufr[pos] == '>' { |
| 217 |
if doStrict { |
| 218 |
// optionally skip backwards past embedded i, b, u, sub, and sup |
| 219 |
// HTML open, close, and empty tags, and MathML instructions |
| 220 |
if htmlBehind(bufr, pos, len(bufr)) { |
| 221 |
continue |
| 222 |
} |
| 223 |
} |
| 224 |
// found end of XML tag, break |
| 225 |
break |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
// trim back to last > character, save remainder for next buffer |
| 230 |
if pos > -1 { |
| 231 |
pos++ |
| 232 |
remainder = string(bufr[pos:]) |
| 233 |
return bufr[:pos], false, false |
| 234 |
} |
| 235 |
|
| 236 |
// no > found, signal need to continue reading long content |
| 237 |
return bufr[:], true, false |
| 238 |
} |
| 239 |
|
| 240 |
// nextBlock reads buffer, concatenates if necessary to place long element content |
| 241 |
// into a single string. All result strings end in > character that is used as a |
| 242 |
// sentinel in subsequent code. |
| 243 |
nextBlock := func() string { |
| 244 |
|
| 245 |
// read next buffer |
| 246 |
line, cont, closed := nextBuffer() |
| 247 |
|
| 248 |
if closed { |
| 249 |
// no sentinel in remainder at end of file |
| 250 |
return "" |
| 251 |
} |
| 252 |
|
| 253 |
if cont { |
| 254 |
// current line does not end with > character |
| 255 |
var buff bytes.Buffer |
| 256 |
|
| 257 |
// keep reading long content blocks |
| 258 |
for { |
| 259 |
if len(line) > 0 { |
| 260 |
buff.Write(line) |
| 261 |
} |
| 262 |
if !cont { |
| 263 |
// last buffer ended with sentinel |
| 264 |
break |
| 265 |
} |
| 266 |
line, cont, closed = nextBuffer() |
| 267 |
if closed { |
| 268 |
// no sentinel in multi-block buffer at end of file |
| 269 |
return "" |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
// concatenate blocks |
| 274 |
return buff.String() |
| 275 |
} |
| 276 |
|
| 277 |
return string(line) |
| 278 |
} |
| 279 |
|
| 280 |
// read XML and send blocks through channel |
| 281 |
for { |
| 282 |
str := nextBlock() |
| 283 |
|
| 284 |
// trimming spaces here would throw off line tracking |
| 285 |
|
| 286 |
// optionally compress/cleanup tags/attributes and contents |
| 287 |
if doCleanup { |
| 288 |
if HasBadSpace(str) { |
| 289 |
str = CleanupBadSpaces(str) |
| 290 |
} |
| 291 |
if HasAdjacentSpaces(str) { |
| 292 |
str = CompressRunsOfSpaces(str) |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
out <- XMLBlock(str) |
| 297 |
|
| 298 |
// bail after sending empty string sentinel |
| 299 |
if str == "" { |
| 300 |
return |
| 301 |
} |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
// launch single block reader goroutine |
| 306 |
go xmlReader(in, out) |
| 307 |
|
| 308 |
return out |
| 309 |
} |
| 310 |
|
| 311 |
// PARSE XML BLOCK STREAM INTO STRINGS FROM <PATTERN> TO </PATTERN> |
| 312 |
|
| 313 |
// PartitionXML splits XML input from <pattern> to </pattern> and sends individual |
| 314 |
// records to a callback. Requiring the input to be an XMLBlock channel of trimmed |
| 315 |
// strings, generated by CreateXMLStreamer, simplifies the code by eliminating the |
| 316 |
// need to check for an incomplete object tag at the end. |
| 317 |
func PartitionXML(pat, star string, turbo bool, inp <-chan XMLBlock, proc func(string)) { |
| 318 |
|
| 319 |
if pat == "" || inp == nil || proc == nil { |
| 320 |
return |
| 321 |
} |
| 322 |
|
| 323 |
patlen := len(pat) |
| 324 |
|
| 325 |
// position of last character in pattern |
| 326 |
last := patlen - 1 |
| 327 |
|
| 328 |
var skip [256]int |
| 329 |
|
| 330 |
// initialize Boyer-Moore-Horspool bad character displacement table |
| 331 |
for i := range skip { |
| 332 |
skip[i] = patlen |
| 333 |
} |
| 334 |
for i := range last { |
| 335 |
ch := pat[i] |
| 336 |
skip[ch] = last - i |
| 337 |
} |
| 338 |
|
| 339 |
// isAnElement checks surroundings of match candidate |
| 340 |
isAnElement := func(text string, lf, rt, mx int) bool { |
| 341 |
|
| 342 |
if (lf >= 0 && text[lf] == '<') || (lf > 0 && text[lf] == '/' && text[lf-1] == '<') { |
| 343 |
if (rt < mx && (text[rt] == '>' || text[rt] == ' ' || text[rt] == '\n')) || |
| 344 |
(rt+1 < mx && text[rt] == '/' && text[rt+1] == '>') { |
| 345 |
return true |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
return false |
| 350 |
} |
| 351 |
|
| 352 |
// findNextMatch is a modified Boyer-Moore-Horspool search function for maximum partitioning speed |
| 353 |
findNextMatch := func(text string, offset int) (int, int, int) { |
| 354 |
|
| 355 |
if text == "" { |
| 356 |
return -1, -1, -1 |
| 357 |
} |
| 358 |
|
| 359 |
txtlen := len(text) |
| 360 |
|
| 361 |
max := txtlen - patlen |
| 362 |
last := patlen - 1 |
| 363 |
|
| 364 |
i := offset |
| 365 |
|
| 366 |
for i <= max { |
| 367 |
|
| 368 |
// start at right-most character |
| 369 |
j := last |
| 370 |
k := i + last |
| 371 |
for j >= 0 && text[k] == pat[j] { |
| 372 |
j-- |
| 373 |
k-- |
| 374 |
} |
| 375 |
|
| 376 |
// require match candidate to be element name, i.e., |
| 377 |
// <pattern ... >, </pattern ... >, or <pattern ... /> |
| 378 |
if j < 0 && isAnElement(text, i-1, i+patlen, txtlen) { |
| 379 |
|
| 380 |
// find positions of flanking angle brackets |
| 381 |
lf := i - 1 |
| 382 |
for lf > 0 && text[lf] != '<' { |
| 383 |
lf-- |
| 384 |
} |
| 385 |
rt := i + patlen |
| 386 |
for rt < txtlen && text[rt] != '>' { |
| 387 |
rt++ |
| 388 |
} |
| 389 |
return i + 1, lf, rt + 1 |
| 390 |
} |
| 391 |
|
| 392 |
// find character in text above last character in pattern |
| 393 |
ch := text[i+last] |
| 394 |
// displacement table can shift pattern by one or more positions |
| 395 |
i += skip[ch] |
| 396 |
} |
| 397 |
|
| 398 |
return -1, -1, -1 |
| 399 |
} |
| 400 |
|
| 401 |
// pattern type keys for XML parsing |
| 402 |
const ( |
| 403 |
noPat = iota |
| 404 |
startPat |
| 405 |
selfPat |
| 406 |
stopPat |
| 407 |
) |
| 408 |
|
| 409 |
// nextPattern finds next element with pattern name |
| 410 |
nextPattern := func(text string, pos int) (int, int, int, int) { |
| 411 |
|
| 412 |
if text == "" { |
| 413 |
return noPat, 0, 0, 0 |
| 414 |
} |
| 415 |
|
| 416 |
prev := pos |
| 417 |
|
| 418 |
for { |
| 419 |
next, start, stop := findNextMatch(text, prev) |
| 420 |
if next < 0 { |
| 421 |
return noPat, 0, 0, 0 |
| 422 |
} |
| 423 |
|
| 424 |
prev = next + 1 |
| 425 |
|
| 426 |
if text[start+1] == '/' { |
| 427 |
return stopPat, start, stop, prev |
| 428 |
} else if text[stop-2] == '/' { |
| 429 |
return selfPat, start, stop, prev |
| 430 |
} else { |
| 431 |
return startPat, start, stop, prev |
| 432 |
} |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
// doNormal handles -pattern Object construct, keeping track of nesting level |
| 437 |
doNormal := func() { |
| 438 |
|
| 439 |
// current depth of -pattern objects |
| 440 |
level := 0 |
| 441 |
|
| 442 |
inPattern := false |
| 443 |
|
| 444 |
var accumulator strings.Builder |
| 445 |
|
| 446 |
for { |
| 447 |
|
| 448 |
match := noPat |
| 449 |
start := 0 |
| 450 |
stop := 0 |
| 451 |
next := 0 |
| 452 |
|
| 453 |
begin := 0 |
| 454 |
|
| 455 |
text := string(<-inp) |
| 456 |
if text == "" { |
| 457 |
return |
| 458 |
} |
| 459 |
|
| 460 |
for { |
| 461 |
match, start, stop, next = nextPattern(text, next) |
| 462 |
if match == startPat { |
| 463 |
if level == 0 { |
| 464 |
inPattern = true |
| 465 |
begin = start |
| 466 |
} |
| 467 |
level++ |
| 468 |
} else if match == stopPat { |
| 469 |
level-- |
| 470 |
if level == 0 { |
| 471 |
inPattern = false |
| 472 |
accumulator.WriteString(text[begin:stop]) |
| 473 |
// read and process one -pattern object at a time |
| 474 |
str := accumulator.String() |
| 475 |
if str != "" { |
| 476 |
proc(str[:]) |
| 477 |
} |
| 478 |
// reset accumulator |
| 479 |
accumulator.Reset() |
| 480 |
} |
| 481 |
} else if match == selfPat { |
| 482 |
if level == 0 { |
| 483 |
str := text[start:stop] |
| 484 |
if str != "" { |
| 485 |
proc(str[:]) |
| 486 |
} |
| 487 |
} |
| 488 |
} else { |
| 489 |
if inPattern { |
| 490 |
accumulator.WriteString(text[begin:]) |
| 491 |
} |
| 492 |
break |
| 493 |
} |
| 494 |
} |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
// doTurbo reads an XML file that has NEXT_RECORD_SIZE objects with |
| 499 |
// the number of bytes to read to get the next indexed pattern |
| 500 |
doTurbo := func() { |
| 501 |
|
| 502 |
var accumulator strings.Builder |
| 503 |
|
| 504 |
for { |
| 505 |
|
| 506 |
// read next XMLBlock ending with '>' character |
| 507 |
text := string(<-inp) |
| 508 |
if text == "" { |
| 509 |
return |
| 510 |
} |
| 511 |
|
| 512 |
// should be at next NEXT_RECORD_SIZE object |
| 513 |
for { |
| 514 |
|
| 515 |
// find start tag of next record size object |
| 516 |
idx := strings.Index(text, "<NEXT_RECORD_SIZE>") |
| 517 |
if idx < 0 { |
| 518 |
break |
| 519 |
} |
| 520 |
text = text[idx+18:] |
| 521 |
|
| 522 |
// if end of buffer, read next XMLBlock |
| 523 |
if text == "" { |
| 524 |
text = string(<-inp) |
| 525 |
if text == "" { |
| 526 |
return |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
// find stop tag of next record size object |
| 531 |
idx = strings.Index(text, "</NEXT_RECORD_SIZE>") |
| 532 |
if idx < 0 { |
| 533 |
break |
| 534 |
} |
| 535 |
str := text[:idx] |
| 536 |
text = text[idx+19:] |
| 537 |
if strings.HasPrefix(text, "\n") { |
| 538 |
text = text[1:] |
| 539 |
} |
| 540 |
|
| 541 |
// convert object value to integer |
| 542 |
size, err := strconv.Atoi(str) |
| 543 |
if err != nil { |
| 544 |
break |
| 545 |
} |
| 546 |
|
| 547 |
accumulator.Reset() |
| 548 |
|
| 549 |
for { |
| 550 |
// size of remaining text in block |
| 551 |
max := len(text) |
| 552 |
|
| 553 |
// is record completely contained in current block |
| 554 |
if size < max { |
| 555 |
rec := text[:size] |
| 556 |
text = text[size:] |
| 557 |
// prepend any text collected from previous blocks |
| 558 |
prev := accumulator.String() |
| 559 |
res := prev + rec |
| 560 |
res = strings.TrimPrefix(res, "\n") |
| 561 |
res = strings.TrimSuffix(res, "\n") |
| 562 |
proc(res[:]) |
| 563 |
break |
| 564 |
} |
| 565 |
|
| 566 |
// otherwise record remainder of block |
| 567 |
accumulator.WriteString(text) |
| 568 |
// decrement remaining size |
| 569 |
size -= len(text) |
| 570 |
// read next block |
| 571 |
text = string(<-inp) |
| 572 |
if text == "" { |
| 573 |
// last record on final block |
| 574 |
res := accumulator.String() |
| 575 |
res = strings.TrimPrefix(res, "\n") |
| 576 |
res = strings.TrimSuffix(res, "\n") |
| 577 |
proc(res[:]) |
| 578 |
return |
| 579 |
} |
| 580 |
// and keep going until desired size is collected |
| 581 |
} |
| 582 |
} |
| 583 |
} |
| 584 |
} |
| 585 |
|
| 586 |
// doStar handles -pattern Parent/* construct for heterogeneous objects. It can work |
| 587 |
// with concatenated files, but not if components are recursive or self-closing objects. |
| 588 |
// Process the latter through transmute -format -self first. |
| 589 |
doStar := func() { |
| 590 |
|
| 591 |
// nextStarPat scans for next XML element matching the current inner pattern |
| 592 |
nextStarPat := func(scr *BMHSearcher, text string, offset int) (int, int, int, int) { |
| 593 |
|
| 594 |
if scr == nil || text == "" { |
| 595 |
return noPat, -1, -1, -1 |
| 596 |
} |
| 597 |
|
| 598 |
ptyp := noPat |
| 599 |
start := 0 |
| 600 |
stop := 0 |
| 601 |
prev := 0 |
| 602 |
|
| 603 |
txtlen := len(text) |
| 604 |
|
| 605 |
scr.Search(text[:], offset, |
| 606 |
func(str, ptn string, pos int) bool { |
| 607 |
|
| 608 |
patlen := len(ptn) |
| 609 |
|
| 610 |
// require match candidate to be element name, i.e., |
| 611 |
// <pattern ... >, </pattern ... >, or <pattern ... /> |
| 612 |
if isAnElement(text[:], pos-1, pos+patlen, txtlen) { |
| 613 |
|
| 614 |
// find positions of flanking angle brackets |
| 615 |
lf := pos - 1 |
| 616 |
for lf > 0 && text[lf] != '<' { |
| 617 |
lf-- |
| 618 |
} |
| 619 |
rt := pos + patlen |
| 620 |
for rt < txtlen && text[rt] != '>' { |
| 621 |
rt++ |
| 622 |
} |
| 623 |
|
| 624 |
// save function return values |
| 625 |
prev = pos + 1 |
| 626 |
start = lf |
| 627 |
stop = rt + 1 |
| 628 |
|
| 629 |
// switch on type of match |
| 630 |
if text[start+1] == '/' { |
| 631 |
ptyp = stopPat |
| 632 |
} else if text[stop-2] == '/' { |
| 633 |
ptyp = selfPat |
| 634 |
} else { |
| 635 |
ptyp = startPat |
| 636 |
} |
| 637 |
|
| 638 |
// callback signal to end search |
| 639 |
return false |
| 640 |
} |
| 641 |
|
| 642 |
// keep going to next candidate |
| 643 |
return true |
| 644 |
}) |
| 645 |
|
| 646 |
return ptyp, start, stop, prev |
| 647 |
} |
| 648 |
|
| 649 |
text := "" |
| 650 |
|
| 651 |
match := noPat |
| 652 |
start := 0 |
| 653 |
stop := 0 |
| 654 |
next := 0 |
| 655 |
|
| 656 |
// read to first <pattern> element |
| 657 |
for { |
| 658 |
|
| 659 |
next = 0 |
| 660 |
|
| 661 |
text = string(<-inp) |
| 662 |
if text == "" { |
| 663 |
break |
| 664 |
} |
| 665 |
|
| 666 |
match, start, stop, next = nextPattern(text, next) |
| 667 |
if match == startPat { |
| 668 |
break |
| 669 |
} |
| 670 |
} |
| 671 |
|
| 672 |
if match != startPat { |
| 673 |
return |
| 674 |
} |
| 675 |
|
| 676 |
// current depth of -pattern objects |
| 677 |
level := 0 |
| 678 |
|
| 679 |
begin := 0 |
| 680 |
|
| 681 |
inPattern := false |
| 682 |
|
| 683 |
var accumulator strings.Builder |
| 684 |
|
| 685 |
last := "" |
| 686 |
|
| 687 |
// string search for inner objects |
| 688 |
var scr *BMHSearcher |
| 689 |
|
| 690 |
// read and process heterogeneous objects immediately below <pattern> parent |
| 691 |
for { |
| 692 |
|
| 693 |
// find next element in XML |
| 694 |
nextElement := func(txt string, pos int) string { |
| 695 |
|
| 696 |
txtlen := len(txt) |
| 697 |
|
| 698 |
tag := "" |
| 699 |
for i := pos; i < txtlen; i++ { |
| 700 |
if txt[i] == '<' { |
| 701 |
tag = txt[i+1:] |
| 702 |
break |
| 703 |
} |
| 704 |
} |
| 705 |
if tag == "" { |
| 706 |
return "" |
| 707 |
} |
| 708 |
if tag[0] == '/' { |
| 709 |
if strings.HasPrefix(tag[1:], pat) { |
| 710 |
//should be </pattern> at end, want to continue if concatenated files |
| 711 |
return "/" |
| 712 |
} |
| 713 |
return "" |
| 714 |
} |
| 715 |
for i, ch := range tag { |
| 716 |
if ch == '>' || ch == ' ' || ch == '/' { |
| 717 |
return tag[0:i] |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
return "" |
| 722 |
} |
| 723 |
|
| 724 |
tag := nextElement(text, next) |
| 725 |
if tag == "" { |
| 726 |
|
| 727 |
begin = 0 |
| 728 |
next = 0 |
| 729 |
|
| 730 |
text = string(<-inp) |
| 731 |
if text == "" { |
| 732 |
break |
| 733 |
} |
| 734 |
|
| 735 |
tag = nextElement(text, next) |
| 736 |
} |
| 737 |
if tag == "" { |
| 738 |
return |
| 739 |
} |
| 740 |
|
| 741 |
// check for concatenated parent set files |
| 742 |
if tag[0] == '/' { |
| 743 |
// confirm end </pattern> just found |
| 744 |
match, start, stop, next = nextPattern(text, next) |
| 745 |
if match != stopPat { |
| 746 |
return |
| 747 |
} |
| 748 |
// now look for a new start <pattern> tag |
| 749 |
for { |
| 750 |
match, start, stop, next = nextPattern(text, next) |
| 751 |
if match == startPat { |
| 752 |
break |
| 753 |
} |
| 754 |
next = 0 |
| 755 |
text = string(<-inp) |
| 756 |
if text == "" { |
| 757 |
break |
| 758 |
} |
| 759 |
} |
| 760 |
if match != startPat { |
| 761 |
return |
| 762 |
} |
| 763 |
// continue with processing loop |
| 764 |
continue |
| 765 |
} |
| 766 |
|
| 767 |
if tag != last { |
| 768 |
// search for inner pattern (may change for heterogeneous sets) |
| 769 |
scr = StringSearcher(tag, true, false, false, false, false) |
| 770 |
if scr == nil { |
| 771 |
return |
| 772 |
} |
| 773 |
last = tag |
| 774 |
} |
| 775 |
|
| 776 |
for { |
| 777 |
match, start, stop, next = nextStarPat(scr, text, next) |
| 778 |
if match == startPat { |
| 779 |
if level == 0 { |
| 780 |
inPattern = true |
| 781 |
begin = start |
| 782 |
} |
| 783 |
level++ |
| 784 |
} else if match == stopPat { |
| 785 |
level-- |
| 786 |
if level == 0 { |
| 787 |
inPattern = false |
| 788 |
accumulator.WriteString(text[begin:stop]) |
| 789 |
// read and process one -pattern/* object at a time |
| 790 |
str := accumulator.String() |
| 791 |
if str != "" { |
| 792 |
proc(str[:]) |
| 793 |
} |
| 794 |
// reset accumulator |
| 795 |
accumulator.Reset() |
| 796 |
break |
| 797 |
} |
| 798 |
} else if match == selfPat { |
| 799 |
if level == 0 { |
| 800 |
str := text[start:stop] |
| 801 |
if str != "" { |
| 802 |
proc(str[:]) |
| 803 |
} |
| 804 |
} |
| 805 |
} else { |
| 806 |
if inPattern { |
| 807 |
accumulator.WriteString(text[begin:]) |
| 808 |
} |
| 809 |
|
| 810 |
begin = 0 |
| 811 |
next = 0 |
| 812 |
|
| 813 |
text = string(<-inp) |
| 814 |
if text == "" { |
| 815 |
break |
| 816 |
} |
| 817 |
} |
| 818 |
} |
| 819 |
} |
| 820 |
} |
| 821 |
|
| 822 |
// call appropriate handler |
| 823 |
if turbo { |
| 824 |
doTurbo() |
| 825 |
} else if star == "" { |
| 826 |
doNormal() |
| 827 |
} else if star == "*" { |
| 828 |
doStar() |
| 829 |
} |
| 830 |
} |
| 831 |
|
| 832 |
// XMLRecord wraps a numbered XML record or the results of data extraction on |
| 833 |
// that record. The Index field stores the record's original position in the |
| 834 |
// input stream. The Data field is used for binary compressed PubmedArticle XML. |
| 835 |
type XMLRecord struct { |
| 836 |
Data []byte |
| 837 |
Ident string |
| 838 |
Text string |
| 839 |
Index int |
| 840 |
} |
| 841 |
|
| 842 |
// CreateXMLProducer partitions an XML set and sends records down a channel. |
| 843 |
// After processing asynchronously in multiple concurrent go routines, the |
| 844 |
// original order can be restored by passage through the XMLUnshuffler. |
| 845 |
func CreateXMLProducer(pat, star string, turbo bool, rdr <-chan XMLBlock) <-chan XMLRecord { |
| 846 |
|
| 847 |
if rdr == nil { |
| 848 |
return nil |
| 849 |
} |
| 850 |
|
| 851 |
out := make(chan XMLRecord, chanDepth) |
| 852 |
if out == nil { |
| 853 |
DisplayError("Unable to create XML producer channel") |
| 854 |
os.Exit(1) |
| 855 |
} |
| 856 |
|
| 857 |
// xmlProducer sends partitioned XML strings through channel. |
| 858 |
xmlProducer := func(pat, star string, turbo bool, rdr <-chan XMLBlock, out chan<- XMLRecord) { |
| 859 |
|
| 860 |
// close channel when all records have been processed |
| 861 |
defer close(out) |
| 862 |
|
| 863 |
rec := 0 |
| 864 |
|
| 865 |
// partition all input by pattern and send XML substring to available consumer through channel |
| 866 |
PartitionXML(pat, star, turbo, rdr, |
| 867 |
func(str string) { |
| 868 |
rec++ |
| 869 |
out <- XMLRecord{Index: rec, Text: str} |
| 870 |
}) |
| 871 |
} |
| 872 |
|
| 873 |
// launch single producer goroutine |
| 874 |
go xmlProducer(pat, star, turbo, rdr, out) |
| 875 |
|
| 876 |
return out |
| 877 |
} |
| 878 |
|
| 879 |
// UNSHUFFLER USES HEAP TO RESTORE OUTPUT OF MULTIPLE CONSUMERS TO ORIGINAL RECORD ORDER |
| 880 |
|
| 881 |
// xmlRecordHeap collects asynchronous processing results for presentation in the original order. |
| 882 |
type xmlRecordHeap []XMLRecord |
| 883 |
|
| 884 |
// methods that satisfy heap.Interface |
| 885 |
func (h xmlRecordHeap) Len() int { |
| 886 |
return len(h) |
| 887 |
} |
| 888 |
func (h xmlRecordHeap) Less(i, j int) bool { |
| 889 |
return h[i].Index < h[j].Index |
| 890 |
} |
| 891 |
func (h xmlRecordHeap) Swap(i, j int) { |
| 892 |
h[i], h[j] = h[j], h[i] |
| 893 |
} |
| 894 |
func (h *xmlRecordHeap) Push(x interface{}) { |
| 895 |
*h = append(*h, x.(XMLRecord)) |
| 896 |
} |
| 897 |
func (h *xmlRecordHeap) Pop() interface{} { |
| 898 |
old := *h |
| 899 |
n := len(old) |
| 900 |
x := old[n-1] |
| 901 |
*h = old[0 : n-1] |
| 902 |
return x |
| 903 |
} |
| 904 |
|
| 905 |
// CreateXMLUnshuffler passes the output of multiple concurrent processors to |
| 906 |
// a heap, which releases results in the same order as the original records. |
| 907 |
func CreateXMLUnshuffler(inp <-chan XMLRecord) <-chan XMLRecord { |
| 908 |
|
| 909 |
if inp == nil { |
| 910 |
return nil |
| 911 |
} |
| 912 |
|
| 913 |
out := make(chan XMLRecord, chanDepth) |
| 914 |
if out == nil { |
| 915 |
DisplayError("Unable to create XML unshuffler channel") |
| 916 |
os.Exit(1) |
| 917 |
} |
| 918 |
|
| 919 |
// xmlUnshuffler restores original order with heap. |
| 920 |
xmlUnshuffler := func(inp <-chan XMLRecord, out chan<- XMLRecord) { |
| 921 |
|
| 922 |
// close channel when all records have been processed |
| 923 |
defer close(out) |
| 924 |
|
| 925 |
// initialize empty heap |
| 926 |
hp := &xmlRecordHeap{} |
| 927 |
heap.Init(hp) |
| 928 |
|
| 929 |
// index of next desired result |
| 930 |
next := 1 |
| 931 |
|
| 932 |
delay := 0 |
| 933 |
|
| 934 |
for ext := range inp { |
| 935 |
|
| 936 |
// push result onto heap |
| 937 |
heap.Push(hp, ext) |
| 938 |
|
| 939 |
// Read several values before checking to see if next record to print has been processed. |
| 940 |
// The default heapSize value has been tuned by experiment for maximum performance. |
| 941 |
if delay < heapSize { |
| 942 |
delay++ |
| 943 |
continue |
| 944 |
} |
| 945 |
|
| 946 |
delay = 0 |
| 947 |
|
| 948 |
for hp.Len() > 0 { |
| 949 |
|
| 950 |
// remove lowest item from heap, use interface type assertion |
| 951 |
curr := heap.Pop(hp).(XMLRecord) |
| 952 |
|
| 953 |
if curr.Index > next { |
| 954 |
|
| 955 |
// record should be printed later, push back onto heap |
| 956 |
heap.Push(hp, curr) |
| 957 |
// and go back to waiting on input channel |
| 958 |
break |
| 959 |
} |
| 960 |
|
| 961 |
// send even if empty to get all record counts for reordering |
| 962 |
out <- XMLRecord{Index: curr.Index, Ident: curr.Ident, Text: curr.Text, Data: curr.Data} |
| 963 |
|
| 964 |
// prevent ambiguous -limit filter from clogging heap (deprecated) |
| 965 |
if curr.Index == next { |
| 966 |
// increment index for next expected match |
| 967 |
next++ |
| 968 |
} |
| 969 |
|
| 970 |
// continue to check heap to see if next result is already available |
| 971 |
} |
| 972 |
} |
| 973 |
|
| 974 |
// flush remainder of heap to output |
| 975 |
for hp.Len() > 0 { |
| 976 |
curr := heap.Pop(hp).(XMLRecord) |
| 977 |
|
| 978 |
out <- XMLRecord{Index: curr.Index, Ident: curr.Ident, Text: curr.Text, Data: curr.Data} |
| 979 |
} |
| 980 |
} |
| 981 |
|
| 982 |
// launch single unshuffler goroutine |
| 983 |
go xmlUnshuffler(inp, out) |
| 984 |
|
| 985 |
return out |
| 986 |
} |
| 987 |
|
| 988 |
// CONCURRENT CONSUMER GOROUTINES PARSE AND PROCESS PARTITIONED XML OBJECTS |
| 989 |
|
| 990 |
// StreamBlocks -> SplitPattern => XmlParse => StreamTokens => ProcessExtract -> MergeResults |
| 991 |
|
| 992 |
// processes with single goroutine call defer close(out) so consumer(s) can range over channel |
| 993 |
// processes with multiple instances call defer wg.Done(), separate goroutine uses wg.Wait() to delay close(out) |
| 994 |
|
| 995 |
// CreateXMLConsumers runs multiple query processing go routines |
| 996 |
func CreateXMLConsumers(cmds *Block, parent, hd, tl string, transform map[string]string, forClassify bool, histogram map[string]int, inp <-chan XMLRecord) <-chan XMLRecord { |
| 997 |
|
| 998 |
if inp == nil { |
| 999 |
return nil |
| 1000 |
} |
| 1001 |
|
| 1002 |
out := make(chan XMLRecord, chanDepth) |
| 1003 |
if out == nil { |
| 1004 |
DisplayError("Unable to create consumer channel") |
| 1005 |
os.Exit(1) |
| 1006 |
} |
| 1007 |
|
| 1008 |
var srchr *FSMSearcher |
| 1009 |
|
| 1010 |
if forClassify { |
| 1011 |
var patterns []string |
| 1012 |
for ky := range transform { |
| 1013 |
patterns = append(patterns, ky) |
| 1014 |
} |
| 1015 |
// initialize string searcher from transform table |
| 1016 |
srchr = PatternSearcher(patterns, false, true, true, false, false) |
| 1017 |
} |
| 1018 |
|
| 1019 |
// xmlConsumer reads partitioned XML from channel and calls parser for processing |
| 1020 |
xmlConsumer := func(cmds *Block, parent string, wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- XMLRecord) { |
| 1021 |
|
| 1022 |
// report when this consumer has no more records to process |
| 1023 |
defer wg.Done() |
| 1024 |
|
| 1025 |
// read partitioned XML from producer channel |
| 1026 |
for ext := range inp { |
| 1027 |
|
| 1028 |
idx := ext.Index |
| 1029 |
ident := ext.Ident |
| 1030 |
text := ext.Text |
| 1031 |
|
| 1032 |
if text == "" { |
| 1033 |
// should never see empty input data |
| 1034 |
out <- XMLRecord{Index: idx, Ident: ident, Text: text} |
| 1035 |
continue |
| 1036 |
} |
| 1037 |
|
| 1038 |
str := ProcessExtract(text[:], parent, idx, hd, tl, transform, srchr, histogram, cmds) |
| 1039 |
|
| 1040 |
// send even if empty to get all record counts for reordering |
| 1041 |
out <- XMLRecord{Index: idx, Ident: ident, Text: str} |
| 1042 |
} |
| 1043 |
} |
| 1044 |
|
| 1045 |
var wg sync.WaitGroup |
| 1046 |
|
| 1047 |
// launch multiple consumer goroutines |
| 1048 |
for range numServe { |
| 1049 |
wg.Add(1) |
| 1050 |
go xmlConsumer(cmds, parent, &wg, inp, out) |
| 1051 |
} |
| 1052 |
|
| 1053 |
// launch separate anonymous goroutine to wait until all consumers are done |
| 1054 |
go func() { |
| 1055 |
wg.Wait() |
| 1056 |
close(out) |
| 1057 |
}() |
| 1058 |
|
| 1059 |
return out |
| 1060 |
} |
| 1061 |
|
| 1062 |
// -select SUPPORT FUNCTIONS |
| 1063 |
|
| 1064 |
// CreateSelectors supports xtract -select parent/element@attribute^version -in file_of_identifiers |
| 1065 |
func CreateSelectors(parent, indx string, order map[string]bool, inp <-chan XMLRecord) <-chan XMLRecord { |
| 1066 |
|
| 1067 |
if parent == "" || indx == "" || order == nil || inp == nil { |
| 1068 |
return nil |
| 1069 |
} |
| 1070 |
|
| 1071 |
find := ParseIndex(indx) |
| 1072 |
|
| 1073 |
out := make(chan XMLRecord, chanDepth) |
| 1074 |
if out == nil { |
| 1075 |
DisplayError("Unable to create selector channel") |
| 1076 |
os.Exit(1) |
| 1077 |
} |
| 1078 |
|
| 1079 |
// xmlSelector reads partitioned XML from channel and matches identifiers of records to keep |
| 1080 |
xmlSelector := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- XMLRecord) { |
| 1081 |
|
| 1082 |
// report when this selector has no more records to process |
| 1083 |
defer wg.Done() |
| 1084 |
|
| 1085 |
// read partitioned XML from producer channel |
| 1086 |
for ext := range inp { |
| 1087 |
|
| 1088 |
text := ext.Text |
| 1089 |
|
| 1090 |
found := false |
| 1091 |
|
| 1092 |
FindIdentifiers(text[:], parent, find, |
| 1093 |
func(id string) { |
| 1094 |
id = SortStringByWords(id) |
| 1095 |
_, ok := order[id] |
| 1096 |
if ok { |
| 1097 |
found = true |
| 1098 |
} |
| 1099 |
}) |
| 1100 |
|
| 1101 |
if !found { |
| 1102 |
// identifier field not found or not in identifier list, send empty placeholder for unshuffler |
| 1103 |
out <- XMLRecord{Index: ext.Index, Ident: ext.Ident} |
| 1104 |
continue |
| 1105 |
} |
| 1106 |
|
| 1107 |
// send selected record |
| 1108 |
out <- XMLRecord{Index: ext.Index, Ident: ext.Ident, Text: text} |
| 1109 |
} |
| 1110 |
} |
| 1111 |
|
| 1112 |
var wg sync.WaitGroup |
| 1113 |
|
| 1114 |
// launch multiple selector goroutines |
| 1115 |
for range numServe { |
| 1116 |
wg.Add(1) |
| 1117 |
go xmlSelector(&wg, inp, out) |
| 1118 |
} |
| 1119 |
|
| 1120 |
// launch separate anonymous goroutine to wait until all selectors are done |
| 1121 |
go func() { |
| 1122 |
wg.Wait() |
| 1123 |
close(out) |
| 1124 |
}() |
| 1125 |
|
| 1126 |
return out |
| 1127 |
} |
| 1128 |
|
| 1129 |
// CreateUnicoders supports xtract -pattern record_name -select -nonascii |
| 1130 |
func CreateUnicoders(inp <-chan XMLRecord) <-chan XMLRecord { |
| 1131 |
|
| 1132 |
if inp == nil { |
| 1133 |
return nil |
| 1134 |
} |
| 1135 |
|
| 1136 |
out := make(chan XMLRecord, chanDepth) |
| 1137 |
if out == nil { |
| 1138 |
DisplayError("Unable to create selector channel") |
| 1139 |
os.Exit(1) |
| 1140 |
} |
| 1141 |
|
| 1142 |
// xmlUnicoder reads partitioned XML from channel and keeps records with non-ASCII characters |
| 1143 |
xmlUnicoder := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- XMLRecord) { |
| 1144 |
|
| 1145 |
// report when this selector has no more records to process |
| 1146 |
defer wg.Done() |
| 1147 |
|
| 1148 |
// read partitioned XML from producer channel |
| 1149 |
for ext := range inp { |
| 1150 |
|
| 1151 |
text := ext.Text |
| 1152 |
|
| 1153 |
if !IsNotASCII(text) { |
| 1154 |
// if only ASCII, send empty placeholder for unshuffler |
| 1155 |
out <- XMLRecord{Index: ext.Index, Ident: ext.Ident} |
| 1156 |
continue |
| 1157 |
} |
| 1158 |
|
| 1159 |
// send selected record |
| 1160 |
out <- XMLRecord{Index: ext.Index, Ident: ext.Ident, Text: text} |
| 1161 |
} |
| 1162 |
} |
| 1163 |
|
| 1164 |
var wg sync.WaitGroup |
| 1165 |
|
| 1166 |
// launch multiple unicoder goroutines |
| 1167 |
for range numServe { |
| 1168 |
wg.Add(1) |
| 1169 |
go xmlUnicoder(&wg, inp, out) |
| 1170 |
} |
| 1171 |
|
| 1172 |
// launch separate anonymous goroutine to wait until all unicoders are done |
| 1173 |
go func() { |
| 1174 |
wg.Wait() |
| 1175 |
close(out) |
| 1176 |
}() |
| 1177 |
|
| 1178 |
return out |
| 1179 |
} |
| 1180 |
|
| 1181 |
// DRAIN OUTPUT CHANNEL TO EXECUTE EXTRACTION COMMANDS, RESTORE OUTPUT ORDER WITH HEAP |
| 1182 |
|
| 1183 |
// DrainExtractions reads from the unshuffler and writes XML extraction output, |
| 1184 |
// for xtract and for rchive -e2index if used without -e2invert |
| 1185 |
func DrainExtractions(head, tail, posn string, mpty, idnt bool, histogram map[string]int, inp <-chan XMLRecord) (int, int) { |
| 1186 |
|
| 1187 |
if inp == nil { |
| 1188 |
return 0, 0 |
| 1189 |
} |
| 1190 |
|
| 1191 |
recordCount := 0 |
| 1192 |
byteCount := 0 |
| 1193 |
|
| 1194 |
var buffer strings.Builder |
| 1195 |
count := 0 |
| 1196 |
okay := false |
| 1197 |
lastTime := time.Now() |
| 1198 |
|
| 1199 |
wrtr := bufio.NewWriter(os.Stdout) |
| 1200 |
|
| 1201 |
// printResult prints output for current pattern, handles -empty and -ident flags, and periodically flushes buffer |
| 1202 |
printResult := func(curr XMLRecord) { |
| 1203 |
|
| 1204 |
str := curr.Text |
| 1205 |
|
| 1206 |
if mpty { |
| 1207 |
|
| 1208 |
if str == "" { |
| 1209 |
|
| 1210 |
okay = true |
| 1211 |
|
| 1212 |
idx := curr.Index |
| 1213 |
val := strconv.Itoa(idx) |
| 1214 |
buffer.WriteString(val[:]) |
| 1215 |
buffer.WriteString("\n") |
| 1216 |
|
| 1217 |
count++ |
| 1218 |
} |
| 1219 |
|
| 1220 |
} else if str != "" { |
| 1221 |
|
| 1222 |
okay = true |
| 1223 |
|
| 1224 |
if idnt { |
| 1225 |
idx := curr.Index |
| 1226 |
val := strconv.Itoa(idx) |
| 1227 |
buffer.WriteString(val[:]) |
| 1228 |
buffer.WriteString("\t") |
| 1229 |
} |
| 1230 |
|
| 1231 |
// save output to byte buffer |
| 1232 |
buffer.WriteString(str[:]) |
| 1233 |
|
| 1234 |
count++ |
| 1235 |
} |
| 1236 |
|
| 1237 |
thisTime := time.Now() |
| 1238 |
duration := thisTime.Sub(lastTime) |
| 1239 |
milliSeconds := duration.Milliseconds() |
| 1240 |
|
| 1241 |
if count > 1000 || milliSeconds > 4999 { |
| 1242 |
count = 0 |
| 1243 |
lastTime = thisTime |
| 1244 |
txt := buffer.String() |
| 1245 |
if txt != "" { |
| 1246 |
// print current buffer |
| 1247 |
wrtr.WriteString(txt[:]) |
| 1248 |
} |
| 1249 |
buffer.Reset() |
| 1250 |
} |
| 1251 |
} |
| 1252 |
|
| 1253 |
if head != "" { |
| 1254 |
buffer.WriteString(head[:]) |
| 1255 |
buffer.WriteString("\n") |
| 1256 |
} |
| 1257 |
|
| 1258 |
// drain unshuffler channel |
| 1259 |
|
| 1260 |
if posn == "outer" { |
| 1261 |
|
| 1262 |
// print only first and last records |
| 1263 |
var beg *XMLRecord |
| 1264 |
var end *XMLRecord |
| 1265 |
|
| 1266 |
for curr := range inp { |
| 1267 |
|
| 1268 |
if beg == nil { |
| 1269 |
beg = &XMLRecord{Index: curr.Index, Ident: curr.Ident, Text: curr.Text} |
| 1270 |
} else { |
| 1271 |
end = &XMLRecord{Index: curr.Index, Ident: curr.Ident, Text: curr.Text} |
| 1272 |
} |
| 1273 |
|
| 1274 |
recordCount++ |
| 1275 |
} |
| 1276 |
|
| 1277 |
if beg != nil { |
| 1278 |
printResult(*beg) |
| 1279 |
} |
| 1280 |
if end != nil { |
| 1281 |
printResult(*end) |
| 1282 |
} |
| 1283 |
|
| 1284 |
} else if posn == "inner" { |
| 1285 |
|
| 1286 |
// print all but first and last records |
| 1287 |
var prev *XMLRecord |
| 1288 |
var next *XMLRecord |
| 1289 |
first := true |
| 1290 |
|
| 1291 |
for curr := range inp { |
| 1292 |
|
| 1293 |
if first { |
| 1294 |
first = false |
| 1295 |
} else { |
| 1296 |
prev = next |
| 1297 |
next = &XMLRecord{Index: curr.Index, Ident: curr.Ident, Text: curr.Text} |
| 1298 |
} |
| 1299 |
|
| 1300 |
if prev != nil { |
| 1301 |
printResult(*prev) |
| 1302 |
} |
| 1303 |
|
| 1304 |
recordCount++ |
| 1305 |
} |
| 1306 |
|
| 1307 |
} else if posn == "even" { |
| 1308 |
|
| 1309 |
even := false |
| 1310 |
|
| 1311 |
for curr := range inp { |
| 1312 |
|
| 1313 |
if even { |
| 1314 |
printResult(curr) |
| 1315 |
} |
| 1316 |
even = !even |
| 1317 |
|
| 1318 |
recordCount++ |
| 1319 |
} |
| 1320 |
|
| 1321 |
} else if posn == "odd" { |
| 1322 |
|
| 1323 |
odd := true |
| 1324 |
|
| 1325 |
for curr := range inp { |
| 1326 |
|
| 1327 |
if odd { |
| 1328 |
printResult(curr) |
| 1329 |
} |
| 1330 |
odd = !odd |
| 1331 |
|
| 1332 |
recordCount++ |
| 1333 |
} |
| 1334 |
|
| 1335 |
} else { |
| 1336 |
|
| 1337 |
// default or -position all |
| 1338 |
for curr := range inp { |
| 1339 |
|
| 1340 |
// send result to output |
| 1341 |
printResult(curr) |
| 1342 |
|
| 1343 |
recordCount++ |
| 1344 |
runtime.Gosched() |
| 1345 |
} |
| 1346 |
} |
| 1347 |
|
| 1348 |
if tail != "" { |
| 1349 |
buffer.WriteString(tail[:]) |
| 1350 |
buffer.WriteString("\n") |
| 1351 |
} |
| 1352 |
|
| 1353 |
// do not print head or tail if no extraction output |
| 1354 |
if okay { |
| 1355 |
txt := buffer.String() |
| 1356 |
if txt != "" { |
| 1357 |
// print final buffer |
| 1358 |
wrtr.WriteString(txt[:]) |
| 1359 |
} |
| 1360 |
} |
| 1361 |
buffer.Reset() |
| 1362 |
|
| 1363 |
wrtr.Flush() |
| 1364 |
|
| 1365 |
// print -histogram results, if populated |
| 1366 |
keys := slices.SortedFunc(maps.Keys(histogram), CompareAlphaOrNumericKeys) |
| 1367 |
|
| 1368 |
for _, str := range keys { |
| 1369 |
|
| 1370 |
count := histogram[str] |
| 1371 |
val := strconv.Itoa(count) |
| 1372 |
os.Stdout.WriteString(val) |
| 1373 |
os.Stdout.WriteString("\t") |
| 1374 |
os.Stdout.WriteString(str) |
| 1375 |
os.Stdout.WriteString("\n") |
| 1376 |
} |
| 1377 |
|
| 1378 |
// force garbage collection and return memory before calculating processing rate |
| 1379 |
debug.FreeOSMemory() |
| 1380 |
|
| 1381 |
return recordCount, byteCount |
| 1382 |
} |
| 1383 |
|
| 1384 |
// PARSE XML INTO TOKENS, IDENTIFIERS, OR STRUCTURED RECORD OBJECT |
| 1385 |
|
| 1386 |
// XML token type |
| 1387 |
const ( |
| 1388 |
NOTAG = iota |
| 1389 |
STARTTAG |
| 1390 |
SELFTAG |
| 1391 |
STOPTAG |
| 1392 |
ATTRIBTAG |
| 1393 |
CONTENTTAG |
| 1394 |
CDATATAG |
| 1395 |
COMMENTTAG |
| 1396 |
DOCTYPETAG |
| 1397 |
PROCESSTAG |
| 1398 |
OBJECTTAG |
| 1399 |
CONTAINERTAG |
| 1400 |
ISCLOSED |
| 1401 |
BADTAG |
| 1402 |
) |
| 1403 |
|
| 1404 |
// content bit flags for performing special cleanup steps only when needed |
| 1405 |
const ( |
| 1406 |
NONE = iota |
| 1407 |
MIXED = 1 << iota |
| 1408 |
AMPER |
| 1409 |
ASCII |
| 1410 |
LFTSPACE |
| 1411 |
RGTSPACE |
| 1412 |
) |
| 1413 |
|
| 1414 |
// internal tracking state for detecting unrecognized mixed content |
| 1415 |
const ( |
| 1416 |
_ = iota |
| 1417 |
START |
| 1418 |
STOP |
| 1419 |
CHAR |
| 1420 |
OTHER |
| 1421 |
) |
| 1422 |
|
| 1423 |
// XMLNode is the node for an internal tree structure representing a single XML record |
| 1424 |
type XMLNode struct { |
| 1425 |
Attribs []string |
| 1426 |
Children *XMLNode |
| 1427 |
Next *XMLNode |
| 1428 |
Name string |
| 1429 |
Parent string |
| 1430 |
Contents string |
| 1431 |
Attributes string |
| 1432 |
} |
| 1433 |
|
| 1434 |
// XMLFind contains individual field values for finding a particular object |
| 1435 |
type XMLFind struct { |
| 1436 |
Index string |
| 1437 |
Parent string |
| 1438 |
Match string |
| 1439 |
Attrib string |
| 1440 |
Versn string |
| 1441 |
} |
| 1442 |
|
| 1443 |
// XMLToken is the unit of XML parsing |
| 1444 |
type XMLToken struct { |
| 1445 |
Name string |
| 1446 |
Attr string |
| 1447 |
Tag int |
| 1448 |
Cont int |
| 1449 |
Index int |
| 1450 |
Line int |
| 1451 |
} |
| 1452 |
|
| 1453 |
// ParseAttributes produces tag/value pairs, only run on request |
| 1454 |
func ParseAttributes(attrb string) []string { |
| 1455 |
|
| 1456 |
if attrb == "" { |
| 1457 |
return nil |
| 1458 |
} |
| 1459 |
|
| 1460 |
attlen := len(attrb) |
| 1461 |
|
| 1462 |
// count equal signs |
| 1463 |
num := 0 |
| 1464 |
inQuote := false |
| 1465 |
|
| 1466 |
for i := range attlen { |
| 1467 |
ch := attrb[i] |
| 1468 |
if ch == '"' || ch == '\'' { |
| 1469 |
// " |
| 1470 |
inQuote = !inQuote |
| 1471 |
} |
| 1472 |
if ch == '=' && !inQuote { |
| 1473 |
num += 2 |
| 1474 |
} |
| 1475 |
} |
| 1476 |
if num < 1 { |
| 1477 |
return nil |
| 1478 |
} |
| 1479 |
|
| 1480 |
// allocate array of proper size |
| 1481 |
arry := make([]string, num) |
| 1482 |
if arry == nil { |
| 1483 |
return nil |
| 1484 |
} |
| 1485 |
|
| 1486 |
start := 0 |
| 1487 |
idx := 0 |
| 1488 |
itm := 0 |
| 1489 |
inQuote = false |
| 1490 |
|
| 1491 |
// place tag and value in successive array slots |
| 1492 |
for idx < attlen && itm < num { |
| 1493 |
ch := attrb[idx] |
| 1494 |
if ch == '"' || ch == '\'' { |
| 1495 |
// " |
| 1496 |
inQuote = !inQuote |
| 1497 |
} |
| 1498 |
if ch == '=' && !inQuote { |
| 1499 |
inQuote = true |
| 1500 |
// skip past possible leading blanks |
| 1501 |
for start < attlen { |
| 1502 |
ch = attrb[start] |
| 1503 |
if inBlank[ch] { |
| 1504 |
start++ |
| 1505 |
} else { |
| 1506 |
break |
| 1507 |
} |
| 1508 |
} |
| 1509 |
// = |
| 1510 |
arry[itm] = strings.TrimSpace(attrb[start:idx]) |
| 1511 |
itm++ |
| 1512 |
// skip past equal sign |
| 1513 |
idx++ |
| 1514 |
ch = attrb[idx] |
| 1515 |
if ch != '"' && ch != '\'' { |
| 1516 |
// " |
| 1517 |
// skip past unexpected blanks |
| 1518 |
for inBlank[ch] { |
| 1519 |
idx++ |
| 1520 |
ch = attrb[idx] |
| 1521 |
} |
| 1522 |
if ch != '"' && ch != '\'' { |
| 1523 |
// " |
| 1524 |
DisplayError("Attribute in '%s' missing double quote", attrb) |
| 1525 |
} |
| 1526 |
} |
| 1527 |
// skip past leading double quote |
| 1528 |
idx++ |
| 1529 |
start = idx |
| 1530 |
} else if ch == '"' || ch == '\'' { |
| 1531 |
// " |
| 1532 |
inQuote = false |
| 1533 |
arry[itm] = strings.TrimSpace(attrb[start:idx]) |
| 1534 |
itm++ |
| 1535 |
// skip past trailing double quote and (possible) space |
| 1536 |
idx += 2 |
| 1537 |
start = idx |
| 1538 |
} else { |
| 1539 |
idx++ |
| 1540 |
} |
| 1541 |
} |
| 1542 |
|
| 1543 |
return arry |
| 1544 |
} |
| 1545 |
|
| 1546 |
// parseXML calls XML parser on a partitioned string or on an XMLBlock channel of trimmed strings. |
| 1547 |
// It is optimized for maximum processing speed, sends tokens for CDATA and COMMENT sections (for |
| 1548 |
// unpacking by NormalizeXML), and optionally tracks line numbers (for ValidateXML). |
| 1549 |
func parseXML(record, parent string, inp <-chan XMLBlock, tokens func(XMLToken), find *XMLFind, ids func(string)) (*XMLNode, string) { |
| 1550 |
|
| 1551 |
if record == "" && (inp == nil || tokens == nil) { |
| 1552 |
return nil, "" |
| 1553 |
} |
| 1554 |
|
| 1555 |
if record != "" { |
| 1556 |
// logic to skip past leading blanks relies on right angle bracket sentinel at end of string |
| 1557 |
record = strings.TrimSpace(record) |
| 1558 |
} |
| 1559 |
|
| 1560 |
// token parser variables |
| 1561 |
recLen := len(record) |
| 1562 |
Idx := 0 |
| 1563 |
|
| 1564 |
// line tracking variables |
| 1565 |
lineNum := 1 |
| 1566 |
lag := 0 |
| 1567 |
|
| 1568 |
// variables to track COMMENT or CDATA sections that span reader blocks |
| 1569 |
which := NOTAG |
| 1570 |
skipTo := "" |
| 1571 |
|
| 1572 |
// updateLineCount is used to keep track of the correct line count for XML validation |
| 1573 |
updateLineCount := func(max int) { |
| 1574 |
// count lines |
| 1575 |
for i := lag; i < max; i++ { |
| 1576 |
if record[i] == '\n' { |
| 1577 |
lineNum++ |
| 1578 |
} |
| 1579 |
} |
| 1580 |
lag = Idx |
| 1581 |
} |
| 1582 |
|
| 1583 |
// currentLineCount calculates correct line for warning messages, does not update lineNum or lag variables |
| 1584 |
currentLineCount := func(max int) int { |
| 1585 |
line := lineNum |
| 1586 |
for i := lag; i < max; i++ { |
| 1587 |
if record[i] == '\n' { |
| 1588 |
line++ |
| 1589 |
} |
| 1590 |
} |
| 1591 |
return line |
| 1592 |
} |
| 1593 |
|
| 1594 |
// nextToken returns the type and content fields for the next XML token |
| 1595 |
nextToken := func(idx int) (int, int, string, string, int) { |
| 1596 |
|
| 1597 |
if record == "" { |
| 1598 |
// buffer is empty |
| 1599 |
if inp != nil { |
| 1600 |
// read next block if available |
| 1601 |
record = string(<-inp) |
| 1602 |
recLen = len(record) |
| 1603 |
Idx = 0 |
| 1604 |
idx = 0 |
| 1605 |
lag = 0 |
| 1606 |
} |
| 1607 |
|
| 1608 |
if record == "" { |
| 1609 |
// signal end of XML data |
| 1610 |
return ISCLOSED, NONE, "", "", 0 |
| 1611 |
} |
| 1612 |
|
| 1613 |
if which != NOTAG && skipTo != "" { |
| 1614 |
// previous block ended inside CDATA object or COMMENT |
| 1615 |
text := record[:] |
| 1616 |
txtlen := recLen |
| 1617 |
whch := which |
| 1618 |
start := idx |
| 1619 |
found := strings.Index(text[idx:], skipTo) |
| 1620 |
if found < 0 { |
| 1621 |
// no stop signal found in next block |
| 1622 |
str := text[start:] |
| 1623 |
if HasFlankingSpace(str) { |
| 1624 |
str = strings.TrimSpace(str) |
| 1625 |
} |
| 1626 |
|
| 1627 |
if countLines { |
| 1628 |
updateLineCount(txtlen) |
| 1629 |
} |
| 1630 |
|
| 1631 |
// signal end of current block |
| 1632 |
record = "" |
| 1633 |
|
| 1634 |
// leave which and skipTo values unchanged as another continuation signal |
| 1635 |
// send CDATA or COMMENT contents |
| 1636 |
return whch, NONE, str[:], "", 0 |
| 1637 |
} |
| 1638 |
// otherwise adjust position past end of skipTo string and return to normal processing |
| 1639 |
idx += found |
| 1640 |
str := text[start:idx] |
| 1641 |
if HasFlankingSpace(str) { |
| 1642 |
str = strings.TrimSpace(str) |
| 1643 |
} |
| 1644 |
idx += len(skipTo) |
| 1645 |
// clear tracking variables |
| 1646 |
which = NOTAG |
| 1647 |
skipTo = "" |
| 1648 |
// send CDATA or COMMENT contents |
| 1649 |
return whch, NONE, str[:], "", idx |
| 1650 |
} |
| 1651 |
} |
| 1652 |
|
| 1653 |
text := record[:] |
| 1654 |
txtlen := recLen |
| 1655 |
|
| 1656 |
// XML string, and all blocks, end with > character, acts as sentinel to check if past end of text |
| 1657 |
if idx >= txtlen { |
| 1658 |
if inp != nil { |
| 1659 |
|
| 1660 |
if countLines { |
| 1661 |
updateLineCount(txtlen) |
| 1662 |
} |
| 1663 |
|
| 1664 |
// signal end of current block, will read next block on next call |
| 1665 |
record = "" |
| 1666 |
|
| 1667 |
return NOTAG, NONE, "", "", 0 |
| 1668 |
} |
| 1669 |
|
| 1670 |
// signal end of XML string |
| 1671 |
return ISCLOSED, NONE, "", "", 0 |
| 1672 |
} |
| 1673 |
|
| 1674 |
ctype := NONE |
| 1675 |
|
| 1676 |
// skip past leading blanks |
| 1677 |
ch := text[idx] |
| 1678 |
if inBlank[ch] { |
| 1679 |
ctype |= LFTSPACE |
| 1680 |
idx++ |
| 1681 |
ch = text[idx] |
| 1682 |
for inBlank[ch] { |
| 1683 |
idx++ |
| 1684 |
ch = text[idx] |
| 1685 |
} |
| 1686 |
} |
| 1687 |
|
| 1688 |
start := idx |
| 1689 |
|
| 1690 |
plainContent := true |
| 1691 |
|
| 1692 |
if doStrict && ch == '<' { |
| 1693 |
// check to see if an HTML or MathML element is at the beginning of a content string |
| 1694 |
if HTMLAhead(text, idx, txtlen) != 0 { |
| 1695 |
plainContent = false |
| 1696 |
} |
| 1697 |
} |
| 1698 |
|
| 1699 |
if plainContent && ch == '<' { |
| 1700 |
|
| 1701 |
// at start of element |
| 1702 |
idx++ |
| 1703 |
ch = text[idx] |
| 1704 |
|
| 1705 |
// check for legal first character of element |
| 1706 |
if inFirst[ch] { |
| 1707 |
|
| 1708 |
// read element name |
| 1709 |
start = idx |
| 1710 |
idx++ |
| 1711 |
|
| 1712 |
ch = text[idx] |
| 1713 |
for inElement[ch] { |
| 1714 |
idx++ |
| 1715 |
ch = text[idx] |
| 1716 |
} |
| 1717 |
|
| 1718 |
str := text[start:idx] |
| 1719 |
|
| 1720 |
if ch == '>' { |
| 1721 |
|
| 1722 |
// end of element |
| 1723 |
idx++ |
| 1724 |
|
| 1725 |
return STARTTAG, NONE, str[:], "", idx |
| 1726 |
|
| 1727 |
} else if ch == '/' { |
| 1728 |
|
| 1729 |
// self-closing element without attributes |
| 1730 |
idx++ |
| 1731 |
ch = text[idx] |
| 1732 |
if ch != '>' { |
| 1733 |
// skip past unexpected blanks |
| 1734 |
for inBlank[ch] { |
| 1735 |
idx++ |
| 1736 |
ch = text[idx] |
| 1737 |
} |
| 1738 |
if ch != '>' { |
| 1739 |
DisplayError("Self-closing element missing right angle bracket") |
| 1740 |
} |
| 1741 |
} |
| 1742 |
idx++ |
| 1743 |
|
| 1744 |
return SELFTAG, NONE, str[:], "", idx |
| 1745 |
|
| 1746 |
} else if inBlank[ch] { |
| 1747 |
|
| 1748 |
// attributes |
| 1749 |
idx++ |
| 1750 |
ch = text[idx] |
| 1751 |
// skip past unexpected blanks |
| 1752 |
for inBlank[ch] { |
| 1753 |
idx++ |
| 1754 |
ch = text[idx] |
| 1755 |
} |
| 1756 |
start = idx |
| 1757 |
for ch != '<' && ch != '>' { |
| 1758 |
idx++ |
| 1759 |
ch = text[idx] |
| 1760 |
} |
| 1761 |
if ch != '>' { |
| 1762 |
DisplayError("Attributes not followed by right angle bracket") |
| 1763 |
} |
| 1764 |
// walk back past trailing blanks |
| 1765 |
lst := idx - 1 |
| 1766 |
ch = text[lst] |
| 1767 |
for inBlank[ch] && lst > start { |
| 1768 |
lst-- |
| 1769 |
ch = text[lst] |
| 1770 |
} |
| 1771 |
if ch == '/' { |
| 1772 |
// self-closing |
| 1773 |
atr := text[start:lst] |
| 1774 |
idx++ |
| 1775 |
|
| 1776 |
return SELFTAG, NONE, str[:], atr[:], idx |
| 1777 |
} |
| 1778 |
atr := text[start:idx] |
| 1779 |
idx++ |
| 1780 |
|
| 1781 |
return STARTTAG, NONE, str[:], atr[:], idx |
| 1782 |
|
| 1783 |
} else { |
| 1784 |
|
| 1785 |
if countLines { |
| 1786 |
DisplayError("Unexpected punctuation '%c' in XML element, line %d", ch, currentLineCount(idx)) |
| 1787 |
} else { |
| 1788 |
DisplayError("Unexpected punctuation '%c' in XML element", ch) |
| 1789 |
} |
| 1790 |
|
| 1791 |
return STARTTAG, NONE, str[:], "", idx |
| 1792 |
} |
| 1793 |
|
| 1794 |
// other punctuation character immediately after first angle bracket |
| 1795 |
|
| 1796 |
} else if ch == '/' { |
| 1797 |
|
| 1798 |
// at start of end tag |
| 1799 |
idx++ |
| 1800 |
start = idx |
| 1801 |
ch = text[idx] |
| 1802 |
// expect legal first character of element |
| 1803 |
if inFirst[ch] { |
| 1804 |
idx++ |
| 1805 |
ch = text[idx] |
| 1806 |
for inElement[ch] { |
| 1807 |
idx++ |
| 1808 |
ch = text[idx] |
| 1809 |
} |
| 1810 |
str := text[start:idx] |
| 1811 |
if ch != '>' { |
| 1812 |
// skip past unexpected blanks |
| 1813 |
for inBlank[ch] { |
| 1814 |
idx++ |
| 1815 |
ch = text[idx] |
| 1816 |
} |
| 1817 |
if ch != '>' { |
| 1818 |
DisplayError("Unexpected characters after end element name") |
| 1819 |
} |
| 1820 |
} |
| 1821 |
idx++ |
| 1822 |
|
| 1823 |
return STOPTAG, NONE, str[:], "", idx |
| 1824 |
} |
| 1825 |
// legal character not found after slash |
| 1826 |
if countLines { |
| 1827 |
DisplayError("Unexpected punctuation '%c' in XML element, line %d", ch, currentLineCount(idx)) |
| 1828 |
} else { |
| 1829 |
DisplayError("Unexpected punctuation '%c' in XML element", ch) |
| 1830 |
} |
| 1831 |
|
| 1832 |
} else if ch == '!' { |
| 1833 |
|
| 1834 |
// skip !DOCTYPE, !COMMENT, and ![CDATA[ |
| 1835 |
idx++ |
| 1836 |
start = idx |
| 1837 |
ch = text[idx] |
| 1838 |
which = NOTAG |
| 1839 |
skipTo = "" |
| 1840 |
if ch == '[' && strings.HasPrefix(text[idx:], "[CDATA[") { |
| 1841 |
which = CDATATAG |
| 1842 |
skipTo = "]]>" |
| 1843 |
start += 7 |
| 1844 |
} else if ch == '-' && strings.HasPrefix(text[idx:], "--") { |
| 1845 |
which = COMMENTTAG |
| 1846 |
skipTo = "-->" |
| 1847 |
start += 2 |
| 1848 |
} else if ch == 'D' && strings.HasPrefix(text[idx:], "DOCTYPE") { |
| 1849 |
which = DOCTYPETAG |
| 1850 |
skipTo = ">" |
| 1851 |
} |
| 1852 |
idx = start |
| 1853 |
if which != NOTAG && skipTo != "" { |
| 1854 |
whch := which |
| 1855 |
// CDATA or COMMENT block may contain internal angle brackets |
| 1856 |
found := strings.Index(text[start:], skipTo) |
| 1857 |
if found < 0 { |
| 1858 |
// string stops in middle of CDATA or COMMENT |
| 1859 |
if inp != nil { |
| 1860 |
str := text[start:] |
| 1861 |
if HasFlankingSpace(str) { |
| 1862 |
str = strings.TrimSpace(str) |
| 1863 |
} |
| 1864 |
|
| 1865 |
if countLines { |
| 1866 |
updateLineCount(txtlen) |
| 1867 |
} |
| 1868 |
|
| 1869 |
// signal end of current block |
| 1870 |
record = "" |
| 1871 |
|
| 1872 |
// leave which and skipTo values unchanged as another continuation signal |
| 1873 |
// send CDATA or COMMENT contents |
| 1874 |
return whch, NONE, str[:], "", 0 |
| 1875 |
} |
| 1876 |
|
| 1877 |
return ISCLOSED, NONE, "", "", idx |
| 1878 |
} |
| 1879 |
// adjust position past end of CDATA or COMMENT |
| 1880 |
if inp != nil { |
| 1881 |
idx += found |
| 1882 |
str := text[start:idx] |
| 1883 |
if HasFlankingSpace(str) { |
| 1884 |
str = strings.TrimSpace(str) |
| 1885 |
} |
| 1886 |
idx += len(skipTo) |
| 1887 |
// clear tracking variables |
| 1888 |
which = NOTAG |
| 1889 |
skipTo = "" |
| 1890 |
// send CDATA or COMMENT contents |
| 1891 |
return whch, NONE, str[:], "", idx |
| 1892 |
} |
| 1893 |
|
| 1894 |
idx += found + len(skipTo) |
| 1895 |
return NOTAG, NONE, "", "", idx |
| 1896 |
} |
| 1897 |
// otherwise just skip to next right angle bracket |
| 1898 |
for ch != '>' { |
| 1899 |
idx++ |
| 1900 |
ch = text[idx] |
| 1901 |
} |
| 1902 |
idx++ |
| 1903 |
return NOTAG, NONE, "", "", idx |
| 1904 |
|
| 1905 |
} else if ch == '?' { |
| 1906 |
|
| 1907 |
// skip ?xml and ?processing instructions |
| 1908 |
idx++ |
| 1909 |
ch = text[idx] |
| 1910 |
which = PROCESSTAG |
| 1911 |
skipTo = "?>" |
| 1912 |
|
| 1913 |
if which != NOTAG && skipTo != "" { |
| 1914 |
whch := which |
| 1915 |
// xml or processing instruction block may contain internal angle brackets |
| 1916 |
found := strings.Index(text[idx:], skipTo) |
| 1917 |
if found < 0 { |
| 1918 |
// string stops in middle of xml or processing instruction |
| 1919 |
if inp != nil { |
| 1920 |
str := text[start:] |
| 1921 |
if HasFlankingSpace(str) { |
| 1922 |
str = strings.TrimSpace(str) |
| 1923 |
} |
| 1924 |
|
| 1925 |
if countLines { |
| 1926 |
updateLineCount(txtlen) |
| 1927 |
} |
| 1928 |
|
| 1929 |
// signal end of current block |
| 1930 |
record = "" |
| 1931 |
|
| 1932 |
// leave which and skipTo values unchanged as another continuation signal |
| 1933 |
// send PROCESSTAG contents |
| 1934 |
return whch, NONE, str[:], "", 0 |
| 1935 |
} |
| 1936 |
|
| 1937 |
return ISCLOSED, NONE, "", "", idx |
| 1938 |
} |
| 1939 |
// adjust position past end of xml or processing instruction |
| 1940 |
if inp != nil { |
| 1941 |
idx += found |
| 1942 |
str := text[start:idx] |
| 1943 |
if HasFlankingSpace(str) { |
| 1944 |
str = strings.TrimSpace(str) |
| 1945 |
} |
| 1946 |
idx += len(skipTo) |
| 1947 |
// clear tracking variables |
| 1948 |
which = NOTAG |
| 1949 |
skipTo = "" |
| 1950 |
// send PROCESSTAG contents |
| 1951 |
return whch, NONE, str[:], "", idx |
| 1952 |
} |
| 1953 |
|
| 1954 |
idx += found + len(skipTo) |
| 1955 |
return NOTAG, NONE, "", "", idx |
| 1956 |
} |
| 1957 |
// otherwise just skip to next right angle bracket |
| 1958 |
for ch != '>' { |
| 1959 |
idx++ |
| 1960 |
ch = text[idx] |
| 1961 |
} |
| 1962 |
idx++ |
| 1963 |
return NOTAG, NONE, "", "", idx |
| 1964 |
|
| 1965 |
} else { |
| 1966 |
|
| 1967 |
if countLines { |
| 1968 |
DisplayError("Unexpected punctuation '%c' (%d) in XML element, line %d", ch, ch, currentLineCount(idx)) |
| 1969 |
} else { |
| 1970 |
DisplayError("Unexpected punctuation '%c' (%d) in XML element", ch, ch) |
| 1971 |
} |
| 1972 |
} |
| 1973 |
|
| 1974 |
} else if ch != '>' { |
| 1975 |
|
| 1976 |
// at start of contents |
| 1977 |
start = idx |
| 1978 |
|
| 1979 |
hasMarkup := false |
| 1980 |
hasNonASCII := false |
| 1981 |
|
| 1982 |
// find end of contents |
| 1983 |
if allowEmbed { |
| 1984 |
|
| 1985 |
for { |
| 1986 |
for inContent[ch] { |
| 1987 |
idx++ |
| 1988 |
ch = text[idx] |
| 1989 |
} |
| 1990 |
// set flags to speed up conditional content processing |
| 1991 |
if ch == '&' { |
| 1992 |
idx++ |
| 1993 |
ch = text[idx] |
| 1994 |
if ch == 'a' { |
| 1995 |
if strings.HasPrefix(text[idx:], "amp;") { |
| 1996 |
hasMarkup = true |
| 1997 |
} |
| 1998 |
} else if ch == 'g' { |
| 1999 |
if strings.HasPrefix(text[idx:], "gt;") { |
| 2000 |
hasMarkup = true |
| 2001 |
} |
| 2002 |
} else if ch == 'l' { |
| 2003 |
if strings.HasPrefix(text[idx:], "lt;") { |
| 2004 |
hasMarkup = true |
| 2005 |
} |
| 2006 |
} |
| 2007 |
continue |
| 2008 |
} |
| 2009 |
if ch > 127 { |
| 2010 |
hasNonASCII = true |
| 2011 |
idx++ |
| 2012 |
ch = text[idx] |
| 2013 |
continue |
| 2014 |
} |
| 2015 |
if ch == '<' && doStrict { |
| 2016 |
// optionally allow HTML text formatting elements and super/subscripts |
| 2017 |
advance := HTMLAhead(text, idx, txtlen) |
| 2018 |
if advance > 0 { |
| 2019 |
idx += advance |
| 2020 |
if idx < txtlen { |
| 2021 |
ch = text[idx] |
| 2022 |
} |
| 2023 |
plainContent = false |
| 2024 |
continue |
| 2025 |
} |
| 2026 |
} |
| 2027 |
break |
| 2028 |
} |
| 2029 |
|
| 2030 |
} else { |
| 2031 |
for ch != '<' && ch != '>' { |
| 2032 |
if ch > 127 { |
| 2033 |
hasNonASCII = true |
| 2034 |
} |
| 2035 |
idx++ |
| 2036 |
ch = text[idx] |
| 2037 |
} |
| 2038 |
} |
| 2039 |
|
| 2040 |
// trim back past trailing blanks |
| 2041 |
lst := idx - 1 |
| 2042 |
ch = text[lst] |
| 2043 |
if inBlank[ch] && lst > start { |
| 2044 |
ctype |= RGTSPACE |
| 2045 |
lst-- |
| 2046 |
ch = text[lst] |
| 2047 |
for inBlank[ch] && lst > start { |
| 2048 |
lst-- |
| 2049 |
ch = text[lst] |
| 2050 |
} |
| 2051 |
} |
| 2052 |
|
| 2053 |
str := text[start : lst+1] |
| 2054 |
|
| 2055 |
if !plainContent { |
| 2056 |
ctype |= MIXED |
| 2057 |
} |
| 2058 |
if hasMarkup { |
| 2059 |
ctype |= AMPER |
| 2060 |
} |
| 2061 |
if hasNonASCII { |
| 2062 |
ctype |= ASCII |
| 2063 |
} |
| 2064 |
|
| 2065 |
return CONTENTTAG, ctype, str[:], "", idx |
| 2066 |
} |
| 2067 |
|
| 2068 |
return BADTAG, NONE, "", "", idx |
| 2069 |
} |
| 2070 |
|
| 2071 |
// node farm variables |
| 2072 |
farmPos := 0 |
| 2073 |
farmMax := farmSize |
| 2074 |
farmItems := make([]XMLNode, farmMax) |
| 2075 |
|
| 2076 |
// nextNode allocates multiple nodes in a large array for memory management efficiency |
| 2077 |
nextNode := func(strt, attr, prnt string) *XMLNode { |
| 2078 |
|
| 2079 |
// if farm array slots used up, allocate new array |
| 2080 |
if farmPos >= farmMax { |
| 2081 |
farmItems = make([]XMLNode, farmMax) |
| 2082 |
farmPos = 0 |
| 2083 |
} |
| 2084 |
|
| 2085 |
if farmItems == nil { |
| 2086 |
return nil |
| 2087 |
} |
| 2088 |
|
| 2089 |
// take node from next available slot in farm array |
| 2090 |
node := &farmItems[farmPos] |
| 2091 |
|
| 2092 |
node.Name = strt[:] |
| 2093 |
node.Attributes = attr[:] |
| 2094 |
node.Parent = prnt[:] |
| 2095 |
|
| 2096 |
farmPos++ |
| 2097 |
|
| 2098 |
return node |
| 2099 |
} |
| 2100 |
|
| 2101 |
// Parse tokens into tree structure for exploration |
| 2102 |
|
| 2103 |
// parseSpecial recursive definition |
| 2104 |
var parseSpecial func(string, string, string) (*XMLNode, bool) |
| 2105 |
|
| 2106 |
// parseSpecial parses XML tags into tree structure for searching, no contentMods flags set |
| 2107 |
parseSpecial = func(strt, attr, prnt string) (*XMLNode, bool) { |
| 2108 |
|
| 2109 |
var obj *XMLNode |
| 2110 |
ok := true |
| 2111 |
|
| 2112 |
// nextNode obtains next node from farm |
| 2113 |
node := nextNode(strt, attr, prnt) |
| 2114 |
if node == nil { |
| 2115 |
return nil, false |
| 2116 |
} |
| 2117 |
|
| 2118 |
var lastNode *XMLNode |
| 2119 |
|
| 2120 |
status := START |
| 2121 |
for { |
| 2122 |
tag, _, name, attr, idx := nextToken(Idx) |
| 2123 |
Idx = idx |
| 2124 |
|
| 2125 |
if tag == BADTAG { |
| 2126 |
if countLines { |
| 2127 |
DisplayError("Unparsable XML element, line %d", lineNum) |
| 2128 |
} else { |
| 2129 |
DisplayError("Unparsable XML element") |
| 2130 |
} |
| 2131 |
break |
| 2132 |
} |
| 2133 |
if tag == ISCLOSED { |
| 2134 |
break |
| 2135 |
} |
| 2136 |
|
| 2137 |
switch tag { |
| 2138 |
case STARTTAG: |
| 2139 |
if status == CHAR { |
| 2140 |
DisplayError("UNEXPECTED MIXED CONTENT <%s> IN <%s>", name, prnt) |
| 2141 |
} |
| 2142 |
// read sub tree |
| 2143 |
obj, ok = parseSpecial(name, attr, node.Name) |
| 2144 |
if !ok { |
| 2145 |
break |
| 2146 |
} |
| 2147 |
|
| 2148 |
// adding next child to end of linked list gives better performance than appending to slice of nodes |
| 2149 |
if node.Children == nil { |
| 2150 |
node.Children = obj |
| 2151 |
} |
| 2152 |
if lastNode != nil { |
| 2153 |
lastNode.Next = obj |
| 2154 |
} |
| 2155 |
lastNode = obj |
| 2156 |
status = STOP |
| 2157 |
case STOPTAG: |
| 2158 |
// pop out of recursive call |
| 2159 |
return node, ok |
| 2160 |
case CONTENTTAG: |
| 2161 |
node.Contents = name |
| 2162 |
status = CHAR |
| 2163 |
case SELFTAG: |
| 2164 |
if attr == "" && !doSelf { |
| 2165 |
// ignore if self-closing tag has no attributes |
| 2166 |
continue |
| 2167 |
} |
| 2168 |
|
| 2169 |
// self-closing tag has no contents, just create child node |
| 2170 |
obj = nextNode(name, attr, node.Name) |
| 2171 |
|
| 2172 |
if doSelf { |
| 2173 |
// add default value for self-closing tag |
| 2174 |
obj.Contents = "1" |
| 2175 |
} |
| 2176 |
|
| 2177 |
if node.Children == nil { |
| 2178 |
node.Children = obj |
| 2179 |
} |
| 2180 |
if lastNode != nil { |
| 2181 |
lastNode.Next = obj |
| 2182 |
} |
| 2183 |
lastNode = obj |
| 2184 |
status = OTHER |
| 2185 |
// continue on same level |
| 2186 |
default: |
| 2187 |
status = OTHER |
| 2188 |
} |
| 2189 |
} |
| 2190 |
|
| 2191 |
return node, ok |
| 2192 |
} |
| 2193 |
|
| 2194 |
// parseLevel recursive definition |
| 2195 |
var parseLevel func(string, string, string) (*XMLNode, bool) |
| 2196 |
|
| 2197 |
// parseLevel parses XML tags into tree structure for searching, some contentMods flags set |
| 2198 |
parseLevel = func(strt, attr, prnt string) (*XMLNode, bool) { |
| 2199 |
|
| 2200 |
var obj *XMLNode |
| 2201 |
ok := true |
| 2202 |
|
| 2203 |
// obtain next node from farm |
| 2204 |
node := nextNode(strt, attr, prnt) |
| 2205 |
if node == nil { |
| 2206 |
return nil, false |
| 2207 |
} |
| 2208 |
|
| 2209 |
var lastNode *XMLNode |
| 2210 |
|
| 2211 |
status := START |
| 2212 |
for { |
| 2213 |
tag, ctype, name, attr, idx := nextToken(Idx) |
| 2214 |
Idx = idx |
| 2215 |
|
| 2216 |
if countLines && Idx > 0 { |
| 2217 |
updateLineCount(Idx) |
| 2218 |
} |
| 2219 |
|
| 2220 |
if tag == BADTAG { |
| 2221 |
if countLines { |
| 2222 |
DisplayError("Unparsable XML element, line %d", lineNum) |
| 2223 |
} else { |
| 2224 |
DisplayError("Unparsable XML element") |
| 2225 |
} |
| 2226 |
break |
| 2227 |
} |
| 2228 |
if tag == ISCLOSED { |
| 2229 |
break |
| 2230 |
} |
| 2231 |
|
| 2232 |
switch tag { |
| 2233 |
case STARTTAG: |
| 2234 |
if status == CHAR { |
| 2235 |
if doStrict { |
| 2236 |
DisplayError("UNRECOGNIZED MIXED CONTENT <%s> IN <%s>", name, prnt) |
| 2237 |
} else if !doMixed { |
| 2238 |
DisplayError("UNEXPECTED MIXED CONTENT <%s> IN <%s>", name, prnt) |
| 2239 |
} |
| 2240 |
} |
| 2241 |
// read sub tree |
| 2242 |
obj, ok = parseLevel(name, attr, node.Name) |
| 2243 |
if !ok { |
| 2244 |
break |
| 2245 |
} |
| 2246 |
|
| 2247 |
// adding next child to end of linked list gives better performance than appending to slice of nodes |
| 2248 |
if node.Children == nil { |
| 2249 |
node.Children = obj |
| 2250 |
} |
| 2251 |
if lastNode != nil { |
| 2252 |
lastNode.Next = obj |
| 2253 |
} |
| 2254 |
lastNode = obj |
| 2255 |
status = STOP |
| 2256 |
case STOPTAG: |
| 2257 |
// pop out of recursive call |
| 2258 |
return node, ok |
| 2259 |
case CONTENTTAG: |
| 2260 |
if doMixed { |
| 2261 |
// create unnamed child node for content string |
| 2262 |
con := nextNode("", "", "") |
| 2263 |
if con == nil { |
| 2264 |
break |
| 2265 |
} |
| 2266 |
str := CleanupContents(name, (ctype&ASCII) != 0, (ctype&ER) != 0, (ctype&MIXED) != 0) |
| 2267 |
if (ctype & LFTSPACE) != 0 { |
| 2268 |
str = " " + str |
| 2269 |
} |
| 2270 |
if (ctype & RGTSPACE) != 0 { |
| 2271 |
str += " " |
| 2272 |
} |
| 2273 |
con.Contents = str |
| 2274 |
if node.Children == nil { |
| 2275 |
node.Children = con |
| 2276 |
} |
| 2277 |
if lastNode != nil { |
| 2278 |
lastNode.Next = con |
| 2279 |
} |
| 2280 |
lastNode = con |
| 2281 |
} else { |
| 2282 |
node.Contents = CleanupContents(name, (ctype&ASCII) != 0, (ctype&ER) != 0, (ctype&MIXED) != 0) |
| 2283 |
} |
| 2284 |
status = CHAR |
| 2285 |
case SELFTAG: |
| 2286 |
if attr == "" && !doSelf { |
| 2287 |
// ignore if self-closing tag has no attributes |
| 2288 |
continue |
| 2289 |
} |
| 2290 |
|
| 2291 |
// self-closing tag has no contents, just create child node |
| 2292 |
obj = nextNode(name, attr, node.Name) |
| 2293 |
|
| 2294 |
if doSelf { |
| 2295 |
// add default value for self-closing tag |
| 2296 |
obj.Contents = "1" |
| 2297 |
} |
| 2298 |
|
| 2299 |
if node.Children == nil { |
| 2300 |
node.Children = obj |
| 2301 |
} |
| 2302 |
if lastNode != nil { |
| 2303 |
lastNode.Next = obj |
| 2304 |
} |
| 2305 |
lastNode = obj |
| 2306 |
status = OTHER |
| 2307 |
// continue on same level |
| 2308 |
default: |
| 2309 |
status = OTHER |
| 2310 |
} |
| 2311 |
} |
| 2312 |
|
| 2313 |
return node, ok |
| 2314 |
} |
| 2315 |
|
| 2316 |
// parseIndex recursive definition |
| 2317 |
var parseIndex func(string, string, string) string |
| 2318 |
|
| 2319 |
// parseIndex parses XML tags looking for trie index element |
| 2320 |
parseIndex = func(strt, attr, prnt string) string { |
| 2321 |
|
| 2322 |
versn := "" |
| 2323 |
|
| 2324 |
// check for version attribute match |
| 2325 |
if attr != "" && find.Versn != "" && strings.Contains(attr, find.Versn) { |
| 2326 |
if strt == find.Match || find.Match == "" { |
| 2327 |
if find.Parent == "" || prnt == find.Parent { |
| 2328 |
attribs := ParseAttributes(attr) |
| 2329 |
for i := 0; i < len(attribs)-1; i += 2 { |
| 2330 |
if attribs[i] == find.Versn { |
| 2331 |
versn = attribs[i+1] |
| 2332 |
} |
| 2333 |
} |
| 2334 |
} |
| 2335 |
} |
| 2336 |
} |
| 2337 |
|
| 2338 |
// check for attribute index match |
| 2339 |
if attr != "" && find.Attrib != "" && strings.Contains(attr, find.Attrib) { |
| 2340 |
if strt == find.Match || find.Match == "" { |
| 2341 |
if find.Parent == "" || prnt == find.Parent { |
| 2342 |
attribs := ParseAttributes(attr) |
| 2343 |
for i := 0; i < len(attribs)-1; i += 2 { |
| 2344 |
if attribs[i] == find.Attrib { |
| 2345 |
return attribs[i+1] |
| 2346 |
} |
| 2347 |
} |
| 2348 |
} |
| 2349 |
} |
| 2350 |
} |
| 2351 |
|
| 2352 |
for { |
| 2353 |
tag, _, name, attr, idx := nextToken(Idx) |
| 2354 |
Idx = idx |
| 2355 |
|
| 2356 |
if tag == BADTAG { |
| 2357 |
if countLines { |
| 2358 |
DisplayError("Unparsable XML element, line %d", lineNum) |
| 2359 |
} else { |
| 2360 |
DisplayError("Unparsable XML element") |
| 2361 |
} |
| 2362 |
break |
| 2363 |
} |
| 2364 |
if tag == ISCLOSED { |
| 2365 |
break |
| 2366 |
} |
| 2367 |
|
| 2368 |
switch tag { |
| 2369 |
case STARTTAG: |
| 2370 |
id := parseIndex(name, attr, strt) |
| 2371 |
if id != "" { |
| 2372 |
return id |
| 2373 |
} |
| 2374 |
case SELFTAG: |
| 2375 |
case STOPTAG: |
| 2376 |
// break recursion |
| 2377 |
return "" |
| 2378 |
case CONTENTTAG: |
| 2379 |
// check for content index match |
| 2380 |
if strt == find.Match || find.Match == "" { |
| 2381 |
if find.Parent == "" || prnt == find.Parent { |
| 2382 |
// append version if specified as parent/element@attribute^version |
| 2383 |
if versn != "" { |
| 2384 |
name += "." |
| 2385 |
name += versn |
| 2386 |
} |
| 2387 |
if ids != nil { |
| 2388 |
ids(name) |
| 2389 |
} else { |
| 2390 |
return name |
| 2391 |
} |
| 2392 |
} |
| 2393 |
} |
| 2394 |
default: |
| 2395 |
} |
| 2396 |
} |
| 2397 |
|
| 2398 |
return "" |
| 2399 |
} |
| 2400 |
|
| 2401 |
// main loops |
| 2402 |
|
| 2403 |
// stream all tokens through callback |
| 2404 |
if tokens != nil { |
| 2405 |
|
| 2406 |
for { |
| 2407 |
tag, ctype, name, attr, idx := nextToken(Idx) |
| 2408 |
Idx = idx |
| 2409 |
|
| 2410 |
if countLines && Idx > 0 { |
| 2411 |
updateLineCount(Idx) |
| 2412 |
} |
| 2413 |
|
| 2414 |
if tag == BADTAG { |
| 2415 |
if countLines { |
| 2416 |
DisplayError("Unparsable XML element, line %d", lineNum) |
| 2417 |
} else { |
| 2418 |
DisplayError("Unparsable XML element") |
| 2419 |
} |
| 2420 |
break |
| 2421 |
} |
| 2422 |
|
| 2423 |
tkn := XMLToken{Tag: tag, Cont: ctype, Name: name, Attr: attr, Index: idx, Line: lineNum} |
| 2424 |
|
| 2425 |
tokens(tkn) |
| 2426 |
|
| 2427 |
if tag == ISCLOSED { |
| 2428 |
break |
| 2429 |
} |
| 2430 |
} |
| 2431 |
|
| 2432 |
return nil, "" |
| 2433 |
} |
| 2434 |
|
| 2435 |
// find value of index element |
| 2436 |
if find != nil && find.Index != "" { |
| 2437 |
|
| 2438 |
// return indexed identifier |
| 2439 |
|
| 2440 |
tag, _, name, attr, idx := nextToken(Idx) |
| 2441 |
|
| 2442 |
// loop until start tag |
| 2443 |
for { |
| 2444 |
Idx = idx |
| 2445 |
|
| 2446 |
if tag == BADTAG { |
| 2447 |
if countLines { |
| 2448 |
DisplayError("Unparsable XML element, line %d", lineNum) |
| 2449 |
} else { |
| 2450 |
DisplayError("Unparsable XML element") |
| 2451 |
} |
| 2452 |
break |
| 2453 |
} |
| 2454 |
if tag == ISCLOSED { |
| 2455 |
break |
| 2456 |
} |
| 2457 |
|
| 2458 |
if tag == STARTTAG { |
| 2459 |
break |
| 2460 |
} |
| 2461 |
|
| 2462 |
tag, _, name, attr, idx = nextToken(Idx) |
| 2463 |
} |
| 2464 |
|
| 2465 |
return nil, parseIndex(name, attr, parent) |
| 2466 |
} |
| 2467 |
|
| 2468 |
// otherwise create node tree for general data extraction |
| 2469 |
tag, _, name, attr, idx := nextToken(Idx) |
| 2470 |
|
| 2471 |
// loop until start tag |
| 2472 |
for { |
| 2473 |
Idx = idx |
| 2474 |
|
| 2475 |
if tag == BADTAG { |
| 2476 |
if countLines { |
| 2477 |
DisplayError("Unparsable XML element, line %d", lineNum) |
| 2478 |
} else { |
| 2479 |
DisplayError("Unparsable XML element") |
| 2480 |
} |
| 2481 |
break |
| 2482 |
} |
| 2483 |
if tag == ISCLOSED { |
| 2484 |
break |
| 2485 |
} |
| 2486 |
|
| 2487 |
if tag == STARTTAG { |
| 2488 |
break |
| 2489 |
} |
| 2490 |
|
| 2491 |
tag, _, name, attr, idx = nextToken(Idx) |
| 2492 |
} |
| 2493 |
|
| 2494 |
if contentMods { |
| 2495 |
// slower parser also handles mixed content |
| 2496 |
top, ok := parseLevel(name, attr, parent) |
| 2497 |
|
| 2498 |
if !ok { |
| 2499 |
return nil, "" |
| 2500 |
} |
| 2501 |
|
| 2502 |
return top, "" |
| 2503 |
} |
| 2504 |
|
| 2505 |
// fastest parsing with no contentMods flags |
| 2506 |
top, ok := parseSpecial(name, attr, parent) |
| 2507 |
|
| 2508 |
if !ok { |
| 2509 |
return nil, "" |
| 2510 |
} |
| 2511 |
|
| 2512 |
return top, "" |
| 2513 |
} |
| 2514 |
|
| 2515 |
// SPECIALIZED PUBLIC parseXML SHORTCUTS |
| 2516 |
|
| 2517 |
// ParseRecord is the main public access to parseXML |
| 2518 |
func ParseRecord(text, parent string) *XMLNode { |
| 2519 |
|
| 2520 |
pat, _ := parseXML(text, parent, nil, nil, nil, nil) |
| 2521 |
|
| 2522 |
return pat |
| 2523 |
} |
| 2524 |
|
| 2525 |
// FindIdentifier returns a single identifier |
| 2526 |
func FindIdentifier(text, parent string, find *XMLFind) string { |
| 2527 |
|
| 2528 |
_, id := parseXML(text, parent, nil, nil, find, nil) |
| 2529 |
|
| 2530 |
return id |
| 2531 |
} |
| 2532 |
|
| 2533 |
// FindIdentifiers returns a set of identifiers through a callback |
| 2534 |
func FindIdentifiers(text, parent string, find *XMLFind, ids func(string)) { |
| 2535 |
|
| 2536 |
parseXML(text, parent, nil, nil, find, ids) |
| 2537 |
} |
| 2538 |
|
| 2539 |
// StreamTokens streams tokens from a reader through a callback |
| 2540 |
func StreamTokens(inp <-chan XMLBlock, streamer func(tkn XMLToken)) { |
| 2541 |
|
| 2542 |
parseXML("", "", inp, streamer, nil, nil) |
| 2543 |
} |
| 2544 |
|
| 2545 |
// StreamValues streams token values from a parsed record through a callback |
| 2546 |
func StreamValues(text, parent string, stream func(string, string, string)) { |
| 2547 |
|
| 2548 |
elementName := "" |
| 2549 |
attributeName := "" |
| 2550 |
|
| 2551 |
streamer := func(tkn XMLToken) { |
| 2552 |
|
| 2553 |
switch tkn.Tag { |
| 2554 |
case STARTTAG: |
| 2555 |
elementName = tkn.Name |
| 2556 |
attributeName = tkn.Attr |
| 2557 |
case CONTENTTAG: |
| 2558 |
// send element name and content to callback |
| 2559 |
stream(elementName, attributeName, tkn.Name) |
| 2560 |
default: |
| 2561 |
} |
| 2562 |
} |
| 2563 |
|
| 2564 |
parseXML(text, parent, nil, streamer, nil, nil) |
| 2565 |
} |
| 2566 |
|
| 2567 |
// CreateTokenizer streams tokens through a channel |
| 2568 |
func CreateTokenizer(inp <-chan XMLBlock) <-chan XMLToken { |
| 2569 |
|
| 2570 |
if inp == nil { |
| 2571 |
return nil |
| 2572 |
} |
| 2573 |
|
| 2574 |
out := make(chan XMLToken, chanDepth) |
| 2575 |
if out == nil { |
| 2576 |
DisplayError("Unable to create XML tokenizer channel") |
| 2577 |
os.Exit(1) |
| 2578 |
} |
| 2579 |
|
| 2580 |
// xmlTokenizer sends XML tokens through channel |
| 2581 |
xmlTokenizer := func(inp <-chan XMLBlock, out chan<- XMLToken) { |
| 2582 |
|
| 2583 |
// close channel when all records have been processed |
| 2584 |
defer close(out) |
| 2585 |
|
| 2586 |
// parse XML and send tokens through channel |
| 2587 |
parseXML("", "", inp, func(tkn XMLToken) { out <- tkn }, nil, nil) |
| 2588 |
} |
| 2589 |
|
| 2590 |
// launch single tokenizer goroutine |
| 2591 |
go xmlTokenizer(inp, out) |
| 2592 |
|
| 2593 |
return out |
| 2594 |
} |
| 2595 |
|
| 2596 |
// EXPLORE XML ELEMENTS |
| 2597 |
|
| 2598 |
// ExploreElements returns matching element values to callback |
| 2599 |
func ExploreElements(curr *XMLNode, mask, prnt, match, attrib string, wildcard, unescape bool, level int, proc func(string, int)) { |
| 2600 |
|
| 2601 |
if curr == nil || proc == nil { |
| 2602 |
return |
| 2603 |
} |
| 2604 |
|
| 2605 |
// **/Object performs deep exploration of recursive data (*/Object also supported) |
| 2606 |
deep := false |
| 2607 |
if prnt == "**" || prnt == "*" { |
| 2608 |
prnt = "" |
| 2609 |
deep = true |
| 2610 |
} |
| 2611 |
|
| 2612 |
// exploreChildren recursive definition |
| 2613 |
var exploreChildren func(curr *XMLNode, acc func(string)) |
| 2614 |
|
| 2615 |
// exploreChildren handles mixed-content chains of embedded tags |
| 2616 |
exploreChildren = func(curr *XMLNode, acc func(string)) { |
| 2617 |
|
| 2618 |
if curr.Contents != "" { |
| 2619 |
acc(curr.Contents) |
| 2620 |
} |
| 2621 |
for chld := curr.Children; chld != nil; chld = chld.Next { |
| 2622 |
if chld.Name != "" { |
| 2623 |
acc("<" + chld.Name + ">") |
| 2624 |
} |
| 2625 |
exploreChildren(chld, acc) |
| 2626 |
if chld.Name != "" { |
| 2627 |
acc("</" + chld.Name + ">") |
| 2628 |
} |
| 2629 |
} |
| 2630 |
} |
| 2631 |
|
| 2632 |
// exploreElements recursive definition |
| 2633 |
var exploreElements func(curr *XMLNode, skip string, lev int) |
| 2634 |
|
| 2635 |
// exploreElements visits nodes looking for matches to requested object |
| 2636 |
exploreElements = func(curr *XMLNode, skip string, lev int) { |
| 2637 |
|
| 2638 |
if !deep && curr.Name == skip { |
| 2639 |
// do not explore within recursive object |
| 2640 |
return |
| 2641 |
} |
| 2642 |
|
| 2643 |
if curr.Name == match || |
| 2644 |
// parent/* matches any subfield |
| 2645 |
(match == "*" && prnt != "") || |
| 2646 |
// wildcard (internal colon) matches any namespace prefix |
| 2647 |
(wildcard && strings.HasPrefix(match, ":") && strings.HasSuffix(curr.Name, match)) || |
| 2648 |
(match == "" && attrib != "") { |
| 2649 |
|
| 2650 |
if prnt == "" || |
| 2651 |
curr.Parent == prnt || |
| 2652 |
(wildcard && strings.HasPrefix(prnt, ":") && strings.HasSuffix(curr.Parent, prnt)) { |
| 2653 |
|
| 2654 |
if attrib != "" { |
| 2655 |
if curr.Attributes != "" && curr.Attribs == nil { |
| 2656 |
// parse attributes on-the-fly if queried |
| 2657 |
curr.Attribs = ParseAttributes(curr.Attributes) |
| 2658 |
} |
| 2659 |
for i := 0; i < len(curr.Attribs)-1; i += 2 { |
| 2660 |
// attributes now parsed into array as [ tag, value, tag, value, tag, value, ... ] |
| 2661 |
if curr.Attribs[i] == attrib || |
| 2662 |
(wildcard && strings.HasPrefix(attrib, ":") && strings.HasSuffix(curr.Attribs[i], attrib)) { |
| 2663 |
proc(curr.Attribs[i+1], level) |
| 2664 |
return |
| 2665 |
} |
| 2666 |
} |
| 2667 |
|
| 2668 |
} else if curr.Contents != "" { |
| 2669 |
|
| 2670 |
str := curr.Contents[:] |
| 2671 |
|
| 2672 |
if unescape && HasAmpOrNotASCII(str) { |
| 2673 |
// processing of <, >, &, ", and ' characters is now delayed until element contents is requested |
| 2674 |
// unescape converts <b> to <b> |
| 2675 |
// also µ to Greek mu character, and &#x...; hex values |
| 2676 |
str = html.UnescapeString(str) |
| 2677 |
} |
| 2678 |
|
| 2679 |
proc(str, level) |
| 2680 |
return |
| 2681 |
|
| 2682 |
} else if curr.Children != nil { |
| 2683 |
|
| 2684 |
if doMixed { |
| 2685 |
// match with mixed contents - send all child strings |
| 2686 |
var buffr strings.Builder |
| 2687 |
exploreChildren(curr, func(str string) { |
| 2688 |
if str != "" { |
| 2689 |
buffr.WriteString(str) |
| 2690 |
} |
| 2691 |
}) |
| 2692 |
str := buffr.String() |
| 2693 |
|
| 2694 |
// clean up reconstructed mixed content |
| 2695 |
str = DoTrimFlankingHTML(str) |
| 2696 |
if HasBadSpace(str) { |
| 2697 |
str = CleanupBadSpaces(str) |
| 2698 |
} |
| 2699 |
if HasAdjacentSpaces(str) { |
| 2700 |
str = CompressRunsOfSpaces(str) |
| 2701 |
} |
| 2702 |
if NeedsTightening(str) { |
| 2703 |
str = TightenParentheses(str) |
| 2704 |
} |
| 2705 |
if unescape && HasAmpOrNotASCII(str) { |
| 2706 |
str = html.UnescapeString(str) |
| 2707 |
} |
| 2708 |
|
| 2709 |
proc(str, level) |
| 2710 |
return |
| 2711 |
} |
| 2712 |
|
| 2713 |
// for XML container object, send empty string to callback to increment count |
| 2714 |
proc("", level) |
| 2715 |
// and continue exploring |
| 2716 |
|
| 2717 |
} else if curr.Attributes != "" { |
| 2718 |
|
| 2719 |
// for self-closing object, indicate presence by sending empty string to callback |
| 2720 |
proc("", level) |
| 2721 |
return |
| 2722 |
} |
| 2723 |
} |
| 2724 |
} |
| 2725 |
|
| 2726 |
for chld := curr.Children; chld != nil; chld = chld.Next { |
| 2727 |
// inner exploration is subject to recursive object exclusion |
| 2728 |
exploreElements(chld, mask, lev+1) |
| 2729 |
} |
| 2730 |
} |
| 2731 |
|
| 2732 |
// start recursive exploration from current scope |
| 2733 |
exploreElements(curr, "", level) |
| 2734 |
} |
| 2735 |
|
| 2736 |
// EXPLORE XML CONTAINERS |
| 2737 |
|
| 2738 |
// ExploreNodes visits XML container nodes |
| 2739 |
func ExploreNodes(curr *XMLNode, prnt, match string, index, level int, proc func(*XMLNode, int, int)) { |
| 2740 |
|
| 2741 |
if curr == nil || proc == nil { |
| 2742 |
return |
| 2743 |
} |
| 2744 |
|
| 2745 |
// leading colon indicates namespace prefix wildcard |
| 2746 |
wildcard := false |
| 2747 |
if strings.HasPrefix(prnt, ":") || strings.HasPrefix(match, ":") { |
| 2748 |
wildcard = true |
| 2749 |
} |
| 2750 |
|
| 2751 |
// Single * allows exploration of heterogeneous data construct without knowing current component name |
| 2752 |
if prnt == "" && match == "*" { |
| 2753 |
match = curr.Name |
| 2754 |
} |
| 2755 |
|
| 2756 |
// **/Object performs deep exploration of recursive data |
| 2757 |
deep := false |
| 2758 |
if prnt == "**" { |
| 2759 |
prnt = "*" |
| 2760 |
deep = true |
| 2761 |
} |
| 2762 |
// Object/** performs exhaustive exploration of nodes |
| 2763 |
tall := false |
| 2764 |
if match == "**" { |
| 2765 |
match = "*" |
| 2766 |
tall = true |
| 2767 |
} |
| 2768 |
|
| 2769 |
// exploreNodes recursive definition |
| 2770 |
var exploreNodes func(*XMLNode, int, int, bool, func(*XMLNode, int, int)) int |
| 2771 |
|
| 2772 |
// exploreNodes visits all nodes that match the selection criteria |
| 2773 |
exploreNodes = func(curr *XMLNode, indx, levl int, force bool, proc func(*XMLNode, int, int)) int { |
| 2774 |
|
| 2775 |
if curr == nil || proc == nil { |
| 2776 |
return indx |
| 2777 |
} |
| 2778 |
|
| 2779 |
// match is "*" for heterogeneous data constructs, e.g., -group PubmedArticleSet/* |
| 2780 |
// wildcard matches any namespace prefix |
| 2781 |
if curr.Name == match || |
| 2782 |
match == "*" || |
| 2783 |
(wildcard && strings.HasPrefix(match, ":") && strings.HasSuffix(curr.Name, match)) { |
| 2784 |
|
| 2785 |
if prnt == "" || |
| 2786 |
curr.Parent == prnt || |
| 2787 |
force || |
| 2788 |
(wildcard && strings.HasPrefix(prnt, ":") && strings.HasSuffix(curr.Parent, prnt)) { |
| 2789 |
|
| 2790 |
proc(curr, indx, levl) |
| 2791 |
indx++ |
| 2792 |
|
| 2793 |
if tall && prnt != "" { |
| 2794 |
// exhaustive exploration of child nodes within region of parent match |
| 2795 |
for chld := curr.Children; chld != nil; chld = chld.Next { |
| 2796 |
indx = exploreNodes(chld, indx, levl+1, true, proc) |
| 2797 |
} |
| 2798 |
} |
| 2799 |
|
| 2800 |
if !deep { |
| 2801 |
// do not explore within recursive object |
| 2802 |
return indx |
| 2803 |
} |
| 2804 |
} |
| 2805 |
} |
| 2806 |
|
| 2807 |
// clearing prnt "*" now allows nested exploration within recursive data, e.g., -pattern Taxon -block */Taxon |
| 2808 |
if prnt == "*" { |
| 2809 |
prnt = "" |
| 2810 |
} |
| 2811 |
|
| 2812 |
// explore child nodes |
| 2813 |
for chld := curr.Children; chld != nil; chld = chld.Next { |
| 2814 |
indx = exploreNodes(chld, indx, levl+1, false, proc) |
| 2815 |
} |
| 2816 |
|
| 2817 |
return indx |
| 2818 |
} |
| 2819 |
|
| 2820 |
exploreNodes(curr, index, level, false, proc) |
| 2821 |
} |
| 2822 |
|
| 2823 |
// EXPLORE SHORTCUTS |
| 2824 |
|
| 2825 |
// VisitElements is a shortcut to ExploreElements |
| 2826 |
// Use mask argument to block exploration into recursive object |
| 2827 |
func VisitElements(curr *XMLNode, match, mask string, proc func(string)) { |
| 2828 |
|
| 2829 |
if curr == nil || proc == nil { |
| 2830 |
return |
| 2831 |
} |
| 2832 |
|
| 2833 |
// parse parent/element@attribute construct |
| 2834 |
prnt, match := SplitInTwoRight(match, "/") |
| 2835 |
match, attrib := SplitInTwoLeft(match, "@") |
| 2836 |
|
| 2837 |
ExploreElements(curr, mask, prnt, match, attrib, false, false, 0, func(str string, lvl int) { proc(str) }) |
| 2838 |
} |
| 2839 |
|
| 2840 |
// VisitNodes is a shortcut to ExploreNodes |
| 2841 |
func VisitNodes(curr *XMLNode, match string, proc func(*XMLNode)) { |
| 2842 |
|
| 2843 |
if curr == nil || proc == nil { |
| 2844 |
return |
| 2845 |
} |
| 2846 |
|
| 2847 |
// parse parent/element@attribute construct |
| 2848 |
prnt, match := SplitInTwoRight(match, "/") |
| 2849 |
match, _ = SplitInTwoLeft(match, "@") |
| 2850 |
|
| 2851 |
ExploreNodes(curr, prnt, match, 0, 0, func(node *XMLNode, idx, lvl int) { proc(node) }) |
| 2852 |
} |
| 2853 |
|
| 2854 |
// STRING TO XML UTILITY |
| 2855 |
|
| 2856 |
// StringToXML supports XXXtoXML convenience functions |
| 2857 |
func StringToXML(rec string, proc func(io.Reader) <-chan string) string { |
| 2858 |
|
| 2859 |
if rec == "" || proc == nil { |
| 2860 |
return "" |
| 2861 |
} |
| 2862 |
|
| 2863 |
rdr := strings.NewReader(rec) |
| 2864 |
if rdr == nil { |
| 2865 |
DisplayError("Unable to create NewReader") |
| 2866 |
return "" |
| 2867 |
} |
| 2868 |
|
| 2869 |
chn := proc(rdr) |
| 2870 |
if chn == nil { |
| 2871 |
DisplayError("Unable to create StringToXML converter") |
| 2872 |
return "" |
| 2873 |
} |
| 2874 |
|
| 2875 |
var arry []string |
| 2876 |
|
| 2877 |
// drain output of channel |
| 2878 |
for str := range chn { |
| 2879 |
if str == "" { |
| 2880 |
continue |
| 2881 |
} |
| 2882 |
|
| 2883 |
if !strings.HasSuffix(str, "\n") { |
| 2884 |
str += "\n" |
| 2885 |
} |
| 2886 |
|
| 2887 |
arry = append(arry, str) |
| 2888 |
} |
| 2889 |
|
| 2890 |
res := strings.Join(arry, "") |
| 2891 |
|
| 2892 |
return res |
| 2893 |
} |