on Mar 25th, 2008Json Lexer/Parser - Part2
(The reason the calls that step back one position are typed “$this->pos = $this->pos-1″ instead of with a double minus-sign is that for some reason wordpress converts two “-” signs, into just one - making the code behave erroneously when you copy it to your editor)
Here’s the second part of my JSON Lexer/Parser tutorial, this will be a rather short post with a lot of self explaining code inside it, here it is:
<?php
class lexer_stream {
var $pos;
var $line;
var $length;
var $string;
function __construct ($string) {
$this->pos = -1;
$this->line = 1;
$this->string = $string;
$this->length = strlen($string);
}
function next () {
if (++$this->pos < $this->length) {
if ($this->curr() == “\n”) {
$this->line++;
}
return $this->curr();
} else {
$this->pos = $this->pos-1;
return false;
}
}
function prev () {
if ($this->pos-1 >= 0) {
if ($this->curr() == “\n”) {
$this->line = $this->line-1;
}
$this->pos = $this->pos-1;
return $this->curr();
} else {
$this->pos = 0;
return false;
}
}
function curr () {
if ($this->pos >= 0 and $this->pos < $this->length) {
return $this->string[$this->pos];
} else {
return false;
}
}
}
This class is a simple abstraction of a string, allowing us to call next(), prev() and curr() to step forward one character, step back one character and print the current character respectively. Why did I wrap a string like this? Why not use it in it’s raw form? Well, it’s not always a string we’re going to be reading our data to parse from, it could be from a socket, http-request or a file for example - and all we need to do is implement a wrapper class like the one above for our data format and we can then pass it to the lexer (that we’re going to build).
The code should be pretty self explanatory, the reason I’ve incorporated a $line-field is so that we can give nice error messages like: “JSON Error: Invalid format <bla bla bla>, on line: 5″. Anyway, that’s all for today folks - gotta hit the sack now, immensely tired after the trip back home to Stockholm from Gothenburg, over and out!