summaryrefslogtreecommitdiffstats
path: root/tcldom-tcl/xmlswitch.tcl
blob: 4e2a2a130320cabf40ede533be11dc09ed7ff5b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# xmlswitch.tcl --
#
#	This file implements a control structure for Tcl.
#	'xmlswitch' iterates over an XML document.  Features in
#	the document may be specified using XPath location paths,
#	and these will trigger Tcl scripts when matched.
#
# Copyright (c) 2008 Explain
# http://www.explain.com.au/
# Copyright (c) 2000-2003 Zveno Pty Ltd
# http://www.zveno.com/
#
# See the file "LICENSE" in this distribution for information on usage and
# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# $Id: xmlswitch.tcl,v 1.1.1.1 2009/01/16 22:11:49 joye Exp $

package provide xmlswitch 3.2

# We need the xml, dom and xpath packages

package require xml 3.2
package require dom 3.2
package require xpath 1.0

namespace eval xmlswitch {
    namespace export xmlswitch xmlswitchcont xmlswitchend
    namespace export domswitch
    namespace export free rootnode

    variable counter 0

    variable typemap
    array set typemap {
	text textNode
	comment comment
	processing-instruction processingInstruction
    }
}

# xmlswitch::xmlswitch --
#
#	Parse XML data, matching for XPath locations along the way
#	and (possibly) triggering callbacks.
#
#	A DOM tree is built as a side-effect (necessary for resolving
#	XPath location paths).
#
# Arguments:
#	xml	XML document
#	args	configuration options,
#		plus a single path/script expression, or multiple expressions
#
# Results:
#	Tcl callbacks may be invoked.
#	If -async option is true returns a token for this "process".

proc xmlswitch::xmlswitch {xml args} {
    variable counter

    set stateVarName [namespace current]::State[incr counter]
    upvar #0 $stateVarName state
    set state(stateVarName) $stateVarName
    set state(-async) 0

    set state(pathArray) ${stateVarName}Paths
    upvar #0 $state(pathArray) paths
    array set paths {}

    set cleanup {
	unset state
	unset paths
    }

    # Find configuration options and remove
    set numOpts 0
    foreach {opt value} $args {
	switch -glob -- $opt {
	    -* {
		set state($opt) $value
		incr numOpts 2
	    }
	    default {
		set args [lrange $args $numOpts end]
		break
	    }
	}
    }

    switch -- [llength $args] {
	0 {
	    # Nothing to do
	    eval $cleanup
	    return $stateVarName
	}
	1 {
	    foreach {path script} [lindex $args 0] {
		set paths([xpath::split $path]) $script
	    }
	}
	default {
	    if {[llength $args] % 2} {
		eval $cleanup
		return -code error "no script matching location path \"[lindex $args end]\""
	    }
	    foreach {path script} $args {
		set paths([xpath::split $path]) $script
	    }
	}
    }

    set root [set state(root) [dom::DOMImplementation create]]
    set state(current) $root

    # Parse the document
    # We're going to do this incrementally, so the caller can
    # break at any time
    set state(parser) [eval xml::parser [array get state -parser]]
    #append cleanup "\n $parser destroy\n"
    $state(parser) configure \
	    -elementstartcommand [namespace code [list ParseElementStart $stateVarName]]	\
	    -elementendcommand [namespace code [list ParseElementEnd $stateVarName]]		\
	    -characterdatacommand [namespace code [list ParseCharacterData $stateVarName]]	\
	    -final 0

#	    -processinginstructioncommand [namespace code [list ParsePI $stateVarName]]		\
#	    -commentcommand [namespace code [list ParseComment]]

    if {[catch {$state(parser) parse $xml} err]} {
	eval $cleanup
	return -code error $err
    }

    if {$state(-async)} {
	return $stateVarName
    } else {
	eval $cleanup
	return {}
    }
}

# xmlswitch::xmlswitchcont --
#
#	Provide more XML data to parse
#
# Arguments:
#	token	state variable name
#	xml	XML data
#
# Results:
#	More parsing

proc xmlswitch::xmlswitchcont {token xml} {
    upvar #0 $token state

    $state(parser) parse $xml

    return {}
}

