-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
leex.erl
2326 lines (1991 loc) · 85.4 KB
/
leex.erl
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).
-moduledoc """
Lexical analyzer generator for Erlang
A regular expression based lexical analyzer generator for Erlang, similar to
`lex` or `flex`.
> #### Note {: .info }
>
> The `leex` module was considered experimental when it was introduced.
## Default Leex Options
The (host operating system) environment variable `ERL_COMPILER_OPTIONS` can be
used to give default Leex options. Its value must be a valid Erlang term. If the
value is a list, it is used as is. If it is not a list, it is put into a list.
The list is appended to any options given to `file/2`.
The list can be retrieved with `compile:env_compiler_options/0`.
## Input File Format
Erlang style comments starting with a `%` are allowed in scanner files. A
definition file has the following format:
```text
<Header>
Definitions.
<Macro Definitions>
Rules.
<Token Rules>
Erlang code.
<Erlang code>
```
The `Definitions.`, `Rules.`, and `Erlang code` headings are mandatory
and must start at the beginning of a source line. The `<Header>`,
`<Macro Definitions>`, and `<Erlang code>` sections are allowed to be
empty, but there must be at least one rule.
Macro definitions have the following format:
```text
NAME = VALUE
```
and there must be spaces around `=`. Macros can be used in the regular
expressions of rules by writing `{NAME}`.
> #### Note {: .info }
>
> When macros are expanded in expressions, the macro calls are replaced by the
> macro value without any form of quoting or enclosing in parentheses.
Rules have the following format:
```text
<Regexp> : <Erlang code>.
```
The `<Regexp>` must occur at the start of a line and not include any blanks; use
`\t` and `\s` to include TAB and SPACE characters in the regular expression. If
`<Regexp>` matches then the corresponding `<Erlang code>` is evaluated to generate a
token. With the Erlang code the following predefined variables are available:
- **`TokenChars`** - A list of the characters in the matched token.
- **`TokenLen`** - The number of characters in the matched token.
- **`TokenLine`** - The line number where the token occurred.
- **`TokenCol`** - The column number where the token occurred (column of the
first character included in the token).
- **`TokenLoc`** - Token location. Expands to `{TokenLine,TokenCol}` (even when
`error_location` is set to `line`).
The code must return:
- **`{token,Token}`** - Return `Token` to the caller.
- **`{end_token,Token}`** - Return `Token` and is last token in a tokens call.
- **`skip_token`** - Skip this token completely.
- **`{error,ErrString}`** - An error in the token, `ErrString` is a string
describing the error.
It is also possible to push back characters into the input characters with the
following returns:
- `{token,Token,PushBackList}`
- `{end_token,Token,PushBackList}`
- `{skip_token,PushBackList}`
These have the same meanings as the normal returns but the characters in
`PushBackList` will be prepended to the input characters and scanned for the
next token. Note that pushing back a newline will mean the line numbering will
no longer be correct.
> #### Note {: .info }
>
> Pushing back characters gives you unexpected possibilities to cause the
> scanner to loop\!
The following example would match a simple Erlang integer or float and return a
token which could be sent to the Erlang parser:
```erlang
D = [0-9]
{D}+ :
{token,{integer,TokenLine,list_to_integer(TokenChars)}}.
{D}+\.{D}+((E|e)(\+|\-)?{D}+)? :
{token,{float,TokenLine,list_to_float(TokenChars)}}.
```
The Erlang code in the `Erlang code.` section is written into the output file
directly after the module declaration and predefined exports declaration, making
it possible to add extra exports, define imports, and other attributes, which are
visible in the whole file.
## Regular Expressions
The regular expressions allowed here is a subset of the set found in `egrep` and
in the AWK programming language, as defined in the book _The AWK Programming
Language_ by A. V. Aho, B. W. Kernighan, and P. J. Weinberger. They are composed of
the following characters:
- **`c`** - Matches the non-metacharacter c.
- **`\c`** - Matches the escape sequence or literal character c.
- **`.`** - Matches any character.
- **`^`** - Matches the beginning of a string.
- **`$`** - Matches the end of a string.
- **`[abc...]`** - Character class, which matches any of the characters
`abc...`. Character ranges are specified by a pair of characters separated by
a `-`.
- **`[^abc...]`** - Negated character class, which matches any character except
`abc...`.
- **`r1 | r2`** - Alternation. It matches either `r1` or `r2`.
- **`r1r2`** - Concatenation. It matches `r1` and then `r2`.
- **`r+`** - Matches one or more `r`s.
- **`r*`** - Matches zero or more `r`s.
- **`r?`** - Matches zero or one `r`s.
- **`(r)`** - Grouping. It matches `r`.
The escape sequences allowed are the same as for Erlang strings:
- **`\b`** - Backspace.
- **`\f`** - Form feed.
- **`\n`** - Newline (line feed).
- **`\r`** - Carriage return.
- **`\t`** - Tab.
- **`\e`** - Escape.
- **`\v`** - Vertical tab.
- **`\s`** - Space.
- **`\d`** - Delete.
- **`\ddd`** - The octal value `ddd`.
- **`\xhh`** - The hexadecimal value `hh`.
- **`\x{h...}`** - The hexadecimal value `h...`.
- **`\c`** - Any other character literally, for example `\\` for backslash, `\"`
for `"`.
The following examples define simplified versions of a few Erlang data types:
```text
Atoms [a-z][0-9a-zA-Z_]*
Variables [A-Z_][0-9a-zA-Z_]*
Floats (\+|-)?[0-9]+\.[0-9]+((E|e)(\+|-)?[0-9]+)?
```
> #### Note {: .info }
>
> Anchoring a regular expression with `^` and `$` is not implemented in the
> current version of `leex` and generates a parse error.
""".
-moduledoc(#{titles => [{function,<<"Generated Scanner Exports">>}]}).
-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}).
%%%
%%% Functions that generated scanner exports,
%%% only used for documentation purposes
%%%
-export([string/1, string/2, token/2, token/3, tokens/2, tokens/3]).
-doc #{equiv => string(String, 1)}.
-doc(#{title => <<"Generated Scanner Exports">>}).
-spec string(String) -> StringRet when
String :: string(),
StringRet :: {ok, Tokens, EndLoc} | ErrorInfo,
Tokens :: [Token],
Token :: term(),
ErrorInfo :: {error, error_info(), erl_anno:location()},
EndLoc :: erl_anno:location().
string(_String) -> error(undef).
-doc """
Scans `String` and returns either all the tokens in it or an `error` tuple.
`StartLoc` and `EndLoc` are either [`erl_anno:line()`](`t:erl_anno:line/0`)
or [`erl_anno:location()`](`t:erl_anno:location/0`), depending on the
`error_location` option.
> #### Note {: .info }
>
> It is an error if not all of the characters in `String` are consumed.
""".
-doc(#{title => <<"Generated Scanner Exports">>}).
-spec string(String, StartLoc) -> StringRet when
String :: string(),
StringRet :: {ok, Tokens, EndLoc} | ErrorInfo,
Tokens :: [Token],
Token :: term(),
ErrorInfo :: {error, error_info(), erl_anno:location()},
StartLoc :: erl_anno:location(),
EndLoc :: erl_anno:location().
string(_String, _StartLoc) -> error(undef).
-doc #{equiv => token(Cont, Chars, 1)}.
-doc(#{title => <<"Generated Scanner Exports">>}).
-spec token(Cont, Chars) ->
{more, Cont1} | {done, TokenRet, RestChars} when
Cont :: [] | Cont1,
Cont1 :: tuple(),
Chars :: string() | eof,
RestChars :: string() | eof,
TokenRet :: {ok, Token, EndLoc} |
{eof, EndLoc} |
ErrorInfo,
ErrorInfo :: {error, error_info(), erl_anno:location()},
Token :: term(),
EndLoc :: erl_anno:location().
token(_Cont, _Chars) -> error(undef).
-doc """
This is a re-entrant call to try and scan a single token from `Chars`.
If there are enough characters in `Chars` to either scan a token or
detect an error then this will be returned with
`{done,...}`. Otherwise `{cont,Cont}` will be returned where `Cont` is
used in the next call to `token()` with more characters to try an scan
the token. This is continued until a token has been scanned. `Cont` is
initially `[]`.
It is not designed to be called directly by an application, but is
used through the I/O system where it can typically be called in an
application by:
```erlang
io:request(InFile, {get_until,unicode,Prompt,Module,token,[Loc]})
-> TokenRet
```
""".
-doc(#{title => <<"Generated Scanner Exports">>}).
-spec token(Cont, Chars, StartLoc) ->
{more, Cont1} | {done, TokenRet, RestChars} when
Cont :: [] | Cont1,
Cont1 :: tuple(),
Chars :: string() | eof,
RestChars :: string() | eof,
TokenRet :: {ok, Token, EndLoc} |
{eof, EndLoc} |
ErrorInfo,
ErrorInfo :: {error, error_info(), erl_anno:location()},
Token :: term(),
StartLoc :: erl_anno:location(),
EndLoc :: erl_anno:location().
token(_Cont, _Chars, _StartLoc) -> error(undef).
-doc #{equiv => tokens(Cont, Chars, 1)}.
-doc(#{title => <<"Generated Scanner Exports">>}).
-spec tokens(Cont, Chars) ->
{more, Cont1} | {done, TokensRet, RestChars} when
Cont :: [] | Cont1,
Cont1 :: tuple(),
Chars :: string() | eof,
RestChars :: string() | eof,
TokensRet :: {ok, Tokens, EndLoc} |
{eof, EndLoc} |
ErrorInfo,
Tokens :: [Token],
Token :: term(),
ErrorInfo :: {error, error_info(), erl_anno:location()},
EndLoc :: erl_anno:location().
tokens(_Cont, _Chars) -> error(undef).
-doc """
This is a re-entrant call to try and scan tokens from `Chars`.
If there are enough characters in `Chars` to either scan tokens or
detect an error then this will be returned with
`{done,...}`. Otherwise `{cont,Cont}` will be returned where `Cont` is
used in the next call to `tokens()` with more characters to try an
scan the tokens. This is continued until all tokens have been
scanned. `Cont` is initially `[]`.
This functions differs from `token` in that it will continue to scan tokens up
to and including an `{end_token,Token}` has been scanned (see next section). It
will then return all the tokens. This is typically used for scanning grammars
like Erlang where there is an explicit end token, `'.'`. If no end token is
found then the whole file will be scanned and returned. If an error occurs then
all tokens up to and including the next end token will be skipped.
It is not designed to be called directly by an application, but used through the
I/O system where it can typically be called in an application by:
```erlang
io:request(InFile, {get_until,unicode,Prompt,Module,tokens,[Loc]})
-> TokensRet
```
""".
-doc(#{title => <<"Generated Scanner Exports">>}).
-spec tokens(Cont, Chars, StartLoc) ->
{more, Cont1} | {done, TokensRet, RestChars} when
Cont :: [] | Cont1,
Cont1 :: tuple(),
Chars :: string() | eof,
RestChars :: string() | eof,
TokensRet :: {ok, Tokens, EndLoc} |
{eof, EndLoc} |
ErrorInfo,
Tokens :: [Token],
Token :: term(),
ErrorInfo :: {error, error_info(), erl_anno:location()},
StartLoc :: erl_anno:location(),
EndLoc :: erl_anno:location().
tokens(_Cont, _Chars, _StartLoc) -> error(undef).
%%%
%%% Exported functions
%%%
%%% Interface to erl_compile.
-doc false.
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),
Deterministic = proplists:get_bool(deterministic, Specific),
Opts = [{scannerfile,Output},{includefile,Includefile},{verbose,Verbose},
{report_errors,true},{report_warnings,WarnLevel > 0},
{warnings_as_errors, Werror}, {deterministic, Deterministic}],
case file(Input, Opts) of
{ok, _} ->
ok;
error ->
error
end.
-doc """
The standard `t:error_info/0` structure that is returned from all I/O modules.
`ErrorDescriptor` is formattable by `format_error/1`.
""".
-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().
-doc #{equiv => file(File, [])}.
-spec file(FileName) -> leex_ret() when
FileName :: file:filename().
file(File) -> file(File, []).
-doc """
Generates a lexical analyzer from the definition in the input file.
The input file has the extension `.xrl`. This is added to the filename
if it is not given. The resulting module is the Xrl filename without
the `.xrl` extension.
The current options are:
- **`dfa_graph`** - Generates a `.dot` file which contains a description of the
DFA in a format which can be viewed with Graphviz, `www.graphviz.com`.
- **`{includefile,Includefile}`** - Uses a specific or customised prologue file
instead of default `lib/parsetools/include/leexinc.hrl` which is otherwise
included.
- **`{report_errors, boolean()}`** - Causes errors to be printed as they occur.
Default is `true`.
- **`{report_warnings, boolean()}`** - Causes warnings to be printed as they
occur. Default is `true`.
- **`{report, boolean()}`** - This is a short form for both `report_errors` and
`report_warnings`.
- **`{return_errors, boolean()}`** - If this flag is set,
`{error, Errors, Warnings}` is returned when there are errors. Default is
`false`.
- **`{return_warnings, boolean()}`** - If this flag is set, an extra field
containing `Warnings` is added to the tuple returned upon success. Default is
`false`.
- **`{return, boolean()}`** - This is a short form for both `return_errors` and
`return_warnings`.
- **`{scannerfile, Scannerfile}`** - `Scannerfile` is the name of the file that
will contain the Erlang scanner code that is generated. The default (`""`) is
to add the extension `.erl` to `FileName` stripped of the `.xrl` extension.
- **`{verbose, boolean()}`** - Outputs information from parsing the input file
and generating the internal tables.
- **`{warnings_as_errors, boolean()}`** - Causes warnings to be treated as
errors.
- **`{deterministic, boolean()}`** - Causes generated `-file()` attributes to only
include the basename of the file path.
- **`{error_location, line | column}`** - If set to `column`, error location
will be `{Line,Column}` tuple instead of just `Line`. Also, `StartLoc` and
`EndLoc` in [`string/2`](`string/2`), [`token/3`](`token/3`), and
[`tokens/3`](`tokens/3`) functions will be `{Line,Column}` tuple instead of
just `Line`. Default is `line`. Note that you can use `TokenLoc` for token
location independently, even if the `error_location` is set to `line`.
Unicode characters are counted as many columns as they use bytes to represent.
- **`{tab_size, pos_integer()}`** - Sets the width of `\t` character (only
relevant if `error_location` is set to `column`). Default is `8`.
Any of the Boolean options can be set to `true` by stating the name of the
option. For example, `verbose` is equivalent to `{verbose, true}`.
Leex will add the extension `.hrl` to the `Includefile` name and the extension
`.erl` to the `Scannerfile` name, unless the extension is already there.
""".
-doc(#{since => <<"OTP R16B02">>}).
-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()}
| {'deterministic', boolean()}
| {'error_location', line | column}
| {'tab_size', pos_integer()}
| '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]).
-doc """
Returns a descriptive string in English of an error reason `ErrorDescriptor`
returned by [`leex:file/1,2`](`file/1`) when there is an error in a regular
expression.
""".
-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([{error_location, Loc}=O | Options], AllOptions, L)
when Loc =:= line; Loc =:= column ->
check_options(Options, AllOptions, [O | L]);
check_options([{tab_size, S}=O | Options], AllOptions, L)
when is_integer(S) andalso S>0 ->
check_options(Options, AllOptions, [O | L]);
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,deterministic,error_location,tab_size].
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;
default_option(deterministic) -> false;
default_option(error_location) -> line;
default_option(tab_size) -> 8.
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(deterministic) -> {deterministic,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) ->