-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathyecc.erl
3315 lines (2921 loc) · 119 KB
/
yecc.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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%% Yacc like LALR-1 parser generator for Erlang.
%% Ref: Aho & Johnson: "LR Parsing", ACM Computing Surveys, vol. 6:2, 1974.
%% Auxiliary files: yeccgramm.yrl, yeccparser.erl, yeccpre.hrl, yeccscan.erl.
%%
-module(yecc).
-moduledoc """
LALR-1 Parser Generator
An LALR-1 parser generator for Erlang, similar to `yacc`. Takes a BNF grammar
definition as input, and produces Erlang code for a parser.
To understand this text, you also have to look at the `yacc` documentation in
the UNIX(TM) manual. This is most probably necessary in order to understand the
idea of a parser generator, and the principle and problems of LALR parsing with
finite look-ahead.
An nice introduction to `yacc` can be found in chapter 8 of "The UNIX
Programming Environment" by Brian W. Kernighan and Rob Pike.
## Default Yecc Options
The (host operating system) environment variable `ERL_COMPILER_OPTIONS` can be
used to give default Yecc 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`.
## Pre-Processing
A `scanner` to pre-process the text (program) to be parsed is not provided
in the `yecc` module. The scanner serves as a kind of lexicon look-up routine.
It is possible to write a grammar that uses only character tokens as terminal
symbols, thereby eliminating the need for a scanner, but this would make the
parser larger and slower.
The user should implement a scanner that segments the input text, and turns it
into one or more lists of tokens. Each token should be a tuple containing
information about syntactic category, position in the text (for example
line number), and the actual terminal symbol found in the text:
`{Category, Position, Symbol}`.
If a terminal symbol is the only member of a category, and the symbol name is
identical to the category name, the token format can be `{Symbol, Position}`.
A list of tokens produced by the scanner should end with a special
`end_of_input` tuple which the parser is looking for. The format of this tuple
should be `{Endsymbol, EndPosition}`, where `Endsymbol` is an identifier that is
distinguished from all the terminal and non-terminal categories of the syntax
rules. The `Endsymbol` can be declared in the grammar file.
The simplest case is to segment the input string into a list of identifiers
(atoms) and use those atoms both as categories and values of the tokens. For
example, the input string `aaa bbb 777, X` may be scanned (tokenized) as:
```erlang
[{aaa, 1}, {bbb, 1}, {777, 1}, {',' , 1}, {'X', 1},
{'$end', 1}].
```
This assumes that this is the first line of the input text, and that `'$end'` is
the distinguished `end_of_input` symbol.
The Erlang scanner in the `io` module can be used as a starting point when
writing a new scanner. Study `yeccscan.erl` in order to see how a filter can be
added on top of `io:scan_erl_form/3` to provide a scanner for Yecc that
tokenizes grammar files before parsing them with the Yecc parser. A more general
approach to scanner implementation is to use a scanner generator such as
`m:leex`.
## Grammar Definition Format
Erlang style `comments`, starting with a `'%'`, are allowed in grammar files.
Each `declaration` or `rule` ends with a dot (the character `'.'`).
The grammar starts with an optional `header` section. The header is put first in
the generated file, before the module declaration. The purpose of the header is
to provide a means to make the documentation generated by [EDoc](`e:edoc:edoc.md`)
look nicer. Each header line should be enclosed in double quotes, and newlines
will be inserted between the lines. For example:
```erlang
Header "%% Copyright (C)"
"%% @private"
"%% @Author John".
```
Next comes a declaration of the `nonterminal categories` to be used in the
rules. For example:
```text
Nonterminals sentence nounphrase verbphrase.
```
A non-terminal category can be used at the left-hand side (= `lhs`, or `head`)
of a grammar rule. It can also appear at the right-hand side of rules.
Next comes a declaration of the `terminal categories`, which are the categories
of tokens produced by the scanner. For example:
```text
Terminals article adjective noun verb.
```
Terminal categories may only appear in the right hand sides (= `rhs`) of grammar
rules.
Next comes a declaration of the `rootsymbol`, or start category of the grammar.
For example:
```text
Rootsymbol sentence.
```
This symbol should appear in the lhs of at least one grammar rule. This is the
most general syntactic category which the parser ultimately will parse every
input string into.
After the rootsymbol declaration comes an optional declaration of the
`end_of_input` symbol that your scanner is expected to use. For example:
```text
Endsymbol '$end'.
```
Next comes one or more declarations of *operator precedences*, if needed. These
are used to resolve shift/reduce conflicts (see `yacc` documentation).
Examples of operator declarations:
```text
Right 100 '='.
Nonassoc 200 '==' '=/='.
Left 300 '+'.
Left 400 '*'.
Unary 500 '-'.
```
These declarations mean that `'='` is defined as a `right associative binary`
operator with precedence 100, `'=='` and `'=/='` are operators with
`no associativity`, `'+'` and `'*'` are `left associative binary` operators,
where `'*'` takes precedence over `'+'` (the normal case), and `'-'` is a
`unary` operator of higher precedence than `'*'`. The fact that '==' has no
associativity means that an expression like `a == b == c` is considered a syntax
error.
Certain rules are assigned precedence: each rule gets its precedence from the
last terminal symbol mentioned in the right hand side of the rule. It is also
possible to declare precedence for non-terminals, "one level up". This is
practical when an operator is overloaded (see also example 3 below).
Next come the *grammar rules*. Each rule has the general form
```erlang
Left_hand_side -> Right_hand_side : Associated_code.
```
The left hand side is a non-terminal category. The right hand side is a sequence
of one or more non-terminal or terminal symbols with spaces between. The
associated code is a sequence of zero or more Erlang expressions (with commas
`','` as separators). If the associated code is empty, the separating colon
`':'` is also omitted. A final dot marks the end of the rule.
Symbols such as `'{'`, `'.'`, and so on, have to be enclosed in single quotes
when used as terminal or non-terminal symbols in grammar rules. The use of the
symbols `'$empty'`, `'$end'`, and `'$undefined'` should be avoided.
The last part of the grammar file is an optional section with Erlang code (=
function definitions) which is included 'as is' in the resulting parser file.
This section must start with the pseudo declaration, or key words
```text
Erlang code.
```
No syntax rule definitions or other declarations must follow this section. To
avoid conflicts with internal variables, do not use variable names beginning
with two underscore characters (`'__'`) in the Erlang code in this section, or
in the code associated with the individual syntax rules.
The optional `expect` declaration can be placed anywhere before the last
optional section with Erlang code. It is used for suppressing the warning about
conflicts that is ordinarily given if the grammar is ambiguous. An example:
```text
Expect 2.
```
The warning is given if the number of shift/reduce conflicts differs from 2, or
if there are reduce/reduce conflicts.
## Examples
A grammar to parse list expressions (with empty associated code):
```text
Nonterminals list elements element.
Terminals atom '(' ')'.
Rootsymbol list.
list -> '(' ')'.
list -> '(' elements ')'.
elements -> element.
elements -> element elements.
element -> atom.
element -> list.
```
This grammar can be used to generate a parser which parses list expressions,
such as `(), (a), (peter charles), (a (b c) d (())), ...` provided that your
scanner tokenizes, for example, the input `(peter charles)` as follows:
```erlang
[{'(', 1} , {atom, 1, peter}, {atom, 1, charles}, {')', 1},
{'$end', 1}]
```
When a grammar rule is used by the parser to parse (part of) the input string as
a grammatical phrase, the associated code is evaluated, and the value of the
last expression becomes the value of the parsed phrase. This value may be used
by the parser later to build structures that are values of higher phrases of
which the current phrase is a part. The values initially associated with
terminal category phrases, i.e. input tokens, are the token tuples themselves.
Below is an example of the grammar above with structure building code added:
```text
list -> '(' ')' : nil.
list -> '(' elements ')' : '$2'.
elements -> element : {cons, '$1', nil}.
elements -> element elements : {cons, '$1', '$2'}.
element -> atom : '$1'.
element -> list : '$1'.
```
With this code added to the grammar rules, the parser produces the following
value (structure) when parsing the input string `(a b c).`. This still assumes
that this was the first input line that the scanner tokenized:
```erlang
{cons, {atom, 1, a}, {cons, {atom, 1, b},
{cons, {atom, 1, c}, nil}}}
```
The associated code contains `pseudo variables` `'$1'`, `'$2'`,
`'$3'`, and so on. which refer to (are bound to) the values
associated previously by the parser with the symbols of the right-hand
side of the rule. When these symbols are terminal categories, the
values are token tuples of the input string (see above).
The associated code may not only be used to build structures
associated with phrases, but may also be used for syntactic and
semantic tests, printout actions (for example for tracing), and so on
during the parsing process. Since tokens contain positional (line
number) information, it is possible to produce error messages which
contain line numbers. If there is no associated code after the
right-hand side of the rule, the value `'$undefined'` is associated
with the phrase.
The right-hand side of a grammar rule can be empty. This is indicated by using
the special symbol `'$empty'` as rhs. Then the list grammar above can be
simplified to:
```text
list -> '(' elements ')' : '$2'.
elements -> element elements : {cons, '$1', '$2'}.
elements -> '$empty' : nil.
element -> atom : '$1'.
element -> list : '$1'.
```
## Generating a Parser
To call the parser generator, use the following command:
```erlang
yecc:file(Grammarfile).
```
An error message from Yecc will be shown if the grammar is not of the LALR type
(for example too ambiguous). Shift/reduce conflicts are resolved in favor of
shifting if there are no operator precedence declarations. Refer to the `yacc`
documentation on the use of operator precedence.
The output file contains Erlang source code for a parser module with module name
equal to the `Parserfile` parameter. After compilation, the parser can be called
as follows (the module name is assumed to be `myparser`):
```erlang
myparser:parse(myscanner:scan(Inport))
```
The call format can be different if a customized prologue file has been included
when generating the parser instead of the default file
`lib/parsetools/include/yeccpre.hrl`.
With the standard prologue, this call will return either `{ok, Result}`, where
`Result` is a structure that the Erlang code of the grammar file has built, or
`{error, {Position, Module, Message}}` if there was a syntax error in the input.
`Message` is something which may be converted into a string by calling
`Module:format_error(Message)` and printed with `io:format/3`.
> #### Note {: .info }
>
> By default, the parser that was generated will not print out error messages to
> the screen. The user will have to do this either by printing the returned
> error messages, or by inserting tests and print instructions in the Erlang
> code associated with the syntax rules of the grammar file.
It is also possible to make the parser ask for more input tokens when needed if
the following call format is used:
```erlang
myparser:parse_and_scan({Function, Args})
myparser:parse_and_scan({Mod, Tokenizer, Args})
```
The tokenizer `Function` is either a fun or a tuple `{Mod, Tokenizer}`. The call
[`apply(Function, Args)`](`apply/2`) or
[`apply({Mod, Tokenizer}, Args)`](`apply/2`) is executed whenever a new token is
needed. This, for example, makes it possible to parse from a file, token by
token.
The tokenizer used above has to be implemented so as to return one of the
following:
```erlang
{ok, Tokens, EndPosition}
{eof, EndPosition}
{error, Error_description, EndPosition}
```
This conforms to the format used by the scanner in the Erlang `io` library
module.
If `{eof, EndPosition}` is returned immediately, the call to `parse_and_scan/1`
returns `{ok, eof}`. If `{eof, EndPosition}` is returned before the parser
expects end of input, `parse_and_scan/1` will, of course, return an error
message (see above). Otherwise `{ok, Result}` is returned.
## More Examples
1\. A grammar for parsing infix arithmetic expressions into prefix notation,
without operator precedence:
```text
Nonterminals E T F.
Terminals '+' '*' '(' ')' number.
Rootsymbol E.
E -> E '+' T: {'$2', '$1', '$3'}.
E -> T : '$1'.
T -> T '*' F: {'$2', '$1', '$3'}.
T -> F : '$1'.
F -> '(' E ')' : '$2'.
F -> number : '$1'.
```
2\. The same with operator precedence becomes simpler:
```text
Nonterminals E.
Terminals '+' '*' '(' ')' number.
Rootsymbol E.
Left 100 '+'.
Left 200 '*'.
E -> E '+' E : {'$2', '$1', '$3'}.
E -> E '*' E : {'$2', '$1', '$3'}.
E -> '(' E ')' : '$2'.
E -> number : '$1'.
```
3\. An overloaded minus operator:
```text
Nonterminals E uminus.
Terminals '*' '-' number.
Rootsymbol E.
Left 100 '-'.
Left 200 '*'.
Unary 300 uminus.
E -> E '-' E.
E -> E '*' E.
E -> uminus.
E -> number.
uminus -> '-' E.
```
4\. The Yecc grammar that is used for parsing grammar files, including itself:
```erlang
Nonterminals
grammar declaration rule head symbol symbols attached_code
token tokens.
Terminals
atom float integer reserved_symbol reserved_word string char var
'->' ':' dot.
Rootsymbol grammar.
Endsymbol '$end'.
grammar -> declaration : '$1'.
grammar -> rule : '$1'.
declaration -> symbol symbols dot: {'$1', '$2'}.
rule -> head '->' symbols attached_code dot: {rule, ['$1' | '$3'],
'$4'}.
head -> symbol : '$1'.
symbols -> symbol : ['$1'].
symbols -> symbol symbols : ['$1' | '$2'].
attached_code -> ':' tokens : {erlang_code, '$2'}.
attached_code -> '$empty' : {erlang_code,
[{atom, 0, '$undefined'}]}.
tokens -> token : ['$1'].
tokens -> token tokens : ['$1' | '$2'].
symbol -> var : value_of('$1').
symbol -> atom : value_of('$1').
symbol -> integer : value_of('$1').
symbol -> reserved_word : value_of('$1').
token -> var : '$1'.
token -> atom : '$1'.
token -> float : '$1'.
token -> integer : '$1'.
token -> string : '$1'.
token -> char : '$1'.
token -> reserved_symbol : {value_of('$1'), line_of('$1')}.
token -> reserved_word : {value_of('$1'), line_of('$1')}.
token -> '->' : {'->', line_of('$1')}.
token -> ':' : {':', line_of('$1')}.
Erlang code.
value_of(Token) ->
element(3, Token).
line_of(Token) ->
element(2, Token).
```
> #### Note {: .info }
>
> The symbols `'->'`, and `':'` have to be treated in a special way, as they are
> meta symbols of the grammar notation, as well as terminal symbols of the Yecc
> grammar.
5\. The file `erl_parse.yrl` in the `lib/stdlib/src` directory contains the
grammar for Erlang.
> #### Note {: .info }
>
> Syntactic tests are used in the code associated with some rules, and an error
> is thrown (and caught by the generated parser to produce an error message)
> when a test fails. The same effect can be achieved with a call to
> `return_error(ErrorPosition, Message_string)`, which is defined in the
> `yeccpre.hrl` default header file.
## Files
```text
lib/parsetools/include/yeccpre.hrl
```
## See Also
* Aho & Johnson: 'LR Parsing', ACM Computing Surveys, vol. 6:2, 1974.
* Kernighan & Pike: The UNIX programming environment, 1984.
""".
-export([compile/3, file/1, file/2, format_error/1]).
-export_type([option/0, yecc_ret/0]).
%% Kept for compatibility with R10B.
-export([yecc/2, yecc/3, yecc/4]).
-import(lists, [append/1, append/2, concat/1, delete/2, filter/2,
flatmap/2, foldl/3, foldr/3, foreach/2, keydelete/3,
keysort/2, last/1, map/2, member/2, reverse/1,
sort/1, usort/1]).
-include("erl_compile.hrl").
-include("ms_transform.hrl").
-record(yecc, {
infile,
outfile,
includefile,
includefile_version,
module,
encoding = none,
options = [],
verbose = false,
file_attrs = true,
errors = [],
warnings = [],
conflicts_done = false,
shift_reduce = [],
reduce_reduce = [],
n_states = 0,
inport,
outport,
line,
parse_actions,
symbol_tab,
inv_symbol_tab,
state_tab,
prec_tab,
goto_tab,
terminals = [],
nonterminals = [],
all_symbols = [],
prec = [],
rules_list = [],
rules, % a tuple of rules_list
rule_pointer2rule,
rootsymbol = [],
endsymbol = [],
expect_shift_reduce = [],
expect_n_states = [],
header = [],
erlang_code = none
}).
-record(rule, {
n, % rule n in the grammar file
location,
symbols, % the names of symbols
tokens,
is_guard, % the action is a guard (not used)
is_well_formed % can be parsed (without macro expansion)
}).
-record(reduce, {
rule_nmbr,
head,
nmbr_of_daughters,
prec,
unused % assure that #reduce{} comes before #shift{} when sorting
}).
-record(shift, {
state,
pos,
prec,
rule_nmbr
}).
-record(user_code, {state, terminal, funname, action}).
-record(symbol, {anno = none, name}).
%% ACCEPT is neither an atom nor a non-terminal.
-define(ACCEPT, {}).
%% During the phase 'compute_states' terminals in lookahead sets are
%% coded as integers; sets of terminals are integer bit masks. This is
%% for efficiency only. '$empty' is always given the mask 1. The
%% behaviour can be turned off by un-defining SYMBOLS_AS_CODES (useful
%% when debugging).
%% Non-terminals are also given integer codes, starting with -1. The
%% absolute value of the code is used for indexing a tuple of lists of
%% rules.
-define(SYMBOLS_AS_CODES, true).
-ifdef(SYMBOLS_AS_CODES).
-define(EMPTY, 0).
-else.
-define(EMPTY, '$empty').
-endif.
%%%
%%% Exported functions
%%%
%%% Interface to erl_compile.
-doc false.
compile(Input0, Output0,
#options{warning = WarnLevel, verbose=Verbose, includes=Includes,
specific=Specific}) ->
Input = shorten_filename(Input0),
Output = shorten_filename(Output0),
Includefile = lists:sublist(Includes, 1),
Werror = proplists:get_bool(warnings_as_errors, Specific),
Deterministic = proplists:get_bool(deterministic, Specific),
Opts = [{parserfile,Output}, {includefile,Includefile}, {verbose,Verbose},
{report_errors, true}, {report_warnings, WarnLevel > 0},
{warnings_as_errors, Werror}, {deterministic, Deterministic}],
case file(Input, Opts) of
{ok, _OutFile} ->
ok;
error ->
error
end.
-doc """
Returns a descriptive string in English of an error reason `ErrorDescriptor`
returned by `yecc:file/1,2`.
This function is mainly used by the compiler invoking Yecc.
""".
-spec format_error(ErrorDescriptor) -> io_lib:chars() when
ErrorDescriptor :: term().
format_error(bad_declaration) ->
io_lib:fwrite("unknown or bad declaration, ignored", []);
format_error({bad_expect, SymName}) ->
io_lib:fwrite("argument ~ts of Expect is not an integer",
[format_symbol(SymName)]);
format_error({bad_rootsymbol, SymName}) ->
io_lib:fwrite("rootsymbol ~ts is not a nonterminal",
[format_symbol(SymName)]);
format_error({bad_states, SymName}) ->
io_lib:fwrite("argument ~ts of States is not an integer",
[format_symbol(SymName)]);
format_error({conflict, Conflict}) ->
format_conflict(Conflict);
format_error({conflicts, SR, RR}) ->
io_lib:fwrite("conflicts: ~w shift/reduce, ~w reduce/reduce", [SR, RR]);
format_error({duplicate_declaration, Tag}) ->
io_lib:fwrite("duplicate declaration of ~s", [atom_to_list(Tag)]);
format_error({duplicate_nonterminal, Nonterminal}) ->
io_lib:fwrite("duplicate non-terminals ~ts",
[format_symbol(Nonterminal)]);
format_error({duplicate_precedence, Op}) ->
io_lib:fwrite("duplicate precedence operator ~ts",
[format_symbol(Op)]);
format_error({duplicate_terminal, Terminal}) ->
io_lib:fwrite("duplicate terminal ~ts",
[format_symbol(Terminal)]);
format_error({endsymbol_is_nonterminal, Symbol}) ->
io_lib:fwrite("endsymbol ~ts is a nonterminal",
[format_symbol(Symbol)]);
format_error({endsymbol_is_terminal, Symbol}) ->
io_lib:fwrite("endsymbol ~ts is a terminal",
[format_symbol(Symbol)]);
format_error({error, Module, Error}) ->
Module:format_error(Error);
format_error({file_error, Reason}) ->
io_lib:fwrite("~ts",[file:format_error(Reason)]);
format_error(illegal_empty) ->
io_lib:fwrite("illegal use of empty symbol", []);
format_error({internal_error, Error}) ->
io_lib:fwrite("internal yecc error: ~w", [Error]);
format_error({missing_syntax_rule, Nonterminal}) ->
io_lib:fwrite("no syntax rule for non-terminal symbol ~ts",
[format_symbol(Nonterminal)]);
format_error({n_states, Exp, N}) ->
io_lib:fwrite("expected ~w states, but got ~p states", [Exp, N]);
format_error(no_grammar_rules) ->
io_lib:fwrite("grammar rules are missing", []);
format_error(nonterminals_missing) ->
io_lib:fwrite("Nonterminals is missing", []);
format_error({precedence_op_is_endsymbol, SymName}) ->
io_lib:fwrite("precedence operator ~ts is endsymbol",
[format_symbol(SymName)]);
format_error({precedence_op_is_unknown, SymName}) ->
io_lib:fwrite("unknown precedence operator ~ts",
[format_symbol(SymName)]);
format_error({reserved, N}) ->
io_lib:fwrite("the use of ~w should be avoided", [N]);
format_error({symbol_terminal_and_nonterminal, SymName}) ->
io_lib:fwrite("symbol ~ts is both a terminal and nonterminal",
[format_symbol(SymName)]);
format_error(rootsymbol_missing) ->
io_lib:fwrite("Rootsymbol is missing", []);
format_error(terminals_missing) ->
io_lib:fwrite("Terminals is missing", []);
format_error({undefined_nonterminal, Symbol}) ->
io_lib:fwrite("undefined nonterminal: ~ts", [format_symbol(Symbol)]);
format_error({undefined_pseudo_variable, Atom}) ->
io_lib:fwrite("undefined pseudo variable ~w", [Atom]);
format_error({undefined_symbol, SymName}) ->
io_lib:fwrite("undefined rhs symbol ~ts", [format_symbol(SymName)]);
format_error({unused_nonterminal, Nonterminal}) ->
io_lib:fwrite("non-terminal symbol ~ts not used",
[format_symbol(Nonterminal)]);
format_error({unused_terminal, Terminal}) ->
io_lib:fwrite("terminal symbol ~ts not used",
[format_symbol(Terminal)]);
format_error({bad_symbol, String}) ->
io_lib:fwrite("bad symbol ~ts", [String]);
format_error(cannot_parse) ->
io_lib:fwrite("cannot parse; possibly encoding mismatch", []).
-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:location() | 'none',
module(), ErrorDescriptor :: term()}.
-type errors() :: [{file:filename(), [error_info()]}].
-type warnings() :: [{file:filename(), [error_info()]}].
-type ok_ret() :: {'ok', Parserfile :: file:filename()}
| {'ok', Parserfile :: file:filename(), warnings()}.
-type error_ret() :: 'error'
| {'error', Errors :: errors(), Warnings :: warnings()}.
-type yecc_ret() :: ok_ret() | error_ret().
-type option() :: {'error_location', 'column' | 'line'}
| {'includefile', Includefile :: file:filename()}
| {'report_errors', boolean()}
| {'report_warnings', boolean()}
| {'report', boolean()}
| {'return_errors', boolean()}
| {'return_warnings', boolean()}
| {'return', boolean()}
| {'parserfile', Parserfile :: file:filename()}
| {'verbose', boolean()}
| {'warnings_as_errors', boolean()}
| {'deterministic', boolean()}
| 'report_errors' | 'report_warnings' | 'report'
| 'return_errors' | 'return_warnings' | 'return'
| 'verbose' | 'warnings_as_errors'.
-doc #{equiv => file(GrammarFile, [report_errors, report_warnings])}.
-spec file(GrammarFile) -> yecc_ret() when
GrammarFile :: file:filename().
file(GrammarFile) ->
file(GrammarFile, [report_errors, report_warnings]).
-doc """
Generates an Erlang file with the parser for the language described by `GrammarFile`.
`Grammarfile` is the file of declarations and grammar rules. Returns `ok` upon
success, or `error` if there are errors. An Erlang file containing the parser is
created if there are no errors.
The options are:
- **`{includefile, Includefile}`.** - Indicates a customized prologue file which
the user may want to use instead of the default file
`lib/parsetools/include/yeccpre.hrl` which is otherwise included at the
beginning of the resulting parser file. Note taht `Includefile` is included
as is in the parser file, so it must not have a module declaration of its
own, and it should not be compiled. It must, however, contain the necessary
export declarations. The default is indicated by `""`.
- **`{parserfile, Parserfile}`.** - `Parserfile` is the name of the file that
will contain the Erlang parser code that is generated. The default (`""`) is
to add the extension `.erl` to `Grammarfile` stripped of the `.yrl` extension.
- **`{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`.
- **`{verbose, boolean()}`.** - Determines whether the parser generator should
give full information about resolved and unresolved parse action conflicts
(`true`), or only about those conflicts that prevent a parser from being
generated from the input grammar (`false`, the default).
- **`{warnings_as_errors, boolean()}`** - Causes warnings to be treated as
errors.
- **`{error_location, column | line}`.** - If the value of this flag is `line`,
the location of warnings and errors is a line number. If the value is
`column`, the location includes a line number and a column number. Default is
`column`.
- **`{deterministic, boolean()}`** - Causes generated `-file()` attributes to only
include the basename of the file path.
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}`.
The value of the `Parserfile` option stripped of the `.erl` extension is used by
Yecc as the module name of the generated parser file.
Yecc will add the extension `.yrl` to the `Grammarfile` name, the extension
`.hrl` to the `Includefile` name, and the extension `.erl` to the `Parserfile`
name, unless the extension is already there.
""".
-spec file(GrammarFile, Options) -> yecc_ret() when
GrammarFile :: file:filename(),
Options :: Option | [Option],
Option :: option().
file(File, Options0) when is_list(Options0) ->
case is_filename(File) of
no -> erlang:error(badarg, [File, Options0]);
_ -> ok
end,
EnvOpts0 = env_default_opts(),
EnvOpts = select_recognized_opts(EnvOpts0),
Options = Options0 ++ EnvOpts,
case options(Options) of
badarg ->
erlang:error(badarg, [File, Options]);
OptionValues ->
Self = self(),
Flag = process_flag(trap_exit, false),
Pid = spawn_link(fun() -> infile(Self, File, OptionValues) end),
receive
{Pid, Rep} ->
receive after 1 -> ok end,
process_flag(trap_exit, Flag),
Rep
end
end;
file(File, Option) ->
file(File, [Option]).
%% Kept for backward compatibility.
-doc false.
yecc(Infile, Outfile) ->
yecc(Infile, Outfile, false, []).
-doc false.
yecc(Infile, Outfile, Verbose) ->
yecc(Infile, Outfile, Verbose, []).
-doc false.
yecc(Infilex, Outfilex, Verbose, Includefilex) ->
_ = statistics(runtime),
case file(Infilex, [{parserfile, Outfilex},
{verbose, Verbose},
{report, true},
{includefile, Includefilex}]) of
{ok, _File} ->
statistics(runtime);
error ->
exit(error)
end.
%%%
%%% Local functions
%%%
%% 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 =:= parserfile ->
case is_filename(FileName0) of
no ->
badarg;
Filename ->
check_options(Options, AllOptions, [{Option, Filename} | L])
end;
check_options([{error_location, ELoc}=OptionValue | Options], AllOptions, L)
when ELoc =:= column; ELoc =:= line ->
check_options(Options, AllOptions, [OptionValue | L]);
check_options([{Option, Boolean}=OptionValue | Options], AllOptions, L)
when is_boolean(Boolean) ->
case lists:member(Option, AllOptions) of
true ->
check_options(Options, AllOptions, [OptionValue | L]);
false ->
badarg
end;
check_options([], _AllOptions, L) ->
L;
check_options(_Options, _, _L) ->
badarg.
all_options() ->
[error_location, file_attributes, includefile, parserfile,
report_errors, report_warnings, return_errors, return_warnings,
time, verbose, warnings_as_errors, deterministic].
default_option(error_location) -> column;
default_option(file_attributes) -> true;
default_option(includefile) -> [];
default_option(parserfile) -> [];
default_option(report_errors) -> true;
default_option(report_warnings) -> true;
default_option(return_errors) -> false;
default_option(return_warnings) -> false;
default_option(time) -> false;
default_option(verbose) -> false;
default_option(warnings_as_errors) -> false;
default_option(deterministic) -> false.
atom_option(file_attributes) -> {file_attributes, true};
atom_option(report_errors) -> {report_errors, true};
atom_option(report_warnings) -> {report_warnings, true};
atom_option(return_errors) -> {return_errors, true};
atom_option(return_warnings) -> {return_warnings, true};
atom_option(time) -> {time, true};
atom_option(verbose) -> {verbose, true};
atom_option(warnings_as_errors) -> {warnings_as_errors, 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.