# xmlswitch::xmlswitchend --
#
#	Signal that no further data is available
#
# Arguments:
#	token	state array
#
# Results:
#	Parser configuration changed

proc xmlswitch::xmlswitchend token {
    upvar #0 $token state

    $state(parser) configure -final true

    return {}
}

# xmlswitch::rootnode --
#
#	Get the root node
#
# Arguments:
#	token	state array
#
# Results:
#	Returns root node token

proc xmlswitch::rootnode token {
    upvar #0 $token state

    return $state(root)
}

# xmlswitch::free --
#
#	Free resources EXCEPT the DOM tree.
#	"-all" causes DOM tree to be destroyed too.
#
# Arguments:
#	token	state array
#	args	options
#
# Results:
#	Resources freed.

proc xmlswitch::free {token args} {
    upvar #0 $token state

    if {[lsearch $args "-all"] >= 0} {
	dom::DOMImplementation destroy $state(root)
    }

    catch {unset $state(pathArray)}
    catch {unset state}

    catch {$state(parser) free}

    return {}
}

# xmlswitch::ParseElementStart --
#
#	Handle element start tag
#
# Arguments:
#	token	state array
#	name	element type
#	attrList attribute list
#	args	options
# Results:
#	All XPath location paths are checked for a match,
#	and script evaluated for matching XPath.
#	DOM tree node added.

proc xmlswitch::ParseElementStart:dbgdisabled {token name attrList args} {
    if {[catch {eval ParseElementStart:dbg [list $token $name $attrList] $args} msg]} {
	puts stderr [list ParseElementStart failed with msg $msg]
	puts stderr $::errorInfo
	return -code error $msg
    } else {
	puts stderr [list ParseElementStart returned OK]
    }
    return $msg
}
proc xmlswitch::ParseElementStart {token name attrList args} {

    upvar #0 $token state
    array set opts $args

    #puts stderr [list xmlswitch::ParseElementStart $token $name $attrList $args]

    lappend state(current) \
	    [dom::document createElement [lindex $state(current) end] $name]
    foreach {name value} $attrList {
	dom::element setAttribute [lindex $state(current) end] $name $value
    }

    MatchTemplates $token [lindex $state(current) end]

    return {}
}

# xmlswitch::ParseElementEnd --
#
#	Handle element end tag
#
# Arguments:
#	token	state array
#	name	element type
#	args	options
# Results:
#	State changed

proc xmlswitch::ParseElementEnd {token name args} {
    upvar #0 $token state

    set state(current) [lreplace $state(current) end end]

    return {}
}

# xmlswitch::ParseCharacterData --
#
#	Handle character data
#
# Arguments:
#	token	state array
#	data	pcdata
#
# Results:
#	All XPath location paths are checked for a match,
#	and script evaluated for matching XPath.
#	DOM tree node added.

proc xmlswitch::ParseCharacterData {token data} {
    upvar #0 $token state

    lappend state(current) \
	    [dom::document createTextNode [lindex $state(current) end] $data]

    MatchTemplates $token [lindex $state(current) end]

    set state(current) [lreplace $state(current) end end]

    return {}
}

# xmlswitch::domswitch --
#
#	Similar to xmlswitch above, but iterates over a pre-built
#	DOM tree.
#
# Arguments:
#	xml	XML document
#	args	a single path/script expression, or multiple expressions
#
# Results:
#	Tcl callbacks may be invoked.

proc xmlswitch::domswitch {xml args} {
}

# xmlswitch::MatchTemplates --
#
#	Check all templates for one which matches
#	the current node.
#
# Arguments:
#	token	state array
#	node	Current DOM node
#
# Results:
#	If a template matches, its script is evaluated

