Source

p5-syntax-highlight-rdf / lib / Syntax / Highlight / RDF.pm

Full commit
  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
package Syntax::Highlight::RDF;

use 5.010001;
use strict;
use warnings;

BEGIN {
	$Syntax::Highlight::RDF::AUTHORITY = 'cpan:TOBYINK';
	$Syntax::Highlight::RDF::VERSION   = '0.001';
}

use MooX::Struct -retain, -rw,
	Feature                   => [],
	Token                     => [-extends => [qw<Feature>], qw($spelling!)],
	Comment                   => [-extends => [qw<Token>]],
	Brace                     => [-extends => [qw<Token>]],
	Bracket                   => [-extends => [qw<Token>]],
	Parenthesis               => [-extends => [qw<Token>]],
	Datatype                  => [-extends => [qw<Token>]],
	AtRule                    => [-extends => [qw<Token>]],
	Shorthand                 => [-extends => [qw<Token>]],
	BNode                     => [-extends => [qw<Token>]],
	Variable                  => [-extends => [qw<Token>]],
	Number                    => [-extends => [qw<Token>]],
	Number_Double             => [-extends => [qw<Number>]],
	Number_Decimal            => [-extends => [qw<Number>]],
	Number_Integer            => [-extends => [qw<Number>]],
	Punctuation               => [-extends => [qw<Token>]],
	Path                      => [-extends => [qw<Token>]],
	Boolean                   => [-extends => [qw<Token>]],
	Sparql                    => [-extends => [qw<Token>]],
	Sparql_Keyword            => [-extends => [qw<Sparql>]],
	Sparql_Operator           => [-extends => [qw<Sparql>]],
	Sparql_Function           => [-extends => [qw<Sparql>]],
	Sparql_Aggregate          => [-extends => [qw<Sparql_Function>]],
	Sparql_Ordering           => [-extends => [qw<Sparql_Function>]],
	IsOf                      => [-extends => [qw<Token>]],
	Language                  => [-extends => [qw<Token>]],
	Unknown                   => [-extends => [qw<Token>]],
	Whitespace                => [-extends => [qw<Token>]],
	Name                      => [-extends => [qw<Token>]],
	URIRef                    => [-extends => [qw<Token>], qw($absolute_uri)],
	CURIE                     => [-extends => [qw<Token>], qw($absolute_uri)],
	String                    => [-extends => [qw<Token>], qw($quote_char $parts $language)],
	LongString                => [-extends => [qw<String>]],
	ShortString               => [-extends => [qw<String>]],
	Structure_Start           => [-extends => [qw<Feature>], qw($end)],
	Structure_End             => [-extends => [qw<Feature>], q($start) => [weak_ref => 1]],
	PrefixDefinition_Start    => [-extends => [qw<Structure_Start>], qw($prefix $absolute_uri)],
	PrefixDefinition_End      => [-extends => [qw<Structure_End>]],
;

use Throwable::Factory
	Tokenization              => [qw( $remaining -caller )],
	NotImplemented            => [qw( -notimplemented )],
	WTF                       => [],
	WrongInvocant             => [qw( -caller )],
;

