This file is indexed.

/usr/lib/swi-prolog/library/http/json.pl is in swi-prolog-nox 7.2.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (C): 1985-2014, University of Amsterdam
			      VU University Amsterdam

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    As a special exception, if you link this library with other files,
    compiled with a Free Software compiler, to produce an executable, this
    library does not by itself cause the resulting executable to be covered
    by the GNU General Public License. This exception does not however
    invalidate any other reasons why the executable file might be covered by
    the GNU General Public License.
*/

:- if(current_predicate(is_dict/1)).

:- module(json,
	  [ json_read/2,		% +Stream, -JSONTerm
	    json_read/3,		% +Stream, -JSONTerm, +Options
	    atom_json_term/3,		% ?Atom, ?JSONTerm, +Options
	    json_write/2,		% +Stream, +Term
	    json_write/3,		% +Stream, +Term, +Options
	    is_json_term/1,		% @Term
	    is_json_term/2,		% @Term, +Options
					% Version 7 dict support
	    json_read_dict/2,		% +Stream, -Dict
	    json_read_dict/3,		% +Stream, -Dict, +Options
	    json_write_dict/2,		% +Stream, +Dict
	    json_write_dict/3,		% +Stream, +Dict, +Options
	    atom_json_dict/3		% ?Atom, ?JSONDict, +Options
	  ]).

:- else.

:- module(json,
	  [ json_read/2,		% +Stream, -JSONTerm
	    json_read/3,		% +Stream, -JSONTerm, +Options
	    atom_json_term/3,		% ?Atom, ?JSONTerm, +Options
	    json_write/2,		% +Stream, +Term
	    json_write/3,		% +Stream, +Term, +Options
	    is_json_term/1,		% @Term
	    is_json_term/2
	  ]).

:- endif.

:- use_module(library(record)).
:- use_module(library(memfile)).
:- use_module(library(error)).
:- use_module(library(option)).

:- use_foreign_library(foreign(json)).

:- predicate_options(json_read/3, 3,
		     [ null(ground),
		       true(ground),
		       false(ground),
		       value_string_as(oneof([atom,string]))
		     ]).
:- predicate_options(json_write/3, 3,
		     [ indent(nonneg),
		       step(positive_integer),
		       tab(positive_integer),
		       width(nonneg),
		       null(ground),
		       true(ground),
		       false(ground),
		       serialize_unknown(boolean)
		     ]).
:- predicate_options(json_read_dict/3, 3,
		     [ tag(atom),
		       pass_to(json_read/3, 3)
		     ]).
:- predicate_options(json_write_dict/3, 3,
		     [ tag(atom),
		       pass_to(json_write/3, 3)
		     ]).
:- predicate_options(is_json_term/2, 2,
		     [ null(ground),
		       true(ground),
		       false(ground)
		     ]).
:- predicate_options(atom_json_term/3, 3,
		     [ as(oneof([atom,string,codes])),
		       pass_to(json_read/3, 3),
		       pass_to(json_write/3, 3)
		     ]).

/** <module> Reading and writing JSON serialization

This module supports reading and  writing   JSON  objects.  This library
supports two Prolog representations (the   _new_  representation is only
supported in SWI-Prolog version 7 and later):

  - The *classical* representation is provided by json_read/3 and
    json_write/3.  This represents a JSON object as json(NameValueList),
    a JSON string as an atom and the JSON constants =null=, =true= and
    =false= as @(null), @(true) and @false.

  - The *new* representation is provided by json_read_dict/3 and
    json_write_dict/3. This represents a JSON object as a dict, a JSON
    string as a Prolog string and the JSON constants using the Prolog
    atoms =null=, =true= and =false=.

@author Jan Wielemaker
@see	http_json.pl links JSON to the HTTP client and server modules.
@see	json_convert.pl converts JSON Prolog terms to more comfortable
terms.
*/

:- record json_options(null:ground = @(null),
		       true:ground = @(true),
		       false:ground = @(false),
		       value_string_as:oneof([atom,string]) = atom,
		       tag:atom = '').

default_json_dict_options(
    json_options(null, true, false, string, '')).


		 /*******************************
		 *	 MAP TO/FROM TEXT	*
		 *******************************/

