forked from softdevteam/grmtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctbuilder.rs
More file actions
1946 lines (1834 loc) · 76.7 KB
/
ctbuilder.rs
File metadata and controls
1946 lines (1834 loc) · 76.7 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
//! Build grammars at compile-time so that they can be statically included into a binary.
use std::{
any::type_name,
collections::{HashMap, HashSet},
env::{current_dir, var},
error::Error,
fmt::{self, Debug, Write as fmtWrite},
fs::{self, File, create_dir_all, read_to_string},
hash::Hash,
io::Write,
marker::PhantomData,
path::{Path, PathBuf},
sync::{LazyLock, Mutex},
};
use crate::{
LexerTypes, RTParserBuilder, RecoveryKind,
diagnostics::{DiagnosticFormatter, SpannedDiagnosticFormatter},
};
#[cfg(feature = "_unstable_api")]
use crate::unstable_api::UnstableApi;
use bincode::{Decode, Encode, decode_from_slice, encode_to_vec};
use cfgrammar::{
Location, RIdx, Span, Symbol,
header::{GrmtoolsSectionParser, Header, HeaderValue, Value},
markmap::{Entry, MergeBehavior},
yacc::{YaccGrammar, YaccKind, YaccOriginalActionKind, ast::ASTWithValidityInfo},
};
use filetime::FileTime;
use lrtable::{Minimiser, StateGraph, StateTable, from_yacc, statetable::Conflicts};
use num_traits::{AsPrimitive, PrimInt, Unsigned};
use proc_macro2::{Literal, TokenStream};
use quote::{ToTokens, TokenStreamExt, format_ident, quote};
use syn::{Generics, parse_quote};
const ACTION_PREFIX: &str = "__gt_";
const GLOBAL_PREFIX: &str = "__GT_";
const ACTIONS_KIND: &str = "__GtActionsKind";
const ACTIONS_KIND_PREFIX: &str = "Ak";
const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden";
const RUST_FILE_EXT: &str = "rs";
const WARNING: &str = "[Warning]";
const ERROR: &str = "[Error]";
static GENERATED_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
struct CTConflictsError<StorageT: Eq + Hash> {
conflicts_diagnostic: String,
#[cfg(test)]
#[cfg_attr(test, allow(dead_code))]
stable: StateTable<StorageT>,
phantom: PhantomData<StorageT>,
}
/// The quote impl of `ToTokens` for `Option` prints an empty string for `None`
/// and the inner value for `Some(inner_value)`.
///
/// This wrapper instead emits both `Some` and `None` variants.
/// See: [quote #20](https://github.com/dtolnay/quote/issues/20)
struct QuoteOption<T>(Option<T>);
impl<T: ToTokens> ToTokens for QuoteOption<T> {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.append_all(match self.0 {
Some(ref t) => quote! { ::std::option::Option::Some(#t) },
None => quote! { ::std::option::Option::None },
});
}
}
/// The quote impl of `ToTokens` for `usize` prints literal values
/// including a type suffix for example `0usize`.
///
/// This wrapper omits the type suffix emitting `0` instead.
struct UnsuffixedUsize(usize);
impl ToTokens for UnsuffixedUsize {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.append(Literal::usize_unsuffixed(self.0))
}
}
/// This wrapper adds a missing impl of `ToTokens` for tuples.
/// For a tuple `(a, b)` emits `(a.to_tokens(), b.to_tokens())`
struct QuoteTuple<T>(T);
impl<A: ToTokens, B: ToTokens> ToTokens for QuoteTuple<(A, B)> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let (a, b) = &self.0;
tokens.append_all(quote!((#a, #b)));
}
}
/// The wrapped `&str` value will be emitted with a call to `to_string()`
struct QuoteToString<'a>(&'a str);
impl ToTokens for QuoteToString<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let x = &self.0;
tokens.append_all(quote! { #x.to_string() });
}
}
impl<StorageT> fmt::Display for CTConflictsError<StorageT>
where
StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
usize: AsPrimitive<StorageT>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.conflicts_diagnostic)
}
}
impl<StorageT> fmt::Debug for CTConflictsError<StorageT>
where
StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
usize: AsPrimitive<StorageT>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.conflicts_diagnostic)
}
}
impl<StorageT> Error for CTConflictsError<StorageT>
where
StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
usize: AsPrimitive<StorageT>,
{
}
/// A string which uses `Display` for it's `Debug` impl.
struct ErrorString(String);
impl fmt::Display for ErrorString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ErrorString(s) = self;
write!(f, "{}", s)
}
}
impl fmt::Debug for ErrorString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ErrorString(s) = self;
write!(f, "{}", s)
}
}
impl Error for ErrorString {}
/// Specify the visibility of the module generated by `CTBuilder`.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Visibility {
/// Module-level visibility only.
Private,
/// `pub`
Public,
/// `pub(super)`
PublicSuper,
/// `pub(self)`
PublicSelf,
/// `pub(crate)`
PublicCrate,
/// `pub(in {arg})`
PublicIn(String),
}
/// Specifies the [Rust Edition] that will be emitted during code generation.
///
/// [Rust Edition]: https://doc.rust-lang.org/edition-guide/rust-2021/index.html
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum RustEdition {
Rust2015,
Rust2018,
Rust2021,
}
impl RustEdition {
fn to_variant_tokens(self) -> TokenStream {
match self {
RustEdition::Rust2015 => quote!(::lrpar::RustEdition::Rust2015),
RustEdition::Rust2018 => quote!(::lrpar::RustEdition::Rust2018),
RustEdition::Rust2021 => quote!(::lrpar::RustEdition::Rust2021),
}
}
}
impl ToTokens for Visibility {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend(match self {
Visibility::Private => quote!(),
Visibility::Public => quote! {pub},
Visibility::PublicSuper => quote! {pub(super)},
Visibility::PublicSelf => quote! {pub(self)},
Visibility::PublicCrate => quote! {pub(crate)},
Visibility::PublicIn(data) => {
let other = str::parse::<TokenStream>(data).unwrap();
quote! {pub(in #other)}
}
})
}
}
impl Visibility {
fn to_variant_tokens(&self) -> TokenStream {
match self {
Visibility::Private => quote!(::lrpar::Visibility::Private),
Visibility::Public => quote!(::lrpar::Visibility::Public),
Visibility::PublicSuper => quote!(::lrpar::Visibility::PublicSuper),
Visibility::PublicSelf => quote!(::lrpar::Visibility::PublicSelf),
Visibility::PublicCrate => quote!(::lrpar::Visibility::PublicCrate),
Visibility::PublicIn(data) => {
let data = QuoteToString(data);
quote!(::lrpar::Visibility::PublicIn(#data))
}
}
}
}
/// A `CTParserBuilder` allows one to specify the criteria for building a statically generated
/// parser.
pub struct CTParserBuilder<'a, LexerTypesT: LexerTypes>
where
LexerTypesT::StorageT: Eq + Hash,
usize: AsPrimitive<LexerTypesT::StorageT>,
{
// Anything stored in here (except `output_path`, `conflicts`, and `error_on_conflict`) almost
// certainly needs to be included as part of the rebuild_cache function below so that, if it's
// changed, the grammar is rebuilt.
grammar_path: Option<PathBuf>,
// If specified rather than reading source from `grammar_path`, use this string directly
grammar_src: Option<String>,
// If specified along with `grammar_src`, use this rather than building an ast from `grammar_src`.
from_ast: Option<ASTWithValidityInfo>,
output_path: Option<PathBuf>,
mod_name: Option<&'a str>,
recoverer: Option<RecoveryKind>,
yacckind: Option<YaccKind>,
error_on_conflicts: bool,
warnings_are_errors: bool,
show_warnings: bool,
visibility: Visibility,
rust_edition: RustEdition,
inspect_rt: Option<
Box<
dyn for<'b> FnMut(
&'b mut Header<Location>,
RTParserBuilder<LexerTypesT::StorageT, LexerTypesT>,
&'b HashMap<String, LexerTypesT::StorageT>,
&PathBuf,
) -> Result<(), Box<dyn Error>>,
>,
>,
// test function for inspecting private state
#[cfg(test)]
inspect_callback: Option<Box<dyn Fn(RecoveryKind) -> Result<(), Box<dyn Error>>>>,
phantom: PhantomData<LexerTypesT>,
}
impl<
'a,
StorageT: 'static + Debug + Hash + PrimInt + Encode + Unsigned,
LexerTypesT: LexerTypes<StorageT = StorageT>,
> CTParserBuilder<'a, LexerTypesT>
where
usize: AsPrimitive<StorageT>,
{
/// Create a new `CTParserBuilder`.
///
/// `StorageT` must be an unsigned integer type (e.g. `u8`, `u16`) which is:
/// * big enough to index (separately) all the tokens, rules, productions in the grammar,
/// * big enough to index the state table created from the grammar,
/// * less than or equal in size to `u32`.
///
/// In other words, if you have a grammar with 256 tokens, 256 rules, and 256 productions,
/// which creates a state table of 256 states you can safely specify `u8` here; but if any of
/// those counts becomes 257 or greater you will need to specify `u16`. If you are parsing
/// large files, the additional storage requirements of larger integer types can be noticeable,
/// and in such cases it can be worth specifying a smaller type. `StorageT` defaults to `u32`
/// if unspecified.
///
/// # Examples
///
/// ```text
/// CTParserBuilder::<DefaultLexerTypes<u8>>::new()
/// .grammar_in_src_dir("grm.y")?
/// .build()?;
/// ```
pub fn new() -> Self {
CTParserBuilder {
grammar_path: None,
grammar_src: None,
from_ast: None,
output_path: None,
mod_name: None,
recoverer: None,
yacckind: None,
error_on_conflicts: true,
warnings_are_errors: true,
show_warnings: true,
visibility: Visibility::Private,
rust_edition: RustEdition::Rust2021,
inspect_rt: None,
#[cfg(test)]
inspect_callback: None,
phantom: PhantomData,
}
}
/// Set the input grammar path to a file relative to this project's `src` directory. This will
/// also set the output path (i.e. you do not need to call [CTParserBuilder::output_path]).
///
/// For example if `a/b.y` is passed as `inp` then [CTParserBuilder::build] will:
/// * use `src/a/b.y` as the input file.
/// * write output to a file which can then be imported by calling `lrpar_mod!("a/b.y")`.
/// * create a module in that output file named `b_y`.
///
/// You can override the output path and/or module name by calling [CTParserBuilder::output_path]
/// and/or [CTParserBuilder::mod_name], respectively, after calling this function.
///
/// This is a convenience function that makes it easier to compile grammar files stored in a
/// project's `src/` directory: please see [CTParserBuilder::build] for additional constraints
/// and information about the generated files. Note also that each `.y` file can only be
/// processed once using this function: if you want to generate multiple grammars from a single
/// `.y` file, you will need to use [CTParserBuilder::output_path].
pub fn grammar_in_src_dir<P>(mut self, srcp: P) -> Result<Self, Box<dyn Error>>
where
P: AsRef<Path>,
{
if !srcp.as_ref().is_relative() {
return Err(format!(
"Grammar path '{}' must be a relative path.",
srcp.as_ref().to_str().unwrap_or("<invalid UTF-8>")
)
.into());
}
let mut grmp = current_dir()?;
grmp.push("src");
grmp.push(srcp.as_ref());
self.grammar_path = Some(grmp);
let mut outp = PathBuf::new();
outp.push(var("OUT_DIR").unwrap());
outp.push(srcp.as_ref().parent().unwrap().to_str().unwrap());
create_dir_all(&outp)?;
let mut leaf = srcp
.as_ref()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned();
write!(leaf, ".{}", RUST_FILE_EXT).ok();
outp.push(leaf);
Ok(self.output_path(outp))
}
/// If set, specifies that this grammar should be built from a pre-validated AST
/// instead of a `.y`` file. When this is specified, `grammar_path` will not be read.
#[cfg(feature = "_unstable_api")]
pub fn grammar_ast(mut self, valid_ast: ASTWithValidityInfo, _api_key: UnstableApi) -> Self {
self.from_ast = Some(valid_ast);
self
}
/// Set the input grammar path to `inp`. If specified, you must also call
/// [CTParserBuilder::output_path]. In general it is easier to use
/// [CTParserBuilder::grammar_in_src_dir].
pub fn grammar_path<P>(mut self, inp: P) -> Self
where
P: AsRef<Path>,
{
self.grammar_path = Some(inp.as_ref().to_owned());
self
}
#[cfg(feature = "_unstable_api")]
pub fn with_grammar_src(mut self, src: String, _api_key: UnstableApi) -> Self {
self.grammar_src = Some(src);
self
}
/// Set the output grammar path to `outp`. Note that there are no requirements on `outp`: the
/// file can exist anywhere you can create a valid [Path] to. However, if you wish to use
/// [crate::lrpar_mod!] you will need to make sure that `outp` is in
/// [std::env::var]`("OUT_DIR")` or one of its subdirectories.
pub fn output_path<P>(mut self, outp: P) -> Self
where
P: AsRef<Path>,
{
self.output_path = Some(outp.as_ref().to_owned());
self
}
/// Set the generated module name to `mod_name`. If no module name is specified,
/// [CTParserBuilder::build] will attempt to create a sensible default based on the grammar
/// filename.
pub fn mod_name(mut self, mod_name: &'a str) -> Self {
self.mod_name = Some(mod_name);
self
}
/// Set the visibility of the generated module to `vis`. Defaults to `Visibility::Private`.
pub fn visibility(mut self, vis: Visibility) -> Self {
self.visibility = vis;
self
}
/// Set the recoverer for this parser to `rk`. Defaults to `RecoveryKind::CPCTPlus`.
pub fn recoverer(mut self, rk: RecoveryKind) -> Self {
self.recoverer = Some(rk);
self
}
/// Set the `YaccKind` for this parser to `ak`.
pub fn yacckind(mut self, yk: YaccKind) -> Self {
self.yacckind = Some(yk);
self
}
/// If set to true, [CTParserBuilder::build] will return an error if the given grammar contains
/// any Shift/Reduce or Reduce/Reduce conflicts. Defaults to `true`.
pub fn error_on_conflicts(mut self, b: bool) -> Self {
self.error_on_conflicts = b;
self
}
/// If set to true, [CTParserBuilder::build] will return an error if the given grammar contains
/// any warnings. Defaults to `true`.
pub fn warnings_are_errors(mut self, b: bool) -> Self {
self.warnings_are_errors = b;
self
}
/// If set to true, [CTParserBuilder::build] will print warnings to stderr, or via cargo when
/// running under cargo. Defaults to `true`.
pub fn show_warnings(mut self, b: bool) -> Self {
self.show_warnings = b;
self
}
/// Sets the rust edition to be used for generated code. Defaults to the latest edition of
/// rust supported by grmtools.
pub fn rust_edition(mut self, edition: RustEdition) -> Self {
self.rust_edition = edition;
self
}
#[cfg(test)]
pub fn inspect_recoverer(
mut self,
cb: Box<dyn for<'h, 'y> Fn(RecoveryKind) -> Result<(), Box<dyn Error>>>,
) -> Self {
self.inspect_callback = Some(cb);
self
}
#[doc(hidden)]
pub fn inspect_rt(
mut self,
cb: Box<
dyn for<'b, 'y> FnMut(
&'b mut Header<Location>,
RTParserBuilder<'y, StorageT, LexerTypesT>,
&'b HashMap<String, StorageT>,
&PathBuf,
) -> Result<(), Box<dyn Error>>,
>,
) -> Self {
self.inspect_rt = Some(cb);
self
}
/// Statically compile the Yacc file specified by [CTParserBuilder::grammar_path()] into Rust,
/// placing the output into the file spec [CTParserBuilder::output_path()]. Note that three
/// additional files will be created with the same name as specified in [self.output_path] but
/// with the extensions `grm`, and `stable`, overwriting any existing files with those names.
///
/// If `%parse-param` is not specified, the generated module follows the form:
///
/// ```text
/// mod <modname> {
/// pub fn parse<'lexer, 'input: 'lexer>(lexer: &'lexer dyn NonStreamingLexer<...>)
/// -> (Option<ActionT>, Vec<LexParseError<...>> { ... }
///
/// pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<StorageT>) -> ::std::option::Option<&'a str> {
/// ...
/// }
///
/// ...
/// }
/// ```
///
/// If `%parse-param x: t` is specified, the generated module follows the form:
///
/// ```text
/// mod <modname> {
/// pub fn parse<'lexer, 'input: 'lexer>(lexer: &'lexer dyn NonStreamingLexer<...>, x: t)
/// -> (Option<ActionT>, Vec<LexParseError<...>> { ... }
///
/// pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<StorageT>) -> ::std::option::Option<&'a str> {
/// ...
/// }
///
/// ...
/// }
/// ```
///
/// where:
/// * `modname` is either:
/// * the module name specified by [CTParserBuilder::mod_name()];
/// * or, if no module name was explicitly specified, then for the file `/a/b/c.y` the
/// module name is `c_y` (i.e. the file's leaf name, minus its extension, with a prefix of
/// `_y`).
/// * `ActionT` is either:
/// * if the `yacckind` was set to `YaccKind::GrmTools` or
/// `YaccKind::Original(YaccOriginalActionKind::UserAction)`, it is
/// the return type of the `%start` rule;
/// * or, if the `yacckind` was set to
/// `YaccKind::Original(YaccOriginalActionKind::GenericParseTree)`, it
/// is `Node<StorageT>` where the `Node` type is defined within your `lrpar_mod!`.
///
/// # Panics
///
/// If `StorageT` is not big enough to index the grammar's tokens, rules, or productions.
pub fn build(mut self) -> Result<CTParser<StorageT>, Box<dyn Error>> {
let grmp = self
.grammar_path
.as_ref()
.expect("grammar_path must be specified before processing.");
let outp = self
.output_path
.as_ref()
.expect("output_path must be specified before processing.");
let mut header = Header::new();
match header.entry("yacckind".to_string()) {
Entry::Occupied(_) => unreachable!(),
Entry::Vacant(mut v) => match self.yacckind {
Some(YaccKind::Eco) => panic!("Eco compile-time grammar generation not supported."),
Some(yk) => {
let yk_value = Value::try_from(yk)?;
let mut o = v.insert_entry(HeaderValue(
Location::Other("CTParserBuilder".to_string()),
yk_value,
));
o.set_merge_behavior(MergeBehavior::Ours);
}
None => {
v.mark_required();
}
},
}
if let Some(recoverer) = self.recoverer {
match header.entry("recoverer".to_string()) {
Entry::Occupied(_) => unreachable!(),
Entry::Vacant(v) => {
let rk_value: Value<Location> = Value::try_from(recoverer)?;
let mut o = v.insert_entry(HeaderValue(
Location::Other("CTParserBuilder".to_string()),
rk_value,
));
o.set_merge_behavior(MergeBehavior::Ours);
}
}
}
{
let mut lk = GENERATED_PATHS.lock().unwrap();
if lk.contains(outp.as_path()) {
return Err(format!("Generating two parsers to the same path ('{}') is not allowed: use CTParserBuilder::output_path (and, optionally, CTParserBuilder::mod_name) to differentiate them.", &outp.to_str().unwrap()).into());
}
lk.insert(outp.clone());
}
let inc = if let Some(grammar_src) = &self.grammar_src {
grammar_src.clone()
} else {
read_to_string(grmp).map_err(|e| format!("When reading '{}': {e}", grmp.display()))?
};
let yacc_diag = SpannedDiagnosticFormatter::new(&inc, grmp);
let parsed_header = GrmtoolsSectionParser::new(&inc, false).parse();
if let Err(errs) = parsed_header {
let mut out = String::new();
out.push_str(&format!(
"\n{ERROR}{}\n",
yacc_diag.file_location_msg(" parsing the `%grmtools` section", None)
));
for e in errs {
out.push_str(&indent(" ", &yacc_diag.format_error(e).to_string()));
}
return Err(ErrorString(out))?;
}
let (parsed_header, _) = parsed_header.unwrap();
header.merge_from(parsed_header)?;
self.yacckind = header
.get("yacckind")
.map(|HeaderValue(_, val)| val)
.map(YaccKind::try_from)
.transpose()?;
header.mark_used(&"yacckind".to_string());
let ast_validation = if let Some(ast) = &self.from_ast {
ast.clone()
} else if let Some(yk) = self.yacckind {
ASTWithValidityInfo::new(yk, &inc)
} else {
Err("Missing 'yacckind'".to_string())?
};
header.mark_used(&"recoverer".to_string());
let rk_val = header.get("recoverer").map(|HeaderValue(_, rk_val)| rk_val);
if let Some(rk_val) = rk_val {
self.recoverer = Some(RecoveryKind::try_from(rk_val)?);
} else {
// Fallback to the default recoverykind.
self.recoverer = Some(RecoveryKind::CPCTPlus);
}
self.yacckind = Some(ast_validation.yacc_kind());
let warnings = ast_validation.ast().warnings();
let res = YaccGrammar::<StorageT>::new_from_ast_with_validity_info(&ast_validation);
let grm = match res {
Ok(_) if self.warnings_are_errors && !warnings.is_empty() => {
let mut out = String::new();
out.push_str(&format!(
"\n{ERROR}{}\n",
yacc_diag.file_location_msg("", None)
));
for e in warnings {
out.push_str(&format!(
"{}\n",
indent(" ", &yacc_diag.format_warning(e).to_string())
));
}
return Err(ErrorString(out))?;
}
Ok(grm) => {
if !warnings.is_empty() {
for w in warnings {
let ws_loc = yacc_diag.file_location_msg("", None);
let ws = indent(" ", &yacc_diag.format_warning(w).to_string());
// Assume if this variable is set we are running under cargo.
if std::env::var("OUT_DIR").is_ok() && self.show_warnings {
for line in ws_loc.lines().chain(ws.lines()) {
println!("cargo:warning={}", line);
}
} else if self.show_warnings {
eprintln!("{}", ws_loc);
eprintln!("{WARNING} {}", ws);
}
}
}
grm
}
Err(errs) => {
let mut out = String::new();
out.push_str(&format!(
"\n{ERROR}{}\n",
yacc_diag.file_location_msg("", None)
));
for e in errs {
out.push_str(&indent(" ", &yacc_diag.format_error(e).to_string()));
out.push('\n');
}
return Err(ErrorString(out))?;
}
};
#[cfg(test)]
if let Some(cb) = &self.inspect_callback {
cb(self.recoverer.expect("has a default value"))?;
}
let rule_ids = grm
.tokens_map()
.iter()
.map(|(&n, &i)| (n.to_owned(), i.as_storaget()))
.collect::<HashMap<_, _>>();
let derived_mod_name = match self.mod_name {
Some(s) => s.to_owned(),
None => {
// The user hasn't specified a module name, so we create one automatically: what we
// do is strip off all the filename extensions (note that it's likely that inp ends
// with `y.rs`, so we potentially have to strip off more than one extension) and
// then add `_y` to the end.
let mut stem = grmp.to_str().unwrap();
loop {
let new_stem = Path::new(stem).file_stem().unwrap().to_str().unwrap();
if stem == new_stem {
break;
}
stem = new_stem;
}
format!("{}_y", stem)
}
};
let cache = self.rebuild_cache(&derived_mod_name, &grm);
// We don't need to go through the full rigmarole of generating an output file if all of
// the following are true: the output file exists; it is newer than the input file; and the
// cache hasn't changed. The last of these might be surprising, but it's vital: we don't
// know, for example, what the IDs map might be from one run to the next, and it might
// change for reasons beyond lrpar's control. If it does change, that means that the lexer
// and lrpar would get out of sync, so we have to play it safe and regenerate in such
// cases.
if let Ok(ref inmd) = fs::metadata(grmp) {
if let Ok(ref out_rs_md) = fs::metadata(outp) {
if FileTime::from_last_modification_time(out_rs_md)
> FileTime::from_last_modification_time(inmd)
{
if let Ok(outc) = read_to_string(outp) {
if outc.contains(&cache.to_string()) {
return Ok(CTParser {
regenerated: false,
rule_ids,
yacc_grammar: grm,
grammar_src: inc,
grammar_path: self.grammar_path.unwrap(),
conflicts: None,
});
} else {
#[cfg(grmtools_extra_checks)]
if std::env::var("CACHE_EXPECTED").is_ok() {
eprintln!("outc: {}", outc);
eprintln!("using cache: {}", cache,);
// Primarily for use in the testsuite.
panic!("The cache regenerated however, it was expected to match");
}
}
}
}
}
}
// At this point, we know we're going to generate fresh output; however, if something goes
// wrong in the process between now and us writing /out/blah.rs, rustc thinks that
// everything's gone swimmingly (even if build.rs errored!), and tries to carry on
// compilation, leading to weird errors. We therefore delete /out/blah.rs at this point,
// which means, at worse, the user gets a "file not found" error from rustc (which is less
// confusing than the alternatives).
fs::remove_file(outp).ok();
let (sgraph, stable) = from_yacc(&grm, Minimiser::Pager)?;
if self.error_on_conflicts {
if let Some(c) = stable.conflicts() {
match (grm.expect(), grm.expectrr()) {
(Some(i), Some(j)) if i == c.sr_len() && j == c.rr_len() => (),
(Some(i), None) if i == c.sr_len() && 0 == c.rr_len() => (),
(None, Some(j)) if 0 == c.sr_len() && j == c.rr_len() => (),
(None, None) if 0 == c.rr_len() && 0 == c.sr_len() => (),
_ => {
let conflicts_diagnostic = yacc_diag.format_conflicts::<LexerTypesT>(
&grm,
ast_validation.ast(),
c,
&sgraph,
&stable,
);
return Err(Box::new(CTConflictsError {
conflicts_diagnostic,
phantom: PhantomData,
#[cfg(test)]
stable,
}));
}
}
}
}
if let Some(ref mut inspector_rt) = self.inspect_rt {
let rt: RTParserBuilder<'_, StorageT, LexerTypesT> =
RTParserBuilder::new(&grm, &stable);
let rt = if let Some(rk) = self.recoverer {
rt.recoverer(rk)
} else {
rt
};
inspector_rt(&mut header, rt, &rule_ids, grmp)?
}
let unused_keys = header.unused();
if !unused_keys.is_empty() {
return Err(format!("Unused keys in header: {}", unused_keys.join(", ")).into());
}
let missing_keys = header
.missing()
.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>();
if !missing_keys.is_empty() {
return Err(format!(
"Required values were missing from the header: {}",
missing_keys.join(", ")
)
.into());
}
self.output_file(
&grm,
&stable,
&derived_mod_name,
outp,
&format!("/* CACHE INFORMATION {} */\n", cache),
&yacc_diag,
)?;
let conflicts = if stable.conflicts().is_some() {
Some((sgraph, stable))
} else {
None
};
Ok(CTParser {
regenerated: true,
rule_ids,
yacc_grammar: grm,
grammar_src: inc,
grammar_path: self.grammar_path.unwrap(),
conflicts,
})
}
/// Given the filename `a/b.y` as input, statically compile the grammar `src/a/b.y` into a Rust
/// module which can then be imported using `lrpar_mod!("a/b.y")`. This is a convenience
/// function around [`process_file`](#method.process_file) which makes it easier to compile
/// grammar files stored in a project's `src/` directory: please see
/// [`process_file`](#method.process_file) for additional constraints and information about the
/// generated files.
#[deprecated(
since = "0.11.0",
note = "Please use grammar_in_src_dir(), build(), and token_map() instead"
)]
#[allow(deprecated)]
pub fn process_file_in_src(
&mut self,
srcp: &str,
) -> Result<HashMap<String, StorageT>, Box<dyn Error>> {
let mut inp = current_dir()?;
inp.push("src");
inp.push(srcp);
let mut outp = PathBuf::new();
outp.push(var("OUT_DIR").unwrap());
outp.push(Path::new(srcp).parent().unwrap().to_str().unwrap());
create_dir_all(&outp)?;
let mut leaf = Path::new(srcp)
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned();
write!(leaf, ".{}", RUST_FILE_EXT).ok();
outp.push(leaf);
self.process_file(inp, outp)
}
/// Statically compile the Yacc file `inp` into Rust, placing the output into the file `outp`.
/// Note that three additional files will be created with the same name as `outp` but with the
/// extensions `grm`, and `stable`, overwriting any existing files with those names.
///
/// `outp` defines a module as follows:
///
/// ```text
/// mod modname {
/// pub fn parse(lexemes: &::std::vec::Vec<::lrpar::Lexeme<StorageT>>) { ... }
/// -> (::std::option::Option<ActionT>,
/// ::std::vec::Vec<::lrpar::LexParseError<StorageT>>)> { ...}
///
/// pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<StorageT>) -> ::std::option::Option<&'a str> {
/// ...
/// }
///
/// ...
/// }
/// ```
///
/// where:
/// * `modname` is either:
/// * the module name specified [`mod_name`](#method.mod_name)
/// * or, if no module name was explicitly specified, then for the file `/a/b/c.y` the
/// module name is `c_y` (i.e. the file's leaf name, minus its extension, with a prefix of
/// `_y`).
/// * `ActionT` is either:
/// * the `%actiontype` value given to the grammar
/// * or, if the `yacckind` was set YaccKind::Original(YaccOriginalActionKind::UserAction),
/// it is [`Node<StorageT>`](../parser/enum.Node.html)
///
/// # Panics
///
/// If `StorageT` is not big enough to index the grammar's tokens, rules, or
/// productions.
#[deprecated(
since = "0.11.0",
note = "Please use grammar_path(), output_path(), build(), and token_map() instead"
)]
pub fn process_file<P, Q>(
&mut self,
inp: P,
outp: Q,
) -> Result<HashMap<String, StorageT>, Box<dyn Error>>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
self.grammar_path = Some(inp.as_ref().to_owned());
self.output_path = Some(outp.as_ref().to_owned());
let cl: CTParserBuilder<LexerTypesT> = CTParserBuilder {
grammar_path: self.grammar_path.clone(),
grammar_src: None,
from_ast: None,
output_path: self.output_path.clone(),
mod_name: self.mod_name,
recoverer: self.recoverer,
yacckind: self.yacckind,
error_on_conflicts: self.error_on_conflicts,
warnings_are_errors: self.warnings_are_errors,
show_warnings: self.show_warnings,
visibility: self.visibility.clone(),
rust_edition: self.rust_edition,
inspect_rt: None,
#[cfg(test)]
inspect_callback: None,
phantom: PhantomData,
};
Ok(cl.build()?.rule_ids)
}
fn output_file<P: AsRef<Path>>(
&self,
grm: &YaccGrammar<StorageT>,
stable: &StateTable<StorageT>,
mod_name: &str,
outp_rs: P,
cache: &str,
diag: &SpannedDiagnosticFormatter,
) -> Result<(), Box<dyn Error>> {
let visibility = self.visibility.clone();
let user_actions = if let Some(
YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools,
) = self.yacckind
{
Some(self.gen_user_actions(grm, diag)?)
} else {
None
};
let rule_consts = self.gen_rule_consts(grm)?;
let token_epp = self.gen_token_epp(grm)?;
let parse_function = self.gen_parse_function(grm, stable)?;
let action_wrappers = match self.yacckind.unwrap() {
YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools => {
Some(self.gen_wrappers(grm)?)
}
YaccKind::Original(YaccOriginalActionKind::NoAction)
| YaccKind::Original(YaccOriginalActionKind::GenericParseTree) => None,
_ => unreachable!(),
};
let additional_decls =
if let Some(YaccKind::Original(YaccOriginalActionKind::GenericParseTree)) =
self.yacckind
{
// `lrpar::Node`` is deprecated within the lrpar crate, but not from within this module,
// Once it is removed from `lrpar`, we should move the declaration here entirely.
Some(quote! {
#[allow(unused_imports)]
pub use ::lrpar::parser::_deprecated_moved_::Node;
})
} else {
None
};
let mod_name =
match syn::parse_str::<proc_macro2::Ident>(mod_name) {
Ok(s) => s,
Err(e) => return Err(format!(
"CTParserBuilder::mod_name(\"{}\") is not a valid rust identifier due to '{}'",
mod_name, e
)
.into()),
};
let out_tokens = quote! {
#visibility mod #mod_name {
// At the top so that `user_actions` may contain #![inner_attribute]
#user_actions
mod _parser_ {
#![allow(clippy::type_complexity)]
#![allow(clippy::unnecessary_wraps)]
#![deny(unsafe_code)]
#[allow(unused_imports)]
use super::*;
#additional_decls
#parse_function
#rule_consts
#token_epp