{
	use HTML::HTML5::Entities qw/encode_entities/;	
	no strict 'refs';
	*{Feature    . "::tok"}        = sub { sprintf "%s~", $_[0]->TYPE };
	*{Token      . "::tok"}        = sub { sprintf "%s[%s]", $_[0]->TYPE, $_[0]->spelling };
	*{Whitespace . "::tok"}        = sub { $_[0]->TYPE };
	*{Feature    . "::TO_STRING"}  = sub { "" };
	*{Token      . "::TO_STRING"}  = sub { $_[0]->spelling };
	*{Token      . "::TO_HTML"}    = sub {
		sprintf "<span class=\"rdf_%s\">%s</span>", lc $_[0]->TYPE, encode_entities($_[0]->spelling)
	};
	*{Whitespace . "::TO_HTML"}  = sub { $_[0]->spelling };
	*{URIRef     . "::uri"}      = sub { my $u = $_[0]->spelling; substr $u, 1, length($u)-2 };  # XXX - unescape
	*{CURIE      . "::prefix"}   = sub { (split ":", $_[0]->spelling)[0] };
	*{CURIE      . "::suffix"}   = sub { (split ":", $_[0]->spelling)[1] };
	*{PrefixDefinition_Start . "::tok"} = sub {
		sprintf '%s{prefix:"%s",uri:"%s"}', $_[0]->TYPE, $_[0]->prefix, $_[0]->absolute_uri;
	};
	*{PrefixDefinition_End . "::tok"} = sub {
		sprintf '%s{prefix:"%s",uri:"%s"}', $_[0]->TYPE, $_[0]->start->prefix, $_[0]->start->absolute_uri;
	};
	*{CURIE      . "::tok"} = sub {
		sprintf '%s[%s]{uri:"%s"}', $_[0]->TYPE, $_[0]->spelling, $_[0]->absolute_uri//"???";
	};
	*{URIRef     . "::tok"} = sub {
		sprintf '%s[%s]{uri:"%s"}', $_[0]->TYPE, $_[0]->spelling, $_[0]->absolute_uri//"???";
	};
	*{Structure_Start . "::TO_HTML"} = sub {
		my @attrs = sprintf 'class="rdf_%s"', lc $_[0]->TYPE;
		sprintf "<span %s>", join " ", @attrs;
	};
	*{Structure_End . "::TO_HTML"} = sub {
		"</span>"
	};
	*{PrefixDefinition_Start . "::TO_HTML"} = sub {
		my @attrs = sprintf 'class="rdf_%s"', lc $_[0]->TYPE;
		push @attrs, sprintf 'data-rdf-prefix="%s"', encode_entities($_[0]->prefix) if defined $_[0]->prefix;
		push @attrs, sprintf 'data-rdf-uri="%s"', encode_entities($_[0]->absolute_uri) if defined $_[0]->absolute_uri;
		sprintf "<span %s>", join " ", @attrs;
	};
	*{CURIE . "::TO_HTML"} = sub {
		my @attrs = sprintf 'class="rdf_%s"', lc $_[0]->TYPE;
		push @attrs, sprintf 'data-rdf-prefix="%s"', encode_entities($_[0]->prefix) if defined $_[0]->prefix;
		push @attrs, sprintf 'data-rdf-suffix="%s"', encode_entities($_[0]->suffix) if defined $_[0]->suffix;
		push @attrs, sprintf 'data-rdf-uri="%s"', encode_entities($_[0]->absolute_uri) if defined $_[0]->absolute_uri;
		sprintf "<span %s>%s</span>", join(" ", @attrs), encode_entities($_[0]->spelling)
	};
	*{URIRef . "::TO_HTML"} = sub {
		my @attrs = sprintf 'class="rdf_%s"', lc $_[0]->TYPE;
		push @attrs, sprintf 'data-rdf-uri="%s"', encode_entities($_[0]->absolute_uri) if defined $_[0]->absolute_uri;
		sprintf "<span %s>%s</span>", join(" ", @attrs), encode_entities($_[0]->spelling)
	};
}

