-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
repoint.sml
3100 lines (2731 loc) · 121 KB
/
repoint.sml
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
(*
DO NOT EDIT THIS FILE.
This file is automatically generated from the individual
source files in the Repoint repository.
*)
(*
Repoint
A simple manager for third-party source code dependencies
Copyright 2017-2021 Chris Cannam, Particular Programs Ltd,
and Queen Mary, University of London
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the names of Chris Cannam,
Particular Programs Ltd, and Queen Mary, University of London
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in this Software without prior written
authorization.
*)
val repoint_version = "1.5"
datatype vcs =
HG |
GIT |
SVN
datatype source =
URL_SOURCE of string |
SERVICE_SOURCE of {
service : string,
owner : string option,
repo : string option
}
type id_or_tag = string
datatype pin =
UNPINNED |
PINNED of id_or_tag
datatype libstate =
ABSENT |
CORRECT |
SUPERSEDED |
WRONG
datatype localstate =
MODIFIED |
LOCK_MISMATCHED |
CLEAN
datatype branch =
BRANCH of string | (* Non-empty *)
DEFAULT_BRANCH
(* If we can recover from an error, for example by reporting failure
for this one thing and going on to the next thing, then the error
should usually be returned through a result type rather than an
exception. *)
datatype 'a result =
OK of 'a |
ERROR of string
type libname = string
type libspec = {
libname : libname,
vcs : vcs,
source : source,
branch : branch,
project_pin : pin,
lock_pin : pin
}
type lock = {
libname : libname,
id_or_tag : id_or_tag
}
type remote_spec = {
anon : string option,
auth : string option
}
type provider = {
service : string,
supports : vcs list,
remote_spec : remote_spec
}
type account = {
service : string,
login : string
}
type status_rec = {
libname : libname,
status : string
}
type status_cache = status_rec list ref
type context = {
rootpath : string,
extdir : string,
providers : provider list,
accounts : account list,
cache : status_cache
}
type userconfig = {
providers : provider list,
accounts : account list
}
type project = {
context : context,
libs : libspec list
}
structure RepointFilenames = struct
val project_file = "repoint-project.json"
val project_lock_file = "repoint-lock.json"
val project_completion_file = ".repoint.point"
val user_config_file = ".repoint.json"
val archive_dir = ".repoint-archive"
end
signature VCS_CONTROL = sig
(** Check whether the given VCS is installed and working *)
val is_working : context -> bool result
(** Test whether the library is present locally at all *)
val exists : context -> libname -> bool result
(** Return the id (hash) of the current revision for the library *)
val id_of : context -> libname -> id_or_tag result
(** Test whether the library is at the given id *)
val is_at : context -> libname * id_or_tag -> bool result
(** Test whether the library is on the given branch, i.e. is at
the branch tip or an ancestor of it *)
val is_on_branch : context -> libname * branch -> bool result
(** Test whether the library is at the newest revision for the
given branch. False may indicate that the branch has advanced
or that the library is not on the branch at all. This function
may use the network to check for new revisions *)
val is_newest : context -> libname * source * branch -> bool result
(** Test whether the library is at the newest revision available
locally for the given branch. False may indicate that the
branch has advanced or that the library is not on the branch
at all. This function must not use the network *)
val is_newest_locally : context -> libname * branch -> bool result
(** Test whether the library has been modified in the local
working copy *)
val is_modified_locally : context -> libname -> bool result
(** Check out, i.e. clone a fresh copy of, the repo for the given
library on the given branch *)
val checkout : context -> libname * source * branch -> unit result
(** Update the library to the given branch tip. Assumes that a
local copy of the library already exists *)
val update : context -> libname * source * branch -> unit result
(** Update the library to the given specific id or tag,
understanding that we are expected to be on the given branch *)
val update_to : context -> libname * source * branch * id_or_tag -> unit result
(** Return a URL from which the library can be cloned, given that
the local copy already exists. For a DVCS this can be the
local copy, but for a centralised VCS it will have to be the
remote repository URL. Used for archiving *)
val copy_url_for : context -> libname -> string result
end
signature LIB_CONTROL = sig
val review : context -> libspec -> (libstate * localstate) result
val status : context -> libspec -> (libstate * localstate) result
val update : context -> libspec -> unit result
val id_of : context -> libspec -> id_or_tag result
val is_working : context -> vcs -> bool result
end
structure StatusCache = struct
val empty : status_cache = ref []
fun lookup (lib : libname) (cache : status_cache) : string option =
let fun lookup' [] = NONE
| lookup' ({ libname, status } :: rs) =
if libname = lib
then SOME status
else lookup' rs
in
lookup' (! cache)
end
fun drop (lib : libname) (cache : status_cache) : unit =
let fun drop' [] = []
| drop' ((r as { libname, status }) :: rs) =
if libname = lib
then rs
else r :: drop' rs
in
cache := drop' (! cache)
end
fun add (status_rec : status_rec) (cache : status_cache) : unit =
let val () = drop (#libname status_rec) cache
in
cache := status_rec :: (! cache)
end
end
structure FileBits :> sig
val extpath : context -> string
val libpath : context -> libname -> string
val subpath : context -> libname -> string -> string
val command_output : context -> libname -> string list -> string result
val command : context -> libname -> string list -> unit result
val file_url : string -> string
val file_contents : string -> string
val mydir : unit -> string
val homedir : unit -> string
val mkpath : string -> unit result
val rmpath : string -> unit result
val nonempty_dir_exists : string -> bool
val project_spec_path : string -> string
val project_lock_path : string -> string
val project_completion_path : string -> string
val verbose : unit -> bool
val insecure : unit -> bool
end = struct
fun verbose () =
case OS.Process.getEnv "REPOINT_VERBOSE" of
SOME "0" => false
| NONE => false
| _ => true
val insecure_warned = ref false
fun insecure () =
case OS.Process.getEnv "REPOINT_INSECURE" of
SOME "0" => false
| NONE => false
| _ =>
(if ! insecure_warned (* deref not negate, so "if we have warned" *)
then ()
else (print "Warning: Insecure mode active in environment, skipping security checks\n";
insecure_warned := true);
true)
fun split_relative path desc =
case OS.Path.fromString path of
{ isAbs = true, ... } => raise Fail (desc ^ " may not be absolute")
| { arcs, ... } => arcs
fun extpath ({ rootpath, extdir, ... } : context) =
let val { isAbs, vol, arcs } = OS.Path.fromString rootpath
in OS.Path.toString {
isAbs = isAbs,
vol = vol,
arcs = arcs @
split_relative extdir "extdir"
}
end
fun subpath ({ rootpath, extdir, ... } : context) libname remainder =
(* NB libname is allowed to be a path fragment, e.g. foo/bar *)
let val { isAbs, vol, arcs } = OS.Path.fromString rootpath
in OS.Path.toString {
isAbs = isAbs,
vol = vol,
arcs = arcs @
split_relative extdir "extdir" @
split_relative libname "library path" @
split_relative remainder "subpath"
}
end
fun libpath context "" =
extpath context
| libpath context libname =
subpath context libname ""
fun project_file_path rootpath filename =
let val { isAbs, vol, arcs } = OS.Path.fromString rootpath
in OS.Path.toString {
isAbs = isAbs,
vol = vol,
arcs = arcs @ [ filename ]
}
end
fun project_spec_path rootpath =
project_file_path rootpath (RepointFilenames.project_file)
fun project_lock_path rootpath =
project_file_path rootpath (RepointFilenames.project_lock_file)
fun project_completion_path rootpath =
project_file_path rootpath (RepointFilenames.project_completion_file)
fun trim str =
hd (String.fields (fn x => x = #"\n" orelse x = #"\r") str)
fun make_canonical path =
(* SML/NJ doesn't properly handle "/" when splitting paths -
it should be a path separator even on Windows, but SML/NJ
treats it as a normal filename character there. So we must
convert these explicitly *)
OS.Path.mkCanonical
(if OS.Path.concat ("a", "b") = "a\\b"
then String.translate (fn #"/" => "\\" |
c => Char.toString c)
path
else path)
fun file_url path =
let val forward_path =
String.translate (fn #"\\" => "/" |
c => Char.toString c)
(OS.Path.mkCanonical path)
in
(* Path is expected to be absolute already, but if it
starts with a drive letter, we'll need an extra slash *)
case explode forward_path of
#"/"::rest => "file:///" ^ implode rest
| _ => "file:///" ^ forward_path
end
fun file_contents filename =
let val stream = TextIO.openIn filename
fun read_all str acc =
case TextIO.inputLine str of
SOME line => read_all str (trim line :: acc)
| NONE => rev acc
val contents = read_all stream []
val _ = TextIO.closeIn stream
in
String.concatWith "\n" contents
end
fun expand_commandline cmdlist =
(* We are quite strict about what we accept here, except
for the first element in cmdlist which is assumed to be a
known command location rather than arbitrary user input. *)
let open Char
fun quote arg =
if List.all
(fn c => isAlphaNum c orelse c = #"-" orelse c = #"_")
(explode arg)
then arg
else "\"" ^ arg ^ "\""
fun check arg =
let val valid = explode " /#:;?,._-{}@=+%"
in
app (fn c =>
if isAlphaNum c orelse
List.exists (fn v => v = c) valid orelse
c > chr 127
then ()
else raise Fail ("Invalid character '" ^
(Char.toString c) ^
"' in command list"))
(explode arg);
arg
end
in
String.concatWith " "
(map quote
(hd cmdlist :: map check (tl cmdlist)))
end
val tick_cycle = ref 0
val tick_chars = Vector.fromList (map String.str (explode "|/-\\"))
fun tick libname cmdlist =
let val n = Vector.length tick_chars
fun pad_to n str =
if n <= String.size str then str
else pad_to n (str ^ " ")
val name = if libname <> "" then libname
else if cmdlist = nil then ""
else hd (rev cmdlist)
in
print (" " ^
Vector.sub(tick_chars, !tick_cycle) ^ " " ^
pad_to 70 name ^
"\r");
tick_cycle := (if !tick_cycle = n - 1 then 0 else 1 + !tick_cycle)
end
fun run_command context libname cmdlist redirect =
let open OS
val dir = libpath context libname
val cmd = expand_commandline cmdlist
val _ = if verbose ()
then print ("\n=== " ^ dir ^ "\n<<< " ^ cmd ^ "\n")
else tick libname cmdlist
val _ = FileSys.chDir dir
val status = case redirect of
NONE => Process.system cmd
| SOME file => Process.system (cmd ^ ">" ^ file)
in
if Process.isSuccess status
then OK ()
else ERROR ("Command failed: " ^ cmd ^ " (in dir " ^ dir ^ ")")
end
handle ex => ERROR ("Unable to run command: " ^ exnMessage ex)
fun command context libname cmdlist =
run_command context libname cmdlist NONE
fun command_output context libname cmdlist =
let open OS
val tmpFile = FileSys.tmpName ()
val result = run_command context libname cmdlist (SOME tmpFile)
val contents = file_contents tmpFile
val _ = if verbose ()
then print (">>> \"" ^ contents ^ "\"\n")
else ()
in
FileSys.remove tmpFile handle _ => ();
case result of
OK () => OK contents
| ERROR e => ERROR e
end
fun mydir () =
let open OS
val { dir, file } = Path.splitDirFile (CommandLine.name ())
in
FileSys.realPath
(if Path.isAbsolute dir
then dir
else Path.concat (FileSys.getDir (), dir))
end
fun homedir () =
(* Failure is not routine, so we use an exception here *)
case (OS.Process.getEnv "HOME",
OS.Process.getEnv "HOMEPATH") of
(SOME home, _) => home
| (NONE, SOME home) => home
| (NONE, NONE) =>
raise Fail "Failed to look up home directory from environment"
fun mkpath' path =
if OS.FileSys.isDir path handle _ => false
then OK ()
else case OS.Path.fromString path of
{ arcs = nil, ... } => OK ()
| { isAbs = false, ... } => ERROR "mkpath requires absolute path"
| { isAbs, vol, arcs } =>
case mkpath' (OS.Path.toString { (* parent *)
isAbs = isAbs,
vol = vol,
arcs = rev (tl (rev arcs)) }) of
ERROR e => ERROR e
| OK () => ((OS.FileSys.mkDir path; OK ())
handle OS.SysErr (e, _) =>
ERROR ("Directory creation failed: " ^ e))
fun mkpath path =
mkpath' (make_canonical path)
fun dir_contents dir =
let open OS
fun files_from dirstream =
case FileSys.readDir dirstream of
NONE => []
| SOME file =>
(* readDir is supposed to filter these,
but let's be extra cautious: *)
if file = Path.parentArc orelse file = Path.currentArc
then files_from dirstream
else file :: files_from dirstream
val stream = FileSys.openDir dir
val files = map (fn f => Path.joinDirFile
{ dir = dir, file = f })
(files_from stream)
val _ = FileSys.closeDir stream
in
files
end
fun rmpath' path =
let open OS
fun remove path =
if FileSys.isLink path (* dangling links bother isDir *)
then FileSys.remove path
else if FileSys.isDir path
then (app remove (dir_contents path); FileSys.rmDir path)
else FileSys.remove path
in
(remove path; OK ())
handle SysErr (e, _) => ERROR ("Path removal failed: " ^ e)
end
fun rmpath path =
rmpath' (make_canonical path)
fun nonempty_dir_exists path =
let open OS.FileSys
in
(not (isLink path) andalso
isDir path andalso
dir_contents path <> [])
handle _ => false
end
end
functor LibControlFn (V: VCS_CONTROL) :> LIB_CONTROL = struct
(* Valid states for unpinned libraries:
- CORRECT: We are on the right branch and are up-to-date with
it as far as we can tell. (If not using the network, this
should be reported to user as "Present" rather than "Correct"
as the remote repo may have advanced without us knowing.)
- SUPERSEDED: We are on the right branch but we can see that
there is a newer revision either locally or on the remote (in
Git terms, we are at an ancestor of the desired branch tip).
- WRONG: We are on the wrong branch (in Git terms, we are not
at the desired branch tip or any ancestor of it).
- ABSENT: Repo doesn't exist here at all.
Valid states for pinned libraries:
- CORRECT: We are at the pinned revision.
- WRONG: We are at any revision other than the pinned one.
- ABSENT: Repo doesn't exist here at all.
*)
fun check with_network context
({ libname, source, branch,
project_pin, lock_pin, ... } : libspec) =
let fun check_unpinned () =
let val newest =
if with_network
then V.is_newest context (libname, source, branch)
else V.is_newest_locally context (libname, branch)
in
case newest of
ERROR e => ERROR e
| OK true => OK CORRECT
| OK false =>
case V.is_on_branch context (libname, branch) of
ERROR e => ERROR e
| OK true => OK SUPERSEDED
| OK false => OK WRONG
end
fun check_pinned target =
case V.is_at context (libname, target) of
ERROR e => ERROR e
| OK true => OK CORRECT
| OK false => OK WRONG
fun check_remote () =
case project_pin of
UNPINNED => check_unpinned ()
| PINNED target => check_pinned target
fun check_local () =
case V.is_modified_locally context libname of
ERROR e => ERROR e
| OK true => OK MODIFIED
| OK false =>
case lock_pin of
UNPINNED => OK CLEAN
| PINNED target =>
case V.is_at context (libname, target) of
ERROR e => ERROR e
| OK true => OK CLEAN
| OK false => OK LOCK_MISMATCHED
in
case V.exists context libname of
ERROR e => ERROR e
| OK false => OK (ABSENT, CLEAN)
| OK true =>
case (check_remote (), check_local ()) of
(ERROR e, _) => ERROR e
| (_, ERROR e) => ERROR e
| (OK r, OK l) => OK (r, l)
end
val review = check true
val status = check false
fun update context
({ libname, source, branch,
project_pin, lock_pin, ... } : libspec) =
let fun update_unpinned () =
case V.is_newest context (libname, source, branch) of
ERROR e => ERROR e
| OK true => OK ()
| OK false => V.update context (libname, source, branch)
fun update_pinned target =
case V.is_at context (libname, target) of
ERROR e => ERROR e
| OK true => OK ()
| OK false => V.update_to context (libname, source, branch, target)
fun update' () =
case lock_pin of
PINNED target => update_pinned target
| UNPINNED =>
case project_pin of
PINNED target => update_pinned target
| UNPINNED => update_unpinned ()
in
case V.exists context libname of
ERROR e => ERROR e
| OK true => update' ()
| OK false =>
case V.checkout context (libname, source, branch) of
ERROR e => ERROR e
| OK () => update' ()
end
fun id_of context ({ libname, ... } : libspec) =
V.id_of context libname
fun is_working context vcs =
V.is_working context
end
(* Simple Standard ML JSON parser
https://hg.sr.ht/~cannam/sml-simplejson
Copyright 2017 Chris Cannam. BSD licence.
Parts based on the JSON parser in the Ponyo library by Phil Eaton.
*)
signature JSON = sig
datatype json = OBJECT of (string * json) list
| ARRAY of json list
| NUMBER of real
| STRING of string
| BOOL of bool
| NULL
datatype 'a result = OK of 'a
| ERROR of string
val parse : string -> json result
val serialise : json -> string
val serialiseIndented : json -> string
end
structure Json :> JSON = struct
datatype json = OBJECT of (string * json) list
| ARRAY of json list
| NUMBER of real
| STRING of string
| BOOL of bool
| NULL
datatype 'a result = OK of 'a
| ERROR of string
structure T = struct
datatype token = NUMBER of char list
| STRING of string
| BOOL of bool
| NULL
| CURLY_L
| CURLY_R
| SQUARE_L
| SQUARE_R
| COLON
| COMMA
fun toString t =
case t of NUMBER digits => implode digits
| STRING s => s
| BOOL b => Bool.toString b
| NULL => "null"
| CURLY_L => "{"
| CURLY_R => "}"
| SQUARE_L => "["
| SQUARE_R => "]"
| COLON => ":"
| COMMA => ","
end
fun bmpToUtf8 cp = (* convert a codepoint in Unicode BMP to utf8 bytes *)
let open Word
infix 6 orb andb >>
in
map (Char.chr o toInt)
(if cp < 0wx80 then
[cp]
else if cp < 0wx800 then
[0wxc0 orb (cp >> 0w6), 0wx80 orb (cp andb 0wx3f)]
else if cp < 0wx10000 then
[0wxe0 orb (cp >> 0w12),
0wx80 orb ((cp >> 0w6) andb 0wx3f),
0wx80 orb (cp andb 0wx3f)]
else raise Fail ("Invalid BMP point " ^ (Word.toString cp)))
end
fun error pos text = ERROR (text ^ " at character position " ^
Int.toString (pos - 1))
fun token_error pos = error pos ("Unexpected token")
fun lexNull pos acc (#"u" :: #"l" :: #"l" :: xs) =
lex (pos + 3) (T.NULL :: acc) xs
| lexNull pos acc _ = token_error pos
and lexTrue pos acc (#"r" :: #"u" :: #"e" :: xs) =
lex (pos + 3) (T.BOOL true :: acc) xs
| lexTrue pos acc _ = token_error pos
and lexFalse pos acc (#"a" :: #"l" :: #"s" :: #"e" :: xs) =
lex (pos + 4) (T.BOOL false :: acc) xs
| lexFalse pos acc _ = token_error pos
and lexChar tok pos acc xs =
lex pos (tok :: acc) xs
and lexString pos acc cc =
let datatype escaped = ESCAPED | NORMAL
fun lexString' pos text ESCAPED [] =
error pos "End of input during escape sequence"
| lexString' pos text NORMAL [] =
error pos "End of input during string"
| lexString' pos text ESCAPED (x :: xs) =
let fun esc c = lexString' (pos + 1) (c :: text) NORMAL xs
in case x of
#"\"" => esc x
| #"\\" => esc x
| #"/" => esc x
| #"b" => esc #"\b"
| #"f" => esc #"\f"
| #"n" => esc #"\n"
| #"r" => esc #"\r"
| #"t" => esc #"\t"
| _ => error pos ("Invalid escape \\" ^
Char.toString x)
end
| lexString' pos text NORMAL (#"\\" :: #"u" ::a::b::c::d:: xs) =
if List.all Char.isHexDigit [a,b,c,d]
then case Word.fromString ("0wx" ^ (implode [a,b,c,d])) of
SOME w => (let val utf = rev (bmpToUtf8 w) in
lexString' (pos + 6) (utf @ text)
NORMAL xs
end
handle Fail err => error pos err)
| NONE => error pos "Invalid Unicode BMP escape sequence"
else error pos "Invalid Unicode BMP escape sequence"
| lexString' pos text NORMAL (x :: xs) =
if Char.ord x < 0x20
then error pos "Invalid unescaped control character"
else
case x of
#"\"" => OK (rev text, xs, pos + 1)
| #"\\" => lexString' (pos + 1) text ESCAPED xs
| _ => lexString' (pos + 1) (x :: text) NORMAL xs
in
case lexString' pos [] NORMAL cc of
OK (text, rest, newpos) =>
lex newpos (T.STRING (implode text) :: acc) rest
| ERROR e => ERROR e
end
and lexNumber firstChar pos acc cc =
let val valid = explode ".+-e"
fun lexNumber' pos digits [] = (rev digits, [], pos)
| lexNumber' pos digits (x :: xs) =
if x = #"E" then lexNumber' (pos + 1) (#"e" :: digits) xs
else if Char.isDigit x orelse List.exists (fn c => x = c) valid
then lexNumber' (pos + 1) (x :: digits) xs
else (rev digits, x :: xs, pos)
val (digits, rest, newpos) =
lexNumber' (pos - 1) [] (firstChar :: cc)
in
case digits of
[] => token_error pos
| _ => lex newpos (T.NUMBER digits :: acc) rest
end
and lex pos acc [] = OK (rev acc)
| lex pos acc (x::xs) =
(case x of
#" " => lex
| #"\t" => lex
| #"\n" => lex
| #"\r" => lex
| #"{" => lexChar T.CURLY_L
| #"}" => lexChar T.CURLY_R
| #"[" => lexChar T.SQUARE_L
| #"]" => lexChar T.SQUARE_R
| #":" => lexChar T.COLON
| #"," => lexChar T.COMMA
| #"\"" => lexString
| #"t" => lexTrue
| #"f" => lexFalse
| #"n" => lexNull
| x => lexNumber x) (pos + 1) acc xs
fun show [] = "end of input"
| show (tok :: _) = T.toString tok
fun parseNumber digits =
(* Note lexNumber already case-insensitised the E for us *)
let open Char
fun okExpDigits [] = false
| okExpDigits (c :: []) = isDigit c
| okExpDigits (c :: cs) = isDigit c andalso okExpDigits cs
fun okExponent [] = false
| okExponent (#"+" :: cs) = okExpDigits cs
| okExponent (#"-" :: cs) = okExpDigits cs
| okExponent cc = okExpDigits cc
fun okFracTrailing [] = true
| okFracTrailing (c :: cs) =
(isDigit c andalso okFracTrailing cs) orelse
(c = #"e" andalso okExponent cs)
fun okFraction [] = false
| okFraction (c :: cs) =
isDigit c andalso okFracTrailing cs
fun okPosTrailing [] = true
| okPosTrailing (#"." :: cs) = okFraction cs
| okPosTrailing (#"e" :: cs) = okExponent cs
| okPosTrailing (c :: cs) =
isDigit c andalso okPosTrailing cs
fun okPositive [] = false
| okPositive (#"0" :: []) = true
| okPositive (#"0" :: #"." :: cs) = okFraction cs
| okPositive (#"0" :: #"e" :: cs) = okExponent cs
| okPositive (#"0" :: cs) = false
| okPositive (c :: cs) = isDigit c andalso okPosTrailing cs
fun okNumber (#"-" :: cs) = okPositive cs
| okNumber cc = okPositive cc
in
if okNumber digits
then case Real.fromString (implode digits) of
NONE => ERROR "Number out of range"
| SOME r => OK r
else ERROR ("Invalid number \"" ^ (implode digits) ^ "\"")
end
fun parseObject (T.CURLY_R :: xs) = OK (OBJECT [], xs)
| parseObject tokens =
let fun parsePair (T.STRING key :: T.COLON :: xs) =
(case parseTokens xs of
ERROR e => ERROR e
| OK (j, xs) => OK ((key, j), xs))
| parsePair other =
ERROR ("Object key/value pair expected around \"" ^
show other ^ "\"")
fun parseObject' acc [] = ERROR "End of input during object"
| parseObject' acc tokens =
case parsePair tokens of
ERROR e => ERROR e
| OK (pair, T.COMMA :: xs) =>
parseObject' (pair :: acc) xs
| OK (pair, T.CURLY_R :: xs) =>
OK (OBJECT (rev (pair :: acc)), xs)
| OK (_, _) => ERROR "Expected , or } after object element"
in
parseObject' [] tokens
end
and parseArray (T.SQUARE_R :: xs) = OK (ARRAY [], xs)
| parseArray tokens =
let fun parseArray' acc [] = ERROR "End of input during array"
| parseArray' acc tokens =
case parseTokens tokens of
ERROR e => ERROR e
| OK (j, T.COMMA :: xs) => parseArray' (j :: acc) xs
| OK (j, T.SQUARE_R :: xs) => OK (ARRAY (rev (j :: acc)), xs)
| OK (_, _) => ERROR "Expected , or ] after array element"
in
parseArray' [] tokens
end
and parseTokens [] = ERROR "Value expected"
| parseTokens (tok :: xs) =
(case tok of
T.NUMBER d => (case parseNumber d of
OK r => OK (NUMBER r, xs)
| ERROR e => ERROR e)
| T.STRING s => OK (STRING s, xs)
| T.BOOL b => OK (BOOL b, xs)
| T.NULL => OK (NULL, xs)
| T.CURLY_L => parseObject xs
| T.SQUARE_L => parseArray xs
| _ => ERROR ("Unexpected token " ^ T.toString tok ^
" before " ^ show xs))
fun parse str =
case lex 1 [] (explode str) of
ERROR e => ERROR e
| OK tokens => case parseTokens tokens of
OK (value, []) => OK value
| OK (_, _) => ERROR "Extra data after input"
| ERROR e => ERROR e
fun stringEscape s =
let fun esc x = [x, #"\\"]
fun escape' acc [] = rev acc
| escape' acc (x :: xs) =
escape' (case x of
#"\"" => esc x @ acc
| #"\\" => esc x @ acc
| #"\b" => esc #"b" @ acc
| #"\f" => esc #"f" @ acc
| #"\n" => esc #"n" @ acc
| #"\r" => esc #"r" @ acc
| #"\t" => esc #"t" @ acc
| _ =>
let val c = Char.ord x
in
if c < 0x20
then let val hex = Word.toString (Word.fromInt c)
in (rev o explode) (if c < 0x10
then ("\\u000" ^ hex)
else ("\\u00" ^ hex))
end @ acc
else
x :: acc
end)
xs
in
implode (escape' [] (explode s))
end
fun serialiseNumber n =
implode (map (fn #"~" => #"-" | c => c)
(explode
(if Real.isFinite n andalso
Real.== (n, Real.realRound n) andalso
Real.<= (Real.abs n, 1e6)
then Int.toString (Real.round n)
else Real.toString n)))
fun serialise json =
case json of
OBJECT pp => "{" ^ String.concatWith
"," (map (fn (key, value) =>
serialise (STRING key) ^ ":" ^
serialise value) pp) ^
"}"
| ARRAY arr => "[" ^ String.concatWith "," (map serialise arr) ^ "]"
| NUMBER n => serialiseNumber n
| STRING s => "\"" ^ stringEscape s ^ "\""
| BOOL b => Bool.toString b
| NULL => "null"
fun serialiseIndented json =
let fun indent 0 = ""
| indent i = " " ^ indent (i - 1)
fun serialiseIndented' i json =
let val ser = serialiseIndented' (i + 1)
in