Unnamed repository; edit this file 'description' to name the repository.
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
mod prefix_entries;
mod top_entries;

use std::{
    fmt::Write,
    fs,
    path::{Path, PathBuf},
};

use expect_test::expect_file;

use crate::{Edition, LexedStr, TopEntryPoint};

#[rustfmt::skip]
#[path = "../test_data/generated/runner.rs"]
mod runner;

fn infer_edition(file_path: &Path) -> Edition {
    let file_content = std::fs::read_to_string(file_path).unwrap();
    if let Some(edition) = file_content.strip_prefix("//@ edition: ") {
        edition[..4].parse().expect("invalid edition directive")
    } else {
        Edition::CURRENT
    }
}

#[test]
fn lex_ok() {
    for case in TestCase::list("lexer/ok") {
        let _guard = stdx::panic_context::enter(format!("{:?}", case.rs));
        let actual = lex(&case.text, infer_edition(&case.rs));
        expect_file![case.rast].assert_eq(&actual)
    }
}

#[test]
fn lex_err() {
    for case in TestCase::list("lexer/err") {
        let _guard = stdx::panic_context::enter(format!("{:?}", case.rs));
        let actual = lex(&case.text, infer_edition(&case.rs));
        expect_file![case.rast].assert_eq(&actual)
    }
}

fn lex(text: &str, edition: Edition) -> String {
    let lexed = LexedStr::new(edition, text);

    let mut res = String::new();
    for i in 0..lexed.len() {
        let kind = lexed.kind(i);
        let text = lexed.text(i);
        let error = lexed.error(i);

        let error = error.map(|err| format!(" error: {err}")).unwrap_or_default();
        writeln!(res, "{kind:?} {text:?}{error}").unwrap();
    }
    res
}

#[test]
fn parse_ok() {
    for case in TestCase::list("parser/ok") {
        let _guard = stdx::panic_context::enter(format!("{:?}", case.rs));
        let (actual, errors) = parse(TopEntryPoint::SourceFile, &case.text, Edition::CURRENT);
        assert!(!errors, "errors in an OK file {}:\n{actual}", case.rs.display());
        expect_file![case.rast].assert_eq(&actual);
    }
}

#[test]
fn parse_err() {
    for case in TestCase::list("parser/err") {
        let _guard = stdx::panic_context::enter(format!("{:?}", case.rs));
        let (actual, errors) = parse(TopEntryPoint::SourceFile, &case.text, Edition::CURRENT);
        assert!(errors, "no errors in an ERR file {}:\n{actual}", case.rs.display());
        expect_file![case.rast].assert_eq(&actual)
    }
}

fn parse(entry: TopEntryPoint, text: &str, edition: Edition) -> (String, bool) {
    let lexed = LexedStr::new(edition, text);
    let input = lexed.to_input(edition);
    let output = entry.parse(&input);

    let mut buf = String::new();
    let mut errors = Vec::new();
    let mut indent = String::new();
    let mut depth = 0;
    let mut len = 0;
    lexed.intersperse_trivia(&output, &mut |step| match step {
        crate::StrStep::Token { kind, text } => {
            assert!(depth > 0);
            len += text.len();
            writeln!(buf, "{indent}{kind:?} {text:?}").unwrap();
        }
        crate::StrStep::Enter { kind } => {
            assert!(depth > 0 || len == 0);
            depth += 1;
            writeln!(buf, "{indent}{kind:?}").unwrap();
            indent.push_str("  ");
        }
        crate::StrStep::Exit => {
            assert!(depth > 0);
            depth -= 1;
            indent.pop();
            indent.pop();
        }
        crate::StrStep::Error { msg, pos } => {
            assert!(depth > 0);
            errors.push(format!("error {pos}: {msg}\n"))
        }
    });
    assert_eq!(
        len,
        text.len(),
        "didn't parse all text.\nParsed:\n{}\n\nAll:\n{}\n",
        &text[..len],
        text
    );

    for (token, msg) in lexed.errors() {
        let pos = lexed.text_start(token);
        errors.push(format!("error {pos}: {msg}\n"));
    }

    let has_errors = !errors.is_empty();
    for e in errors {
        buf.push_str(&e);
    }
    (buf, has_errors)
}

#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct TestCase {
    rs: PathBuf,
    rast: PathBuf,
    text: String,
}