%%	atom_json_term(+Atom, -JSONTerm, +Options) is det.
%%	atom_json_term(-Text, +JSONTerm, +Options) is det.
%
%	Convert between textual  representation  and   a  JSON  term. In
%	_write_ mode, the option
%
%	    * as(Type)
%	    defines the output type, which is one of =atom=,
%	    =string= or =codes=.

atom_json_term(Atom, Term, Options) :-
	ground(Atom), !,
	setup_call_cleanup(
	    ( atom_to_memory_file(Atom, MF),
	      open_memory_file(MF, read, In, [free_on_close(true)])
	    ),
	    json_read(In, Term, Options),
	    close(In)).
atom_json_term(Result, Term, Options) :-
	select_option(as(Type), Options, Options1),
	(   type_term(Type, Result, Out)
	->  true
	;   must_be(oneof([atom,string,codes]), Type)
	),
	with_output_to(Out,
		       json_write(current_output, Term, Options1)).

type_term(atom,   Result, atom(Result)).
type_term(string, Result, string(Result)).
type_term(codes,  Result, codes(Result)).


		 /*******************************
		 *	     READING		*
		 *******************************/

%%	json_read(+Stream, -Term) is det.
%%	json_read(+Stream, -Term, +Options) is det.
%
%	Read next JSON value from Stream into a Prolog term. The
%	canonical representation for Term is:
%
%	  * A JSON object is mapped to a term json(NameValueList), where
%	    NameValueList is a list of Name=Value. Name is an atom
%	    created from the JSON string.
%
%	  * A JSON array is mapped to a Prolog list of JSON values.
%
%	  * A JSON string is mapped to a Prolog atom
%
%	  * A JSON number is mapped to a Prolog number
%
%	  * The JSON constants =true= and =false= are mapped -like JPL-
%	    to @(true) and @(false).
%
%	  * The JSON constant =null= is mapped to the Prolog term
%	    @(null)
%
%	Here is a complete example in  JSON and its corresponding Prolog
%	term.
%
%	  ==
%	  { "name":"Demo term",
%	    "created": {
%	      "day":null,
%	      "month":"December",
%	      "year":2007
%	    },
%	    "confirmed":true,
%	    "members":[1,2,3]
%	  }
%	  ==
%
%	  ==
%	  json([ name='Demo term',
%	         created=json([day= @null, month='December', year=2007]),
%	         confirmed= @true,
%	         members=[1, 2, 3]
%	       ])
%	  ==
%
%	The following options are processed:
%
%		* null(NullTerm)
%		Term used to represent JSON =null=.  Default @(null)
%		* true(TrueTerm)
%		Term used to represent JSON =true=.  Default @(true)
%		* false(FalsTerm)
%		Term used to represent JSON =false=.  Default @(false)
%		* value_string_as(Type)
%		Prolog type used for strings used as value.  Default
%		is =atom=.  The alternative is =string=, producing a
%		packed string object.  Please note that =codes= or
%		=chars= would produce ambiguous output and is therefore
%		not supported.
%
%	If json_read/3 encounters end-of-file before any real data it
%	binds Term to the term @(end_of_file).
%
%	@see	json_read_dict/3 to read a JSON term using the version 7
%		extended data types.

json_read(Stream, Term) :-
	default_json_options(Options),
	(   json_value(Stream, Term, _, Options)
	->  true
	;   syntax_error(illegal_json, Stream)
	).
json_read(Stream, Term, Options) :-
	make_json_options(Options, OptionTerm, _RestOptions),
	(   json_value(Stream, Term, _, OptionTerm)
	->  true
	;   syntax_error(illegal_json, Stream)
	).

json_value(Stream, Term, Next, Options) :-
	get_code(Stream, C0),
	ws(C0, Stream, C1),
	(   C1 == -1
	->  Term = @(end_of_file),
	    Next = -1
	;   json_term(C1, Stream, Term, Next, Options)
	).