our %STYLE = (
	rdf_brace       => 'color:#990000;font-weight:bold',
	rdf_bracket     => 'color:#990000;font-weight:bold',
	rdf_parenthesis => 'color:#990000;font-weight:bold',
	rdf_punctuation => 'color:#990000;font-weight:bold',
	rdf_datatype    => 'color:#990000;font-weight:bold',
	rdf_atrule      => 'color:#000000;font-weight:bold',
	rdf_comment     => 'color:#669933;font-style:italic',
	rdf_isof        => 'color:#000099;font-style:italic',
	rdf_sparql_keyword    => 'color:#000000;font-weight:bold;font-style:italic',
	rdf_sparql_operator   => 'color:#000000;font-weight:bold;font-style:italic',
	rdf_sparql_function   => 'color:#000000;font-weight:bold;font-style:italic',
	rdf_sparql_aggregate  => 'color:#000000;font-weight:bold;font-style:italic',
	rdf_sparql_ordering   => 'color:#000000;font-weight:bold;font-style:italic',
	rdf_unknown     => 'color:#ffff00;background-color:#660000;font-weight:bold',
	rdf_uriref      => 'color:#0000cc',
	rdf_curie       => 'color:#000099;font-weight:bold',
	rdf_bnode       => 'color:#009900;font-weight:bold',
	rdf_shorthand   => 'color:#000099;font-weight:bold;font-style:italic',
	rdf_variable    => 'color:#009900;font-weight:bold;font-style:italic',
	rdf_shortstring => 'color:#cc00cc',
	rdf_longstring  => 'color:#cc00cc;background-color:#ffddff;font-style:italic',
	rdf_language    => 'color:#ff0000',
	rdf_number_double     => 'color:#cc00cc;font-weight:bold',
	rdf_number_decimal    => 'color:#cc00cc;font-weight:bold',
	rdf_number_integer    => 'color:#cc00cc;font-weight:bold',
	rdf_boolean     => 'color:#cc00cc;font-weight:bold;font-style:italic',
	rdf_path        => 'color:#000099;background-color:#99ffff;font-weight:bold',
	rdf_name        => 'color:#000099;background-color:#ffff99;font-weight:bold',
);

use Moo;

use IO::Detect qw( as_filehandle );

use constant {
	MODE_NTRIPLES       => 0,
	MODE_TURTLE         => 1,
	MODE_NOTATION_3     => 2,
	MODE_SPARQL         => 4,
	MODE_PRETDSL        => 8,
	MODE_TRIG           => 16,
};

use constant mode => (MODE_NTRIPLES | MODE_TURTLE | MODE_NOTATION_3 | MODE_SPARQL | MODE_PRETDSL | MODE_TRIG);

has _remaining => (is => "rw");
has _tokens    => (is => "rw");

# XXX - May be able to get better regexps from Trine?
my $nameStartChar  = qr{A-Za-z_\x{00C0}-\x{00D6}\x{00D8}-\x{00F6}\x{00F8}-\x{02FF}\x{0370}-\x{037D}\x{037F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}};
my $nameStartChar2 = qr{A-Za-yz\x{00C0}-\x{00D6}\x{00D8}-\x{00F6}\x{00F8}-\x{02FF}\x{0370}-\x{037D}\x{037F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}};
my $nameChar       = qr{A-Za-z_\x{00C0}-\x{00D6}\x{00D8}-\x{00F6}\x{00F8}-\x{037D}\x{037F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}\x{00B7}\x{203F}\x{2040}0-9-};

our @sparqlQueryWord = qw(
	BASE
	PREFIX
	SELECT
	DISTINCT
	REDUCED
	AS
	CONSTRUCT
	WHERE
	DESCRIBE
	ASK
	FROM
	NAMED
	GROUP__BY
	HAVING
	ORDER__BY
	LIMIT
	OFFSET
	VALUES
	DEFAULT
	ALL
	OPTIONAL
	SERVICE
	BIND
	UNDEF
	MINUS
	FILTER
);

our @sparqlUpdateWord = qw(
	LOAD
	SILENT
	INTO
	CLEAR
	DROP
	CREATE
	ADD
	MOVE
	COPY
	INSERT__DATA
	DELETE__DATA
	DELETE__WHERE
	DELETE
	INSERT
	USING
);

our @sparqlOperator = qw(
	||
	&&
	=
	!=
	<
	>
	<=
	>=
	NOT__IN
	NOT
	IN
	+
	-
	*
	/
	!
);

our @sparqlFunction = qw(
	STR
	LANG
	LANGMATCHES
	DATATYPE
	BOUND
	IRI
	URI
	BNODE
	RAND
	ABS
	CEIL
	FLOOR
	ROUND
	CONCAT
	STRLEN
	UCASE
	LCASE
	ENCODE_FOR_URI
	CONTAINS
	STRSTARTS
	STRENDS
	STRBEFORE
	STRAFTER
	YEAR
	MONTH
	DAY
	HOURS
	MINUTES
	SECONDS
	TIMEZONE
	TZ
	NOW
	UUID
	STRUUID
	MD5
	SHA1
	SHA256
	SHA384
	SHA512
	COALESCE
	IF
	STRLANG
	STRDT
	sameTerm
	isIRI
	isURI
	isBLANK
	isLITERAL
	isNUMERIC
	REGEX
	SUBSTR
	REPLACE
	NOT__EXISTS
	EXISTS
);