impl TestCase {
    fn list(path: &'static str) -> Vec<TestCase> {
        let crate_root_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let test_data_dir = crate_root_dir.join("test_data");
        let dir = test_data_dir.join(path);

        let mut res = Vec::new();
        let read_dir = fs::read_dir(&dir)
            .unwrap_or_else(|err| panic!("can't `read_dir` {}: {err}", dir.display()));
        for file in read_dir {
            let file = file.unwrap();
            let path = file.path();
            if path.extension().unwrap_or_default() == "rs" {
                let rs = path;
                let rast = rs.with_extension("rast");
                let text = fs::read_to_string(&rs).unwrap();
                res.push(TestCase { rs, rast, text });
            }
        }
        res.sort();
        res
    }
}

#[track_caller]
fn run_and_expect_no_errors(path: &str) {
    run_and_expect_no_errors_with_edition(path, Edition::CURRENT)
}

#[track_caller]
fn run_and_expect_errors(path: &str) {
    run_and_expect_errors_with_edition(path, Edition::CURRENT)
}

#[track_caller]
fn run_and_expect_no_errors_with_edition(path: &str, edition: Edition) {
    let path = PathBuf::from(path);
    let text = std::fs::read_to_string(&path).unwrap();
    let (actual, errors) = parse(TopEntryPoint::SourceFile, &text, edition);
    assert!(!errors, "errors in an OK file {}:\n{actual}", path.display());
    let mut p = PathBuf::from("..");
    p.push(path);
    p.set_extension("rast");
    expect_file![p].assert_eq(&actual)
}