proc xmlswitch::MatchTemplates {token node} {
    upvar #0 $token state
    upvar #0 $state(pathArray) paths

    #puts stderr [list xmlswitch::MatchTemplates $token $node (type: [dom::node cget $node -nodeType]) (name: [dom::node cget $node -nodeName])]

    set matches {}

    foreach {path script} [array get paths] {

	#puts stderr [list checking path $path for a match]

	set context $node

	# Work backwards along the path, reversing each axis
	set match 0
	set i [llength $path]
	#puts stderr [list $i steps to be tested]
	while {[incr i -1] >= 0} {
	    #puts stderr [list step $i [lindex $path $i]]
	    switch -glob [llength [lindex $path $i]],$i {
		0,0 {
		    #puts stderr [list absolute path, end of steps - am I at the root?]
		    if {![string length [dom::node parent $context]]} {
			#puts stderr [list absolute path matched]
			lappend matches [list $path $script]
		    } else {
			#puts stderr [list absolute path did not match]
		    }
		}
		*,0 {
		    #puts stderr [list last step, relative path]
		    switch [lindex [lindex $path $i] 0] {
			child {
			    if {[NodeTest [lindex $path $i] $context] && \
				    [CheckPredicates [lindex $path $i] $context]} {
				#puts stderr [list relative path matched]
				lappend matches [list $path $script]
			    } else {
				#puts stderr [list relative path did not match]
			    }
			}
			default {
			    return -code error "axis \"[lindex [lindex $path $i] 0]\" not supported"
			}
		    }
		}
		default {
		    #puts stderr [list continuing checking steps]
		    switch [lindex [lindex $path $i] 0] {
			child {
			    if {[NodeTest [lindex $path $i] $context] && \
				    [CheckPredicates [lindex $path $i] $context]} {
				set context [dom::node parent $context]
			    } else {
				#puts stderr [list no match]
			    }
			}
			default {
			    return -code error "axis \"[lindex [lindex $path $i] 0]\" not supported"
			}
		    }
		}
	    }
	}
    }

    # TODO: If there are multiple matches then we must pick the
    # most specific match

    if {[llength $matches] > 1} {
	# For the moment we'll just take the first match
	set matches [list [lindex $matches 0]]
    }

    if {[llength $matches]} {
	#puts stderr [list evaluating callback at level [info level]]
	uplevel 3 [lindex [lindex $matches 0] 1]
    }

    return {}
}

# xmlswitch::NodeTest --
#
#	Check that the node passes the node (type) test
#
# Arguments:
#	step	Location step
#	node	DOM node
#
# Results:
#	Boolean

proc xmlswitch::NodeTest {step node} {

    if {[llength [lindex $step 1]] > 1} {
	switch -glob -- [lindex [lindex $step 1] 0],[dom::node cget $node -nodeType] {
	    node,* -
	    text,textNode -
	    comment,comment -
	    processing-instruction,processingInstruction {
		return 1
	    }
	    default {
		return 0
	    }
	}
    } elseif {![string compare [lindex $step 1] "*"]} {
	return 1
    } elseif {![string compare [lindex $step 1] [dom::node cget $node -nodeName]]} {
	return 1
    } else {
	return 0
    }
}

# xmlswitch::CheckPredicates --
#
#	Check that the node passes the predicates
#
# Arguments:
#	step	Location step
#	node	DOM node
#
# Results:
#	Boolean

proc xmlswitch::CheckPredicates {step node} {
    variable typemap

    set predicates [lindex $step 2]
    # Shortcut: no predicates means everything passes
    if {![llength $predicates]} {
	return 1
    }

    # Get the context node set
    switch [lindex $step 0] {
	child {
	    set nodeset {}
	    if {[llength [lindex $step 1]]} {
		foreach {name typetest} [lindex $step 1] break
		switch -- $name {
		    node {
			set nodeset [dom::node children [dom::node parent $node]]
		    }
		    text -
		    comment -
		    processing-instruction {
			foreach child [dom::node children [dom::node parent $node]] {
			    if {![string compare [dom::node cget $child -nodeType] $typemap($name)]} {
				lappend nodeset $child
			    }
			}
		    }
		    default {
			# Error
		    }
		}
	    } else {
		foreach child [dom::node children [dom::node parent $node]] {
		    if {![string compare [lindex $step 1] [dom::node cget $child -nodeName]]} {
			lappend nodeset $child
		    }
		}
	    }
	}
	default {
	    return -code error "axis \"[lindex $step 0]\" not supported"
	}
    }

    foreach predicate $predicates {
	# position() is the only supported predicate
	if {[lsearch $nodeset $node] + 1 == $predicate} {
	    # continue
	} else {
	    return 0
	}
    }

    return 1
}