File: util_norm_peg.tcl

package info (click to toggle)
tcllib 1.20%2Bdfsg-1
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 68,064 kB
  • sloc: tcl: 216,842; ansic: 14,250; sh: 2,846; xml: 1,766; yacc: 1,145; pascal: 881; makefile: 107; perl: 84; f90: 84; python: 33; ruby: 13; php: 11
file content (415 lines) | stat: -rw-r--r-- 10,637 bytes parent folder | download | duplicates (8)
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
# -*- tcl -*-
#
# Copyright (c) 2005 by Andreas Kupries <andreas_kupries@users.sourceforge.net>
# Parser Generator / Transformation - Normalize PEG AST for later.

# This package assumes to be used from within a PAGE plugin. It uses
# the API commands listed below. These are identical across the major
# types of PAGE plugins, allowing this package to be used in reader,
# transform, and writer plugins. It cannot be used in a configuration
# plugin, and this makes no sense either.
#
# To ensure that our assumption is ok we require the relevant pseudo
# package setup by the PAGE plugin management code.
#
# -----------------+--
# page_info        | Reporting to the user.
# page_warning     |
# page_error       |
# -----------------+--
# page_log_error   | Reporting of internals.
# page_log_warning |
# page_log_info    |
# -----------------+--

# ### ### ### ######### ######### #########
## Requisites

# @mdgen NODEP: page::plugin

package require page::plugin ; # S.a. pseudo-package.
package require treeql
package require page::util::quote

namespace eval ::page::util::norm::peg {
    # Get the peg char de/encoder commands.
    # (unquote, quote'tcl)

    namespace import ::page::util::quote::*
}

# ### ### ### ######### ######### #########
## API

proc ::page::util::norm::peg {t} {
    set q [treeql q -tree $t]

    page_info {[PEG Normalization]}
    page_log_info ..Terminals   ; peg::Terminals   $q $t
    page_log_info ..Chains      ; peg::CutChains   $q $t
    page_log_info ..Metadata    ; peg::Metadata    $q $t
    page_log_info ..Definitions ; peg::Definitions $q $t
    page_log_info ..Expressions ; peg::Expressions $q $t

    # Sentinel for PE algorithms.
    $t set root symbol <StartExpression>
    $q destroy

    page_log_info Ok
    return
}

# ### ### ### ######### ######### #########
## Documentation
#
## See doc_normalize.txt for the specification of the publicly visible
## attributes.
##
## Internal attributes
## - DATA - Transient storage for terminal data.

# ### ### ### ######### ######### #########
## Internal. Helpers

proc ::page::util::norm::peg::Terminals {q t} {
    # The data for all terminals is stored in their grandparental
    # nodes. We get rid of both terminals and their parents.

    $q query tree withatt type terminal over n {
	set p  [$t parent $n]
	set gp [$t parent $p]

	CopyLocation $t $n $gp
	AttrCopy     $t $n detail $gp DATA
	TokReduce    $t           $gp DATA
	$t delete $p
    }

    # We can now drop the type attribute, as all the remaining nodes
    # (which have it) will contain the value 'nonterminal'.

    $q query tree hasatt type over n {
	$t unset $n type
    }
    return
}

proc ::page::util::norm::peg::CutChains {q t} {
    # All nodes which have exactly one child are irrelevant. We get
    # rid of them. The root node is the sole exception. The immediate
    # child of the root however is superfluous as well.

    $q query tree notq {root} over n {
	if {[llength [$t children $n]] != 1} continue
	$t cut $n
    }

    foreach n [$t children root] {$t cut $n}
    return
}

proc ::page::util::norm::peg::Metadata {q t} {
    # Having the name of the grammar in a tree node is overkill. We
    # move this information into an attribute of the root node.
    # The node keeping the start expression separate is irrelevant as
    # well. We get rid of it, and tag the root of the start expression
    # with a marker attribute.

    $q query tree withatt detail Header over n {
	set tmp    [Child $t $n 0]
	set sexpr  [Child $t $n 1]

	AttrCopy $t $tmp DATA root name
	$t cut $tmp
	$t cut $n
	break
    }

    # Remember the node for the start expression in the root for quick
    # access by later stages.

    $t set root start $sexpr
    return
}

proc ::page::util::norm::peg::Definitions {q t} {
    # We move nonterminal hint information from nodes into attributes,
    # and delete the now irrelevant nodes.

    # NOTE: This transformation is dependent on the removal of all
    # nodes with exactly one child, as it removes the all 'Attribute'
    # nodes already. Otherwise this transformation would have to put
    # the information into the grandparental node.

    # The default mode for nonterminals is 'value'.

    $q query tree withatt detail Definition over n {
	$t set $n mode value
    }

    foreach {a mode} {
	VOID  discard
	MATCH match
	LEAF  leaf
    } {
	$q query tree withatt detail $a over n {
	    set p [$t parent $n]
	    $t set $p mode $mode
	    $t delete $n
	}
    }

    # Like with the global metadata we move definition specific
    # information out of nodes into attributes, get rid of the
    # superfluous nodes, and tag the definition roots with marker
    # attributes.

    set defs {}
    $q query tree withatt detail Definition over n {
	# Define mode information for all nonterminals without an
	# explicit specification. We also save the mode information
	# from deletion when we redo the definition node.

	set first [Child $t $n 0]

	set sym [$t get $first DATA]
	$t set $n symbol $sym
	$t set $n label  $sym
	$t set $n users  {}

	# Now determine the range in the input covered by the
	# definition. The left extent comes from the terminal for the
	# nonterminal symbol it defines. The right extent comes from
	# the rightmost child under the definition. While this not an
	# expression tree yet the location data is sound already.

	MergeLocations $t $first [Rightmost $t $n] $n
	$t unset $n detail

	lappend defs $sym $n
	$t cut $first
    }

    # We remember a mapping from nonterminal names to their defining
    # nodes in the root as well, for quick reference later, when we
    # build nonterminal usage references

    $t set root definitions $defs
    return
}

