1<?php
2/*
3    This program is free software: you can redistribute it and/or modify
4    it under the terms of the GNU General Public License as published by
5    the Free Software Foundation, either version 3 of the License, or
6    (at your option) any later version.
7
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12
13    You should have received a copy of the GNU General Public License
14    along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16    Vincent Tscherter, tscherter@karmin.ch, Solothurn, 2009-01-18
17
18    2009-01-18 version 0.1 first release
19    2009-01-02 version 0.2
20      - title und comment literal added
21      - ";" als terminator-symbol added
22    2023-09-28 version 0.3 prefixed all constants
23*/
24
25define('META', 'https://www.dokuwiki.org/plugin:ebnf');
26
27// parser
28define('EBNF_OPERATOR_TOKEN', 1);
29define('EBNF_LITERAL_TOKEN', 2);
30define('EBNF_WHITESPACE_TOKEN', 3);
31define('EBNF_IDENTIFIER_TOKEN', 4);
32
33// rendering
34define('EBNF_FONT', 2);
35define('EBNF_U', 10);
36define('EBNF_AW', 3);
37
38// lexemes
39$ebnf_lexemes[] = array( 'type' => EBNF_OPERATOR_TOKEN, 'expr' => '[={}()|.;[\]]' );
40$ebnf_lexemes[] = array( 'type' => EBNF_LITERAL_TOKEN,  'expr' => "\"[^\"]*\"" );
41$ebnf_lexemes[] = array( 'type' => EBNF_LITERAL_TOKEN,  'expr' => "'[^']*'" );
42$ebnf_lexemes[] = array( 'type' => EBNF_IDENTIFIER_TOKEN,  'expr' => "[a-zA-Z0-9_-]+" );
43$ebnf_lexemes[] = array( 'type' => EBNF_WHITESPACE_TOKEN,  'expr' => "\\s+" );
44
45// input example
46$input = <<<EOD
47"EBNF defined in itself" {
48  syntax     = [ title ] "{" { rule } "}" [ comment ].
49  rule       = identifier "=" expression ( "." | ";" ) .
50  expression = term { "|" term } .
51  term       = factor { factor } .
52  factor     = identifier
53             | literal
54             | "[" expression "]"
55             | "(" expression ")"
56             | "{" expression "}" .
57  identifier = character { character } .
58  title      = literal .
59  comment    = literal .
60  literal    = "'" character { character } "'"
61             | '"' character { character } '"' .
62}
63EOD;
64
65if (isset($_GET['syntax'])) {
66  $input = $_GET['syntax'];
67  $input = stripslashes($input);
68}
69
70$format = "png";
71if (isset($_GET['format'])) $format = $_GET['format'];
72
73try {
74  $tokens = ebnf_scan($input, true);
75  $dom = ebnf_parse_syntax($tokens);
76  if ($format == 'xml') {
77    header('Content-Type: application/xml');
78    echo $dom->saveXML();
79  } else {
80    render_node($dom->firstChild, true);
81  }
82} catch (Exception $e) {
83    header('Content-Type: text/plain');
84    $dom = new DOMDocument();
85    $syntax = $dom->createElement("syntax");
86    $syntax->setAttribute('title', 'EBNF - Syntax Error');
87    $syntax->setAttribute('meta', $e->getMessage());
88    $dom->appendChild($syntax);
89    render_node($dom->firstChild, true);
90}
91
92function rr($im, $x1, $y1, $x2, $y2, $r, $black){
93  imageline($im, $x1+$r, $y1, $x2-$r, $y1, $black);
94  imageline($im, $x1+$r, $y2, $x2-$r, $y2, $black);
95  imageline($im, $x1, $y1+$r, $x1, $y2-$r, $black);
96  imageline($im, $x2, $y1+$r, $x2, $y2-$r, $black);
97  imagearc($im, $x1+$r, $y1+$r, 2*$r, 2*$r, 180, 270, $black);
98  imagearc($im, $x2-$r, $y1+$r, 2*$r, 2*$r, 270, 360, $black);
99  imagearc($im, $x1+$r, $y2-$r, 2*$r, 2*$r, 90, 180, $black);
100  imagearc($im, $x2-$r, $y2-$r, 2*$r, 2*$r, 0, 90, $black);
101}
102
103function create_image($w, $h) {
104  global $white, $black, $blue, $red, $green, $silver;
105  $im = imagecreatetruecolor($w, $h) or die("no img");
106  imageantialias($im, true);
107  $white = imagecolorallocate ($im, 255, 255, 255);
108  $black = imagecolorallocate ($im, 0, 0, 0);
109  $blue = imagecolorallocate ($im, 0, 0, 255);
110  $red = imagecolorallocate ($im, 255, 0, 0);
111  $green = imagecolorallocate ($im, 0, 200, 0);
112  $silver = imagecolorallocate ($im, 127, 127, 127);
113  imagefilledrectangle($im, 0,0,$w,$h,$white);
114  return $im;
115}
116
117function arrow($image, $x, $y, $lefttoright) {
118  global $white, $black;
119  if (!$lefttoright)
120    imagefilledpolygon($image,
121      array($x, $y-EBNF_U/3, $x-EBNF_U, $y, $x, $y+EBNF_U/3), 3, $black);
122  else
123    imagefilledpolygon($image,
124      array($x-EBNF_U, $y-EBNF_U/3, $x, $y, $x-EBNF_U, $y+EBNF_U/3), 3, $black);
125}
126
127
128function render_node($node, $lefttoright) {
129  global $white, $black, $blue, $red, $green, $silver;
130  if ($node->nodeName=='identifier' || $node->nodeName=='terminal') {
131    $text = html_entity_decode($node->getAttribute('value'));
132    $w = imagefontwidth(EBNF_FONT)*(strlen($text)) + 4*EBNF_U;
133    $h = 2*EBNF_U;
134    $im = create_image($w, $h);
135
136    if ($node->nodeName!='terminal') {
137        imagerectangle($im, EBNF_U, 0, $w-EBNF_U-1, $h-1, $black);
138      imagestring($im, EBNF_FONT, 2*EBNF_U, ($h-imagefontheight(EBNF_FONT))/2,   $text, $red);
139    } else {
140      if ($text!="...")
141	      rr($im, EBNF_U, 0, $w-EBNF_U-1, $h-1, EBNF_U/2, $black);
142      imagestring($im, EBNF_FONT, 2*EBNF_U, ($h-imagefontheight(EBNF_FONT))/2,
143        $text, $text!="..."?$blue:$black);
144    }
145    imageline($im,0,EBNF_U, EBNF_U, EBNF_U, $black);
146    imageline($im,$w-EBNF_U,EBNF_U, $w+1, EBNF_U, $black);
147    return $im;
148  } else if ($node->nodeName=='option' || $node->nodeName=='loop') {
149    if ($node->nodeName=='loop')
150      $lefttoright = ! $lefttoright;
151    $inner = render_node($node->firstChild, $lefttoright);
152    $w = imagesx($inner)+6*EBNF_U;
153    $h = imagesy($inner)+2*EBNF_U;
154    $im = create_image($w, $h);
155    imagecopy($im, $inner, 3*EBNF_U, 2*EBNF_U, 0,0, imagesx($inner), imagesy($inner));
156    imageline($im,0,EBNF_U, $w, EBNF_U, $black);
157    arrow($im, $w/2+EBNF_U/2, EBNF_U, $node->nodeName=='loop'?!$lefttoright:$lefttoright);
158    arrow($im, 3*EBNF_U, 3*EBNF_U, $lefttoright);
159    arrow($im, $w-2*EBNF_U, 3*EBNF_U, $lefttoright);
160    imageline($im,EBNF_U,EBNF_U, EBNF_U, 3*EBNF_U, $black);
161    imageline($im,EBNF_U,3*EBNF_U, 2*EBNF_U, 3*EBNF_U, $black);
162    imageline($im,$w-EBNF_U,EBNF_U, $w-EBNF_U, 3*EBNF_U, $black);
163	imageline($im,$w-3*EBNF_U-1,3*EBNF_U, $w-EBNF_U, 3*EBNF_U, $black);
164    return $im;
165  } else if ($node->nodeName=='sequence') {
166    $inner = render_childs($node, $lefttoright);
167    if (!$lefttoright)
168      $inner = array_reverse($inner);
169    $w = count($inner)*EBNF_U-EBNF_U; $h = 0;
170    for ($i = 0; $i<count($inner); $i++) {
171      $w += imagesx($inner[$i]);
172      $h = max($h, imagesy($inner[$i]));
173    } $im = create_image($w, $h);
174    imagecopy($im, $inner[0], 0, 0, 0,0, imagesx($inner[0]), imagesy($inner[0]));
175    $x = imagesx($inner[0])+EBNF_U;
176    for ($i = 1; $i<count($inner); $i++) {
177      imageline($im, $x-EBNF_U-1, EBNF_U, $x, EBNF_U, $black);
178      arrow($im, $x, EBNF_U, $lefttoright);
179      imagecopy($im, $inner[$i], $x, 0, 0,0, imagesx($inner[$i]), imagesy($inner[$i]));
180      $x += imagesx($inner[$i])+EBNF_U;
181    } return $im;
182  } else if ($node->nodeName=='choise') {
183    $inner = render_childs($node, $lefttoright);
184    $h = (count($inner)-1)*EBNF_U; $w = 0;
185    for ($i = 0; $i<count($inner); $i++) {
186      $h += imagesy($inner[$i]);
187      $w = max($w, imagesx($inner[$i]));
188    } $w += 6*EBNF_U; $im = create_image($w, $h); $y = 0;
189    imageline($im, 0, EBNF_U, EBNF_U, EBNF_U, $black);
190    imageline($im, $w-EBNF_U, EBNF_U, $w, EBNF_U, $black);
191    for ($i = 0; $i<count($inner); $i++) {
192      imageline($im, EBNF_U, $y+EBNF_U, $w-EBNF_U, $y+EBNF_U, $black);
193      imagecopy($im, $inner[$i], 3*EBNF_U, $y, 0,0, imagesx($inner[$i]), imagesy($inner[$i]));
194      arrow($im, 3*EBNF_U, $y+EBNF_U, $lefttoright);
195      arrow($im, $w-2*EBNF_U, $y+EBNF_U, $lefttoright);
196      $top = $y + EBNF_U;
197      $y += imagesy($inner[$i])+EBNF_U;
198    }
199    imageline($im, EBNF_U, EBNF_U, EBNF_U, $top, $black);
200    imageline($im, $w-EBNF_U, EBNF_U, $w-EBNF_U, $top, $black);
201    return $im;
202  } else if ($node->nodeName=='syntax') {
203    $title = $node->getAttribute('title');
204    $meta = $node->getAttribute('meta');
205    $node = $node->firstChild;
206    $names = array();
207    $images = array();
208    while ($node!=null) {
209	   $names[] = $node->getAttribute('name');
210	   $im = render_node($node->firstChild, $lefttoright);
211	   $images[] = $im;
212       $node = $node->nextSibling;
213    } $wn  = 0; $wr = 0; $h = 5*EBNF_U;
214    for ($i = 0; $i<count($images); $i++) {
215      $wn = max($wn, imagefontwidth(EBNF_FONT)*strlen($names[$i]));
216      $wr = max($wr, imagesx($images[$i]));
217	  $h += imagesy($images[$i])+2*EBNF_U;
218    }
219    if ($title=='') $h -= 2*EBNF_U;
220    if ($meta=='') $h -= 2*EBNF_U;
221    $w = max($wr+$wn+3*EBNF_U, imagefontwidth(1)*strlen($meta)+2*EBNF_U);
222    $im = create_image($w, $h);
223    $y = 2*EBNF_U;
224    if ($title!='') {
225      imagestring($im, EBNF_FONT, EBNF_U, (2*EBNF_U-imagefontheight(EBNF_FONT))/2,
226      $title, $green);
227      imageline($im, 0, 2*EBNF_U, $w, 2*EBNF_U, $green);
228      $y += 2*EBNF_U;
229    }
230    for ($i = 0; $i<count($images); $i++) {
231      imagestring($im, EBNF_FONT, EBNF_U, $y-EBNF_U+(2*EBNF_U-imagefontheight(EBNF_FONT))/2, $names[$i], $red);
232      imagecopy($im, $images[$i], $wn+2*EBNF_U, $y, 0,0, imagesx($images[$i]) , imagesy($images[$i]));
233      imageline($im, EBNF_U, $y+EBNF_U, $wn+2*EBNF_U, $y+EBNF_U, $black);
234      imageline($im, $wn+2*EBNF_U+imagesx($images[$i])-1, $y+EBNF_U, $w-EBNF_U, $y+EBNF_U, $black);
235      imageline($im, $w-EBNF_U, $y+EBNF_U/2, $w-EBNF_U ,$y+1.5*EBNF_U, $black);
236      $y += 2*EBNF_U + imagesy($images[$i]);
237    }
238    imagestring($im, 1, EBNF_U, $h-2*EBNF_U+(2*EBNF_U-imagefontheight(1))/2,
239      $meta, $silver);
240    rr($im, 0,0,$w-1, $h-1, EBNF_U/2, $green);
241    header('Content-Type: image/png');
242    imagepng($im);
243    return $im;
244  }
245}
246
247function render_childs($node, $lefttoright) {
248   $childs = array();
249   $node = $node->firstChild;
250   while ($node!=null) {
251     $childs[] = render_node($node, $lefttoright);
252     $node = $node->nextSibling;
253   } return $childs;
254}
255
256function ebnf_scan(&$input) {
257  global $ebnf_lexemes;
258  $i = 0; $n = strlen($input); $m = count($ebnf_lexemes); $tokens = array();
259  while ($i < $n) {
260    $j = 0;
261    while ($j < $m &&
262      preg_match("/^{$ebnf_lexemes[$j]['expr']}/", substr($input,$i), $matches)==0) $j++;
263    if ($j<$m) {
264      if ($ebnf_lexemes[$j]['type']!=EBNF_WHITESPACE_TOKEN)
265        $tokens[] = array('type' => $ebnf_lexemes[$j]['type'],
266          'value' => $matches[0], 'pos' => $i);
267      $i += strlen($matches[0]);
268	} else
269	  throw new Exception("Invalid token at position: $i");
270  } return $tokens;
271}
272
273
274function ebnf_check_token($token, $type, $value) {
275  return $token['type']==$type && $token['value']==$value;
276}
277
278function ebnf_parse_syntax(&$tokens) {
279  $dom = new DOMDocument();
280  $syntax = $dom->createElement("syntax");
281  $syntax->setAttribute('meta', META);
282  $dom->appendChild($syntax);
283  $i = 0; $token = $tokens[$i++];
284  if ($token['type'] == EBNF_LITERAL_TOKEN) {
285    $syntax->setAttribute('title',
286      stripcslashes(substr($token['value'], 1, strlen($token['value'])-2 )));
287    $token = $tokens[$i++];
288  }
289  if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '{') )
290    throw new Exception("Syntax must start with '{': {$token['pos']}");
291  $token = $tokens[$i];
292  while ($i < count($tokens) && $token['type'] == EBNF_IDENTIFIER_TOKEN) {
293    $syntax->appendChild(ebnf_parse_production($dom, $tokens, $i));
294    if ($i<count($tokens)) $token = $tokens[$i];
295  } $i++; if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '}'))
296    throw new Exception("Syntax must end with '}': ".$tokens[count($tokens)-1]['pos']);
297  if ($i<count($tokens)) {
298    $token = $tokens[$i];
299    if ($token['type'] == EBNF_LITERAL_TOKEN) {
300      $syntax->setAttribute('meta',
301        stripcslashes(substr($token['value'], 1, strlen($token['value'])-2 )));
302    }
303  }
304    return $dom;
305}
306
307function ebnf_parse_production(&$dom, &$tokens, &$i) {
308  $token = $tokens[$i++];
309  if ($token['type']!=EBNF_IDENTIFIER_TOKEN)
310    throw new Exception("Production must start with an identifier'{': {$token['pos']}");
311  $production = $dom->createElement("rule");
312  $production->setAttribute('name', $token['value']);
313  $token = $tokens[$i++];
314  if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, "="))
315    throw new Exception("Identifier must be followed by '=': {$token['pos']}");
316  $production->appendChild( ebnf_parse_expression($dom, $tokens, $i));
317  $token = $tokens[$i++];
318  if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '.')
319    && !ebnf_check_token($token, EBNF_OPERATOR_TOKEN, ';'))
320    throw new Exception("Rule must end with '.' or ';' : {$token['pos']}");
321  return $production;
322}
323
324function ebnf_parse_expression(&$dom, &$tokens, &$i) {
325  $choise = $dom->createElement("choise");
326  $choise->appendChild(ebnf_parse_term($dom, $tokens, $i));
327  $token=$tokens[$i]; $mul = false;
328  while (ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '|')) {
329    $i++;
330    $choise->appendChild(ebnf_parse_term($dom, $tokens, $i));
331    $token=$tokens[$i]; $mul = true;
332  } return $mul ? $choise : $choise->removeChild($choise->firstChild);
333}
334
335function ebnf_parse_term(&$dom, &$tokens, &$i) {
336  $sequence = $dom->createElement("sequence");
337  $factor = ebnf_parse_factor($dom, $tokens, $i);
338  $sequence->appendChild($factor);
339  $token=$tokens[$i]; $mul = false;
340  while ($token['value']!='.' && $token['value']!='=' && $token['value']!='|'
341    && $token['value']!=')' && $token['value']!=']' && $token['value']!='}') {
342    $sequence->appendChild(ebnf_parse_factor($dom, $tokens, $i));
343    $token=$tokens[$i]; $mul = true;
344  } return $mul ? $sequence: $sequence->removeChild($sequence->firstChild);
345}
346
347function ebnf_parse_factor(&$dom, &$tokens, &$i) {
348  $token = $tokens[$i++];
349  if ($token['type']==EBNF_IDENTIFIER_TOKEN) {
350    $identifier = $dom->createElement("identifier");
351    $identifier->setAttribute('value', $token['value']);
352    return $identifier;
353  } if ($token['type']==EBNF_LITERAL_TOKEN){
354    $literal = $dom->createElement("terminal");
355    $literal->setAttribute('value', stripcslashes(substr($token['value'], 1, strlen($token['value'])-2 )));
356    return $literal;
357  } if (ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '(')) {
358    $expression = ebnf_parse_expression($dom, $tokens, $i);
359    $token = $tokens[$i++];
360    if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, ')'))
361      throw new Exception("Group must end with ')': {$token['pos']}");
362    return $expression;
363  } if (ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '[')) {
364    $option = $dom->createElement("option");
365    $option->appendChild(ebnf_parse_expression($dom, $tokens, $i));
366    $token = $tokens[$i++];
367    if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, ']'))
368      throw new Exception("Option must end with ']': {$token['pos']}");
369    return $option;
370  } if (ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '{')) {
371    $loop = $dom->createElement("loop");
372    $loop->appendChild(ebnf_parse_expression($dom, $tokens, $i));
373    $token = $tokens[$i++];
374    if (!ebnf_check_token($token, EBNF_OPERATOR_TOKEN, '}'))
375      throw new Exception("Loop must end with '}': {$token['pos']}");
376    return $loop;
377  }
378  throw new Exception("Factor expected: {$token['pos']}");
379}
380