/
ocpp.ml
1213 lines (1098 loc) · 34.3 KB
/
ocpp.ml
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
(**************************************************************************)
(* *)
(* Typerex Tools *)
(* *)
(* Copyright 2011-2017 OCamlPro SAS *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU General Public License version 3 described in the file *)
(* LICENSE. *)
(* *)
(**************************************************************************)
open Ocpp_version
open Versioning
(* TODO: re-enable parse_check_spaces. It could be moved somewhere else ! *)
let debug_ocpp = try
ignore (Sys.getenv ("OCPP_DEBUG"));
Printf.eprintf "OCPP_DEBUG: trigger debugging\n%!";
true
with Not_found -> false
open Lexing
open Location
open Parser
open Ocpp_types
(* Might conflict with toplevel directives:
"quit", "directory", "remove_directory", "cd", "load", "load_rec",
"use", "mod_use", "install_printer", "remove_printer",
"trace", "untrace", "untrace_all", "print_depth", "print_length",
"labels", "principal", "rectypes", "warnings", "warn_error"
*)
type macro = {
macro_name : string;
macro_tokens : token list;
}
type pp_state = {
pp_buffer : Buffer.t;
pp_name : string;
mutable pp_last_lnum : int;
mutable pp_last_fname : string;
}
type state =
| AfterIf of bool
| AfterElse of bool
| InIncludedFileAt of
Lexing.lexbuf *
Parser.token list *
Lexing.position
| BeginPP of (Lexing.lexbuf -> Parser.token)
type stack = (state * bool) list
let token_of_token tok =
Ocpp_parser.STRING (Compat.get_STRING tok)
let lines_of_file filename =
let ic = open_in filename in
let lines = ref [] in
try
while true do
lines := (input_line ic) :: !lines
done;
assert false
with End_of_file ->
close_in ic;
List.rev !lines
let files = Hashtbl.create 13
let lexbuf_of_file filename =
let lines =
try
lines_of_file filename
with _e ->
Printf.eprintf "Error: could not include file %S\n%!" filename;
exit 2
in
let file_content = String.concat "\n" lines in
let lines = Array.of_list lines in
let lexbuf = Lexing.from_string file_content in
Location.init lexbuf filename;
Hashtbl.add files filename lines;
lexbuf
let reset () =
Hashtbl.clear files
let lines_of_file filename =
Hashtbl.find files filename
let macro_version version =
[ LIDENT "version" ; LPAREN; Compat.mk_string version; RPAREN]
module StringMap = Map.Make(String)
let env = ref StringMap.empty
let stack = ref ([] : stack)
let keep = ref true
let current_lexbuf = ref (Lexing.from_string "")
let original_lexbuf = ref !current_lexbuf
let _ = Location.init !current_lexbuf "<none>"
let after_eol = ref true
let new_run = ref true
let queued_tokens = ref []
let optionsMap = ref StringMap.empty
let add_option name f =
optionsMap := StringMap.add name f !optionsMap
let set_option name v =
(try
StringMap.find name !optionsMap
with Not_found ->
(fun name _ ->
Printf.eprintf "Warning: #option %S is not available\n%!" name)
) name v
let default_macros = ref
[
"OCAML_VERSION", Some (macro_version Sys.ocaml_version);
(*
"OCAMLLIB", STRING Config.standard_library;
"ARCHITECTURE", STRING (Config.architecture);
"MODEL", STRING (Config.model);
"SYSTEM", STRING (Config.system);
(* Beware for cross-compilation *)
"OS_TYPE", STRING Sys.os_type;
"WORD_SIZE", INT Sys.word_size;
"MAX_STRING_LENGTH", INT Sys.max_string_length;
"MAX_ARRAY_LENGTH", INT Sys.max_array_length;
*)
]
let pp_state = ref (None : pp_state option)
(*let preprocessors = ref StringMap.empty *)
let name_of_token token =
match token with
| AMPERAMPER -> "AMPERAMPER"
| AMPERSAND -> "AMPERSAND"
| AND -> "AND"
| AS -> "AS"
| ASSERT -> "ASSERT"
| BACKQUOTE -> "BACKQUOTE"
| BANG -> "BANG"
| BAR -> "BAR"
| BARBAR -> "BARBAR"
| BARRBRACKET -> "BARRBRACKET"
| BEGIN -> "BEGIN"
| CLASS -> "CLASS"
| COLON -> "COLON"
| COLONCOLON -> "COLONCOLON"
| COLONEQUAL -> "COLONEQUAL"
| COLONGREATER -> "COLONGREATER"
| COMMA -> "COMMA"
| COMMENT (begin_pos, _end_loc) ->
Printf.sprintf "COMMENT (%S)" begin_pos
| CONSTRAINT -> "CONSTRAINT"
| DO -> "DO"
| DONE -> "DONE"
| DOT -> "DOT"
| DOTDOT -> "DOTDOT"
| DOWNTO -> "DOWNTO"
| ELSE -> "ELSE"
| END -> "END"
| EOF -> "EOF"
| EQUAL -> "EQUAL"
| EXCEPTION -> "EXCEPTION"
| EXTERNAL -> "EXTERNAL"
| FALSE -> "FALSE"
| FOR -> "FOR"
| FUN -> "FUN"
| FUNCTION -> "FUNCTION"
| FUNCTOR -> "FUNCTOR"
| GREATER -> "GREATER"
| GREATERRBRACE -> "GREATERRBRACE"
| GREATERRBRACKET -> "GREATERRBRACKET"
| IF -> "IF"
| IN -> "IN"
| INCLUDE -> "INCLUDE"
| INHERIT -> "INHERIT"
| INITIALIZER -> "INITIALIZER"
| LAZY -> "LAZY"
| LBRACE -> "LBRACE"
| LBRACELESS -> "LBRACELESS"
| LBRACKET -> "LBRACKET"
| LBRACKETBAR -> "LBRACKETBAR"
| LBRACKETLESS -> "LBRACKETLESS"
| LBRACKETGREATER -> "LBRACKETGREATER"
| LESS -> "LESS"
| LESSMINUS -> "LESSMINUS"
| LET -> "LET"
| LPAREN -> "LPAREN"
| MATCH -> "MATCH"
| METHOD -> "METHOD"
| MINUS -> "MINUS"
| MINUSDOT -> "MINUSDOT"
| MINUSGREATER -> "MINUSGREATER"
| MODULE -> "MODULE"
| MUTABLE -> "MUTABLE"
| NEW -> "NEW"
| OBJECT -> "OBJECT"
| OF -> "OF"
| OPEN -> "OPEN"
| OR -> "OR"
| PLUS -> "PLUS"
| PLUSDOT -> "PLUSDOT"
| PRIVATE -> "PRIVATE"
| QUESTION -> "QUESTION"
| QUOTE -> "QUOTE"
| RBRACE -> "RBRACE"
| RBRACKET -> "RBRACKET"
| REC -> "REC"
| RPAREN -> "RPAREN"
| SEMI -> "SEMI"
| SEMISEMI -> "SEMISEMI"
| SIG -> "SIG"
| STAR -> "STAR"
| STRUCT -> "STRUCT"
| THEN -> "THEN"
| TILDE -> "TILDE"
| TO -> "TO"
| TRUE -> "TRUE"
| TRY -> "TRY"
| TYPE -> "TYPE"
| UNDERSCORE -> "UNDERSCORE"
| VAL -> "VAL"
| VIRTUAL -> "VIRTUAL"
| WHEN -> "WHEN"
| WHILE -> "WHILE"
| WITH -> "WITH"
(* tryocaml: syntax extensions *)
(*
| SHARPJS -> "SHARPJS"
| BIGINT s -> Printf.sprintf "BIGINT(%s)" s
*)
| LIDENT string -> Printf.sprintf "LIDENT(%s)" string
| OPTLABEL(string) -> Printf.sprintf "OPTLABEL(%s)" string
| LABEL(string) -> Printf.sprintf "LABEL(%s)" string
| UIDENT string -> Printf.sprintf "UIDENT(%s)" string
| CHAR char -> Printf.sprintf "CHAR(%S)" (String.make 1 char)
| PREFIXOP(string) -> Printf.sprintf "PREFIXOP(%s)" string
| INFIXOP0(op) -> Printf.sprintf "INFIXOP0(%s)" op
| INFIXOP1(op) -> Printf.sprintf "INFIXOP1(%s)" op
| INFIXOP2(op) -> Printf.sprintf "INFIXOP2(%s)" op
| INFIXOP3(op) -> Printf.sprintf "INFIXOP3(%s)" op
| INFIXOP4(op) -> Printf.sprintf "INFIXOP4(%s)" op
| EOL -> "EOL"
| _ -> Compat.name_of_token token
let string_of_token token =
match token with
| AMPERAMPER -> "&&"
| AMPERSAND -> "&"
| AND -> "and"
| AS -> "as"
| ASSERT -> "assert"
| BACKQUOTE -> "`"
| BANG -> "!"
| BAR -> "|"
| BARBAR -> "||"
| BARRBRACKET -> "|]"
| BEGIN -> "begin"
| CLASS -> "class"
| COLON -> ":"
| COLONCOLON -> "::"
| COLONEQUAL -> ":="
| COLONGREATER -> ":>"
| COMMA -> ","
| COMMENT (comment, _loc) ->
Printf.sprintf "COMMENT (%s)" (String.escaped comment)
| CONSTRAINT -> "constraint"
| DO -> "do"
| DONE -> "done"
| DOT -> "."
| DOTDOT -> ".."
| DOWNTO -> "downto"
| ELSE -> "else"
| END -> "end"
| EQUAL -> "="
| EXCEPTION -> "exception"
| EXTERNAL -> "external"
| FALSE -> "false"
| FOR -> "for"
| FUN -> "fun"
| FUNCTION -> "function"
| FUNCTOR -> "functor"
| GREATER -> ">"
| GREATERRBRACE -> ">}"
| GREATERRBRACKET -> ">]"
| IF -> "if"
| IN -> "in"
| INCLUDE -> "include"
| INHERIT -> "inherit"
| INITIALIZER -> "initializer"
| LAZY -> "lazy"
| LBRACE -> "{"
| LBRACELESS -> "{<"
| LBRACKET -> "["
| LBRACKETBAR -> "[|"
| LBRACKETLESS -> "[<"
| LBRACKETGREATER -> "[>"
| LESS -> "<"
| LESSMINUS -> "<-"
| LET -> "let"
| LPAREN -> "("
| MATCH -> "match"
| METHOD -> "method"
| MINUS -> "-"
| MINUSDOT -> "-."
| MINUSGREATER -> "->"
| MODULE -> "module"
| MUTABLE -> "mutable"
| NEW -> "new"
| OBJECT -> "object"
| OF -> "of"
| OPEN -> "open"
| OR -> "or"
| PLUS -> "+"
| PLUSDOT -> "+."
| PRIVATE -> "private"
| QUESTION -> "?"
| QUOTE -> "'"
| RBRACE -> "}"
| RBRACKET -> "]"
| REC -> "rec"
| RPAREN -> ")"
| SEMI -> ";"
| SEMISEMI -> ";;"
| SIG -> "sig"
| STAR -> "*"
| STRUCT -> "struct"
| THEN -> "then"
| TILDE -> "~"
| TO -> "to"
| TRUE -> "true"
| TRY -> "try"
| TYPE -> "type"
| UNDERSCORE -> "_"
| VAL -> "val"
| VIRTUAL -> "virtual"
| WHEN -> "when"
| WHILE -> "while"
| WITH -> "with"
(* tryocaml: syntax extensions *)
(* | SHARPJS -> "##"
| BIGINT s -> Printf.sprintf "%sI" s *)
| LIDENT string -> string
| OPTLABEL(string) -> Printf.sprintf "?%s:" string
| LABEL(string) -> Printf.sprintf "~%s:" string
| UIDENT string -> Printf.sprintf "%s" string
| CHAR char -> Printf.sprintf "'%s'" (String.escaped (String.make 1 char))
| PREFIXOP(string) -> string
| INFIXOP0(op) -> op
| INFIXOP1(op) -> op
| INFIXOP2(op) -> op
| INFIXOP3(op) -> op
| INFIXOP4(op) -> op
| EOL -> "\n"
| EOF -> "\n"
| _ -> Compat.string_of_token token
let string_of_directive = function
| OCPP_INCLUDE -> "OCPP_INCLUDE"
| OCPP_DEFINE -> "OCPP_DEFINE"
| OCPP_DEFUN -> "OCPP_DEFUN"
| OCPP_UNDEF -> "OCPP_UNDEF"
| OCPP_IFDEF -> "OCPP_IFDEF"
| OCPP_IFNDEF -> "OCPP_IFNDEF"
| OCPP_IF -> "OCPP_IF"
| OCPP_ELSE -> "OCPP_ELSE"
| OCPP_ELIF -> "OCPP_ELIF"
| OCPP_ENDIF -> "OCPP_ENDIF"
| OCPP_ERROR -> "OCPP_ERROR"
| OCPP_WARNING -> "OCPP_WARNING"
| OCPP_OPTION -> "OCPP_OPTION"
(*
| OCPP_DBL_LBRACE -> "OCPP_DBL_LBRACE"
| OCPP_DBL_RBRACE -> "OCPP_DBL_RBRACE"
*)
let string_of_tokens tokens =
String.concat "," (List.map name_of_token tokens)
(* Entry points in the parser *)
let set_ocaml_version version =
default_macros := !default_macros @ [
"OCAML_VERSION", Some (macro_version version) ]
let add_macro name macro =
default_macros := !default_macros @ [ name, Some macro ]
let remove_macro name =
default_macros := !default_macros @ [ name, None ]
(* This function is called from Lexer.init when the lexer is initialized *)
let init () =
new_run := true;
env := StringMap.empty;
stack := [];
keep := true;
after_eol := true;
List.iter (fun (macro_name, value) ->
(* Printf.eprintf "Defining macro %S\n%!" macro_name; *)
match value with
| Some value ->
env := StringMap.add macro_name {
macro_name = macro_name;
macro_tokens = value;
} !env
| None ->
env := StringMap.remove macro_name !env
) !default_macros
let parse_expr tokens lexbuf =
let tokens = ref tokens in
let module P = Ocpp_parser in
try
P.ocpp_expr (fun _lexbuf ->
match !tokens with
[] -> P.EOF
| token :: tail -> tokens := tail;
match token with
| INT _ -> P.INT (Compat.int_of_token token)
| DOT -> P.DOT
| TRUE -> P.TRUE
| FALSE -> P.FALSE
| LIDENT s -> P.LIDENT s
| UIDENT s -> P.UIDENT s
| LPAREN -> P.LPAREN
| RPAREN -> P.RPAREN
| PLUS -> P.PLUS
| MINUS -> P.MINUS
| STAR -> P.STAR
| EQUAL -> P.EQUAL
| LESS -> P.LESS
| GREATER -> P.GREATER
| INFIXOP0 s -> P.INFIXOP0 s
| BANG -> P.BANG
| PREFIXOP s -> P.PREFIXOP s
| BARBAR -> P.BARBAR
| AMPERAMPER -> P.AMPERAMPER
| _ -> token_of_token token
) lexbuf
with _ ->
Printf.eprintf "Error while parsing directive expression\n%!";
exit 2
let compare arg1 arg2 =
match arg1, arg2 with
| Int n1, Int n2 -> compare n1 n2
| String n1, String n2 -> compare n1 n2
| Version v1, Version v2 -> version_compare v1 v2
| String s1, Version v2 -> version_compare (version_of_string s1) v2
| Version v1, String s2 -> version_compare v1 (version_of_string s2)
| Undefined s, _
| _, Undefined s ->
Printf.kprintf failwith "ident %S is undefined in comparison" s.txt
| _ -> failwith "type mismatch in comparison"
let version_of_string s =
if debug_ocpp then Printf.eprintf "version_of_string %S\n%!" s;
let v = version_of_string s in
if debug_ocpp then
Printf.eprintf "version(%s) -> %s\n%!" s (string_of_version v);
v
let int_of_string n s =
try
int_of_string s
with e ->
Printf.eprintf "int_of_string%d[%S] failed\n%!" n s;
raise e
let rec ocpp_apply action args =
if debug_ocpp then
Printf.eprintf "ocpp_apply: action %S\n%!" action;
match action, args with
| "version", [ String s ] -> Version (version_of_string s)
| "version", [ Int n ] -> Version [ VPositive, VInt n ]
| "version", [ Version v ] -> Version v
| "major", [ Version ( (VPositive, VInt major) :: _) ] -> Int major
| "major", [ Version _ ] -> failwith "version has not major"
| "major", [ String s ] -> ocpp_apply "major"
[ Version (version_of_string s) ]
| "major", [ _ ] -> failwith "arg is not a version for major(_)"
| "minor", [ Version ( (VPositive, VInt _) ::
(VPositive, VInt minor) :: _) ] -> Int minor
| "minor", [ Version _ ] -> failwith "version has no minor"
| "minor", [ String s ] -> ocpp_apply "minor"
[ Version (version_of_string s) ]
| "minor", [ _ ] -> failwith "arg is not a version for minor(_)"
| "defined", [ String s ] ->
if StringMap.mem s !env then Int 1 else Int 0
| "defined", _ ->
failwith "for defined, an argument string is"
| "int", [ String s ] -> Int (int_of_string 6 s)
| "int", [ Int n ] -> Int n
| "string", [ String s ] -> String s
| "string", [ Int n ] -> String (string_of_int n)
| "!", [ Int 0 ] -> Int 1
| "!", [ Int _ ] -> Int 0
| "=", [ arg1; arg2 ] ->
if compare arg1 arg2 = 0 then Int 1 else Int 0
| "<>", [ arg1; arg2 ] ->
if compare arg1 arg2 <> 0 then Int 1 else Int 0
| ">", [ arg1; arg2 ] ->
if compare arg1 arg2 > 0 then Int 1 else Int 0
| "<", [ arg1; arg2 ] ->
if compare arg1 arg2 < 0 then Int 1 else Int 0
| ">=", [ arg1; arg2 ] ->
if compare arg1 arg2 >= 0 then Int 1 else Int 0
| "<=", [ arg1; arg2 ] ->
if compare arg1 arg2 <= 0 then Int 1 else Int 0
| "+", [ String s1; String s2 ] ->
String (s1 ^ s2)
| "+", [ Int i1; Int i2 ] ->
Int (i1 + i2)
| _ -> failwith "bad expression in #if"
(*
let parse_check_spaces = function
| "0" ->
(* Lexer.check_spaces := None *)
()
| "file" ->
let count = ref 0 in
Lexer.check_spaces := Some
(fun loc msg ->
let ppf = Format.err_formatter in
incr count;
match !count with
| 1 ->
Location.print_loc ppf loc;
Format.fprintf ppf "@.Warning: %s.@." msg;
| 2 ->
Format.fprintf ppf "Warning: (other space errors found, not printed in 'file' mode).@."
| _ -> ()
);
| "error" ->
Lexer.check_spaces := Some
(fun loc msg ->
let ppf = Format.err_formatter in
Location.print_loc ppf loc;
Format.fprintf ppf "@.Error: %s.@." msg;
exit 2
);
| v ->
Lexer.check_spaces := Some
(fun loc msg ->
let ppf = Format.err_formatter in
Location.print_loc ppf loc;
Format.fprintf ppf "@.Warning: %s.@." msg)
*)
let read_token lexer =
match !queued_tokens with
| token :: tail ->
queued_tokens := tail; token
| [] ->
let token = lexer !current_lexbuf in
if debug_ocpp then begin
Printf.eprintf "read_token[%s]%s[%d] <- lexer: %s\n%!"
(if !keep then "keep" else "disc")
(if !after_eol then "[eol]" else "")
(List.length !stack) (name_of_token token);
end;
token
let expand_token token tokens_ref =
match token with
| UIDENT s | LIDENT s ->
(* Don't expand macros in the discarded branch of #if/#ifdef *)
if !keep then
try
let macro = StringMap.find s !env in
let tokens = macro.macro_tokens in
begin match tokens with
[] -> None
| token :: tokens ->
tokens_ref := tokens @ !tokens_ref;
Some token
end
with Not_found ->
Some token
else Some token
| _ ->
Some token
let expand_tokens tokens =
let before = tokens in
let tokens = ref tokens in
let macro_tokens = ref [] in
while !tokens <> [] do
match !tokens with
| [] -> assert false
| token :: tail ->
tokens := tail;
match expand_token token tokens with
| None -> ()
| Some token -> macro_tokens := token :: !macro_tokens
done;
let after = List.rev !macro_tokens in
if debug_ocpp then begin
Printf.eprintf "expand_tokens:\n %s\n-> %s\n%!"
(string_of_tokens before)
(string_of_tokens after)
end;
after
let rec get_token lexer =
let token = read_token lexer in
match expand_token token queued_tokens with
| None ->
get_token lexer
| Some token -> token
let bool_of_expr = function
| String s -> Printf.kprintf failwith "bool(%s)" s
| Int n -> n <> 0
| Undefined s -> Printf.kprintf failwith "bool(Undefined %S)" s.txt
| Version _ -> failwith "bool(Version)"
let tokenify_string lexer s =
let rec iter lexbuf rev =
let token = lexer lexbuf in
if debug_ocpp then
Printf.eprintf "tokenify_string: %s\n%!" (name_of_token token);
match token with
| EOF -> List.rev rev
| token ->
iter lexbuf (token :: rev)
in
if debug_ocpp then
Printf.eprintf "Tokenify %S\n%!" s;
iter (Lexing.from_string s) []
let rec preprocess lexer =
let token = get_token lexer in
if debug_ocpp then begin
Printf.eprintf "preprocess[%s]%s[%d] <- %s\n%!"
(if !keep then "keep" else "disc")
(if !after_eol then "[eol]" else "")
(List.length !stack) (name_of_token token);
end;
match token with
| EOL -> after_eol := true; preprocess lexer
(*
| OCPP_PP_DIRECTIVE s ->
if debug_ocpp then
Printf.eprintf "OCPP_PP_DIRECTIVE %S\n" s;
let tokens = tokenify_string Lexer.raw_lexer s in
if debug_ocpp then
List.iter (fun token ->
Printf.eprintf "tokenified in ocpp_pp: %s\n%!"
(string_of_token token)
) tokens;
after_eol := true;
queued_tokens := tokens @ [EOL];
preprocess lexer lexbuf
| OCPP_PP_CONTENT s ->
if debug_ocpp then
Printf.eprintf "OCPP_PP_CONTENT %S\n" s;
if !keep then begin
match !pp_state with
| None -> assert false
| Some ps ->
let b = ps.pp_buffer in
let lnum = lexbuf.lex_curr_p.pos_lnum in
let fname = lexbuf.lex_curr_p.pos_fname in
(* TODO: optimize to remove useless lines *)
Printf.bprintf b "# %d %S\n" lnum fname;
Buffer.add_string b s;
Buffer.add_char b '\n';
end;
preprocess lexer lexbuf
*)
| EOF ->
begin
match !stack with
[] -> EOF
| (InIncludedFileAt (old_lexbuf, queue, curr_p), _) :: stack_tail ->
old_lexbuf.lex_curr_p <- curr_p;
queued_tokens := queue;
after_eol := true;
if debug_ocpp then
Printf.eprintf "Popping old lexbuf from stack\n%!";
current_lexbuf := old_lexbuf;
stack := stack_tail;
preprocess lexer
| _ ->
Printf.kprintf failwith "unclosed #if/#ifdef"
end
| _ ->
if Compat.is_sharp token && !after_eol then begin
if debug_ocpp then
Printf.eprintf "SHARP maybe directive...\n%!";
begin match get_token lexer with
| INCLUDE ->
preprocess_directive lexer OCPP_INCLUDE
| LIDENT "define" ->
preprocess_directive lexer OCPP_DEFINE
| LIDENT "defun" ->
preprocess_directive lexer OCPP_DEFUN
| LIDENT "undef" ->
preprocess_directive lexer OCPP_UNDEF
| LIDENT "ifdef" ->
preprocess_directive lexer OCPP_IFDEF
| LIDENT "ifndef" ->
preprocess_directive lexer OCPP_IFNDEF
| IF ->
preprocess_directive lexer OCPP_IF
| LIDENT "elif" ->
preprocess_directive lexer OCPP_ELIF
| ELSE ->
preprocess_directive lexer OCPP_ELSE
| LIDENT "endif" ->
preprocess_directive lexer OCPP_ENDIF
| LIDENT "error" ->
preprocess_directive lexer OCPP_ERROR
| LIDENT "warning" ->
preprocess_directive lexer OCPP_WARNING
| LIDENT "option" ->
preprocess_directive lexer OCPP_OPTION
| token ->
if debug_ocpp then
Printf.eprintf "oups, not a directive\n%!";
queued_tokens := token :: !queued_tokens;
token
end
end else begin
after_eol := false;
if !keep then begin
if !stack <> [] then begin
let orig_lexbuf = !original_lexbuf in
let new_lexbuf = !current_lexbuf in
orig_lexbuf.lex_start_p <- new_lexbuf.lex_start_p;
orig_lexbuf.lex_curr_p <- new_lexbuf.lex_curr_p;
end;
token
end
else
preprocess lexer
end
and preprocess_directive lexer directive =
let rec iter lexer tokens =
let token = read_token lexer in
match token with
| EOF | EOL -> queued_tokens := token :: !queued_tokens; List.rev tokens
| COMMENT _ -> iter lexer tokens
| _ -> iter lexer (token :: tokens)
in
let args = iter lexer [ ] in
let do_if args =
let expr = expand_tokens args in
let expr = parse_expr expr !current_lexbuf in
if debug_ocpp then Printf.eprintf "do_if: parsed\n%!";
let rec eval_expr expr =
match expr.desc with
| Pexp_constant (String s) -> String s
| Pexp_constant (Int n) -> Int n
| Pexp_uident ident -> Undefined ident
| Pexp_ident( { txt = "ocaml_version" } ) ->
begin try
match (StringMap.find "OCAML_VERSION" !env).macro_tokens with
| [ (STRING _) as token ] ->
Version (version_of_string (Compat.get_STRING token))
| _ -> raise Not_found
with Not_found ->
Printf.eprintf "Error: ocaml_version used, but OCAML_VERSION not defined, or not a string\n%!";
exit 2
end
| Pexp_apply( { desc = Pexp_ident( { txt = action } ) },
args ) ->
begin
match action, args with
| "&&", [ left; right ] ->
let left = eval_expr left in
if bool_of_expr left then eval_expr right else left
| "||", [ left; right ] ->
let left = eval_expr left in
if not (bool_of_expr left) then eval_expr right else left
| _ ->
let args = List.map (fun arg ->
eval_expr arg) args in
ocpp_apply action args
end
| _ ->
if debug_ocpp then Printf.eprintf "do_if error\n%!";
failwith "bad expression in #if"
in
let v = eval_expr expr in
if debug_ocpp then begin Printf.eprintf "Evaluated\n%!" end;
match v with
| Int 0 ->
stack := (AfterIf false, !keep) :: !stack;
keep := false
| Int _n ->
stack := (AfterIf true, !keep) :: !stack;
keep := true
| Undefined s ->
Printf.kprintf failwith "value of #if %S is undefined, integer" s.txt
| _ ->
failwith "result of #if expression is not an integer"
in
match directive with
| OCPP_UNDEF ->
if !keep then begin
List.iter (fun token ->
match token with
| UIDENT uident ->
env := StringMap.remove uident !env
| _ -> failwith "Macro name expected after #undef"
) args;
end;
preprocess lexer
| OCPP_DEFINE ->
if !keep then begin
match args with
| UIDENT macro_name :: tokens ->
let macro_tokens = expand_tokens tokens in
let macro = {
macro_name;
macro_tokens;
} in
env := StringMap.add macro_name macro !env;
preprocess lexer
| _ ->
if debug_ocpp then
Printf.eprintf "Tokens: %s\n%!" (string_of_tokens args);
raise (Syntaxerr.Error (Syntaxerr.Other (
Location.curr !current_lexbuf)))
end else
preprocess lexer
| OCPP_OPTION ->
if !keep then begin
match args with
| [ UIDENT name; STRING _ as token ] ->
set_option name (Compat.get_STRING token)
| [ UIDENT name; (INT _) as int ] ->
set_option name (string_of_int (Compat.int_of_token int))
| [ UIDENT name ] -> set_option name "1"
| _ -> failwith "Error after #option: should be Option \"value\""
end;
preprocess lexer
| OCPP_IFDEF ->
if !keep then begin match args with
[ UIDENT uident ] ->
if StringMap.mem uident !env then begin
stack := (AfterIf true, !keep) :: !stack;
keep := true;
end else begin
stack := (AfterIf false, !keep) :: !stack;
keep := false;
end
| _ -> failwith "Macro name expected after #ifdef"
end else begin
stack := (AfterIf true, !keep) :: !stack;
keep := false
end;
preprocess lexer
| OCPP_IFNDEF ->
if !keep then begin
match args with
[ UIDENT uident ] ->
if not (StringMap.mem uident !env) then begin
stack := (AfterIf true, !keep) :: !stack;
keep := true;
end else begin
stack := (AfterIf false, !keep) :: !stack;
keep := false;
end
| _ -> failwith "Macro name expected after #ifndef"
end else begin
stack := (AfterIf true, !keep) :: !stack;
keep := false
end;
preprocess lexer
| OCPP_ENDIF ->
if args <> [] then failwith "junk after #endif";
begin match !stack with
| [] -> failwith "#endif without #if/#ifdef"
| ((AfterIf _, old_keep) | (AfterElse _, old_keep)) :: stack_tail ->
keep := old_keep;
stack := stack_tail
| _ -> failwith "mismatched #endif"
end;
preprocess lexer
| OCPP_INCLUDE ->
if !keep then begin
let args = expand_tokens args in
match args with
[ STRING _ as token ] ->
preprocess_include lexer (Compat.get_STRING token)
| _ ->
failwith "invalid arguments to #include"
end else
preprocess lexer
| OCPP_ELSE ->
if args <> [] then failwith "junk after #else";
begin match !stack with
| [] -> failwith "#else without #if/#ifdef"
| (AfterIf cond, old_keep) :: stack_tail ->
keep := (not cond) && old_keep;
stack := (AfterElse !keep, old_keep) :: stack_tail
| _ ->
failwith "#else after #else"
end;
preprocess lexer
| OCPP_ELIF ->
(* OCPP_ELSE *)
begin match !stack with
| [] -> failwith "#else without #if/#ifdef"
| (AfterIf cond, old_keep) :: stack_tail ->
keep := old_keep;
stack := stack_tail;
if (not cond) && old_keep then begin
do_if args
end else begin
stack := (AfterIf true, old_keep) :: !stack;
keep := false
end;
preprocess lexer
| _ ->
failwith "#elif after #else"
end;
| OCPP_IF ->
if !keep then begin
do_if args
end else begin
stack := (AfterIf true, !keep) :: !stack;
keep := false
end;
preprocess lexer
| OCPP_WARNING ->
if !keep then begin
match expand_tokens args with