proc ::page::util::norm::peg::Rightmost {t n} {
    # Determine the rightmost leaf under the specified node.

    if {[$t isleaf $n]} {return $n}
    return [Rightmost $t [lindex [$t children $n] end]]
}

proc ::page::util::norm::peg::Expressions {q t} {
    # We now transform the remaining nodes into proper expression
    # trees. The order matters, to shed as much nodes as possible
    # early, and to avoid unncessary work.

    ExprRanges       $q $t
    ExprUnaryOps     $q $t
    ExprChars        $q $t
    ExprNonterminals $q $t
    ExprOperators    $q $t
    ExprFlatten      $q $t
    return
}

proc ::page::util::norm::peg::ExprRanges {q t} {
    # Ranges = .. operator

    $q query tree withatt detail Range over n {
	# Two the children, both of text 'Char', their data is what we
	# take. The children become irrelevant and are removed.

	foreach {b e} [$t children $n] break
	set begin [unquote [$t get $b DATA]]
	set end   [unquote [$t get $e DATA]]

	$t set $n op ..
	$t set $n begin $begin
	$t set $n end   $end

	MergeLocations $t $b $e $n

	$t unset $n detail

	$t delete $b
	$t delete $e
    }
    return
}

proc ::page::util::norm::peg::ExprUnaryOps {q t} {
    # Unary operators ... Their transformation sheds more nodes.

    foreach {a op} {
	QUESTION ?
	STAR     *
	PLUS     +
	AND      &
	NOT      !
    } {
	$q query tree withatt detail $a over n {
	    set p [$t parent $n]

	    $t set $p op $op
	    $t cut $n

	    $t unset $p detail
	}
    }
    return
}

proc ::page::util::norm::peg::ExprChars {q t} {
    # Chars = t operator (The remaining Char'acters are plain terminal
    # symbols.

    $q query tree withatt detail Char over n {
	set ch [unquote [$t get $n DATA]]

	$t set $n op   t
	$t set $n char $ch

	$t unset $n detail
	$t unset $n DATA
    }
    return
}

proc ::page::util::norm::peg::ExprNonterminals {q t} {
    # Identifiers = n operator (nonterminal references) ...

    array set defs [$t get root definitions]
    array set undefined {}

    $q query tree withatt detail Identifier over n {
	set sym [$t get $n DATA]

	$t set $n op  n
	$t set $n sym $sym

	$t unset $n detail
	$t unset $n DATA

	# Create x-references between the users and the definition of
	# a nonterminal symbol.

	if {![info exists defs($sym)]} {
	    $t set $n def {}
	    lappend undefined($sym) $n
	    continue
	} else {
	    set def $defs($sym)
	    $t set $n def $def
	}

	set users [$t get $def users]
	lappend users $n
	$t set $def users $users
    }

    $t set root undefined [array get undefined]
    return
}

proc ::page::util::norm::peg::ExprOperators {q t} {
    # The remaining operator nodes can be changed directly from node
    # text to operator. Se we do.

    foreach {a op} {
	EPSILON    epsilon
	ALNUM      alnum
	ALPHA      alpha
	DOT        dot
	Literal    x
	Class      /
	Sequence   x
	Expression /
    } {
	$q query tree withatt detail $a over n {
	    $t set   $n op $op
	    $t unset $n detail
	}
    }
    return
}

proc ::page::util::norm::peg::ExprFlatten {q t} {
    # Last tweaks of the expressions. Classes inside of Expressions,
    # and Literals in Sequences create nested / or x expressions. We
    # locate such and flatten the nested expression, cutting out the
    # superfluous operator.

    foreach op {x /} {
	# Locate all x operators, whose parents are x operators as
	# well, then go back to the child operators and cut them out.

	$q query tree withatt op $op \
		parent unique withatt op $op \
		children withatt op $op \
		over n {
	    $t cut $n
	}

	# Locate all x operators without children and convert them
	# into epsilon operators. Because that is what they accept,
	# nothing.

	$q query tree withatt op $op over n {
	    if {[$t numchildren $n]} continue
	    $t set $n op epsilon
	}
    }
    return
}

# ### ### ### ######### ######### #########
## Internal. Low-level helpers.

proc ::page::util::norm::peg::CopyLocation {t src dst} {
    $t set $dst range    [$t get $src range]
    $t set $dst range_lc [$t get $src range_lc]
    return
}

proc ::page::util::norm::peg::MergeLocations {t srca srcb dst} {
    set ar   [$t get $srca range]
    set arlc [$t get $srca range_lc]

    set br   [$t get $srcb range]
    set brlc [$t get $srcb range_lc]

    $t set $dst range    [list [lindex $ar   0] [lindex $br   1]]
    $t set $dst range_lc [list [lindex $arlc 0] [lindex $brlc 1]]
    return
}

proc ::page::util::norm::peg::TokReduce {t src attr} {
    set tokens [$t get $src $attr]
    set ch     {}
    foreach tok $tokens {
	lappend ch [lindex $tok 0]
    }
    $t set $src $attr [join $ch {}]
    return
}

proc ::page::util::norm::peg::AttrCopy {t src asrc dst adst} {
    $t set $dst $adst [$t get $src $asrc]
    return
}

proc ::page::util::norm::peg::Child {t n index} {
    return [lindex [$t children $n] $index]
}

# ### ### ### ######### ######### #########
## Ready

package provide page::util::norm::peg 0.1