summaryrefslogtreecommitdiffstats
path: root/tcllib/modules/pt/pt_peg_to_peg.tcl
blob: 9622b5754fb4b5d6938b98451eacc8f38742bc5f (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
# peg_to_peg.tcl --
#
#	Conversion from PEG to PEG (Human readable text).
#
# Copyright (c) 2009-2014 Andreas Kupries <andreas_kupries@sourceforge.net>
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
# 
# RCS: @(#) $Id: pt_peg_to_peg.tcl,v 1.1 2010/03/26 05:07:24 andreas_kupries Exp $

# This package takes the canonical serialization of a parsing
# expression grammar and produces text in PEG format, a form of text
# which specifies a PEG in a human readable, yet formal manner,
# similar too, but not identical to EBNF.

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

package  require Tcl 8.5
package  require pt::peg  ; # Verification that the input
				       # is proper.
package  require pt::pe              ; # Walking an expression.
package  require pt::pe::op          ; # Flatten & fuse.
package  require text::write         ; # Text generation support
package  require textutil::adjust
package  require struct::list

# ### ### ### ######### ######### #########
##

namespace eval ::pt::peg::to::peg {
    namespace export \
	reset configure convert

    namespace ensemble create
}

# ### ### ### ######### ######### #########
## API.

proc ::pt::peg::to::peg::reset {} {
    variable template @code@
    variable name     a_pe_grammar
    variable file     unknown
    variable user     unknown
    variable fused    1
    return
}

proc ::pt::peg::to::peg::configure {args} {
    variable template
    variable name
    variable file
    variable user
    variable fused

    if {[llength $args] == 0} {
	return [list \
		    -file     $file \
		    -fused    $fused \
		    -name     $name \
		    -template $template \
		    -user     $user]
    } elseif {[llength $args] == 1} {
	lassign $args option
	set variable [string range $option 1 end]
	if {[info exists $variable]} {
	    return [set $variable]
	} else {
	    return -code error "Expected one of -file, -fused, -name, -template, or -user, got \"$option\""
	}
    } elseif {[llength $args] % 2 == 0} {
	foreach {option value} $args {
	    set variable [string range $option 1 end]
	    if {![info exists $variable]} {
		return -code error "Expected one of -file, -fused, -name, -template, or -user, got \"$option\""
	    }
	}
	foreach {option value} $args {
	    set variable [string range $option 1 end]
	    switch -exact -- $variable {
		template {
		    if {$value eq {}} {
			return -code error "Expected template, got the empty string"
		    }
		}
		fused {
		    if {![::string is boolean -strict $value]} {
			return -code error "Expected boolean, got \"$value\""
		    }
		}
		name -
		file -
		user { }
	    }
	    set $variable $value
	}
    } else {
	return -code error {wrong#args, expected option value ...}
    }
}

proc ::pt::peg::to::peg::convert {serial} {
    variable template
    variable name
    variable file
    variable user

    ::pt::peg verify-as-canonical $serial

    # Unpack the serialization, known as canonical
    array set peg $serial
    array set peg $peg(pt::grammar::peg)
    unset     peg(pt::grammar::peg)

    # Determine the field sizes for nonterminal symbol names and
    # semantic modes.

    set smax [text::write maxlen [dict keys $peg(rules)]]
    set mmax [ModeSize                      $peg(rules)]

    # Assemble the output, various pieces
    text::write reset
    Header $peg(start)
    Rules  $peg(rules) $mmax $smax
    Trailer

    # At last retrieve the fully assembled result and integrate with
    # the chosen template.
    return [string map \
		[list \
		     @user@   $user \
		     @format@ PEG   \
		     @file@   $file \
		     @name@   $name \
		     @code@   [text::write get]] $template]

    # ### ### ### ######### ######### #########
}

# ### ### ### ######### ######### #########
## Internals

proc ::pt::peg::to::peg::Header {startexpression} {
    variable name

    text::write field  PEG
    text::write field  $name
    text::write field  ([Expression $startexpression])
    text::write /line
    return
}

proc ::pt::peg::to::peg::Rules {rules mmax smax} {
    if {[llength $rules]} { text::write /line }

    foreach {symbol def} $rules {
	lassign $def _ is _ mode
	set mode  [expr {($mode eq "value")
			 ? ""
			 : "${mode}:"}]

	text::write fieldl $mmax $mode
	text::write fieldl $smax $symbol
	text::write field        "<-"
	text::write field        [Expression $is] 
	text::write field        ";"
	text::write /line
    }

    if {[llength $rules]} { text::write /line }
    return
}

proc ::pt::peg::to::peg::Trailer {} {
    text::write field  {END;}
    text::write /line
    return
}

# ### ### ### ######### ######### #########

proc ::pt::peg::to::peg::Expression {pe} {
    variable fused

    if {$fused} {
	# First flatten for a maximum amount of adjacent terminals and
	# ranges, then fuse these into strings and classes, then
	# flatten again, eliminating all sequences and choices fully
	# subsumed by the new elements.

	set pe [pt::pe::op flatten \
		    [pt::pe::op fusechars \
			 [pt::pe::op flatten \
			      $pe]]]
    }

    return [lindex [pt::pe bottomup \
			[namespace current]::Convert \
			$pe] 0]
}

proc ::pt::peg::to::peg::Convert {pe operator arguments} {
    # For the inner nodes the each of arguments are a pair of
    # generated text, and the sub-expression it came from, in this
    # order.

    switch -exact -- $operator {
	alpha - alnum - ascii - control - digit - graph - lower - print -
	punct - space - upper - wordchar - xdigit - ddigit {
	    # Special forms ...
	    return [list <$operator> $pe]
	}
	dot {
	    # Special form ...
	    return [list "." $pe]
	}
	epsilon {
	    # Special form, represented by the empty string ...
	    return [list "''" $pe]
	}
	t {
	    # Character ...
	    lassign $arguments char
	    return [list "'[Char ${char}]'" $pe]
	}
	.. {
	    # Range of characters ... Show as character class.
	    # Note: Canonical input means that an expression like
	    # {.. X X} cannot occur, and can be ignored.

	    lassign $arguments chstart chend
	    return [list "\[[Char ${chstart}]-[Char $chend]\]" $pe]
	}
	n {
	    # Nonterminal symbol
	    lassign $arguments symbol
	    return [list $symbol $pe]
	}
	? - * - + {
	    # Suffix operators (Option, Kleene Closure, Positive KC) ...
	    lassign $arguments child
	    lassign $child text def
	    lassign $def coperator
	    return [list [MayParens $operator $coperator $text]$operator $pe]
	}
	& -
	! {
	    # Prefix operators (And/Not Lookahead) ...
	    lassign $arguments child
	    lassign $child text def
	    lassign $def coperator
	    return [list $operator[MayParens $operator $coperator $text] $pe]
	}
	x {
	    # Sequences ...
	    # TODO :: merge adjacent chars into strings ...  also, cut
	    # x out if only one child

	    set t {}
	    set x {}
	    foreach a $arguments {
		lassign $a text def
		lassign $def coperator
		lappend t [MayParens $operator $coperator $text]
		lappend x $def
	    }
	    return [list [join $t { }] [list x {*}$x]]
	}
	/ {
	    # Choices ...
	    # TODO :: merge adjacent chars and ranges into classes ...
	    # also, cut / out if only one child

	    set t {}
	    set x {}
	    foreach a $arguments {
		lassign $a text def
		lassign $def coperator
		lappend t [MayParens $operator $coperator $text]
		lappend x $def
	    }
	    return [list [join $t { / }] [list / {*}$x]]
	}
	str {
	    return [list \
			'[join [struct::list map $arguments \
				    [namespace current]::Char] {}]' \
			$pe]
	}
	cl {
	    return [list \
			\[[join [struct::list map $arguments \
				     [namespace current]::Range] {}]\] \
			$pe]
	}
    }
}

proc ::pt::peg::to::peg::Range {range} {
    # See also pt::peg::to::tclparam

    # Use string ops here to distinguish terminals and ranges. The
    # input can be a single char, not a list, and further the char may
    # not be a proper list. Example: double-apostroph.
    if {[string length $range] > 1} {
	lassign $range s e
	return [Char $s]-[Char $e]
    } else {
	return [Char $range]
    }
}

proc ::pt::peg::to::peg::Char {ch} {
    # Encode a character, handle special cases.  We cannot use package
    # char, as that is geared towards character encoding for Tcl code.

    switch -exact -- $ch {
	"\n" { return "\\n"  }
	"\r" { return "\\r"  }
	"\t" { return "\\t"  }
	"\\" { return "\\\\" }
	"\"" { return "\\\"" }
	"'"  { return "\\'"  }
	"\]" { return "\\\]" }
	"\[" { return "\\\[" }
    }

    scan $ch %c chcode

    # Control characters: Octal
    if {[::string is control -strict $ch]} {
	return \\[format %o $chcode]
    }

    # Beyond 7-bit ASCII: Unicode

    if {$chcode > 127} {
	return \\u[format %04x $chcode]
    }

    # Regular character: Is its own representation.

    return $ch

}

proc ::pt::peg::to::peg::MayParens {op cop text} {
    if {![NeedParens $op $cop]} { return $text }
    return "([::textutil::adjust::indent $text " " 1])"
}

proc ::pt::peg::to::peg::NeedParens {op cop} {
    variable priority
    # c(hild)op is nested under op.
    # Parens are required if cop has a lower priority than op.

    return [expr {$priority($cop) < $priority($op)}]
}

# ### ### ### ######### ######### #########

proc ::pt::peg::to::peg::ModeSize {rules} {
    set modes {}
    foreach {symbol def} $rules {
	lassign $def _ is _ mode
	if {$mode eq "value"} continue ; # These are not shown in the
					 # text representation, as
					 # they are the implicit
					 # default for it.
	lappend modes ${mode}:
    }
    return [text::write maxlen [lsort -uniq $modes]]
}

# ### ### ### ######### ######### #########
## Configuration

namespace eval ::pt::peg::to::peg {

    variable template @code@       ; # A string. Specifies how to
				     # embed the generated code into a
				     # larger frame- work (the
				     # template).
    variable name     a_pe_grammar ; # String. Name of the grammar.
    variable file     unknown      ; # String. Name of the file or
				     # other entity the grammar came
				     # from.
    variable user     unknown      ; # String. Name of the user on
				     # which behalf the conversion has
				     # been invoked.
    variable fused    1            ; # Boolean flag. If true character
				     # sequences and choices are fused
				     # into strings and classes.

    variable  priority
    array set priority {
	/ 0  t       4  ascii 4  upper    4
	x 1  n       4  digit 4  wordchar 4
	& 2  ..      4  graph 4  xdigit   4
	! 2  dot     4  lower 4  ddigit   4
	+ 3  epsilon 4  print 4  str      4
	* 3  alnum   4  punct 4  cl       4
	? 3  alpha   4  space 4  control  4
    }
}

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

package provide pt::peg::to::peg 1.0.2
return