our @sparqlAggregate = qw(
	COUNT
	SUM
	MIN
	MAX
	AVG
	SAMPLE
	GROUP_CONCAT
);

our @sparqlOrdering = qw(
	ASC
	DESC
);

sub _peek
{
	my $self = shift;
	my ($regexp) = @_;
	$regexp = qr{^(\Q$regexp\E)} unless ref $regexp;
	
	if (my @m = (${$self->_remaining} =~ $regexp))
	{
		return \@m;
	}
	
	return;
}

sub _pull_token
{
	my $self = shift;
	my ($spelling, $class, %more) = @_;
	defined $spelling or WTF->throw("Tried to pull undef token!");
	substr(${$self->_remaining}, 0, length $spelling, "");
	push @{$self->_tokens}, $class->new(spelling => $spelling, %more);
}

sub _pull_bnode
{
	my $self = shift;
	${$self->_remaining} =~ m/^(_:[$nameStartChar][$nameChar]*)/
		? $self->_pull_token($1, BNode)
		: $self->_pull("_:", BNode)
}

sub _pull_variable
{
	my $self = shift;
	${$self->_remaining} =~ m/^([\?\$][$nameStartChar][$nameChar]*)/
		? $self->_pull_token($1, Variable)
		: $self->_pull(substr(${$self->_remaining}, 0, 1), Variable)
}

sub _pull_whitespace
{
	my $self = shift;
	$self->_pull_token($1, Whitespace)
		if ${$self->_remaining} =~ m/^(\s*)/sm;
}

sub _pull_uri
{
	my $self = shift;
	$self->_pull_token($1, URIRef)
		if ${$self->_remaining} =~ m/^(<(?:\\\\|\\>|\\<|[^<>\\]){0,1024}>)/;
}

sub _pull_curie
{
	my $self = shift;
	$self->_pull_token($1, CURIE)
		if ${$self->_remaining} =~ m/^(([$nameStartChar2][$nameChar]*)?:([$nameStartChar2][$nameChar]*)?)/;
}

# XXX - this is probably too naive
sub _pull_shortstring
{
	my $self = shift;
	my $quote_char = substr(${$self->_remaining}, 0, 1);
	$self->_pull_token($1, ShortString, quote_char => $quote_char)
		if ${$self->_remaining} =~ m/^($quote_char(?:\\\\|\\.|[^$quote_char])*?$quote_char)/;
}

# XXX - this is probably too naive
sub _pull_longstring
{
	my $self = shift;
	my $quote_char = substr(${$self->_remaining}, 0, 1);
	$self->_pull_token($1, LongString, quote_char => $quote_char)
		if ${$self->_remaining} =~ m/^($quote_char{3}.*?$quote_char{3})/ms;
}

