Repository navigation
Expand file tree
/
Copy pathleex.erl
More file actions
1765 lines (1547 loc) · 65.6 KB
/
Copy pathleex.erl
File metadata and controls
1765 lines (1547 loc) · 65.6 KB
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
%% Copyright (c) 2008,2009 Robert Virding. All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions
%% are met:
%%
%% 1. Redistributions of source code must retain the above copyright
%% notice, this list of conditions and the following disclaimer.
%% 2. Redistributions in binary form must reproduce the above copyright
%% notice, this list of conditions and the following disclaimer in the
%% documentation and/or other materials provided with the distribution.
%%
%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
%% COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%% POSSIBILITY OF SUCH DAMAGE.
%%% A Lexical Analyser Generator for Erlang.
%%%
%%% Most of the algorithms used here are taken pretty much as
%%% described in the "Dragon Book" by Aho, Sethi and Ullman. Some
%%% completing details were taken from "Compiler Design in C" by
%%% Hollub.
-module(leex).
-export([compile/3,file/1,file/2,format_error/1]).
-import(lists, [member/2,reverse/1,sort/1,keysort/2,
map/2,foldl/3,foldr/3,foreach/2,flatmap/2]).
-import(ordsets, [is_element/2,add_element/2,union/2]).
-import(orddict, [store/3]).
-include("erl_compile.hrl").
%%-include_lib("stdlib/include/erl_compile.hrl").
-define(LEEXINC, "leexinc.hrl"). % Include file
-define(LEEXLIB, parsetools). % Leex is in lib parsetools
%%-define(LEEXLIB, leex). % Leex is in lib leex
-define(DEFS_HEAD, "Definitions.").
-define(RULE_HEAD, "Rules.").
-define(CODE_HEAD, "Erlang code.").
-record(leex, {xfile=[], % Xrl file
efile=[], % Erl file
ifile=[], % Include file
gfile=[], % Graph file
module, % Module name
opts=[], % Options
encoding=none, % Encoding of Xrl file
% posix=false, % POSIX regular expressions
errors=[],
warnings=[]
}).
-record(nfa_state, {no,edges=[],accept=noaccept}).
-record(dfa_state, {no,nfa=[],trans=[],accept=noaccept}).
%%%
%%% Exported functions
%%%
%%% Interface to erl_compile.
compile(Input0, Output0,
#options{warning = WarnLevel, verbose=Verbose, includes=Includes,
specific=Specific}) ->
Input = assure_extension(shorten_filename(Input0), ".xrl"),
Output = assure_extension(shorten_filename(Output0), ".erl"),
Includefile = lists:sublist(Includes, 1),
Werror = proplists:get_bool(warnings_as_errors, Specific),
Opts = [{scannerfile,Output},{includefile,Includefile},{verbose,Verbose},
{report_errors,true},{report_warnings,WarnLevel > 0},
{warnings_as_errors, Werror}],
case file(Input, Opts) of
{ok, _} ->
ok;
error ->
error
end.
-type error_info() :: {erl_anno:line() | 'none',
module(), ErrorDescriptor :: term()}.
-type errors() :: [{file:filename(), [error_info()]}].
-type warnings() :: [{file:filename(), [error_info()]}].
-type ok_ret() :: {'ok', Scannerfile :: file:filename()}
| {'ok', Scannerfile :: file:filename(), warnings()}.
-type error_ret() :: 'error'
| {'error', Errors :: errors(), Warnings :: warnings()}.
-type leex_ret() :: ok_ret() | error_ret().
-spec file(FileName) -> leex_ret() when
FileName :: file:filename().
file(File) -> file(File, []).
-spec file(FileName, Options) -> leex_ret() when
FileName :: file:filename(),
Options :: Option | [Option],
Option :: {'dfa_graph', boolean()}
| {'includefile', Includefile :: file:filename()}
| {'report_errors', boolean()}
| {'report_warnings', boolean()}
| {'report', boolean()}
| {'return_errors', boolean()}
| {'return_warnings', boolean()}
| {'return', boolean()}
| {'scannerfile', Scannerfile :: file:filename()}
| {'verbose', boolean()}
| {'warnings_as_errors', boolean()}
| 'dfa_graph'
| 'report_errors' | 'report_warnings' | 'report'
| 'return_errors' | 'return_warnings' | 'return'
| 'verbose' | 'warnings_as_errors'.
file(File, Opts0) when is_list(Opts0) ->
case is_filename(File) of
no -> erlang:error(badarg, [File,Opts0]);
_ -> ok
end,
EnvOpts0 = env_default_opts(),
EnvOpts = select_recognized_opts(EnvOpts0),
Opts1 = Opts0 ++ EnvOpts,
Opts = case options(Opts1) of
badarg ->
erlang:error(badarg, [File,Opts0]);
Options ->
Options
end,
St0 = #leex{},
St1 = filenames(File, Opts, St0), % Get all the filenames
St = try
{ok,REAs,Actions,Code,St2} = parse_file(St1),
{DFA,DF} = make_dfa(REAs, St2),
case werror(St2) of
false ->
St3 = out_file(St2, DFA, DF, Actions, Code),
case lists:member(dfa_graph, St3#leex.opts) of
true -> out_dfa_graph(St3, DFA, DF);
false -> St3
end;
true ->
St2
end
catch #leex{}=St4 ->
St4
end,
leex_ret(St);
file(File, Opt) ->
file(File, [Opt]).
-spec format_error(ErrorDescriptor) -> io_lib:chars() when
ErrorDescriptor :: term().
format_error({file_error, Reason}) ->
io_lib:fwrite("~ts",[file:format_error(Reason)]);
format_error(missing_defs) -> "missing Definitions";
format_error(missing_rules) -> "missing Rules";
format_error(missing_code) -> "missing Erlang code";
format_error(empty_rules) -> "no rules";
format_error(bad_rule) -> "bad rule";
format_error({regexp,E})->
Es = case E of
{interval_range,_} -> "interval range";
{unterminated,Cs} ->
"unterminated " ++ Cs;
{illegal_char,Cs} ->
"illegal character " ++ Cs;
%% {posix_cc,What} ->
%% ["illegal POSIX character class ",io_lib:write_string(What)];
{char_class,What} ->
["illegal character class ",io_lib:write_string(What)]
end,
["bad regexp `",Es,"'"];
format_error(ignored_characters) ->
"ignored characters";
format_error(cannot_parse) ->
io_lib:fwrite("cannot parse; probably encoding mismatch", []).
%%%
%%% Local functions
%%%
assure_extension(File, Ext) ->
lists:concat([strip_extension(File, Ext), Ext]).
%% Assumes File is a filename.
strip_extension(File, Ext) ->
case filename:extension(File) of
Ext -> filename:rootname(File);
_Other -> File
end.
%% Copied from compile.erl.
env_default_opts() ->
Key = "ERL_COMPILER_OPTIONS",
case os:getenv(Key) of
false -> [];
Str when is_list(Str) ->
case erl_scan:string(Str) of
{ok,Tokens,_} ->
Dot = {dot, erl_anno:new(1)},
case erl_parse:parse_term(Tokens ++ [Dot]) of
{ok,List} when is_list(List) -> List;
{ok,Term} -> [Term];
{error,_Reason} ->
io:format("Ignoring bad term in ~s\n", [Key]),
[]
end;
{error, {_,_,_Reason}, _} ->
io:format("Ignoring bad term in ~s\n", [Key]),
[]
end
end.
select_recognized_opts(Options0) ->
Options = preprocess_options(Options0),
AllOptions = all_options(),
[Option ||
{Name, _} = Option <- Options,
lists:member(Name, AllOptions)].
options(Options0) ->
Options1 = preprocess_options(Options0),
AllOptions = all_options(),
case check_options(Options1, AllOptions, []) of
badarg ->
badarg;
OptionValues ->
AllOptionValues =
[case lists:keyfind(Option, 1, OptionValues) of
false ->
{Option, default_option(Option)};
OptionValue ->
OptionValue
end || Option <- AllOptions],
foldr(fun({_, false}, L) -> L;
({Option, true}, L) -> [Option | L];
(OptionValue, L) -> [OptionValue | L]
end, [], AllOptionValues)
end.
preprocess_options(Options) ->
foldr(fun preproc_opt/2, [], Options).
preproc_opt(return, Os) ->
[{return_errors, true}, {return_warnings, true} | Os];
preproc_opt(report, Os) ->
[{report_errors, true}, {report_warnings, true} | Os];
preproc_opt({return, T}, Os) ->
[{return_errors, T}, {return_warnings, T} | Os];
preproc_opt({report, T}, Os) ->
[{report_errors, T}, {report_warnings, T} | Os];
preproc_opt(Option, Os) ->
[try atom_option(Option) catch error:_ -> Option end | Os].
check_options([{Option, FileName0} | Options], AllOptions, L)
when Option =:= includefile; Option =:= scannerfile ->
case is_filename(FileName0) of
no ->
badarg;
Filename ->
check_options(Options, AllOptions, [{Option, Filename} | L])
end;
check_options([{Option, Boolean} | Options], AllOptions, L)
when is_boolean(Boolean) ->
case lists:member(Option, AllOptions) of
true ->
check_options(Options, AllOptions, [{Option, Boolean} | L]);
false ->
badarg
end;
check_options([], _AllOptions, L) ->
L;
check_options(_Options, _, _L) ->
badarg.
all_options() ->
[dfa_graph,includefile,report_errors,report_warnings,
return_errors,return_warnings,scannerfile,verbose,
warnings_as_errors].
default_option(dfa_graph) -> false;
default_option(includefile) -> [];
default_option(report_errors) -> true;
default_option(report_warnings) -> true;
default_option(return_errors) -> false;
default_option(return_warnings) -> false;
default_option(scannerfile) -> [];
default_option(verbose) -> false;
default_option(warnings_as_errors) -> false.
atom_option(dfa_graph) -> {dfa_graph,true};
atom_option(report_errors) -> {report_errors,true};
atom_option(report_warnings) -> {report_warnings,true};
atom_option(warnings_as_errors) -> {warnings_as_errors,true};
atom_option(return_errors) -> {return_errors,true};
atom_option(verbose) -> {verbose,true};
atom_option(return_warnings) -> {return_warnings,true};
atom_option(Key) -> Key.
is_filename(T) ->
try filename:flatten(T)
catch error: _ -> no
end.
shorten_filename(Name0) ->
{ok,Cwd} = file:get_cwd(),
case string:prefix(Name0, Cwd) of
nomatch -> Name0;
Rest ->
case unicode:characters_to_list(Rest) of
"/"++N -> N;
N -> N
end
end.
leex_ret(St) ->
report_errors(St),
report_warnings(St),
Es = pack_errors(St#leex.errors),
Ws = pack_warnings(St#leex.warnings),
Werror = werror(St),
if
Werror ->
do_error_return(St, Es, Ws);
Es =:= [] ->
case member(return_warnings, St#leex.opts) of
true -> {ok, St#leex.efile, Ws};
false -> {ok, St#leex.efile}
end;
true ->
do_error_return(St, Es, Ws)
end.
do_error_return(St, Es, Ws) ->
case member(return_errors, St#leex.opts) of
true -> {error, Es, Ws};
false -> error
end.
werror(St) ->
St#leex.warnings =/= []
andalso member(warnings_as_errors, St#leex.opts).
pack_errors([{File,_} | _] = Es) ->
[{File, flatmap(fun({_,E}) -> [E] end, sort(Es))}];
pack_errors([]) ->
[].
pack_warnings([{File,_} | _] = Ws) ->
[{File, flatmap(fun({_,W}) -> [W] end, sort(Ws))}];
pack_warnings([]) ->
[].
report_errors(St) ->
when_opt(fun () ->
foreach(fun({File,{none,Mod,E}}) ->
io:fwrite("~ts: ~ts\n",
[File,Mod:format_error(E)]);
({File,{Line,Mod,E}}) ->
io:fwrite("~ts:~w: ~ts\n",
[File,Line,Mod:format_error(E)])
end, sort(St#leex.errors))
end, report_errors, St#leex.opts).
report_warnings(St) ->
Werror = member(warnings_as_errors, St#leex.opts),
Prefix = case Werror of
true -> "";
false -> "Warning: "
end,
ReportWerror = Werror andalso member(report_errors, St#leex.opts),
ShouldReport = member(report_warnings, St#leex.opts) orelse ReportWerror,
when_bool(fun () ->
foreach(fun({File,{none,Mod,W}}) ->
io:fwrite("~ts: ~s~ts\n",
[File,Prefix,
Mod:format_error(W)]);
({File,{Line,Mod,W}}) ->
io:fwrite("~ts:~w: ~s~ts\n",
[File,Line,Prefix,
Mod:format_error(W)])
end, sort(St#leex.warnings))
end, ShouldReport).
-spec add_error(_, #leex{}) -> no_return().
add_error(E, St) ->
add_error(St#leex.xfile, E, St).
add_error(File, Error, St) ->
throw(St#leex{errors = [{File,Error}|St#leex.errors]}).
add_warning(Line, W, St) ->
St#leex{warnings = [{St#leex.xfile,{Line,leex,W}}|St#leex.warnings]}.
%% filenames(File, Options, State) -> State.
%% The default output dir is the current directory unless an
%% explicit one has been given in the options.
filenames(File, Opts, St0) ->
Dir = filename:dirname(File),
Base = filename:basename(File, ".xrl"),
Xfile = filename:join(Dir, Base ++ ".xrl"),
Efile = Base ++ ".erl",
Gfile = Base ++ ".dot",
Module = list_to_atom(Base),
St1 = St0#leex{xfile=Xfile,
opts=Opts,
module=Module},
{includefile,Ifile0} = lists:keyfind(includefile, 1, Opts),
Ifile = inc_file_name(Ifile0),
%% Test for explicit scanner file.
{scannerfile,Ofile} = lists:keyfind(scannerfile, 1, Opts),
if
Ofile =:= [] ->
St1#leex{efile=filename:join(Dir, Efile),
ifile=Ifile,
gfile=filename:join(Dir, Gfile)};
true ->
D = filename:dirname(Ofile),
St1#leex{efile=Ofile,
ifile=Ifile,
gfile=filename:join(D, Gfile)}
end.
when_opt(Do, Opt, Opts) ->
case member(Opt, Opts) of
true -> Do();
false -> ok
end.
when_bool(Do, Bool) ->
case Bool of
true -> Do();
false -> ok
end.
verbose_print(St, Format, Args) ->
when_opt(fun () -> io:fwrite(Format, Args) end, verbose, St#leex.opts).
%% parse_file(State) -> {ok,[REA],[Action],Code,NewState} | throw(NewState)
%% when
%% REA = {RegExp,ActionNo};
%% Action = {ActionNo,ActionString};
%% Code = {StartLine, StartPos, NumOfLines}. Where the Erlang code is.
%%
%% Read and parse the file Xfile.
%% After each section of the file has been parsed we directly call the
%% next section. This is done when we detect a line we don't recognise
%% in the current section. The file format is very simple and Erlang
%% token based, we allow empty lines and Erlang style comments.
parse_file(St0) ->
case file:open(St0#leex.xfile, [read]) of
{ok,Xfile} ->
St1 = St0#leex{encoding = epp:set_encoding(Xfile)},
try
verbose_print(St1, "Parsing file ~ts, ", [St1#leex.xfile]),
%% We KNOW that errors throw so we can ignore them here.
{ok,Line1,St2} = parse_head(Xfile, St1),
{ok,Line2,Macs,St3} = parse_defs(Xfile, Line1, St2),
{ok,Line3,REAs,Actions,St4} =
parse_rules(Xfile, Line2, Macs, St3),
{ok,Code,St5} = parse_code(Xfile, Line3, St4),
verbose_print(St5, "contained ~w rules.~n", [length(REAs)]),
{ok,REAs,Actions,Code,St5}
after ok = file:close(Xfile)
end;
{error,Error} ->
add_error({none,leex,{file_error,Error}}, St0)
end.
%% parse_head(File, State) -> {ok,NextLine,State}.
%% Parse the head of the file. Skip all comments and blank lines.
parse_head(Ifile, St) -> {ok,nextline(Ifile, 0, St),St}.
%% parse_defs(File, Line, State) -> {ok,NextLine,Macros,State}.
%% Parse the macro definition section of a file. This must exist.
%% The section is ended by a non-blank line which is not a macro def.
parse_defs(Ifile, {ok,?DEFS_HEAD ++ Rest,L}, St) ->
St1 = warn_ignored_chars(L, Rest, St),
parse_defs(Ifile, nextline(Ifile, L, St), [], St1);
parse_defs(_, {ok,_,L}, St) ->
add_error({L,leex,missing_defs}, St);
parse_defs(_, {eof,L}, St) ->
add_error({L,leex,missing_defs}, St).
parse_defs(Ifile, {ok,Chars,L}=Line, Ms, St) ->
%% This little beauty matches out a macro definition, RE's are so clear.
MS = "^[ \t]*([A-Z_][A-Za-z0-9_]*)[ \t]*=[ \t]*([^ \t\r\n]*)[ \t\r\n]*\$",
case re:run(Chars, MS, [{capture,all_but_first,list},unicode]) of
{match,[Name,Def]} ->
%%io:fwrite("~p = ~p\n", [Name,Def]),
parse_defs(Ifile, nextline(Ifile, L, St), [{Name,Def}|Ms], St);
_ -> {ok,Line,Ms,St} % Anything else
end;
parse_defs(_, Line, Ms, St) ->
{ok,Line,Ms,St}.
%% parse_rules(File, Line, Macros, State) -> {ok,NextLine,REAs,Actions,State}.
%% Parse the RE rules section of the file. This must exist.
parse_rules(Ifile, {ok,?RULE_HEAD ++ Rest,L}, Ms, St) ->
St1 = warn_ignored_chars(L, Rest, St),
parse_rules(Ifile, nextline(Ifile, L, St), Ms, [], [], 0, St1);
parse_rules(_, {ok,_,L}, _, St) ->
add_error({L,leex,missing_rules}, St);
parse_rules(_, {eof,L}, _, St) ->
add_error({L,leex,missing_rules}, St).
%% parse_rules(File, Result, Macros, RegExpActions, Actions, Acount, State) ->
%% {ok,NextCLine,RegExpActions,Actions,NewState} | throw(NewState)
parse_rules(Ifile, NextLine, Ms, REAs, As, N, St) ->
case NextLine of
{ok,?CODE_HEAD ++ _Rest,_} ->
parse_rules_end(Ifile, NextLine, REAs, As, St);
{ok,Chars,L0} ->
%%io:fwrite("~w: ~p~n", [L0,Chars]),
case collect_rule(Ifile, Chars, L0) of
{ok,Re,Atoks,L1} ->
{ok,REA,A,St1} = parse_rule(Re, L0, Atoks, Ms, N, St),
parse_rules(Ifile, nextline(Ifile, L1, St), Ms,
[REA|REAs], [A|As], N+1, St1);
{error,E} -> add_error(E, St)
end;
{eof,_} ->
parse_rules_end(Ifile, NextLine, REAs, As, St)
end.
parse_rules_end(_, {ok,_,L}, [], [], St) ->
add_error({L,leex,empty_rules}, St);
parse_rules_end(_, {eof,L}, [], [], St) ->
add_error({L,leex,empty_rules}, St);
parse_rules_end(_, NextLine, REAs, As, St) ->
%% Must be *VERY* careful to put rules in correct order!
{ok,NextLine,reverse(REAs),reverse(As),St}.
%% collect_rule(File, Line, Lineno) ->
%% {ok,RegExp,ActionTokens,NewLineno} | {error,E}.
%% Collect a complete rule by reading lines until the the regexp and
%% action has been read. Keep track of line number.
collect_rule(Ifile, Chars, L0) ->
{RegExp,Rest} = string:take(Chars, " \t\r\n", true),
case collect_action(Ifile, Rest, L0, []) of
{ok,[{':',_}|Toks],L1} -> {ok,RegExp,Toks,L1};
{ok,_,_} -> {error,{L0,leex,bad_rule}};
{eof,L1} -> {error,{L1,leex,bad_rule}};
{error,E,_} -> {error,E}
end.
collect_action(_Ifile, {error, _}, L, _Cont0) ->
{error, {L, leex, cannot_parse}, ignored_end_line};
collect_action(Ifile, Chars, L0, Cont0) ->
case erl_scan:tokens(Cont0, Chars, L0) of
{done,{ok,Toks,_},_} -> {ok,Toks,L0};
{done,{eof,_},_} -> {eof,L0};
{done,{error,E,_},_} -> {error,E,L0};
{more,Cont1} ->
collect_action(Ifile, io:get_line(Ifile, leex), L0+1, Cont1)
end.
%% parse_rule(RegExpString, RegExpLine, ActionTokens, Macros, Counter, State) ->
%% {ok,{RE,Action},ActionData,State}.
%% Parse one regexp after performing macro substition.
parse_rule(S, Line, [{dot,_}], Ms, N, St) ->
case parse_rule_regexp(S, Ms, St) of
{ok,R} ->
{ok,{R,N},{N,empty_action},St};
{error,E} ->
add_error({Line,leex,E}, St)
end;
parse_rule(S, Line, Atoks, Ms, N, St) ->
case parse_rule_regexp(S, Ms, St) of
{ok,R} ->
%%io:fwrite("RE = ~p~n", [R]),
%% Check for token variables.
TokenChars = var_used('TokenChars', Atoks),
TokenLen = var_used('TokenLen', Atoks),
TokenLine = var_used('TokenLine', Atoks),
{ok,{R,N},{N,Atoks,TokenChars,TokenLen,TokenLine},St};
{error,E} ->
add_error({Line,leex,E}, St)
end.
var_used(Name, Toks) ->
case lists:keyfind(Name, 3, Toks) of
{var,_,Name} -> true; %It's the var we want
_ -> false
end.
%% parse_rule_regexp(RegExpString, Macros, State) ->
%% {ok,RegExp} | {error,Error}.
%% Substitute in macros and parse RegExpString. Cannot use re:replace
%% here as it uses info in replace string (&).
parse_rule_regexp(RE0, [{M,Exp}|Ms], St) ->
Split= re:split(RE0, "\\{" ++ M ++ "\\}", [{return,list},unicode]),
RE1 = lists:append(lists:join(Exp, Split)),
parse_rule_regexp(RE1, Ms, St);
parse_rule_regexp(RE, [], St) ->
%%io:fwrite("RE = ~p~n", [RE]),
case re_parse(RE, St) of
{ok,R} -> {ok,R};
{error,E} -> {error,{regexp,E}}
end.
%% parse_code(File, Line, State) -> {ok,Code,NewState}.
%% Finds the line and the position where the code section of the file
%% begins. This must exist.
parse_code(Ifile, {ok,?CODE_HEAD ++ Rest,CodeL}, St) ->
St1 = warn_ignored_chars(CodeL, Rest, St),
{ok, CodePos} = file:position(Ifile, cur),
%% Just count the lines; copy the code from file to file later.
EndCodeLine = count_lines(Ifile, CodeL, St),
NCodeLines = EndCodeLine - CodeL,
{ok,{CodeL,CodePos,NCodeLines},St1};
parse_code(_, {ok,_,L}, St) ->
add_error({L,leex,missing_code}, St);
parse_code(_, {eof,L}, St) ->
add_error({L,leex,missing_code}, St).
count_lines(File, N, St) ->
case io:get_line(File, leex) of
eof -> N;
{error, _} -> add_error({N+1, leex, cannot_parse}, St);
_Line -> count_lines(File, N+1, St)
end.
%% nextline(InputFile, PrevLineNo, State) -> {ok,Chars,LineNo} | {eof,LineNo}.
%% Get the next line skipping comment lines and blank lines.
nextline(Ifile, L, St) ->
case io:get_line(Ifile, leex) of
eof -> {eof,L};
{error, _} -> add_error({L+1, leex, cannot_parse}, St);
Chars ->
case string:take(Chars, " \t\n") of
{_, [$%|_Rest]} -> nextline(Ifile, L+1, St);
{_, []} -> nextline(Ifile, L+1, St);
_Other -> {ok,Chars,L+1}
end
end.
warn_ignored_chars(Line, S, St) ->
case non_white(S) of
[] -> St;
_ -> add_warning(Line, ignored_characters, St)
end.
non_white(S) ->
[C || C <- S, C > $\s, C < $\200 orelse C > $\240].
%% This is the regular expression grammar used. It is equivalent to the
%% one used in AWK, except that we allow ^ $ to be used anywhere and fail
%% in the matching.
%%
%% reg -> alt : '$1'.
%% alt -> seq "|" seq ... : {alt,['$1','$2'...]}.
%% seq -> repeat repeat ... : {seq,['$1','$2'...]}.
%% repeat -> repeat "*" : {kclosure,'$1'}.
%% repeat -> repeat "+" : {pclosure,'$1'}.
%% repeat -> repeat "?" : {optional,'$1'}.
%% repeat -> repeat "{" [Min],[Max] "}" : {interval,'$1',Min,Max}
%% repeat -> single : '$1'.
%% single -> "(" reg ")" : {sub,'$2',Number}.
%% single -> "^" : bos/bol.
%% single -> "$" : eos/eol.
%% single -> "." : any.
%% single -> "[" class "]" : {char_class,char_class('$2')}
%% single -> "[" "^" class "]" : {comp_class,char_class('$3')}.
%% single -> "\"" chars "\"" : {lit,'$2'}.
%% single -> "\\" char : {lit,['$2']}.
%% single -> char : {lit,['$1']}.
%% single -> empty : epsilon.
%% The grammar of the current regular expressions. The actual parser
%% is a recursive descent implementation of the grammar.
%% re_parse(Chars, State) -> {ok,RegExp} | {error,Error}.
re_parse(Cs0, St) ->
case catch re_reg(Cs0, 0, St) of
{RE,_,[]} -> {ok,RE};
{_,_,[C|_]} -> {error,{illegal_char,[C]}};
{parse_error,E} -> {error,E}
end.
parse_error(E) -> throw({parse_error,E}).
re_reg(Cs, Sn, St) -> re_alt(Cs, Sn, St).
re_alt(Cs0, Sn0, St) ->
{L,Sn1,Cs1} = re_seq(Cs0, Sn0, St),
case re_alt1(Cs1, Sn1, St) of
{[],Sn2,Cs2} -> {L,Sn2,Cs2};
{Rs,Sn2,Cs2} -> {{alt,[L|Rs]},Sn2,Cs2}
end.
re_alt1([$||Cs0], Sn0, St) ->
{L,Sn1,Cs1} = re_seq(Cs0, Sn0, St),
{Rs,Sn2,Cs2} = re_alt1(Cs1, Sn1, St),
{[L|Rs],Sn2,Cs2};
re_alt1(Cs, Sn, _) -> {[],Sn,Cs}.
%% Parse a sequence of regexps. Don't allow the empty sequence.
%% re_seq(Cs0, Sn0, St) ->
%% {L,Sn1,Cs1} = repeat(Cs0, Sn0, St),
%% case re_seq1(Cs1, Sn1, St) of
%% {[],Sn2,Cs2} -> {L,Sn2,Cs2};
%% {Rs,Sn2,Cs2} -> {{seq,[L|Rs]},Sn2,Cs2}
%% end.
%% re_seq(Chars, SubNumber, State) -> {RegExp,SubNumber,Chars}.
%% Parse a sequence of regexps. Allow the empty sequence, returns epsilon.
re_seq(Cs0, Sn0, St) ->
case re_seq1(Cs0, Sn0, St) of
{[],Sn1,Cs1} -> {epsilon,Sn1,Cs1};
{[R],Sn1,Cs1} -> {R,Sn1,Cs1};
{Rs,Sn1,Cs1} -> {{seq,Rs},Sn1,Cs1}
end.
re_seq1([C|_]=Cs0, Sn0, St) when C =/= $|, C =/= $) ->
{L,Sn1,Cs1} = re_repeat(Cs0, Sn0, St),
{Rs,Sn2,Cs2} = re_seq1(Cs1, Sn1, St),
{[L|Rs],Sn2,Cs2};
re_seq1(Cs, Sn, _) -> {[],Sn,Cs}.
%% re_repeat(Chars, SubNumber, State) -> {RegExp,SubNumber,Chars}.
re_repeat(Cs0, Sn0, St) ->
{S,Sn1,Cs1} = re_single(Cs0, Sn0, St),
re_repeat1(Cs1, Sn1, S, St).
re_repeat1([$*|Cs], Sn, S, St) -> re_repeat1(Cs, Sn, {kclosure,S}, St);
re_repeat1([$+|Cs], Sn, S, St) -> re_repeat1(Cs, Sn, {pclosure,S}, St);
re_repeat1([$?|Cs], Sn, S, St) -> re_repeat1(Cs, Sn, {optional,S}, St);
%% { only starts interval when ere is true, otherwise normal character.
%% re_repeat1([${|Cs0], Sn, S, #leex{posix=true}=St) -> % $}
%% case re_interval_range(Cs0) of
%% {Min,Max,[$}|Cs1]} when is_integer(Min), is_integer(Max), Min =< Max ->
%% re_repeat1(Cs1, Sn, {interval,S,Min,Max}, St);
%% {Min,Max,[$}|Cs1]} when is_integer(Min), is_atom(Max) ->
%% re_repeat1(Cs1, Sn, {interval,S,Min,Max}, St);
%% {_,_,Cs1} -> parse_error({interval_range,string_between([${|Cs0], Cs1)})
%% end;
re_repeat1(Cs, Sn, S, _) -> {S,Sn,Cs}.
%% re_single(Chars, SubNumber, State) -> {RegExp,SubNumber,Chars}.
%% Parse a re_single regexp.
re_single([$(|Cs0], Sn0, St) -> % $)
Sn1 = Sn0 + 1, % Keep track of sub count anyway
case re_reg(Cs0, Sn1, St) of
{S,Sn2,[$)|Cs1]} -> {S,Sn2,Cs1};
%%{S,Sn2,[$)|Cs1]} -> {{sub,S,Sn1},Sn2,Cs1};
_ -> parse_error({unterminated,"("})
end;
%% These are not legal inside a regexp.
%% re_single([$^|Cs], Sn, St) -> {bos,Sn,Cs};
%% re_single([$$|Cs], Sn, St) -> {eos,Sn,Cs};
%% re_single([$.|Cs], Sn, St) -> {any,Sn,Cs};
re_single([$.|Cs], Sn, _) -> {{comp_class,"\n"},Sn,Cs}; % Do this here?
re_single("[^" ++ Cs0, Sn, St) ->
case re_char_class(Cs0, St) of
{Cc,[$]|Cs1]} -> {{comp_class,Cc},Sn,Cs1};
_ -> parse_error({unterminated,"["})
end;
re_single([$[|Cs0], Sn, St) ->
case re_char_class(Cs0, St) of
{Cc,[$]|Cs1]} -> {{char_class,Cc},Sn,Cs1};
_ -> parse_error({unterminated,"["})
end;
re_single([$\\|Cs0], Sn, _) ->
{C,Cs1} = re_char($\\, Cs0),
{{lit,[C]},Sn,Cs1};
re_single([C|Cs0], Sn, St) ->
case special_char(C, St) of
true -> parse_error({illegal_char,[C]});
false ->
{C,Cs1} = re_char(C, Cs0),
{{lit,[C]},Sn,Cs1}
end.
-define(IS_HEX(C), C >= $0 andalso C =< $9 orelse
C >= $A andalso C =< $F orelse
C >= $a andalso C =< $f).
%% re_char(Char, Chars) -> {CharValue,Chars}.
%% Reads one character value from the input list, it knows about escapes.
re_char($\\, [O1,O2,O3|S]) when
O1 >= $0, O1 =< $7, O2 >= $0, O2 =< $7, O3 >= $0, O3 =< $7 ->
{(O1*8 + O2)*8 + O3 - 73*$0,S};
re_char($\\, [$x,H1,H2|S]) when ?IS_HEX(H1), ?IS_HEX(H2) ->
{erlang:list_to_integer([H1,H2], 16),S};
re_char($\\,[$x,${|S0]) ->
re_hex(S0, []);
re_char($\\,[$x|_]) ->
parse_error({illegal_char,"\\x"});
re_char($\\, [C|S]) -> {escape_char(C),S};
re_char($\\, []) -> parse_error({unterminated,"\\"});
re_char(C, S) -> {C,S}. % Just this character
re_hex([C|Cs], L) when ?IS_HEX(C) -> re_hex(Cs, [C|L]);
re_hex([$}|S], L0) ->
L = lists:reverse(L0),
case erlang:list_to_integer(L, 16) of
C when C =< 16#10FFFF -> {C,S};
_ -> parse_error({illegal_char,[$\\,$x,${|L]++"}"})
end;
re_hex(_, _) -> parse_error({unterminated,"\\x{"}).
%% special_char(Char, State) -> bool().
%% These are the special characters for an ERE.
%% N.B. ]}) are only special in the context after [{(.
special_char($^, _) -> true;
special_char($., _) -> true;
special_char($[, _) -> true;
special_char($$, _) -> true;
special_char($(, _) -> true;
special_char($), _) -> true;
special_char($|, _) -> true;
special_char($*, _) -> true;
special_char($+, _) -> true;
special_char($?, _) -> true;
%% special_char(${, #leex{posix=true}) -> true; % Only when POSIX set
special_char($\\, _) -> true;
special_char(_, _) -> false.
%% re_char_class(Chars, State) -> {CharClass,Chars}.
%% Parse a character class.
re_char_class([$]|Cs], St) -> % Must special case this.
re_char_class(Cs, [$]], St);
re_char_class(Cs, St) -> re_char_class(Cs, [], St).
%% re_char_class("[:" ++ Cs0, Cc, #leex{posix=true}=St) ->
%% %% POSIX char class only.
%% case posix_cc(Cs0) of
%% {Pcl,":]" ++ Cs1} -> re_char_class(Cs1, [{posix,Pcl}|Cc], St);
%% {_,Cs1} -> parse_error({posix_cc,string_between(Cs0, Cs1)})
%% end;
re_char_class([C1|Cs0], Cc, St) when C1 =/= $] ->
case re_char(C1, Cs0) of
{Cf,[$-,C2|Cs1]} when C2 =/= $] ->
case re_char(C2, Cs1) of
{Cl,Cs2} when Cf < Cl ->
re_char_class(Cs2, [{range,Cf,Cl}|Cc], St);
{_,Cs2} ->
parse_error({char_class,string_between([C1|Cs0], Cs2)})
end;
{C,Cs1} -> re_char_class(Cs1, [C|Cc], St)
end;
re_char_class(Cs, Cc, _) -> {reverse(Cc),Cs}. % Preserve order
%% posix_cc(String) -> {PosixClass,RestString}.
%% Handle POSIX character classes.
%% posix_cc("alnum" ++ Cs) -> {alnum,Cs};
%% posix_cc("alpha" ++ Cs) -> {alpha,Cs};
%% posix_cc("blank" ++ Cs) -> {blank,Cs};
%% posix_cc("cntrl" ++ Cs) -> {cntrl,Cs};
%% posix_cc("digit" ++ Cs) -> {digit,Cs};
%% posix_cc("graph" ++ Cs) -> {graph,Cs};
%% posix_cc("lower" ++ Cs) -> {lower,Cs};
%% posix_cc("print" ++ Cs) -> {print,Cs};
%% posix_cc("punct" ++ Cs) -> {punct,Cs};
%% posix_cc("space" ++ Cs) -> {space,Cs};
%% posix_cc("upper" ++ Cs) -> {upper,Cs};
%% posix_cc("xdigit" ++ Cs) -> {xdigit,Cs};
%% posix_cc(Cs) -> parse_error({posix_cc,string:slice(Cs, 0, 5)}).
escape_char($n) -> $\n; % \n = LF
escape_char($r) -> $\r; % \r = CR
escape_char($t) -> $\t; % \t = TAB
escape_char($v) -> $\v; % \v = VT
escape_char($b) -> $\b; % \b = BS
escape_char($f) -> $\f; % \f = FF
escape_char($e) -> $\e; % \e = ESC
escape_char($s) -> $\s; % \s = SPACE
escape_char($d) -> $\d; % \d = DEL
escape_char(C) -> C. % Pass it straight through
%% re_interval_range(Chars) -> {Min,Max,RestChars}.
%% NoInt -> none,none
%% Int -> Int,none
%% Int, -> Int,any
%% Int1,Int2 -> Int1,Int2
%% re_interval_range(Cs0) ->
%% case re_number(Cs0) of
%% {none,Cs1} -> {none,none,Cs1};
%% {N,[$,|Cs1]} ->
%% case re_number(Cs1) of
%% {none,Cs2} -> {N,any,Cs2};
%% {M,Cs2} -> {N,M,Cs2}
%% end;
%% {N,Cs1} -> {N,none,Cs1}
%% end.
%% re_number([C|Cs]) when C >= $0, C =< $9 ->
%% re_number(Cs, C - $0);
%% re_number(Cs) -> {none,Cs}.
%% re_number([C|Cs], Acc) when C >= $0, C =< $9 ->
%% re_number(Cs, 10*Acc + (C - $0));
%% re_number(Cs, Acc) -> {Acc,Cs}.
string_between(Cs1, Cs2) ->
string:slice(Cs1, 0, string:length(Cs1)-string:length(Cs2)).
%% We use standard methods, Thompson's construction and subset
%% construction, to create first an NFA and then a DFA from the
%% regexps. A non-standard feature is that we work with sets of
%% character ranges (crs) instead sets of characters. This is most
%% noticeable when constructing DFAs. The major benefit is that we can
%% handle characters from any set, not just limited ASCII or 8859,
%% even 16/32 bit unicode.
%%
%% The whole range of characters is 0-maxchar, where maxchar is a BIG
%% number. We don't make any assumptions about the size of maxchar, it
%% is just bigger than any character.
%%
%% Using character ranges makes describing many regexps very simple,
%% for example the regexp "." just becomes the range
%% [{0-9},{11-maxchar}].
%% make_nfa(RegExpActions) -> {ok,{NFA,StartState}} | {error,E}.
%% Build a complete nfa from a list of {RegExp,Action}. The NFA field
%% accept has values {yes,Action}|no. The NFA is a list of states.
make_dfa(REAs, St) ->
{NFA,NF} = build_combined_nfa(REAs),
verbose_print(St, "NFA contains ~w states, ", [tuple_size(NFA)]),
{DFA0,DF0} = build_dfa(NFA, NF),
verbose_print(St, "DFA contains ~w states, ", [length(DFA0)]),
{DFA,DF} = minimise_dfa(DFA0, DF0),
verbose_print(St, "minimised to ~w states.~n", [length(DFA)]),
%%io:fwrite("~p\n", [{NF,NFA}]),
%%io:fwrite("~p\n", [{DF0,DFA0}]),
%%io:fwrite("~p\n", [{DF,DFA}]),
{DFA,DF}.
%% build_combined_nfa(RegExpActionList) -> {NFA,FirstState}.
%% Build the combined NFA using Thompson's construction straight out
%% of the book. Build the separate NFAs in the same order as the
%% rules so that the accepting have ascending states have ascending
%% state numbers. Start numbering the states from 1 as we put the
%% states in a tuple with the state number as the index.
%%
%% The edges from a state are a list of {CharRange,State} | {epsilon,State}.
build_combined_nfa(REAs) ->
{NFA0,Firsts,Free} = build_nfa_list(REAs, [], [], 1),
F = #nfa_state{no=Free,edges=epsilon_trans(Firsts)},
{list_to_tuple(keysort(#nfa_state.no, [F|NFA0])),Free}.
build_nfa_list([{RE,Action}|REAs], NFA0, Firsts, Free0) ->
{NFA1,Free1,First} = build_nfa(RE, Free0, Action),
build_nfa_list(REAs, NFA1 ++ NFA0, [First|Firsts], Free1);
build_nfa_list([], NFA, Firsts, Free) ->
{NFA,reverse(Firsts),Free}.
epsilon_trans(Firsts) -> [ {epsilon,F} || F <- Firsts ].
%% build_nfa(RegExp, NextState, Action) -> {NFA,NextState,FirstState}.
%% When building the NFA states for a regexp we don't build the end
%% state, just allocate a State for it and return this state's
%% number. This allows us to avoid building unnecessary states for
%% concatenation which would then have to be removed by overwriting
%% an existing state.
build_nfa(RE, N0, Action) ->
{NFA,N1,E} = build_nfa(RE, N0+1, N0, []),
{[#nfa_state{no=E,accept={accept,Action}}|NFA],N1,N0}.
%% build_nfa(RegExp, NextState, FirstState, NFA) -> {NFA,NextState,EndState}.
%% Build an NFA from the RegExp. NFA is a list of #nfa_state{} in no
%% predefined order. NextState is the number of the next free state
%% to use, FirstState is the the state which must be the start for
%% this regexp as a previous regexp refers to it, EndState is the
%% state to which this NFA will exit to. The number of the returned
%% EndState is already allocated!