#[track_caller]
fn run_and_expect_errors_with_edition(path: &str, edition: Edition) {
    let path = PathBuf::from(path);
    let text = std::fs::read_to_string(&path).unwrap();
    let (actual, errors) = parse(TopEntryPoint::SourceFile, &text, edition);
    assert!(errors, "no errors in an ERR file {}:\n{actual}", path.display());
    let mut p = PathBuf::from("..");
    p.push(path);
    p.set_extension("rast");
    expect_file![p].assert_eq(&actual)
}
= Map<dyn Any>; impl<A: ?Sized + Downcast> Default for Map<A> { #[inline] fn default() -> Map<A> { Map { raw: RawMap::with_hasher(Default::default()) } } } impl<A: ?Sized + Downcast> Map<A> { /// Returns a reference to the value stored in the collection for the type `T`, /// if it exists. #[inline] #[must_use] pub fn get<T: IntoBox<A>>(&self) -> Option<&T> { self.raw.get(&TypeId::of::<T>()).map(|any| unsafe { any.downcast_unchecked_ref::<T>() }) } /// Gets the entry for the given type in the collection for in-place manipulation #[inline] pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<'_, A, T> { match self.raw.entry(TypeId::of::<T>()) { hash_map::Entry::Occupied(e) => { Entry::Occupied(OccupiedEntry { inner: e, type_: PhantomData }) } hash_map::Entry::Vacant(e) => { Entry::Vacant(VacantEntry { inner: e, type_: PhantomData }) } } } } /// A view into a single occupied location in an `Map`. pub struct OccupiedEntry<'map, A: ?Sized + Downcast, V: 'map> { inner: hash_map::OccupiedEntry<'map, TypeId, Box<A>>, type_: PhantomData<V>, } /// A view into a single empty location in an `Map`. pub struct VacantEntry<'map, A: ?Sized + Downcast, V: 'map> { inner: hash_map::VacantEntry<'map, TypeId, Box<A>>, type_: PhantomData<V>, } /// A view into a single location in an `Map`, which may be vacant or occupied. pub enum Entry<'map, A: ?Sized + Downcast, V> { /// An occupied Entry Occupied(OccupiedEntry<'map, A, V>), /// A vacant Entry Vacant(VacantEntry<'map, A, V>), } impl<'map, A: ?Sized + Downcast, V: IntoBox<A>> Entry<'map, A, V> { /// Ensures a value is in the entry by inserting the result of the default function if /// empty, and returns a mutable reference to the value in the entry. #[inline] pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'map mut V { match self { Entry::Occupied(inner) => inner.into_mut(), Entry::Vacant(inner) => inner.insert(default()), } } } impl<'map, A: ?Sized + Downcast, V: IntoBox<A>> OccupiedEntry<'map, A, V> { /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry /// with a lifetime bound to the collection itself #[inline] #[must_use] pub fn into_mut(self) -> &'map mut V { unsafe { self.inner.into_mut().downcast_unchecked_mut() } } } impl<'map, A: ?Sized + Downcast, V: IntoBox<A>> VacantEntry<'map, A, V> { /// Sets the value of the entry with the `VacantEntry`'s key, /// and returns a mutable reference to it #[inline] pub fn insert(self, value: V) -> &'map mut V { unsafe { self.inner.insert(value.into_box()).downcast_unchecked_mut() } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_varieties() { fn assert_send<T: Send>() {} fn assert_sync<T: Sync>() {} fn assert_debug<T: ::core::fmt::Debug>() {} assert_send::<Map<dyn Any + Send>>(); assert_send::<Map<dyn Any + Send + Sync>>(); assert_sync::<Map<dyn Any + Send + Sync>>(); assert_debug::<Map<dyn Any>>(); assert_debug::<Map<dyn Any + Send>>(); assert_debug::<Map<dyn Any + Send + Sync>>(); } #[test] fn type_id_hasher() { use core::any::TypeId; use core::hash::Hash as _; fn verify_hashing_with(type_id: TypeId) { let mut hasher = TypeIdHasher::default(); type_id.hash(&mut hasher); _ = hasher.finish(); } // Pick a variety of types, just to demonstrate it's all sane. Normal, zero-sized, unsized, &c. verify_hashing_with(TypeId::of::<usize>()); verify_hashing_with(TypeId::of::<()>()); verify_hashing_with(TypeId::of::<str>()); verify_hashing_with(TypeId::of::<&str>()); verify_hashing_with(TypeId::of::<Vec<u8>>()); } } /// Methods for downcasting from an `Any`-like trait object. /// /// This should only be implemented on trait objects for subtraits of `Any`, though you can /// implement it for other types and it'll work fine, so long as your implementation is correct. pub trait Downcast { /// Gets the `TypeId` of `self`. fn type_id(&self) -> TypeId; // Note the bound through these downcast methods is 'static, rather than the inexpressible // concept of Self-but-as-a-trait (where Self is `dyn Trait`). This is sufficient, exceeding // TypeId's requirements. Sure, you *can* do CloneAny.downcast_unchecked::<NotClone>() and the // type system won't protect you, but that doesn't introduce any unsafety: the method is // already unsafe because you can specify the wrong type, and if this were exposing safe // downcasting, CloneAny.downcast::<NotClone>() would just return an error, which is just as // correct. // // Now in theory we could also add T: ?Sized, but that doesn't play nicely with the common // implementation, so I'm doing without it. /// Downcast from `&Any` to `&T`, without checking the type matches. /// /// # Safety /// /// The caller must ensure that `T` matches the trait object, on pain of *undefined behavior*. unsafe fn downcast_unchecked_ref<T: 'static>(&self) -> &T; /// Downcast from `&mut Any` to `&mut T`, without checking the type matches. /// /// # Safety /// /// The caller must ensure that `T` matches the trait object, on pain of *undefined behavior*. unsafe fn downcast_unchecked_mut<T: 'static>(&mut self) -> &mut T; } /// A trait for the conversion of an object into a boxed trait object. pub trait IntoBox<A: ?Sized + Downcast>: Any { /// Convert self into the appropriate boxed form. fn into_box(self) -> Box<A>; } macro_rules! implement { ($any_trait:ident $(+ $auto_traits:ident)*) => { impl Downcast for dyn $any_trait $(+ $auto_traits)* { #[inline] fn type_id(&self) -> TypeId { self.type_id() } #[inline] unsafe fn downcast_unchecked_ref<T: 'static>(&self) -> &T { unsafe { &*std::ptr::from_ref::<Self>(self).cast::<T>() } } #[inline] unsafe fn downcast_unchecked_mut<T: 'static>(&mut self) -> &mut T { unsafe { &mut *std::ptr::from_mut::<Self>(self).cast::<T>() } } } impl<T: $any_trait $(+ $auto_traits)*> IntoBox<dyn $any_trait $(+ $auto_traits)*> for T { #[inline] fn into_box(self) -> Box<dyn $any_trait $(+ $auto_traits)*> { Box::new(self) } } } } implement!(Any); implement!(Any + Send); implement!(Any + Send + Sync);