sub tokenize
{
	my $self = shift;
	ref $self or WrongInvocant->throw("this is an object method!");
	
	my ($text_ref) = @_;
	$self->_remaining(
		ref($text_ref) eq 'SCALAR'
			? $text_ref
			: do { local $/; my $h = as_filehandle($text_ref); \(my $t = <$h>) }
	);
	$self->_tokens([]);
	
	# Calculate these each time in case somebody wants to play with
	# our variables!
	my $_regexify = sub
	{
		my @in     = @_;
		my $joined = join "|", map { s/__/\\s+/g; $_ } map quotemeta, @in;
		qr{^($joined)}i;
	};
	my $sparqlKeyword   = $_regexify->(@sparqlQueryWord, @sparqlUpdateWord);
	my $sparqlFunction  = $_regexify->(@sparqlFunction);
	my $sparqlAggregate = $_regexify->(@sparqlAggregate);
	my $sparqlOrdering  = $_regexify->(@sparqlOrdering);
	my $sparqlOperator  = $_regexify->(@sparqlOperator);
	
	# Don't need to repeatedly call this method!
	my $IS_NTRIPLES    = ($self->mode & MODE_NTRIPLES);
	my $IS_TURTLE      = ($self->mode & MODE_TURTLE or $self->mode & MODE_TRIG or $self->mode & MODE_NOTATION_3 or $self->mode & MODE_PRETDSL);
	my $IS_NOTATION_3  = ($self->mode & MODE_NOTATION_3 or $self->mode & MODE_PRETDSL);
	my $IS_SPARQL      = ($self->mode & MODE_SPARQL);
	my $IS_PRETDSL     = ($self->mode & MODE_PRETDSL);
	my $IS_TRIG        = ($self->mode & MODE_TRIG);
	my $ABOVE_NTRIPLES = ($IS_TURTLE or $IS_NOTATION_3 or $IS_SPARQL or $IS_PRETDSL or $IS_TRIG);
	
	# Declare this ahead of time for use in the big elsif!
	my $matches;
	
	while (length ${ $self->_remaining })
	{
		if ($self->_peek(' ') || $self->_peek("\n") || $self->_peek("\r") || $self->_peek("\t"))
		{
			$self->_pull_whitespace;
		}
		elsif ($IS_NOTATION_3||$IS_SPARQL||$IS_TRIG and $self->_peek('{'))
		{
			$self->_pull_token('{', Brace);
		}
		elsif ($IS_NOTATION_3||$IS_SPARQL||$IS_TRIG and $self->_peek('}'))
		{
			$self->_pull_token('}', Brace);
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek('['))
		{
			$self->_pull_token('[', Bracket);
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek(']'))
		{
			$self->_pull_token(']', Bracket);
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek('('))
		{
			$self->_pull_token('(', Parenthesis);
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek(')'))
		{
			$self->_pull_token(')', Parenthesis);
		}
		elsif ($self->_peek('^^'))
		{
			$self->_pull_token('^^', Datatype);
		}
		# Need to handle SPARQL property paths!
		elsif ($IS_NOTATION_3 and $matches = $self->_peek(qr/^([\!\^])/))
		{
			$self->_pull_token($matches->[0], Path);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\,\;])/))
		{
			$self->_pull_token($matches->[0], Punctuation);
		}
		elsif ($self->_peek('.'))
		{
			$self->_pull_token('.', Punctuation);
		}
		elsif ($IS_NOTATION_3||$IS_TURTLE||$IS_TRIG and $matches = $self->_peek(qr/^(\@(?:prefix|base))/))
		{
			$self->_pull_token($matches->[0], AtRule);
		}
		elsif ($IS_NOTATION_3 and $matches = $self->_peek(qr/^(\@(?:keywords|forSome|forAll))/))
		{
			$self->_pull_token($matches->[0], AtRule);
		}
		elsif ($matches = $self->_peek(qr/^(\@[a-z0-9-]+)/i))
		{
			$self->_pull_token($matches->[0], Language);
		}
		elsif ($matches = $self->_peek(qr/^(#.*)(\r|\n|$)/ims))
		{
			$self->_pull_token($matches->[0], Comment);
		}
		elsif ($self->_peek('_:'))
		{
			$self->_pull_bnode;
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([$nameStartChar2][$nameChar]*)?:([$nameStartChar2][$nameChar]*)?/))
		{
			$self->_pull_curie;
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\-\+]?([0-9]+\.[0-9]*e[\-\+]?[0-9]+))/i))
		{
			$self->_pull_token($matches->[0], Number_Double);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\-\+]?(\.[0-9]+e[\-\+]?[0-9]+))/i))
		{
			$self->_pull_token($matches->[0], Number_Double);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\-\+]?([0-9]+e[\-\+]?[0-9]+))/i))
		{
			$self->_pull_token($matches->[0], Number_Double);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\-\+]?([0-9]+\.[0-9]*))/))
		{
			$self->_pull_token($matches->[0], Number_Decimal);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\-\+]?(\.[0-9]+))/))
		{
			$self->_pull_token($matches->[0], Number_Decimal);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([\-\+]?([0-9]+))/))
		{
			$self->_pull_token($matches->[0], Number_Integer);
		}
		elsif ($self->_peek('<'))
		{
			$self->_pull_uri;
		}
		elsif ($IS_NOTATION_3||$IS_SPARQL and $self->_peek('?'))
		{
			$self->_pull_variable;
		}
		elsif ($IS_SPARQL and $self->_peek('$'))
		{
			$self->_pull_variable;
		}
		elsif ($IS_SPARQL and $self->_peek('*'))
		{
			$self->_pull_token('*', Variable);
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek('"""') || $self->_peek("'''"))
		{
			$self->_pull_longstring;
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek("'"))
		{
			$self->_pull_shortstring;
		}
		elsif ($self->_peek('"'))
		{
			$self->_pull_shortstring;
		}
		elsif ($IS_SPARQL and $matches = $self->_peek($sparqlKeyword))
		{
			$self->_pull_token($matches->[0], Sparql_Keyword);
		}
		elsif ($IS_SPARQL and $matches = $self->_peek($sparqlFunction))
		{
			$self->_pull_token($matches->[0], Sparql_Function);
		}
		elsif ($IS_SPARQL and $matches = $self->_peek($sparqlAggregate))
		{
			$self->_pull_token($matches->[0], Sparql_Aggregate);
		}
		elsif ($IS_SPARQL and $matches = $self->_peek($sparqlOrdering))
		{
			$self->_pull_token($matches->[0], Sparql_Ordering);
		}
		elsif ($IS_SPARQL and $matches = $self->_peek($sparqlOperator))
		{
			$self->_pull_token($matches->[0], Sparql_Operator);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^(true|false)\b/i))
		{
			$self->_pull_token($matches->[0], Boolean);
		}
		elsif ($ABOVE_NTRIPLES and $self->_peek('a'))
		{
			$self->_pull_token('a', Shorthand);
		}
		elsif ($IS_NOTATION_3 and $matches = $self->_peek(qr/^(=|=>|<=)/))
		{
			$self->_pull_token($matches->[0], Shorthand);
		}
		elsif ($IS_TRIG and $self->_peek("="))
		{
			$self->_pull_token("=", Shorthand);
		}
		elsif ($IS_NOTATION_3 and $matches = $self->_peek(qr/^(is|of)/i))
		{
			$self->_pull_token($matches->[0], IsOf);
		}
		elsif ($ABOVE_NTRIPLES and $matches = $self->_peek(qr/^([$nameStartChar][$nameChar]*)/))
		{
			$self->_pull_token($matches->[0], Name);
		}
		elsif ($matches = $self->_peek(qr/^([^\s\r\n]+)[\s\r\n]/ms))
		{
			$self->_pull_token($matches->[0], Unknown);
		}
		elsif ($matches = $self->_peek(qr/^([^\s\r\n]+)$/ms))
		{
			$self->_pull_token($matches->[0], Unknown);
		}
		else
		{
			Tokenization->throw(
				"Could not tokenise string!",
				remaining => ${ $self->_remaining },
			);
		}
	}
	
	return $self->_tokens;
}

