summaryrefslogtreecommitdiffstats
path: root/core/vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/Turtle.php
blob: bbbec479b1de1ebe50329e47fef63f9168492eb9 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
<?php

/**
 * EasyRdf
 *
 * LICENSE
 *
 * Copyright (c) 2009-2012 Nicholas J Humfrey.
 * Copyright (c) 1997-2006 Aduna (http://www.aduna-software.com/)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author 'Nicholas J Humfrey" may be used to endorse or
 *    promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2012 Nicholas J Humfrey
 *             Copyright (c) 1997-2006 Aduna (http://www.aduna-software.com/)
 * @license    http://www.opensource.org/licenses/bsd-license.php
 * @version    $Id$
 */

/**
 * Class to parse Turtle with no external dependancies.
 *
 * http://www.w3.org/TR/turtle/
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2012 Nicholas J Humfrey
 *             Copyright (c) 1997-2006 Aduna (http://www.aduna-software.com/)
 * @license    http://www.opensource.org/licenses/bsd-license.php
 */
class EasyRdf_Parser_Turtle extends EasyRdf_Parser_Ntriples
{
    /**
     * Constructor
     *
     * @return object EasyRdf_Parser_Turtle
     */
    public function __construct()
    {
    }

    /**
     * Parse Turtle into an EasyRdf_Graph
     *
     * @param object EasyRdf_Graph $graph   the graph to load the data into
     * @param string               $data    the RDF document data
     * @param string               $format  the format of the input data
     * @param string               $baseUri the base URI of the data being parsed
     * @return integer             The number of triples added to the graph
     */
    public function parse($graph, $data, $format, $baseUri)
    {
        parent::checkParseParams($graph, $data, $format, $baseUri);

        if ($format != 'turtle') {
            throw new EasyRdf_Exception(
                "EasyRdf_Parser_Turtle does not support: $format"
            );
        }

        $this->data = $data;
        $this->len = strlen($data);
        $this->pos = 0;

        $this->namespaces = array();
        $this->subject = null;
        $this->predicate = null;
        $this->object = null;

        $this->resetBnodeMap();

        $c = $this->skipWSC();
        while ($c != -1) {
            $this->parseStatement();
            $c = $this->skipWSC();
        }

        return $this->tripleCount;
    }


    /**
     * Parse a statement [2]
     * @ignore
     */
    protected function parseStatement()
    {
        $c = $this->peek();
        if ($c == '@') {
            $this->parseDirective();
            $this->skipWSC();
            $this->verifyCharacter($this->read(), ".");
        } else {
            $this->parseTriples();
            $this->skipWSC();
            $this->verifyCharacter($this->read(), ".");
        }
    }

