aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: df67a9a314508a59da30bb1e1db99690e6b6bec7 (plain)
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
// locals
mod error;
mod traverse;

// std
use std::{
    fmt,
    ops::Not,
    path::{Path, PathBuf},
};

// extern
use error::SimError;
use itertools::{EitherOrBoth, Itertools};
use traverse::PreOrder;
use tree_sitter::{Node, Parser, Tree};

type Result<T> = std::result::Result<T, SimError>;

const THRESHOLD: f64 = 0.6;

// Check if two tree-sitter objects (trees or nodes etc.) are "similar"
pub trait Similarity {
    // This function accepts a predicate to filter out nodes,
    // for e.g.: trivia such as comments and whitespace may be filtered
    // out with `!node.is_extra()`
    fn is_similar<P>(&self, other: &Self, predicate: P) -> bool
    where
        P: Fn(&Node) -> bool;
}

// Representation of a fully parsed file from the filesystem
pub struct ProgramFile {
    pub path: PathBuf,
    pub src: String,
    pub tree: Tree,
    pub simhash: u64,
}

impl Similarity for ProgramFile {
    fn is_similar<P>(&self, other: &Self, predicate: P) -> bool
    where
        P: Fn(&Node) -> bool,
    {
        // The order of traversal is unimportant
        let mine = PreOrder::new(&self.tree).filter(|n| predicate(n));
        let theirs = PreOrder::new(&other.tree).filter(|n| predicate(n));

        // Simultaneously traverse both the trees, and find dissimilarities.
        //
        // A dissimilarity is when:
        // - one tree's traversal is longer than the other
        // - the trees have identical traversal lengths but non-identical
        //   nodes along the traversal
        let structurally_similar = mine
            .zip_longest(theirs)
            .any(|result| match result {
                EitherOrBoth::Both(mine, theirs) => mine.kind_id() != theirs.kind_id(),
                EitherOrBoth::Left(_) | EitherOrBoth::Right(_) => true,
            })
            .not();
        let textually_similar = (simhash::hash_similarity(self.simhash, other.simhash)) > THRESHOLD;
        structurally_similar && textually_similar
    }
}

impl fmt::Debug for ProgramFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ProgramFile")
            .field("path", &self.path)
            .field("src", &self.src.len())
            .finish()
    }
}

impl ProgramFile {
    pub fn new<P: AsRef<Path>>(path: P, parser: &mut Parser) -> Result<Self> {
        let src = std::fs::read_to_string(&path)?;
        let path = path.as_ref().to_owned();
        let tree = parser.parse(&src, None).ok_or(SimError::LanguageNotSet)?;
        let simhash = simhash::simhash(&src);
        Ok(Self {
            path,
            src,
            tree,
            simhash,
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use tree_sitter::Parser;

    // Utility to quickly bootstrap ProgramFiles
    // and run similarity checks
    fn is_similar(mine: &str, their: &str) -> bool {
        let lang = tree_sitter_javascript::language();
        let mut parser = Parser::new();
        parser.set_language(lang).unwrap();

        let my_program_file = ProgramFile {
            path: PathBuf::from("mine"),
            src: mine.to_owned(),
            tree: parser.parse(&mine, None).unwrap(),
            simhash: simhash::simhash(&mine),
        };

        let their_program_file = ProgramFile {
            path: PathBuf::from("their"),
            src: their.to_owned(),
            tree: parser.parse(&their, None).unwrap(),
            simhash: simhash::simhash(&their),
        };

        my_program_file.is_similar(&their_program_file, |n| !n.is_extra())
    }

    #[test]
    fn trivial() {
        assert!(is_similar(
            r#"
            var x = 2;
            "#,
            r#"
            var y = 5;
            "#
        ))
    }

    #[test]
    fn automorphism() {
        assert!(is_similar(
            r#"
            function(x) {
                x * 2
            }
            "#,
            r#"
            function(x) {
                x * 2
            }
            "#
        ))
    }

    #[test]
    fn sample() {
        assert!(is_similar(
            r#"
            var scrapeWebsite = async function scrapeWebsite(website) {
                try {
                    var url = normalizeUrl(website);
                    var html = await fetch(url).then(function (res) {
                        return res.text();
                    });
                    var $ = load(html);
                    var handles = {};
                    module.exports.CONFIG.socialNetworks.forEach(function (socialNetwork) {
                        handles[socialNetwork] = parse(socialNetwork)($);
                    })
                    return handles;
                } catch (error) {
                    throw new Error("Error scraping website data for " + website + ": " + error.message)
                }
            }
            "#,
            r#"
            var parseWebsite = async function parseWebsite(website) {
                try {
                    var url = normalizeUrl(website);
                    var html = await fetch(url).then(function (res) {
                        return res.text();
                    });
                    var $ = load(html);
                    var handles = {};
                    module.exports.CONFIG.socialNetworks.forEach(function (socialNetwork) {
                        handles[socialNetwork] = parse(socialNetwork)($);
                    })
                    return handles;
                } catch (error) {
                    throw new Error("Error fetching website data for " + website + ": " + error.message)
                }
            }
        "#
        ))
    }

    #[test]
    fn ignore_comment_trivia() {
        assert!(is_similar(
            r#"
            // doubles x
            function(x) {
                x * 2
            }
            "#,
            r#"
            function(x) {
                x * 2 // doubles x
            }
            "#
        ))
    }

    #[test]
    fn ignore_whitespace_trivia() {
        assert!(is_similar(
            r#"
            function(x) {
return x * 2;
            }
            "#,
            r#"
            function(x  ) {
                return x * 2;
            }
            "#
        ))
    }

    #[test]
    fn dissimilar() {
        assert!(!is_similar(
            r#"
            var t = function(x, y) { }
            "#,
            r#"
            var l = function(x) { }
            "#
        ))
    }
}