sub _fixup
{
	my $self = shift;
	my ($base) = @_;
	$self->_fixup_urirefs($base);
	$self->_fixup_prefix_declarations;
	$self->_fixup_curies;
}

sub _resolve_uri
{
	shift;
	my ($relative, $base) = @_;
	return $relative unless length $base;
	
	# XXX - cope with situation where $base exists but is relative
	
	require URI;
	"URI"->new_abs(@_)->as_string;
}

sub _fixup_urirefs
{
	my $self = shift;
	my ($base) = @_;
	$base //= "";
	
	my $tokens = $self->_tokens;
	my $i = 0;
	while ($i < @$tokens)
	{
		my $t = $tokens->[$i];
		
		if ($t->isa(URIRef) and not defined $t->absolute_uri)
		{
			$t->absolute_uri($self->_resolve_uri($t->uri, $base));
		}
		elsif ( ($t->isa(Sparql_Keyword) and lc($t->spelling) eq 'base')
		or      ($t->isa(AtRule) and lc($t->spelling) eq '@base') )
		{
			# search ahead for the new base URI
			my $j = 1;
			while ($tokens->[$i+$j]->isa(Comment) || $tokens->[$i+$j]->isa(Whitespace))
			{
				$j++;
				last if !defined $tokens->[$i+$j];
			}
			if (defined $tokens->[$i+$j] and $tokens->[$i+$j]->can("uri"))
			{
				# new base URI found!
				$base = $self->_resolve_uri($tokens->[$i+$j]->uri, $base);
				$i += ($j - 1);
			}
		}
		
		$i++;
	}
}

