3 * Configuration file editor.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * This is a state machine style parser with two internal stacks:
25 * * A next state stack, which determines the state the machine will progress to next
26 * * A path stack, which keeps track of the logical location in the file.
30 * file = T_OPEN_TAG *statement
31 * statement = T_VARIABLE "=" expression ";"
32 * expression = array / scalar / T_VARIABLE
33 * array = T_ARRAY "(" [ element *( "," element ) [ "," ] ] ")"
34 * element = assoc-element / expression
35 * assoc-element = scalar T_DOUBLE_ARROW expression
36 * scalar = T_LNUMBER / T_DNUMBER / T_STRING / T_CONSTANT_ENCAPSED_STRING
39 /** The text to parse */
42 /** The token array from token_get_all() */
45 /** The current position in the token array */
48 /** The current 1-based line number */
51 /** The current 1-based column number */
54 /** The current 0-based byte number */
57 /** The current ConfEditorToken object */
60 /** The previous ConfEditorToken object */
64 * The state machine stack. This is an array of strings where the topmost
65 * element will be popped off and become the next parser state.
71 * The path stack is a stack of associative arrays with the following elements:
72 * name The name of top level of the path
73 * level The level (number of elements) of the path
74 * startByte The byte offset of the start of the path
75 * startToken The token offset of the start
76 * endByte The byte offset of thee
77 * endToken The token offset of the end, plus one
78 * valueStartToken The start token offset of the value part
79 * valueStartByte The start byte offset of the value part
80 * valueEndToken The end token offset of the value part, plus one
81 * valueEndByte The end byte offset of the value part, plus one
82 * nextArrayIndex The next numeric array index at this level
83 * hasComma True if the array element ends with a comma
84 * arrowByte The byte offset of the "=>", or false if there isn't one
89 * The elements of the top of the pathStack for every path encountered, indexed
90 * by slash-separated path.
95 * Next serial number for whitespace placeholder paths (\@extra-N)
100 * Editor state. This consists of the internal copy/insert operations which
101 * are applied to the source string to obtain the destination string.
106 * Simple entry point for command-line testing
108 * @param $text string
112 static function test( $text ) {
114 $ce = new self( $text );
116 } catch ( ConfEditorParseError
$e ) {
117 return $e->getMessage() . "\n" . $e->highlight( $text );
123 * Construct a new parser
125 public function __construct( $text ) {
130 * Edit the text. Returns the edited text.
131 * @param $ops Array of operations.
133 * Operations are given as an associative array, with members:
134 * type: One of delete, set, append or insert (required)
135 * path: The path to operate on (required)
136 * key: The array key to insert/append, with PHP quotes
137 * value: The value, with PHP quotes
140 * Deletes an array element or statement with the specified path.
142 * array('type' => 'delete', 'path' => '$foo/bar/baz' )
143 * is equivalent to the runtime PHP code:
144 * unset( $foo['bar']['baz'] );
147 * Sets the value of an array element. If the element doesn't exist, it
148 * is appended to the array. If it does exist, the value is set, with
149 * comments and indenting preserved.
152 * Appends a new element to the end of the array. Adds a trailing comma.
154 * array( 'type' => 'append', 'path', '$foo/bar',
155 * 'key' => 'baz', 'value' => "'x'" )
156 * is like the PHP code:
157 * $foo['bar']['baz'] = 'x';
160 * Insert a new element at the start of the array.
164 public function edit( $ops ) {
167 $this->edits
= array(
168 array( 'copy', 0, strlen( $this->text
) )
170 foreach ( $ops as $op ) {
173 $value = isset( $op['value'] ) ?
$op['value'] : null;
174 $key = isset( $op['key'] ) ?
$op['key'] : null;
178 list( $start, $end ) = $this->findDeletionRegion( $path );
179 $this->replaceSourceRegion( $start, $end, false );
182 if ( isset( $this->pathInfo
[$path] ) ) {
183 list( $start, $end ) = $this->findValueRegion( $path );
184 $encValue = $value; // var_export( $value, true );
185 $this->replaceSourceRegion( $start, $end, $encValue );
188 // No existing path, fall through to append
189 $slashPos = strrpos( $path, '/' );
190 $key = var_export( substr( $path, $slashPos +
1 ), true );
191 $path = substr( $path, 0, $slashPos );
194 // Find the last array element
195 $lastEltPath = $this->findLastArrayElement( $path );
196 if ( $lastEltPath === false ) {
197 throw new MWException( "Can't find any element of array \"$path\"" );
199 $lastEltInfo = $this->pathInfo
[$lastEltPath];
201 // Has it got a comma already?
202 if ( strpos( $lastEltPath, '@extra' ) === false && !$lastEltInfo['hasComma'] ) {
203 // No comma, insert one after the value region
204 list( , $end ) = $this->findValueRegion( $lastEltPath );
205 $this->replaceSourceRegion( $end - 1, $end - 1, ',' );
208 // Make the text to insert
209 list( $start, $end ) = $this->findDeletionRegion( $lastEltPath );
211 if ( $key === null ) {
212 list( $indent, ) = $this->getIndent( $start );
213 $textToInsert = "$indent$value,";
215 list( $indent, $arrowIndent ) =
216 $this->getIndent( $start, $key, $lastEltInfo['arrowByte'] );
217 $textToInsert = "$indent$key$arrowIndent=> $value,";
219 $textToInsert .= ( $indent === false ?
' ' : "\n" );
222 $this->replaceSourceRegion( $end, $end, $textToInsert );
225 // Find first array element
226 $firstEltPath = $this->findFirstArrayElement( $path );
227 if ( $firstEltPath === false ) {
228 throw new MWException( "Can't find array element of \"$path\"" );
230 list( $start, ) = $this->findDeletionRegion( $firstEltPath );
231 $info = $this->pathInfo
[$firstEltPath];
233 // Make the text to insert
234 if ( $key === null ) {
235 list( $indent, ) = $this->getIndent( $start );
236 $textToInsert = "$indent$value,";
238 list( $indent, $arrowIndent ) =
239 $this->getIndent( $start, $key, $info['arrowByte'] );
240 $textToInsert = "$indent$key$arrowIndent=> $value,";
242 $textToInsert .= ( $indent === false ?
' ' : "\n" );
245 $this->replaceSourceRegion( $start, $start, $textToInsert );
248 throw new MWException( "Unrecognised operation: \"$type\"" );
254 foreach ( $this->edits
as $edit ) {
255 if ( $edit[0] == 'copy' ) {
256 $out .= substr( $this->text
, $edit[1], $edit[2] - $edit[1] );
257 } else { // if ( $edit[0] == 'insert' )
262 // Do a second parse as a sanity check
266 } catch ( ConfEditorParseError
$e ) {
267 throw new MWException(
268 "Sorry, ConfEditor broke the file during editing and it won't parse anymore: " .
275 * Get the variables defined in the text
276 * @return array( varname => value )
281 foreach( $this->pathInfo
as $path => $data ) {
282 if ( $path[0] != '$' )
284 $trimmedPath = substr( $path, 1 );
285 $name = $data['name'];
286 if ( $name[0] == '@' )
288 if ( $name[0] == '$' )
289 $name = substr( $name, 1 );
290 $parentPath = substr( $trimmedPath, 0,
291 strlen( $trimmedPath ) - strlen( $name ) );
292 if( substr( $parentPath, -1 ) == '/' )
293 $parentPath = substr( $parentPath, 0, -1 );
295 $value = substr( $this->text
, $data['valueStartByte'],
296 $data['valueEndByte'] - $data['valueStartByte']
298 $this->setVar( $vars, $parentPath, $name,
299 $this->parseScalar( $value ) );
305 * Set a value in an array, unless it's set already. For instance,
306 * setVar( $arr, 'foo/bar', 'baz', 3 ); will set
307 * $arr['foo']['bar']['baz'] = 3;
308 * @param $array array
309 * @param $path string slash-delimited path
310 * @param $key mixed Key
311 * @param $value mixed Value
313 function setVar( &$array, $path, $key, $value ) {
314 $pathArr = explode( '/', $path );
316 if ( $path !== '' ) {
317 foreach ( $pathArr as $p ) {
318 if( !isset( $target[$p] ) )
319 $target[$p] = array();
320 $target =& $target[$p];
323 if ( !isset( $target[$key] ) )
324 $target[$key] = $value;
328 * Parse a scalar value in PHP
329 * @return mixed Parsed value
331 function parseScalar( $str ) {
332 if ( $str !== '' && $str[0] == '\'' )
333 // Single-quoted string
334 // @todo FIXME: trim() call is due to mystery bug where whitespace gets
335 // appended to the token; without it we ended up reading in the
336 // extra quote on the end!
337 return strtr( substr( trim( $str ), 1, -1 ),
338 array( '\\\'' => '\'', '\\\\' => '\\' ) );
339 if ( $str !== '' && $str[0] == '"' )
340 // Double-quoted string
341 // @todo FIXME: trim() call is due to mystery bug where whitespace gets
342 // appended to the token; without it we ended up reading in the
343 // extra quote on the end!
344 return stripcslashes( substr( trim( $str ), 1, -1 ) );
345 if ( substr( $str, 0, 4 ) == 'true' )
347 if ( substr( $str, 0, 5 ) == 'false' )
349 if ( substr( $str, 0, 4 ) == 'null' )
351 // Must be some kind of numeric value, so let PHP's weak typing
352 // be useful for a change
357 * Replace the byte offset region of the source with $newText.
358 * Works by adding elements to the $this->edits array.
360 function replaceSourceRegion( $start, $end, $newText = false ) {
361 // Split all copy operations with a source corresponding to the region
364 foreach ( $this->edits
as $edit ) {
365 if ( $edit[0] !== 'copy' ) {
369 $copyStart = $edit[1];
371 if ( $start >= $copyEnd ||
$end <= $copyStart ) {
372 // Outside this region
376 if ( ( $start < $copyStart && $end > $copyStart )
377 ||
( $start < $copyEnd && $end > $copyEnd )
379 throw new MWException( "Overlapping regions found, can't do the edit" );
382 $newEdits[] = array( 'copy', $copyStart, $start );
383 if ( $newText !== false ) {
384 $newEdits[] = array( 'insert', $newText );
386 $newEdits[] = array( 'copy', $end, $copyEnd );
388 $this->edits
= $newEdits;
392 * Finds the source byte region which you would want to delete, if $pathName
393 * was to be deleted. Includes the leading spaces and tabs, the trailing line
394 * break, and any comments in between.
397 function findDeletionRegion( $pathName ) {
398 if ( !isset( $this->pathInfo
[$pathName] ) ) {
399 throw new MWException( "Can't find path \"$pathName\"" );
401 $path = $this->pathInfo
[$pathName];
404 while ( $this->pos
!= $path['startToken'] ) {
407 $regionStart = $path['startByte'];
408 for ( $offset = -1; $offset >= -$this->pos
; $offset-- ) {
409 $token = $this->getTokenAhead( $offset );
410 if ( !$token->isSkip() ) {
411 // If there is other content on the same line, don't move the start point
412 // back, because that will cause the regions to overlap.
413 $regionStart = $path['startByte'];
416 $lfPos = strrpos( $token->text
, "\n" );
417 if ( $lfPos === false ) {
418 $regionStart -= strlen( $token->text
);
420 // The line start does not include the LF
421 $regionStart -= strlen( $token->text
) - $lfPos - 1;
426 while ( $this->pos
!= $path['endToken'] ) {
429 $regionEnd = $path['endByte']; // past the end
430 for ( $offset = 0; $offset < count( $this->tokens
) - $this->pos
; $offset++
) {
431 $token = $this->getTokenAhead( $offset );
432 if ( !$token->isSkip() ) {
435 $lfPos = strpos( $token->text
, "\n" );
436 if ( $lfPos === false ) {
437 $regionEnd +
= strlen( $token->text
);
439 // This should point past the LF
440 $regionEnd +
= $lfPos +
1;
444 return array( $regionStart, $regionEnd );
448 * Find the byte region in the source corresponding to the value part.
449 * This includes the quotes, but does not include the trailing comma
452 * The end position is the past-the-end (end + 1) value as per convention.
455 function findValueRegion( $pathName ) {
456 if ( !isset( $this->pathInfo
[$pathName] ) ) {
457 throw new MWException( "Can't find path \"$pathName\"" );
459 $path = $this->pathInfo
[$pathName];
460 if ( $path['valueStartByte'] === false ||
$path['valueEndByte'] === false ) {
461 throw new MWException( "Can't find value region for path \"$pathName\"" );
463 return array( $path['valueStartByte'], $path['valueEndByte'] );
467 * Find the path name of the last element in the array.
468 * If the array is empty, this will return the \@extra interstitial element.
469 * If the specified path is not found or is not an array, it will return false.
470 * @return bool|int|string
472 function findLastArrayElement( $path ) {
473 // Try for a real element
474 $lastEltPath = false;
475 foreach ( $this->pathInfo
as $candidatePath => $info ) {
476 $part1 = substr( $candidatePath, 0, strlen( $path ) +
1 );
477 $part2 = substr( $candidatePath, strlen( $path ) +
1, 1 );
478 if ( $part2 == '@' ) {
480 } elseif ( $part1 == "$path/" ) {
481 $lastEltPath = $candidatePath;
482 } elseif ( $lastEltPath !== false ) {
486 if ( $lastEltPath !== false ) {
490 // Try for an interstitial element
492 foreach ( $this->pathInfo
as $candidatePath => $info ) {
493 $part1 = substr( $candidatePath, 0, strlen( $path ) +
1 );
494 if ( $part1 == "$path/" ) {
495 $extraPath = $candidatePath;
496 } elseif ( $extraPath !== false ) {
504 * Find the path name of first element in the array.
505 * If the array is empty, this will return the \@extra interstitial element.
506 * If the specified path is not found or is not an array, it will return false.
507 * @return bool|int|string
509 function findFirstArrayElement( $path ) {
510 // Try for an ordinary element
511 foreach ( $this->pathInfo
as $candidatePath => $info ) {
512 $part1 = substr( $candidatePath, 0, strlen( $path ) +
1 );
513 $part2 = substr( $candidatePath, strlen( $path ) +
1, 1 );
514 if ( $part1 == "$path/" && $part2 != '@' ) {
515 return $candidatePath;
519 // Try for an interstitial element
520 foreach ( $this->pathInfo
as $candidatePath => $info ) {
521 $part1 = substr( $candidatePath, 0, strlen( $path ) +
1 );
522 if ( $part1 == "$path/" ) {
523 return $candidatePath;
530 * Get the indent string which sits after a given start position.
531 * Returns false if the position is not at the start of the line.
534 function getIndent( $pos, $key = false, $arrowPos = false ) {
536 if ( $pos == 0 ||
$this->text
[$pos-1] == "\n" ) {
537 $indentLength = strspn( $this->text
, " \t", $pos );
538 $indent = substr( $this->text
, $pos, $indentLength );
542 if ( $indent !== false && $arrowPos !== false ) {
543 $arrowIndentLength = $arrowPos - $pos - $indentLength - strlen( $key );
544 if ( $arrowIndentLength > 0 ) {
545 $arrowIndent = str_repeat( ' ', $arrowIndentLength );
548 return array( $indent, $arrowIndent );
552 * Run the parser on the text. Throws an exception if the string does not
553 * match our defined subset of PHP syntax.
555 public function parse() {
557 $this->pushState( 'file' );
558 $this->pushPath( '@extra-' . ($this->serial++
) );
559 $token = $this->firstToken();
561 while ( !$token->isEnd() ) {
562 $state = $this->popState();
564 $this->error( 'internal error: empty state stack' );
569 $this->expect( T_OPEN_TAG
);
570 $token = $this->skipSpace();
571 if ( $token->isEnd() ) {
574 $this->pushState( 'statement', 'file 2' );
577 $token = $this->skipSpace();
578 if ( $token->isEnd() ) {
581 $this->pushState( 'statement', 'file 2' );
584 $token = $this->skipSpace();
585 if ( !$this->validatePath( $token->text
) ) {
586 $this->error( "Invalid variable name \"{$token->text}\"" );
588 $this->nextPath( $token->text
);
589 $this->expect( T_VARIABLE
);
591 $arrayAssign = false;
592 if ( $this->currentToken()->type
== '[' ) {
594 $token = $this->skipSpace();
595 if ( !$token->isScalar() ) {
596 $this->error( "expected a string or number for the array key" );
598 if ( $token->type
== T_CONSTANT_ENCAPSED_STRING
) {
599 $text = $this->parseScalar( $token->text
);
601 $text = $token->text
;
603 if ( !$this->validatePath( $text ) ) {
604 $this->error( "Invalid associative array name \"$text\"" );
606 $this->pushPath( $text );
609 $this->expect( ']' );
613 $this->expect( '=' );
615 $this->startPathValue();
617 $this->pushState( 'expression', 'array assign end' );
619 $this->pushState( 'expression', 'statement end' );
621 case 'array assign end':
622 case 'statement end':
623 $this->endPathValue();
624 if ( $state == 'array assign end' )
627 $this->expect( ';' );
628 $this->nextPath( '@extra-' . ($this->serial++
) );
631 $token = $this->skipSpace();
632 if ( $token->type
== T_ARRAY
) {
633 $this->pushState( 'array' );
634 } elseif ( $token->isScalar() ) {
636 } elseif ( $token->type
== T_VARIABLE
) {
639 $this->error( "expected simple expression" );
644 $this->expect( T_ARRAY
);
646 $this->expect( '(' );
648 $this->pushPath( '@extra-' . ($this->serial++
) );
649 if ( $this->isAhead( ')' ) ) {
651 $this->pushState( 'array end' );
653 $this->pushState( 'element', 'array end' );
659 $this->expect( ')' );
662 $token = $this->skipSpace();
663 // Look ahead to find the double arrow
664 if ( $token->isScalar() && $this->isAhead( T_DOUBLE_ARROW
, 1 ) ) {
665 // Found associative element
666 $this->pushState( 'assoc-element', 'element end' );
669 $this->nextPath( '@next' );
670 $this->startPathValue();
671 $this->pushState( 'expression', 'element end' );
675 $token = $this->skipSpace();
676 if ( $token->type
== ',' ) {
677 $this->endPathValue();
680 $this->nextPath( '@extra-' . ($this->serial++
) );
681 // Look ahead to find ending bracket
682 if ( $this->isAhead( ")" ) ) {
683 // Found ending bracket, no continuation
686 // No ending bracket, continue to next element
687 $this->pushState( 'element' );
689 } elseif ( $token->type
== ')' ) {
691 $this->endPathValue();
693 $this->error( "expected the next array element or the end of the array" );
696 case 'assoc-element':
697 $token = $this->skipSpace();
698 if ( !$token->isScalar() ) {
699 $this->error( "expected a string or number for the array key" );
701 if ( $token->type
== T_CONSTANT_ENCAPSED_STRING
) {
702 $text = $this->parseScalar( $token->text
);
704 $text = $token->text
;
706 if ( !$this->validatePath( $text ) ) {
707 $this->error( "Invalid associative array name \"$text\"" );
709 $this->nextPath( $text );
713 $this->expect( T_DOUBLE_ARROW
);
715 $this->startPathValue();
716 $this->pushState( 'expression' );
720 if ( count( $this->stateStack
) ) {
721 $this->error( 'unexpected end of file' );
727 * Initialise a parse.
729 protected function initParse() {
730 $this->tokens
= token_get_all( $this->text
);
731 $this->stateStack
= array();
732 $this->pathStack
= array();
734 $this->pathInfo
= array();
739 * Set the parse position. Do not call this except from firstToken() and
740 * nextToken(), there is more to update than just the position.
742 protected function setPos( $pos ) {
744 if ( $this->pos
>= count( $this->tokens
) ) {
745 $this->currentToken
= ConfEditorToken
::newEnd();
747 $this->currentToken
= $this->newTokenObj( $this->tokens
[$this->pos
] );
749 return $this->currentToken
;
753 * Create a ConfEditorToken from an element of token_get_all()
754 * @return ConfEditorToken
756 function newTokenObj( $internalToken ) {
757 if ( is_array( $internalToken ) ) {
758 return new ConfEditorToken( $internalToken[0], $internalToken[1] );
760 return new ConfEditorToken( $internalToken, $internalToken );
765 * Reset the parse position
767 function firstToken() {
769 $this->prevToken
= ConfEditorToken
::newEnd();
773 return $this->currentToken
;
777 * Get the current token
779 function currentToken() {
780 return $this->currentToken
;
784 * Advance the current position and return the resulting next token
786 function nextToken() {
787 if ( $this->currentToken
) {
788 $text = $this->currentToken
->text
;
789 $lfCount = substr_count( $text, "\n" );
791 $this->lineNum +
= $lfCount;
792 $this->colNum
= strlen( $text ) - strrpos( $text, "\n" );
794 $this->colNum +
= strlen( $text );
796 $this->byteNum +
= strlen( $text );
798 $this->prevToken
= $this->currentToken
;
799 $this->setPos( $this->pos +
1 );
800 return $this->currentToken
;
804 * Get the token $offset steps ahead of the current position.
805 * $offset may be negative, to get tokens behind the current position.
806 * @return ConfEditorToken
808 function getTokenAhead( $offset ) {
809 $pos = $this->pos +
$offset;
810 if ( $pos >= count( $this->tokens
) ||
$pos < 0 ) {
811 return ConfEditorToken
::newEnd();
813 return $this->newTokenObj( $this->tokens
[$pos] );
818 * Advances the current position past any whitespace or comments
820 function skipSpace() {
821 while ( $this->currentToken
&& $this->currentToken
->isSkip() ) {
824 return $this->currentToken
;
828 * Throws an error if the current token is not of the given type, and
829 * then advances to the next position.
831 function expect( $type ) {
832 if ( $this->currentToken
&& $this->currentToken
->type
== $type ) {
833 return $this->nextToken();
835 $this->error( "expected " . $this->getTypeName( $type ) .
836 ", got " . $this->getTypeName( $this->currentToken
->type
) );
841 * Push a state or two on to the state stack.
843 function pushState( $nextState, $stateAfterThat = null ) {
844 if ( $stateAfterThat !== null ) {
845 $this->stateStack
[] = $stateAfterThat;
847 $this->stateStack
[] = $nextState;
851 * Pop a state from the state stack.
854 function popState() {
855 return array_pop( $this->stateStack
);
859 * Returns true if the user input path is valid.
860 * This exists to allow "/" and "@" to be reserved for string path keys
863 function validatePath( $path ) {
864 return strpos( $path, '/' ) === false && substr( $path, 0, 1 ) != '@';
868 * Internal function to update some things at the end of a path region. Do
869 * not call except from popPath() or nextPath().
873 foreach ( $this->pathStack
as $pathInfo ) {
877 $key .= $pathInfo['name'];
879 $pathInfo['endByte'] = $this->byteNum
;
880 $pathInfo['endToken'] = $this->pos
;
881 $this->pathInfo
[$key] = $pathInfo;
885 * Go up to a new path level, for example at the start of an array.
887 function pushPath( $path ) {
888 $this->pathStack
[] = array(
890 'level' => count( $this->pathStack
) +
1,
891 'startByte' => $this->byteNum
,
892 'startToken' => $this->pos
,
893 'valueStartToken' => false,
894 'valueStartByte' => false,
895 'valueEndToken' => false,
896 'valueEndByte' => false,
897 'nextArrayIndex' => 0,
904 * Go down a path level, for example at the end of an array.
908 array_pop( $this->pathStack
);
912 * Go to the next path on the same level. This ends the current path and
913 * starts a new one. If $path is \@next, the new path is set to the next
914 * numeric array element.
916 function nextPath( $path ) {
918 $i = count( $this->pathStack
) - 1;
919 if ( $path == '@next' ) {
920 $nextArrayIndex =& $this->pathStack
[$i]['nextArrayIndex'];
921 $this->pathStack
[$i]['name'] = $nextArrayIndex;
924 $this->pathStack
[$i]['name'] = $path;
926 $this->pathStack
[$i] =
928 'startByte' => $this->byteNum
,
929 'startToken' => $this->pos
,
930 'valueStartToken' => false,
931 'valueStartByte' => false,
932 'valueEndToken' => false,
933 'valueEndByte' => false,
935 'arrowByte' => false,
936 ) +
$this->pathStack
[$i];
940 * Mark the start of the value part of a path.
942 function startPathValue() {
943 $path =& $this->pathStack
[count( $this->pathStack
) - 1];
944 $path['valueStartToken'] = $this->pos
;
945 $path['valueStartByte'] = $this->byteNum
;
949 * Mark the end of the value part of a path.
951 function endPathValue() {
952 $path =& $this->pathStack
[count( $this->pathStack
) - 1];
953 $path['valueEndToken'] = $this->pos
;
954 $path['valueEndByte'] = $this->byteNum
;
958 * Mark the comma separator in an array element
960 function markComma() {
961 $path =& $this->pathStack
[count( $this->pathStack
) - 1];
962 $path['hasComma'] = true;
966 * Mark the arrow separator in an associative array element
968 function markArrow() {
969 $path =& $this->pathStack
[count( $this->pathStack
) - 1];
970 $path['arrowByte'] = $this->byteNum
;
974 * Generate a parse error
976 function error( $msg ) {
977 throw new ConfEditorParseError( $this, $msg );
981 * Get a readable name for the given token type.
984 function getTypeName( $type ) {
985 if ( is_int( $type ) ) {
986 return token_name( $type );
993 * Looks ahead to see if the given type is the next token type, starting
994 * from the current position plus the given offset. Skips any intervening
998 function isAhead( $type, $offset = 0 ) {
1000 $token = $this->getTokenAhead( $offset );
1001 while ( !$token->isEnd() ) {
1002 if ( $token->isSkip() ) {
1004 $token = $this->getTokenAhead( $ahead );
1006 } elseif ( $token->type
== $type ) {
1018 * Get the previous token object
1020 function prevToken() {
1021 return $this->prevToken
;
1025 * Echo a reasonably readable representation of the tokenizer array.
1027 function dumpTokens() {
1029 foreach ( $this->tokens
as $token ) {
1030 $obj = $this->newTokenObj( $token );
1031 $out .= sprintf( "%-28s %s\n",
1032 $this->getTypeName( $obj->type
),
1033 addcslashes( $obj->text
, "\0..\37" ) );
1035 echo "<pre>" . htmlspecialchars( $out ) . "</pre>";
1040 * Exception class for parse errors
1042 class ConfEditorParseError
extends MWException
{
1043 var $lineNum, $colNum;
1044 function __construct( $editor, $msg ) {
1045 $this->lineNum
= $editor->lineNum
;
1046 $this->colNum
= $editor->colNum
;
1047 parent
::__construct( "Parse error on line {$editor->lineNum} " .
1048 "col {$editor->colNum}: $msg" );
1051 function highlight( $text ) {
1052 $lines = StringUtils
::explode( "\n", $text );
1053 foreach ( $lines as $lineNum => $line ) {
1054 if ( $lineNum == $this->lineNum
- 1 ) {
1055 return "$line\n" .str_repeat( ' ', $this->colNum
- 1 ) . "^\n";
1063 * Class to wrap a token from the tokenizer.
1065 class ConfEditorToken
{
1068 static $scalarTypes = array( T_LNUMBER
, T_DNUMBER
, T_STRING
, T_CONSTANT_ENCAPSED_STRING
);
1069 static $skipTypes = array( T_WHITESPACE
, T_COMMENT
, T_DOC_COMMENT
);
1071 static function newEnd() {
1072 return new self( 'END', '' );
1075 function __construct( $type, $text ) {
1076 $this->type
= $type;
1077 $this->text
= $text;
1081 return in_array( $this->type
, self
::$skipTypes );
1084 function isScalar() {
1085 return in_array( $this->type
, self
::$scalarTypes );
1089 return $this->type
== 'END';