json_term(0'{, Stream, json(Pairs), Next, Options) :- !,
	ws(Stream, C),
	json_pairs(C, Stream, Pairs, Options),
	get_code(Stream, Next).
json_term(0'[, Stream, Array, Next, Options) :- !,
	ws(Stream, C),
	json_array(C, Stream, Array, Options),
	get_code(Stream, Next).
json_term(0'", Stream, String, Next, Options) :- !,
	get_code(Stream, C1),
	json_string_codes(C1, Stream, Codes),
	json_options_value_string_as(Options, Type),
	codes_to_type(Type, Codes, String),
	get_code(Stream, Next).
json_term(0'-, Stream, Number, Next, _Options) :- !,
	json_number_codes(Stream, Codes, Next),
	number_codes(Number, [0'-|Codes]).
json_term(D, Stream, Number, Next, _Options) :-
	between(0'0, 0'9, D), !,
	json_number_codes(Stream, Codes, Next),
	number_codes(Number, [D|Codes]).
json_term(C, Stream, Constant, Next, Options) :-
	get_code(Stream, C1),
	json_identifier_codes(C1, Stream, Codes, Next),
	atom_codes(ID, [C|Codes]),
	json_constant(ID, Constant, Options).

json_pairs(0'}, _, [], _) :- !.
json_pairs(C0, Stream, [Pair|Tail], Options) :-
	json_pair(C0, Stream, Pair, C, Options),
	ws(C, Stream, Next),
	(   Next == 0',
	->  ws(Stream, C2),
	    json_pairs(C2, Stream, Tail, Options)
	;   Next == 0'}
	->  Tail = []
	;   syntax_error(illegal_object, Stream)
	).

json_pair(C0, Stream, Name=Value, Next, Options) :-
	json_string_as_atom(C0, Stream, Name),
	ws(Stream, C),
	C == 0':,
	json_value(Stream, Value, Next, Options).


json_array(0'], _, [], _) :- !.
json_array(C0, Stream, [Value|Tail], Options) :-
	json_term(C0, Stream, Value, C, Options),
	ws(C, Stream, Next),
	(   Next == 0',
	->  ws(Stream, C1),
	    json_array(C1, Stream, Tail, Options)
	;   Next == 0']
	->  Tail = []
	;   syntax_error(illegal_array, Stream)
	).

codes_to_type(atom, Codes, Atom) :-
	atom_codes(Atom, Codes).
codes_to_type(string, Codes, Atom) :-
	string_codes(Atom, Codes).
codes_to_type(codes, Codes, Codes).

json_string_as_atom(0'", Stream, Atom) :-
	get_code(Stream, C1),
	json_string_codes(C1, Stream, Codes),
	atom_codes(Atom, Codes).

json_string_codes(0'", _, []) :- !.
json_string_codes(0'\\, Stream, [H|T]) :- !,
	get_code(Stream, C0),
	(   escape(C0, Stream, H)
	->  true
	;   syntax_error(illegal_string_escape, Stream)
	),
	get_code(Stream, C1),
	json_string_codes(C1, Stream, T).
json_string_codes(-1, Stream, _) :- !,
	syntax_error(eof_in_string, Stream).
json_string_codes(C, Stream, [C|T]) :-
	get_code(Stream, C1),
	json_string_codes(C1, Stream, T).

escape(0'", _, 0'") :- !.
escape(0'\\, _, 0'\\) :- !.
escape(0'/, _, 0'/) :- !.
escape(0'b, _, 0'\b) :- !.
escape(0'f, _, 0'\f) :- !.
escape(0'n, _, 0'\n) :- !.
escape(0'r, _, 0'\r) :- !.
escape(0't, _, 0'\t) :- !.
escape(0'u, Stream, C) :- !,
	get_code(Stream, C1),
	get_code(Stream, C2),
	get_code(Stream, C3),
	get_code(Stream, C4),
	code_type(C1, xdigit(D1)),
	code_type(C2, xdigit(D2)),
	code_type(C3, xdigit(D3)),
	code_type(C4, xdigit(D4)),
	C is D1<<12+D2<<8+D3<<4+D4.

json_number_codes(Stream, Codes, Next) :-
	get_code(Stream, C1),
	json_number_codes(C1, Stream, Codes, Next).

json_number_codes(C1, Stream, [C1|Codes], Next) :-
	number_code(C1), !,
	get_code(Stream, C2),
	json_number_codes(C2, Stream, Codes, Next).
json_number_codes(C, _, [], C).

number_code(C) :-
	between(0'0, 0'9, C), !.
number_code(0'.).
number_code(0'-).
number_code(0'e).
number_code(0'E).

json_identifier_codes(C1, Stream, [C1|T], Next) :-
	between(0'a, 0'z, C1), !,
	get_code(Stream, C2),
	json_identifier_codes(C2, Stream, T, Next).
json_identifier_codes(C, _, [], C).


json_constant(true, Constant, Options) :- !,
	json_options_true(Options, Constant).
json_constant(false, Constant, Options) :- !,
	json_options_false(Options, Constant).
json_constant(null, Constant, Options) :- !,
	json_options_null(Options, Constant).

%%	ws(+Stream, -Next) is det.
%%	ws(+C0, +Stream, -Next)
%
%	Skip white space on the Stream, returning the first non-ws
%	character.  Also skips =|//|= ... comments.

ws(Stream, Next) :-
	get_code(Stream, C0),
	ws(C0, Stream, Next).

ws(C0, Stream, C) :-
	ws(C0), !,
	get_code(Stream, C1),
	ws(C1, Stream, C).
ws(0'/, Stream, C) :- !,
	get_code(Stream, Cmt1), !,
	expect(Cmt1, 0'/, Stream),
	skip(Stream, 0'\n),
	get_code(Stream, C0),
	ws(C0, Stream, C).
ws(C, _, C).

ws(0' ).
ws(0'\t).
ws(0'\n).
ws(0'\r).

expect(C, C, _) :- !.
expect(_, 0'/, Stream) :- !,
	syntax_error(illegal_comment, Stream).

syntax_error(Message, Stream) :-
	stream_error_context(Stream, Context),
	throw(error(syntax_error(json(Message)), Context)).

stream_error_context(Stream, stream(Stream, Line, LinePos, CharNo)) :-
	character_count(Stream, CharNo),
	line_position(Stream, LinePos),
	line_count(Stream, Line).


		 /*******************************
		 *	    JSON OUTPUT		*
		 *******************************/

%%	json_write_string(+Stream, +Text) is det.
%
%	Write a JSON string to  Stream.  Stream   must  be  opened  in a
%	Unicode capable encoding, typically UTF-8.

% foreign json_write_string/2.

%%	json_write_indent(+Stream, +Indent, +TabDistance) is det.
%
%	Newline and indent to  Indent.  A   Newline  is  only written if
%	line_position(Stream, Pos) is not 0. Then   it  writes Indent //
%	TabDistance tab characters and Indent mode TabDistance spaces.

% foreign json_write_indent/3.

%%	json_write(+Stream, +Term) is det.
%%	json_write(+Stream, +Term, +Options) is det.
%
%	Write a JSON term to Stream.  The   JSON  object  is of the same
%	format as produced by json_read/2, though we allow for some more
%	flexibility with regard to pairs in  objects. All of Name=Value,
%	Name-Value and Name(Value) produce the  same output.
%
%	Values can be of the form  #(Term),   which  causes `Term` to be
%	_stringified_ if it is not an atom or string. Stringification is
%	based on term_string/2.
%
%	The version 7 _dict_ type is supported as well. If the dicts has
%	a _tag_, a property "type":"tag" is   added  to the object. This
%	behaviour can be changed using the =tag= option (see below). For
%	example:
%
%	  ==
%	  ?- json_write(current_output, point{x:1,y:2}).
%	  {
%	    "type":"point",
%	    "x":1,
%	    "y":2
%	  }
%	  ==
%
%	In addition to the options recognised by json_read/3, we process
%	the following options are recognised:
%
%	    * width(+Width)
%	    Width in which we try to format the result.  Too long lines
%	    switch from _horizontal_ to _vertical_ layout for better
%	    readability. If performance is critical and human
%	    readability is not an issue use Width = 0, which causes a
%	    single-line output.
%
%	    * step(+Step)
%	    Indentation increnment for next level.  Default is 2.
%
%	    * tab(+TabDistance)
%	    Distance between tab-stops.  If equal to Step, layout
%	    is generated with one tab per level.
%
%	    * serialize_unknown(+Boolean)
%	    If =true= (default =false=), serialize unknown terms and
%	    print them as a JSON string.  The default raises a type
%	    error.  Note that this option only makes sense if you can
%	    guarantee that the passed value is not an otherwise valid
%	    Prolog reporesentation of a Prolog term.
%
%	If a string is  emitted,  the   sequence  =|</|=  is  emitted as
%	=|<\/|=. This is valid  JSON  syntax   which  ensures  that JSON
%	objects  can  be  safely  embedded  into  an  HTML  =|<script>|=
%	element.

:- record json_write_state(indent:nonneg = 0,
			   step:positive_integer = 2,
			   tab:positive_integer = 8,
			   width:nonneg = 72,
			   serialize_unknown:boolean = false
			  ).

json_write(Stream, Term) :-
	json_write(Stream, Term, []).
json_write(Stream, Term, Options) :-
	make_json_write_state(Options, State, Options1),
	make_json_options(Options1, OptionTerm, _RestOptions),
	json_write_term(Term, Stream, State, OptionTerm).

json_write_term(Var, _, _, _) :-
	var(Var), !,
	instantiation_error(Var).
json_write_term(json(Pairs), Stream, State, Options) :- !,
	json_write_object(Pairs, Stream, State, Options).
:- if(current_predicate(is_dict/1)).
json_write_term(Dict, Stream, State, Options) :-
	is_dict(Dict), !,
	dict_pairs(Dict, Tag, Pairs0),
	(   nonvar(Tag),
	    json_options_tag(Options, Name),
	    Name \== ''
	->  Pairs = [Name-Tag|Pairs0]
	;   Pairs = Pairs0
	),
	json_write_object(Pairs, Stream, State, Options).
:- endif.
json_write_term(List, Stream, State, Options) :-
	is_list(List), !,
	space_if_not_at_left_margin(Stream, State),
	write(Stream, '['),
	(   json_write_state_width(State, Width),
	    (   Width == 0
	    ->  true
	    ;   json_write_state_indent(State, Indent),
		json_print_length(List, Options, Width, Indent, _)
	    )
	->  set_width_of_json_write_state(0, State, State2),
	    write_array_hor(List, Stream, State2, Options),
	    write(Stream, ']')
	;   step_indent(State, State2),
	    write_array_ver(List, Stream, State2, Options),
	    indent(Stream, State),
	    write(Stream, ']')
	).
json_write_term(Number, Stream, _State, _Options) :-
	number(Number), !,
	write(Stream, Number).
json_write_term(True, Stream, _State, Options) :-
	json_options_true(Options, True), !,
	write(Stream, true).
json_write_term(False, Stream, _State, Options) :-
	json_options_false(Options, False), !,
	write(Stream, false).
json_write_term(Null, Stream, _State, Options) :-
	json_options_null(Options, Null), !,
	write(Stream, null).
json_write_term(#(Text), Stream, _State, _Options) :- !,
	(   (   atom(Text)
	    ;	string(Text)
	    )
	->  json_write_string(Stream, Text)
	;   term_string(Text, String),
	    json_write_string(Stream, String)
	).
json_write_term(String, Stream, _State, _Options) :-
	atom(String), !,
	json_write_string(Stream, String).
json_write_term(String, Stream, _State, _Options) :-
	string(String), !,
	json_write_string(Stream, String).
json_write_term(AnyTerm, Stream, State, _Options) :-
	(   json_write_state_serialize_unknown(State, true)
	->  term_string(AnyTerm, String),
	    json_write_string(Stream, String)
	;   type_error(json_term, AnyTerm)
	).

json_write_object(Pairs, Stream, State, Options) :-
	space_if_not_at_left_margin(Stream, State),
	write(Stream, '{'),
	(   json_write_state_width(State, Width),
	    (   Width == 0
	    ->  true
	    ;   json_write_state_indent(State, Indent),
		json_print_length(json(Pairs), Options, Width, Indent, _)
	    )
	->  set_width_of_json_write_state(0, State, State2),
	    write_pairs_hor(Pairs, Stream, State2, Options),
	    write(Stream, '}')
	;   step_indent(State, State2),
	    write_pairs_ver(Pairs, Stream, State2, Options),
	    indent(Stream, State),
	    write(Stream, '}')
	).


write_pairs_hor([], _, _, _).
write_pairs_hor([H|T], Stream, State, Options) :-
	json_pair(H, Name, Value),
	json_write_string(Stream, Name),
	write(Stream, ':'),
	json_write_term(Value, Stream, State, Options),
	(   T == []
	->  true
	;   write(Stream, ', '),
	    write_pairs_hor(T, Stream, State, Options)
	).

write_pairs_ver([], _, _, _).
write_pairs_ver([H|T], Stream, State, Options) :-
	indent(Stream, State),
	json_pair(H, Name, Value),
	json_write_string(Stream, Name),
	write(Stream, ':'),
	json_write_term(Value, Stream, State, Options),
	(   T == []
	->  true
	;   write(Stream, ','),
	    write_pairs_ver(T, Stream, State, Options)
	).


json_pair(Var, _, _) :-
	var(Var), !,
	instantiation_error(Var).
json_pair(Name=Value, Name, Value) :- !.
json_pair(Name-Value, Name, Value) :- !.
json_pair(NameValue, Name, Value) :-
	compound(NameValue),
	NameValue =.. [Name, Value], !.
json_pair(Pair, _, _) :-
	type_error(json_pair, Pair).


write_array_hor([], _, _, _).
write_array_hor([H|T], Stream, State, Options) :-
	json_write_term(H, Stream, State, Options),
	(   T == []
	->  write(Stream, ' ')
	;   write(Stream, ', '),
	    write_array_hor(T, Stream, State, Options)
	).

write_array_ver([], _, _, _).
write_array_ver([H|T], Stream, State, Options) :-
	indent(Stream, State),
	json_write_term(H, Stream, State, Options),
	(   T == []
	->  true
	;   write(Stream, ','),
	    write_array_ver(T, Stream, State, Options)
	).


indent(Stream, State) :-
	json_write_state_indent(State, Indent),
	json_write_state_tab(State, Tab),
	json_write_indent(Stream, Indent, Tab).

step_indent(State0, State) :-
	json_write_state_indent(State0, Indent),
	json_write_state_step(State0, Step),
	NewIndent is Indent+Step,
	set_indent_of_json_write_state(NewIndent, State0, State).

space_if_not_at_left_margin(Stream, State) :-
	line_position(Stream, LinePos),
	(   LinePos == 0
	;   json_write_state_indent(State, LinePos)
	), !.
space_if_not_at_left_margin(Stream, _) :-
	put_char(Stream, ' ').


%%	json_print_length(+Value, +Options, +Max, +Len0, +Len) is semidet.
%
%	True if Len-Len0 is the print-length of Value on a single line
%	and Len-Len0 =< Max.
%
%	@tbd	Escape sequences in strings are not considered.

json_print_length(json(Pairs), Options, Max, Len0, Len) :- !,
	Len1 is Len0 + 2,
	Len1 =< Max,
	pairs_print_length(Pairs, Options, Max, Len1, Len).
:- if(current_predicate(is_dict/1)).
json_print_length(Dict, Options, Max, Len0, Len) :-
	is_dict(Dict), !,
	dict_pairs(Dict, _Tag, Pairs),
	Len1 is Len0 + 2,
	Len1 =< Max,
	pairs_print_length(Pairs, Options, Max, Len1, Len).
:- endif.
json_print_length(Array, Options, Max, Len0, Len) :-
	is_list(Array), !,
	Len1 is Len0 + 2,
	Len1 =< Max,
	array_print_length(Array, Options, Max, Len1, Len).
json_print_length(Null, Options, Max, Len0, Len) :-
	json_options_null(Options, Null), !,
	Len is Len0 + 4,
	Len =< Max.
json_print_length(False, Options, Max, Len0, Len) :-
	json_options_false(Options, False), !,
	Len is Len0 + 5,
	Len =< Max.
json_print_length(True, Options, Max, Len0, Len) :-
	json_options_true(Options, True), !,
	Len is Len0 + 4,
	Len =< Max.
json_print_length(Number, _Options, Max, Len0, Len) :-
	number(Number), !,
	write_length(Number, AL, []),
	Len is Len0 + AL,
	Len =< Max.
json_print_length(@(Id), _Options, Max, Len0, Len) :-
	atom(Id), !,
	atom_length(Id, IdLen),
	Len is Len0+IdLen,
	Len =< Max.
json_print_length(String, _Options, Max, Len0, Len) :-
	string_len(String, Len0, Len), !,
	Len =< Max.
json_print_length(AnyTerm, _Options, Max, Len0, Len) :-
	write_length(AnyTerm, AL, []),		% will be serialized
	Len is Len0 + AL+2,
	Len =< Max.

pairs_print_length([], _, _, Len, Len).
pairs_print_length([H|T], Options, Max, Len0, Len) :-
	pair_len(H, Options, Max, Len0, Len1),
	(   T == []
	->  Len = Len1
	;   Len2 is Len1 + 2,
	    Len2 =< Max,
	    pairs_print_length(T, Options, Max, Len2, Len)
	).

pair_len(Pair, Options, Max, Len0, Len) :-
	pair_nv(Pair, Name, Value),
	string_len(Name, Len0, Len1),
	Len2 is Len1+2,
	Len2 =< Max,
	json_print_length(Value, Options, Max, Len2, Len).

pair_nv(Name=Value, Name, Value).
pair_nv(Name-Value, Name, Value).

array_print_length([], _, _, Len, Len).
array_print_length([H|T], Options, Max, Len0, Len) :-
	json_print_length(H, Options, Max, Len0, Len1),
	(   T == []
	->  Len = Len1
	;   Len2 is Len1+2,
	    Len2 =< Max,
	    array_print_length(T, Options, Max, Len2, Len)
	).

string_len(String, Len0, Len) :-
	atom(String), !,
	atom_length(String, AL),
	Len is Len0 + AL + 2.
string_len(String, Len0, Len) :-
	string(String), !,
	string_length(String, AL),
	Len is Len0 + AL + 2.


		 /*******************************
		 *	       TEST		*
		 *******************************/

%%	is_json_term(@Term) is semidet.
%%	is_json_term(@Term, +Options) is semidet.
%
%	True if Term is  a  json  term.   Options  are  the  same as for
%	json_read/2, defining the Prolog  representation   for  the JSON
%	=true=, =false= and =null= constants.

is_json_term(Term) :-
	default_json_options(Options),
	is_json_term2(Options, Term).

is_json_term(Term, Options) :-
	make_json_options(Options, OptionTerm, _RestOptions),
	is_json_term2(OptionTerm, Term).

is_json_term2(_, Var) :-
	var(Var), !, fail.
is_json_term2(Options, json(Pairs)) :- !,
	is_list(Pairs),
	maplist(is_json_pair(Options), Pairs).
is_json_term2(Options, List) :-
	is_list(List), !,
	maplist(is_json_term2(Options), List).
is_json_term2(_, Primitive) :-
	atomic(Primitive), !.		% atom, string or number
is_json_term2(Options, True) :-
	json_options_true(Options, True).
is_json_term2(Options, False) :-
	json_options_false(Options, False).
is_json_term2(Options, Null) :-
	json_options_null(Options, Null).

is_json_pair(_, Var) :-
	var(Var), !, fail.
is_json_pair(Options, Name=Value) :-
	atom(Name),
	is_json_term2(Options, Value).

:- if(current_predicate(is_dict/1)).

		 /*******************************
		 *	   DICT SUPPORT		*
		 *******************************/

%%	json_read_dict(+Stream, -Dict) is det.
%%	json_read_dict(+Stream, -Dict, +Options) is det.
%
%	Read  a  JSON  object,  returning  objects    as  a  dicts.  The
%	representation depends on the options, where the default is:
%
%	  * String values are mapped to Prolog strings
%	  * JSON =true=, =false= and =null= are represented using these
%	    Prolog atoms.
%	  * JSON objects are mapped to dicts.
%	  * By default, a =type= field in an object assigns a tag for
%	    the dict.
%
%	On  addition  to  the   options    processed   by   json_read/3,
%	json_read_dict/3 processes this additional option:
%
%	  * tag(+Name)
%	    When converting to/from a dict, map the indicated JSON
%	    attribute to the dict _tag_. No mapping is performed if Name
%	    is the empty atom ('', default). See json_read_dict/2 and
%	    json_write_dict/2.

json_read_dict(Stream, Dict) :-
	json_read_dict(Stream, Dict, []).

json_read_dict(Stream, Dict, Options) :-
	make_json_dict_options(Options, OptionTerm, _RestOptions),
	json_value(Stream, Term, _, OptionTerm),
	term_to_dict(Term, Dict, OptionTerm).

term_to_dict(json(Pairs), Dict, Options) :- !,
	(   json_options_tag(Options, TagName),
	    Tag \== '',
	    select(TagName = Tag0, Pairs, NVPairs),
	    to_atom(Tag0, Tag)
	->  json_dict_pairs(NVPairs, DictPairs, Options)
	;   json_dict_pairs(Pairs, DictPairs, Options)
	),
	dict_create(Dict, Tag, DictPairs).
term_to_dict(Value0, Value, _Options) :-
	atomic(Value0), Value0 \== [], !,
	Value = Value0.
term_to_dict(List0, List, Options) :-
	assertion(is_list(List0)),
	terms_to_dicts(List0, List, Options).

json_dict_pairs([], [], _).
json_dict_pairs([Name=Value0|T0], [Name=Value|T], Options) :-
	term_to_dict(Value0, Value, Options),
	json_dict_pairs(T0, T, Options).

terms_to_dicts([], [], _).
terms_to_dicts([Value0|T0], [Value|T], Options) :-
	term_to_dict(Value0, Value, Options),
	terms_to_dicts(T0, T, Options).

to_atom(Tag, Atom) :-
	string(Tag), !,
	atom_string(Atom, Tag).
to_atom(Atom, Atom) :-
	atom(Atom).

%%	json_write_dict(+Stream, +Dict) is det.
%%	json_write_dict(+Stream, +Dict, +Options) is det.
%
%	Write a JSON term, represented using dicts.  This is the same as
%	json_write/3, but assuming the default   representation  of JSON
%	objects as dicts.

json_write_dict(Stream, Dict) :-
	json_write_dict(Stream, Dict, []).

json_write_dict(Stream, Dict, Options) :-
	make_json_write_state(Options, State, Options1),
	make_json_dict_options(Options1, OptionTerm, _RestOptions),
	json_write_term(Dict, Stream, State, OptionTerm).


make_json_dict_options(Options, Record, RestOptions) :-
	default_json_dict_options(Record0),
	set_json_options_fields(Options, Record0, Record, RestOptions).

%%	atom_json_dict(+Atom, -JSONDict, +Options) is det.
%%	atom_json_dict(-Text, +JSONDict, +Options) is det.
%
%	Convert  between  textual  representation  and    a   JSON  term
%	represented as a dict. Options are as for json_read/3.
%	In _write_ mode, the addtional option
%
%	    * as(Type)
%	    defines the output type, which is one of =atom=,
%	    =string= or =codes=.

atom_json_dict(Atom, Term, Options) :-
	ground(Atom), !,
	setup_call_cleanup(
	    ( atom_to_memory_file(Atom, MF),
	      open_memory_file(MF, read, In, [free_on_close(true)])
	    ),
	    json_read_dict(In, Term, Options),
	    close(In)).
atom_json_dict(Result, Term, Options) :-
	select_option(as(Type), Options, Options1, atom),
	(   type_term(Type, Result, Out)
	->  true
	;   must_be(oneof([atom,string,codes]), Type)
	),
	with_output_to(Out,
		       json_write_dict(current_output, Term, Options1)).

:- endif.

		 /*******************************
		 *	     MESSAGES		*
		 *******************************/

:- multifile
	prolog:error_message/3.

prolog:error_message(syntax_error(json(Id))) -->
	[ 'JSON syntax error: ' ],
	json_syntax_error(Id).

json_syntax_error(illegal_comment) -->
	[ 'Illegal comment' ].
json_syntax_error(illegal_string_escape) -->
	[ 'Illegal escape sequence in string' ].