sub _fixup_prefix_declarations
{
	my $self = shift;
	
	my $tokens = $self->_tokens;
	my $i = 0;
	my $started;
	my @bits;
	while ($i < @$tokens)
	{
		my $t = $tokens->[$i];
		my $is_end;
		
		if ($t->isa(AtRule) and lc($t->spelling) eq '@prefix')
		{
			$started = $i;
			@bits    = $t;
		}
		elsif ($t->isa(Sparql_Keyword) and lc($t->spelling) eq 'PREFIX')
		{
			$started = $i;
			@bits    = $t;
		}
		elsif (defined $started and $t->isa(CURIE) || $t->isa(URIRef))
		{
			push @bits, $t;
		}
		elsif (defined $started and @bits==3 and $t->spelling eq "." and $bits[0]->isa(AtRule))
		{
			$is_end = 1;
		}
		
		if (!$is_end and defined $started and @bits==3 and $bits[0]->isa(Sparql_Keyword))
		{
			$is_end = 1;
		}
		
		if ($is_end)
		{
			my $END   = PrefixDefinition_End->new;
			my $START = PrefixDefinition_Start->new(
				prefix       => $bits[1]->prefix,
				absolute_uri => $bits[2]->absolute_uri,
				end          => $END
			);
			$END->start($START);
			
			$bits[1]->absolute_uri($bits[2]->absolute_uri);
			
			splice(@$tokens, $started, 0, $START); $i++;
			splice(@$tokens, $i+1,     0, $END); $i++;
		}
		
		$i++;
	}
}