    /**
     * Parse a directive [3]
     * @ignore
     */
    protected function parseDirective()
    {
        // Verify that the first characters form the string "prefix"
        $this->verifyCharacter($this->read(), "@");

        $directive = '';

        $c = $this->read();
        while ($c != -1 && !self::isWhitespace($c)) {
            $directive .= $c;
            $c = $this->read();
        }

        if ($directive == "prefix") {
            $this->parsePrefixID();
        } elseif ($directive == "base") {
            $this->parseBase();
        } elseif (strlen($directive) == 0) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: directive name is missing, expected @prefix or @base"
            );
        } else {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: unknown directive \"@$directive\""
            );
        }
    }

    /**
     * Parse a prefixID [4]
     * @ignore
     */
    protected function parsePrefixID()
    {
        $this->skipWSC();

        // Read prefix ID (e.g. "rdf:" or ":")
        $prefixID = '';

        while (true) {
            $c = $this->read();
            if ($c == ':') {
                $this->unread($c);
                break;
            } elseif (self::isWhitespace($c)) {
                break;
            } elseif ($c == -1) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: unexpected end of file while reading prefix id"
                );
            }

            $prefixID .= $c;
        }

        $this->skipWSC();
        $this->verifyCharacter($this->read(), ":");
        $this->skipWSC();

        // Read the namespace URI
        $namespace = $this->parseURI();

        // Store local namespace mapping
        $this->namespaces[$prefixID] = $namespace['value'];
    }

    /**
     * Parse base [5]
     * @ignore
     */
    protected function parseBase()
    {
        $this->skipWSC();

        $baseUri = $this->parseURI();
        $this->baseUri = new EasyRdf_ParsedUri($baseUri['value']);
    }

    /**
     * Parse triples [6]
     * @ignore
     */
    protected function parseTriples()
    {
        $this->parseSubject();
        $this->skipWSC();
        $this->parsePredicateObjectList();

        $this->subject = null;
        $this->predicate = null;
        $this->object = null;
    }

    /**
     * Parse a predicateObjectList [7]
     * @ignore
     */
    protected function parsePredicateObjectList()
    {
        $this->predicate = $this->parsePredicate();

        $this->skipWSC();
        $this->parseObjectList();

        while ($this->skipWSC() == ';') {
            $this->read();

            $c = $this->skipWSC();

            if ($c == '.' || $c == ']') {
                break;
            }

            $this->predicate = $this->parsePredicate();

            $this->skipWSC();

            $this->parseObjectList();
        }
    }

    /**
     * Parse a objectList [8]
     * @ignore
     */
    protected function parseObjectList()
    {
        $this->parseObject();

        while ($this->skipWSC() == ',') {
            $this->read();
            $this->skipWSC();
            $this->parseObject();
        }
    }

    /**
     * Parse a subject [10]
     * @ignore
     */
    protected function parseSubject()
    {
        $c = $this->peek();
        if ($c == '(') {
            $this->subject = $this->parseCollection();
        } elseif ($c == '[') {
            $this->subject = $this->parseImplicitBlank();
        } else {
            $value = $this->parseValue();

            if ($value['type'] == 'uri' or $value['type'] == 'bnode') {
                $this->subject = $value;
            } else {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: illegal subject type: ".$value['type']
                );
            }
        }
    }

    /**
     * Parse a predicate [11]
     * @ignore
     */
    protected function parsePredicate()
    {
        // Check if the short-cut 'a' is used
        $c1 = $this->read();

        if ($c1 == 'a') {
            $c2 = $this->read();

            if (self::isWhitespace($c2)) {
                // Short-cut is used, return the rdf:type URI
                return array(
                    'type' => 'uri',
                    'value' => EasyRdf_Namespace::get('rdf') . 'type'
                );
            }

            // Short-cut is not used, unread all characters
            $this->unread($c2);
        }
        $this->unread($c1);

        // Predicate is a normal resource
        $predicate = $this->parseValue();
        if ($predicate['type'] == 'uri') {
            return $predicate;
        } else {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: Illegal predicate value: " . $predicate
            );
        }
    }

    /**
     * Parse a object [12]
     * @ignore
     */
    protected function parseObject()
    {
        $c = $this->peek();

        if ($c == '(') {
            $this->object = $this->parseCollection();
        } elseif ($c == '[') {
            $this->object = $this->parseImplicitBlank();
        } else {
            $this->object = $this->parseValue();
        }

        $this->addTriple(
            $this->subject['value'],
            $this->predicate['value'],
            $this->object
        );
    }

    /**
     * Parses a blankNodePropertyList [15]
     *
     * This method parses the token []
     * and predicateObjectLists that are surrounded by square brackets.
     *
     * @ignore
     */
    protected function parseImplicitBlank()
    {
        $this->verifyCharacter($this->read(), "[");

        $bnode = array(
            'type' => 'bnode',
            'value' => $this->graph->newBNodeId()
        );

        $c = $this->read();
        if ($c != ']') {
            $this->unread($c);

            // Remember current subject and predicate
            $oldSubject = $this->subject;
            $oldPredicate = $this->predicate;

            // generated bNode becomes subject
            $this->subject = $bnode;

            // Enter recursion with nested predicate-object list
            $this->skipWSC();

            $this->parsePredicateObjectList();

            $this->skipWSC();

            // Read closing bracket
            $this->verifyCharacter($this->read(), "]");

            // Restore previous subject and predicate
            $this->subject = $oldSubject;
            $this->predicate = $oldPredicate;
        }

        return $bnode;
    }

    /**
     * Parses a collection [16], e.g: ( item1 item2 item3 )
     * @ignore
     */
    protected function parseCollection()
    {
        $this->verifyCharacter($this->read(), "(");

        $c = $this->skipWSC();
        if ($c == ')') {
            // Empty list
            $this->read();
            return array(
                'type' => 'uri',
                'value' => EasyRdf_Namespace::get('rdf') . 'nil'
            );
        } else {
            $listRoot = array(
                'type' => 'bnode',
                'value' => $this->graph->newBNodeId()
            );

            // Remember current subject and predicate
            $oldSubject = $this->subject;
            $oldPredicate = $this->predicate;

            // generated bNode becomes subject, predicate becomes rdf:first
            $this->subject = $listRoot;
            $this->predicate = array(
                'type' => 'uri',
                'value' => EasyRdf_Namespace::get('rdf') . 'first'
            );

            $this->parseObject();
            $bNode = $listRoot;

            while ($this->skipWSC() != ')') {
                // Create another list node and link it to the previous
                $newNode = array(
                    'type' => 'bnode',
                    'value' => $this->graph->newBNodeId()
                );

                $this->addTriple(
                    $bNode['value'],
                    EasyRdf_Namespace::get('rdf') . 'rest',
                    $newNode
                );

                // New node becomes the current
                $this->subject = $bNode = $newNode;

                $this->parseObject();
            }

            // Skip ')'
            $this->read();

            // Close the list
            $this->addTriple(
                $bNode['value'],
                EasyRdf_Namespace::get('rdf') . 'rest',
                array(
                    'type' => 'uri',
                    'value' => EasyRdf_Namespace::get('rdf') . 'nil'
                )
            );

            // Restore previous subject and predicate
            $this->subject = $oldSubject;
            $this->predicate = $oldPredicate;

            return $listRoot;
        }
    }

    /**
     * Parses an RDF value. This method parses uriref, qname, node ID, quoted
     * literal, integer, double and boolean.
     * @ignore
     */
    protected function parseValue()
    {
        $c = $this->peek();

        if ($c == '<') {
            // uriref, e.g. <foo://bar>
            return $this->parseURI();
        } elseif ($c == ':' || self::isPrefixStartChar($c)) {
            // qname or boolean
            return $this->parseQNameOrBoolean();
        } elseif ($c == '_') {
            // node ID, e.g. _:n1
            return $this->parseNodeID();
        } elseif ($c == '"' or $c == "'") {
            // quoted literal, e.g. "foo" or """foo""" or 'foo' or '''foo'''
            return $this->parseQuotedLiteral($c);
        } elseif (ctype_digit($c) || $c == '.' || $c == '+' || $c == '-') {
            // integer or double, e.g. 123 or 1.2e3
            return $this->parseNumber();
        } elseif ($c == -1) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: unexpected end of file while reading value"
            );
        } else {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: expected an RDF value here, found '$c'"
            );
        }
    }

    /**
     * Parses a quoted string, optionally followed by a language tag or datatype.
     * @param string  $quote  The type of quote to use (either ' or ")
     * @ignore
     */
    protected function parseQuotedLiteral($quote)
    {
        $label = $this->parseQuotedString($quote);

        // Check for presence of a language tag or datatype
        $c = $this->peek();

        if ($c == '@') {
            $this->read();

            // Read language
            $lang = '';
            $c = $this->read();
            if ($c == -1) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: unexpected end of file while reading language"
                );
            } elseif (!self::isLanguageStartChar($c)) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: expected a letter, found '$c'"
                );
            }

            $lang .= $c;

            $c = $this->read();
            while (self::isLanguageChar($c)) {
                $lang .= $c;
                $c = $this->read();
            }

            $this->unread($c);

            return array(
                'type' => 'literal',
                'value' => $label,
                'lang' => $lang
            );
        } elseif ($c == '^') {
            $this->read();

            // next character should be another '^'
            $this->verifyCharacter($this->read(), "^");

            // Read datatype
            $datatype = $this->parseValue();
            if ($datatype['type'] == 'uri') {
                return array(
                    'type' => 'literal',
                    'value' => $label,
                    'datatype' => $datatype['value']
                );
            } else {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: illegal datatype value: $datatype"
                );
            }
        } else {
            return array(
                'type' => 'literal',
                'value' => $label
            );
        }
    }

    /**
     * Parses a quoted string, which is either a "normal string" or a """long string""".
     * @param string  $quote  The type of quote to use (either ' or ")
     * @ignore
     */
    protected function parseQuotedString($quote)
    {
        $result = null;

        // First character should be ' or "
        $this->verifyCharacter($this->read(), $quote);

        // Check for long-string, which starts and ends with three double quotes
        $c2 = $this->read();
        $c3 = $this->read();

        if ($c2 == $quote && $c3 == $quote) {
            // Long string
            $result = $this->parseLongString($quote);
        } else {
            // Normal string
            $this->unread($c3);
            $this->unread($c2);

            $result = $this->parseString($quote);
        }

        // Unescape any escape sequences
        return $this->unescapeString($result);
    }

    /**
     * Parses a "normal string". This method assumes that the first double quote
     * has already been parsed.
     * @param string  $quote  The type of quote to use (either ' or ")
     * @ignore
     */
    protected function parseString($quote)
    {
        $str = '';

        while (true) {
            $c = $this->read();

            if ($c == $quote) {
                break;
            } elseif ($c == -1) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: unexpected end of file while reading string"
                );
            }

            $str .= $c;

            if ($c == '\\') {
                // This escapes the next character, which might be a ' or a "
                $c = $this->read();
                if ($c == -1) {
                    throw new EasyRdf_Exception(
                        "Turtle Parse Error: unexpected end of file while reading string"
                    );
                }
                $str .= $c;
            }
        }

        return $str;
    }

    /**
     * Parses a """long string""". This method assumes that the first three
     * double quotes have already been parsed.
     * @param string  $quote  The type of quote to use (either ' or ")
     * @ignore
     */
    protected function parseLongString($quote)
    {
        $str = '';
        $doubleQuoteCount = 0;

        while ($doubleQuoteCount < 3) {
            $c = $this->read();

            if ($c == -1) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: unexpected end of file while reading long string"
                );
            } elseif ($c == $quote) {
                $doubleQuoteCount++;
            } else {
                $doubleQuoteCount = 0;
            }

            $str .= $c;

            if ($c == '\\') {
                // This escapes the next character, which might be a ' or "
                $c = $this->read();
                if ($c == -1) {
                    throw new EasyRdf_Exception(
                        "Turtle Parse Error: unexpected end of file while reading long string"
                    );
                }
                $str .= $c;
            }
        }

        return substr($str, 0, -3);
    }

    /**
     * Parses a numeric value, either of type integer, decimal or double
     * @ignore
     */
    protected function parseNumber()
    {
        $value = '';
        $datatype = EasyRdf_Namespace::get('xsd').'integer';

        $c = $this->read();

        // read optional sign character
        if ($c == '+' || $c == '-') {
            $value .= $c;
            $c = $this->read();
        }

        while (ctype_digit($c)) {
            $value .= $c;
            $c = $this->read();
        }

        if ($c == '.' || $c == 'e' || $c == 'E') {
            // We're parsing a decimal or a double
            $datatype = EasyRdf_Namespace::get('xsd').'decimal';

            // read optional fractional digits
            if ($c == '.') {
                $value .= $c;
                $c = $this->read();
                while (ctype_digit($c)) {
                    $value .= $c;
                    $c = $this->read();
                }

                if (strlen($value) == 1) {
                    // We've only parsed a '.'
                    throw new EasyRdf_Exception(
                        "Turtle Parse Error: object for statement missing"
                    );
                }
            } else {
                if (strlen($value) == 0) {
                    // We've only parsed an 'e' or 'E'
                    throw new EasyRdf_Exception(
                        "Turtle Parse Error: object for statement missing"
                    );
                }
            }

            // read optional exponent
            if ($c == 'e' || $c == 'E') {
                $datatype = EasyRdf_Namespace::get('xsd').'double';
                $value .= $c;

                $c = $this->read();
                if ($c == '+' || $c == '-') {
                    $value .= $c;
                    $c = $this->read();
                }

                if (!ctype_digit($c)) {
                    throw new EasyRdf_Exception(
                        "Turtle Parse Error: Exponent value missing"
                    );
                }

                $value .= $c;

                $c = $this->read();
                while (ctype_digit($c)) {
                    $value .= $c;
                    $c = $this->read();
                }
            }
        }

        // Unread last character, it isn't part of the number
        $this->unread($c);

        // Return result as a typed literal
        return array(
            'type' => 'literal',
            'value' => $value,
            'datatype' => $datatype
        );
    }

    /**
     * Parses a URI / IRI
     * @ignore
     */
    protected function parseURI()
    {
        $uri = '';

        // First character should be '<'
        $this->verifyCharacter($this->read(), "<");

        // Read up to the next '>' character
        while (true) {
            $c = $this->read();

            if ($c == '>') {
                break;
            } elseif ($c == -1) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: unexpected end of file while reading URI"
                );
            }

            $uri .= $c;

            if ($c == '\\') {
                // This escapes the next character, which might be a '>'
                $c = $this->read();
                if ($c == -1) {
                    throw new EasyRdf_Exception(
                        "Turtle Parse Error: unexpected end of file while reading URI"
                    );
                }
                $uri .= $c;
            }
        }

        // Unescape any escape sequences
        $uri = $this->unescapeString($uri);

        return array(
            'type' => 'uri',
            'value' => $this->resolve($uri)
        );
    }

    /**
     * Parses qnames and boolean values, which have equivalent starting
     * characters.
     * @ignore
     */
    protected function parseQNameOrBoolean()
    {
        // First character should be a ':' or a letter
        $c = $this->read();
        if ($c == -1) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: unexpected end of file while readying value"
            );
        }
        if ($c != ':' && !self::isPrefixStartChar($c)) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: expected a ':' or a letter, found '$c'"
            );
        }

        $namespace = null;

        if ($c == ':') {
            // qname using default namespace
            $namespace = $this->namespaces[""];
            if ($namespace == null) {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: default namespace used but not defined"
                );
            }
        } else {
            // $c is the first letter of the prefix
            $prefix = $c;

            $c = $this->read();
            while (self::isPrefixChar($c)) {
                $prefix .= $c;
                $c = $this->read();
            }

            if ($c != ':') {
                // prefix may actually be a boolean value
                $value = $prefix;

                if ($value == "true" || $value == "false") {
                    return array(
                        'type' => 'literal',
                        'value' => $value,
                        'datatype' => EasyRdf_Namespace::get('xsd') . 'boolean'
                    );
                }
            }

            $this->verifyCharacter($c, ":");

            if (isset($this->namespaces[$prefix])) {
                $namespace = $this->namespaces[$prefix];
            } else {
                throw new EasyRdf_Exception(
                    "Turtle Parse Error: namespace prefix '$prefix' used but not defined"
                );
            }
        }

        // $c == ':', read optional local name
        $localName = '';
        $c = $this->read();
        if (self::isNameStartChar($c)) {
            $localName .= $c;

            $c = $this->read();
            while (self::isNameChar($c)) {
                $localName .= $c;
                $c = $this->read();
            }
        }

        // Unread last character
        $this->unread($c);

        // Note: namespace has already been resolved
        return array(
            'type' => 'uri',
            'value' => $namespace . $localName
        );
    }

    /**
     * Parses a blank node ID, e.g: _:node1
     * @ignore
     */
    protected function parseNodeID()
    {
        // Node ID should start with "_:"
        $this->verifyCharacter($this->read(), "_");
        $this->verifyCharacter($this->read(), ":");

        // Read the node ID
        $c = $this->read();
        if ($c == -1) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: unexpected end of file while reading node id"
            );
        } elseif (!self::isNameStartChar($c)) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: expected a letter, found '$c'"
            );
        }

        // Read all following letter and numbers, they are part of the name
        $name = $c;
        $c = $this->read();
        while (self::isNameChar($c)) {
            $name .= $c;
            $c = $this->read();
        }

        $this->unread($c);

        return array(
            'type' => 'bnode',
            'value' => $this->remapBnode($name)
        );
    }

    protected function resolve($uri)
    {
        if ($this->baseUri) {
            return $this->baseUri->resolve($uri)->toString();
        } else {
            return $uri;
        }
    }

    /**
     * Verifies that the supplied character $c is one of the expected
     * characters specified in $expected. This method will throw a
     * exception if this is not the case.
     * @ignore
     */
    protected function verifyCharacter($c, $expected)
    {
        if ($c == -1) {
            throw new EasyRdf_Exception(
                "Turtle Parse Error: unexpected end of file"
            );
        } elseif (strpbrk($c, $expected) === false) {
            $msg = 'expected ';
            for ($i = 0; $i < strlen($expected); $i++) {
                if ($i > 0) {
                    $msg .= " or ";
                }
                $msg .= '\''.$expected[$i].'\'';
            }
            $msg .= ", found '$c'";

            throw new EasyRdf_Exception("Turtle Parse Error: $msg");
        }
    }

    /**
     * Skip through whitespace and comments
     * @ignore
     */
    protected function skipWSC()
    {
        $c = $this->read();
        while (self::isWhitespace($c) || $c == '#') {
            if ($c == '#') {
                $this->skipLine();
            }

            $c = $this->read();
        }

        $this->unread($c);
        return $c;
    }

    /**
     * Consumes characters from reader until the first EOL has been read.
     * @ignore
     */
    protected function skipLine()
    {
        $c = $this->read();
        while ($c != -1 && $c != "\r" && $c != "\n") {
            $c = $this->read();
        }

        // c is equal to -1, \r or \n.
        // In case c is equal to \r, we should also read a following \n.
        if ($c == "\r") {
            $c = $this->read();
            if ($c != "\n") {
                $this->unread($c);
            }
        }
    }

    /**
     * Read a single character from the input buffer.
     * Returns -1 when the end of the file is reached.
     * @ignore
     */
    protected function read()
    {
        if ($this->pos < $this->len) {
            $c = $this->data[$this->pos];
            $this->pos++;
            return $c;
        } else {
            return -1;
        }
    }

    /**
     * Gets the next character to be returned by read()
     * without removing it from the input buffer.
     * @ignore
     */
    protected function peek()
    {
        if ($this->pos < $this->len) {
            return $this->data[$this->pos];
        } else {
            return -1;
        }
    }


    /**
     * Steps back, restoring the previous character read() to the input buffer
     * @ignore
     */
    protected function unread()
    {
        if ($this->pos > 0) {
            $this->pos--;
        } else {
            throw new EasyRdf_Exception("Turtle Parse Error: unread error");
        }
    }

    /**
     * Returns true if $c is a whitespace character
     * @ignore
     */
    public static function isWhitespace($c)
    {
        // Whitespace character are space, tab, newline and carriage return:
        return $c == " " || $c == "\t" || $c == "\r" || $c == "\n";
    }

    /** @ignore */
    public static function isPrefixStartChar($c)
    {
        $o = ord($c);
        return
            $o >= 0x41   && $o <= 0x5a ||     # A-Z
            $o >= 0x61   && $o <= 0x7a ||     # a-z
            $o >= 0x00C0 && $o <= 0x00D6 ||
            $o >= 0x00D8 && $o <= 0x00F6 ||
            $o >= 0x00F8 && $o <= 0x02FF ||
            $o >= 0x0370 && $o <= 0x037D ||
            $o >= 0x037F && $o <= 0x1FFF ||
            $o >= 0x200C && $o <= 0x200D ||
            $o >= 0x2070 && $o <= 0x218F ||
            $o >= 0x2C00 && $o <= 0x2FEF ||
            $o >= 0x3001 && $o <= 0xD7FF ||
            $o >= 0xF900 && $o <= 0xFDCF ||
            $o >= 0xFDF0 && $o <= 0xFFFD ||
            $o >= 0x10000 && $o <= 0xEFFFF;
    }

    /** @ignore */
    public static function isNameStartChar($c)
    {
        return $c == '_' || self::isPrefixStartChar($c);
    }

    /** @ignore */
    public static function isNameChar($c)
    {
        $o = ord($c);
        return
            self::isNameStartChar($c) ||
            $c == '-' ||
            $o >= 0x30 && $o <= 0x39 ||   # numeric
            $o == 0x00B7 ||
            $o >= 0x0300 && $o <= 0x036F ||
            $o >= 0x203F && $o <= 0x2040;
    }

    /** @ignore */
    public static function isPrefixChar($c)
    {
        return self::isNameChar($c);
    }

    /** @ignore */
    public static function isLanguageStartChar($c)
    {
        $o = ord($c);
        return
            $o >= 0x41   && $o <= 0x5a ||
            $o >= 0x61   && $o <= 0x7a;
    }

    /** @ignore */
    public static function isLanguageChar($c)
    {
        $o = ord($c);
        return
            $o >= 0x41   && $o <= 0x5a ||   # A-Z
            $o >= 0x61   && $o <= 0x7a ||   # a-z
            $o >= 0x30   && $o <= 0x39 ||   # 0-9
            $c == '-';
    }
}