sub _fixup_curies
{
	my $self = shift;
	
	my $map    = {};
	my $tokens = $self->_tokens;
	
	for my $t (@$tokens)
	{
		if ($t->isa(PrefixDefinition_End))
		{
			$map->{ $t->start->prefix } = $t->start->absolute_uri;
		}
		elsif ($t->isa(CURIE) and defined $t->prefix and exists $map->{$t->prefix})
		{
			$t->absolute_uri($map->{$t->prefix} . ($t->suffix//""));
		}
	}
}

sub highlight
{
	my $self = shift;
	ref $self or WrongInvocant->throw("this is an object method!");
	
	my ($text, $base) = @_;
	
	$self->tokenize($text);
	$self->_fixup($base);
	
	return join "", map $_->TO_HTML, @{$self->_tokens};
}

{
	package Syntax::Highlight::RDF::NTriples;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES;
}

{
	package Syntax::Highlight::RDF::Turtle;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES
	                  |  Syntax::Highlight::RDF::MODE_TURTLE;
}

{
	package Syntax::Highlight::RDF::Notation_3;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES
	                  |  Syntax::Highlight::RDF::MODE_TURTLE
	                  |  Syntax::Highlight::RDF::MODE_NOTATION_3;
}

{
	package Syntax::Highlight::RDF::SPARQL_Query;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES
	                  |  Syntax::Highlight::RDF::MODE_TURTLE
	                  |  Syntax::Highlight::RDF::MODE_SPARQL;
}

{
	package Syntax::Highlight::RDF::SPARQL_Update;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES
	                  |  Syntax::Highlight::RDF::MODE_TURTLE
	                  |  Syntax::Highlight::RDF::MODE_SPARQL;
}

{
	package Syntax::Highlight::RDF::Pretdsl;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES
	                  |  Syntax::Highlight::RDF::MODE_TURTLE
	                  |  Syntax::Highlight::RDF::MODE_NOTATION_3
	                  |  Syntax::Highlight::RDF::MODE_PRETDSL;
}

{
	package Syntax::Highlight::RDF::NQuads;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES;
}

{
	package Syntax::Highlight::RDF::TriG;
	use Moo;
	extends "Syntax::Highlight::RDF";
	use constant mode => Syntax::Highlight::RDF::MODE_NTRIPLES
	                  |  Syntax::Highlight::RDF::MODE_TURTLE
	                  |  Syntax::Highlight::RDF::MODE_TRIG;
}

sub highlighter
{
	my $class = shift;
	$class eq __PACKAGE__ or WrongInvocant->throw("this is a factory method!");
	
	my ($hint) = @_;
	
	$hint =~ m{xml}i and do {
		require Syntax::Highlight::XML;
		return "Syntax::Highlight::XML"->new;
	};
	
	$hint =~ m{json}i and do {
		require Syntax::Highlight::JSON2;
		return "Syntax::Highlight::JSON2"->new;
	};
	
	$hint =~ m{(ttl|turtle)}i       and return "$class\::Turtle"->new;
	$hint =~ m{(nt|n.?triples)}i    and return "$class\::NTriples"->new;
	$hint =~ m{(nq|n.?quads)}i      and return "$class\::NQuads"->new;
	$hint =~ m{(trig)}i             and return "$class\::TriG"->new;
	$hint =~ m{(n3|notation.?3)}i   and return "$class\::Notation_3"->new;
	$hint =~ m{(pret)}i             and return "$class\::Pretdsl"->new;
	$hint =~ m{(sparql.?update)}i   and return "$class\::SPARQL_Update"->new;
	$hint =~ m{(sparql)}i           and return "$class\::SPARQL_Query"->new;
	$hint =~ m{(text/plain)}i       and return "$class\::NTriples"->new;
	
	return $class->new;
}

1;

__END__

=pod

=encoding utf-8

=head1 NAME

Syntax::Highlight::RDF - syntax highlighting for various RDF-related formats

=head1 SYNOPSIS

  use Syntax::Highlight::RDF;
  my $syntax = "Syntax::Highlight::RDF"->highlighter("Turtle");
  print $syntax->highlight($filehandle);

=head1 DESCRIPTION

Outputs pretty syntax-highlighted HTML for RDF-related formats. (Actually just
adds C<< <span> >> elements with C<< class >> attributes. You're expected to
bring your own CSS.

=head2 Formats

=over

=item *

N-Triples

=item *

N-Quads

=item *

Turtle

=item *

TriG

=item *

Notation 3

=item *

SPARQL Query 1.1 (but not property paths yet)

=item *

SPARQL Update 1.1 (but not property paths yet)

=item *

JSON - intended for RDF/JSON and SPARQL Results JSON, but just generic highlighting

=item *

XML - intended for RDF/XML and SPARQL Results XML, but just generic highlighting

=back

=head2 Methods

=over

=item C<< highlighter($format) >>

Factory method; generally preferred over calling C<new> on a specific
class.

  "Syntax::Highlight::RDF"->highlighter("Turtle");
  "Syntax::Highlight::RDF::Turtle"->new;  # avoid!

=item C<< highlight($input, $base) >>

Highlight some RDF.

C<< $input >> may be a file handle, filename or a scalar ref of text.
C<< $base >> is an optional base for resolving relative URIs.

Returns a string of HTML.

=item C<< tokenize($input) >>

This is mostly intended for subclassing Syntax::Highlight::RDF.

C<< $input >> may be a file handle, filename or a scalar ref of text.

Returns an arrayref of token objects. The exact API for the token objects
is subject to change, but currently they support C<< TYPE >> and
C<< spelling >> methods.

=back

=head1 BUGS

Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=Syntax-Highlight-RDF>.

=head1 SEE ALSO

L<PPI::HTML>,
L<Syntax::Highlight::Engine::Kate>.

L<RDF::Trine>, L<RDF::Query>.

L<http://www.perlrdf.org/>.

=head1 AUTHOR

Toby Inkster E<lt>tobyink@cpan.orgE<gt>.

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2013 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.