File size: 13,901 Bytes
d5bfab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use super::{AnalyticsDirectory, BatchProgramAnalyzerPlugin, BatchProgramAnalyzerContext};
use crate::common::{create_csv_file, save_program_ids_csv_file};
use loda_rust_core;
use loda_rust_core::parser::{InstructionId, ParsedProgram};
use std::path::PathBuf;
use std::error::Error;
use std::collections::HashMap;
use serde::Serialize;

const IGNORE_ANY_PROGRAM_SHORTER_THAN: usize = 8;
const IGNORE_PROGRAM_WITHOUT_LOOPS_SHORTER_THAN: usize = 13;
const IGNORE_PROGRAM_WITHOUT_NESTED_SEQ_SHORTER_THAN: usize = 9;
const CONSIDER_ANY_PROGRAM_LONGER_THAN: usize = 60;
const ONE_SEQ_AND_NUMBER_OF_LINES_OF_OTHER_STUFF: usize = 10;

enum ProgramComplexityClassification {
    SimpleAndShort,
    SimpleWithoutLoops,
    MediumWithLoops,
    ComplexOneSeqAndOtherStuff,
    ComplexTwoOrMoreSeq,
    ComplexNestedSeq,
    ComplexAndLong,
    ComplexOtherReasons,
}

impl ProgramComplexityClassification {
    fn is_optimizable(&self) -> bool {
        match self {
            ProgramComplexityClassification::SimpleAndShort => false,
            ProgramComplexityClassification::SimpleWithoutLoops => false,
            ProgramComplexityClassification::MediumWithLoops => false,
            ProgramComplexityClassification::ComplexOneSeqAndOtherStuff => true,
            ProgramComplexityClassification::ComplexTwoOrMoreSeq => true,
            ProgramComplexityClassification::ComplexNestedSeq => true,
            ProgramComplexityClassification::ComplexAndLong => true,
            ProgramComplexityClassification::ComplexOtherReasons => false,
        }
    }

    fn optimizable_string(&self) -> String {
        if self.is_optimizable() {
            return "1".to_string();
        } else {
            return "0".to_string();
        }
    }

    fn comment(&self) -> String {
        match self {
            ProgramComplexityClassification::SimpleAndShort => "very short program, low chance it can be optimized further".to_string(),
            ProgramComplexityClassification::SimpleWithoutLoops => "short program without loops, low chance it can be optimized further".to_string(),
            ProgramComplexityClassification::MediumWithLoops => "simple loops without eval seq, medium chance it can be optimized".to_string(),
            ProgramComplexityClassification::ComplexOneSeqAndOtherStuff => "one seq and other stuff, high chance it can be optimized".to_string(),
            ProgramComplexityClassification::ComplexTwoOrMoreSeq => "two or more eval seq, high chance it can be optimized".to_string(),
            ProgramComplexityClassification::ComplexNestedSeq => "eval seq inside loop, high chance it can be optimized".to_string(),
            ProgramComplexityClassification::ComplexAndLong => "long program, high chance that it can be optimized".to_string(),
            ProgramComplexityClassification::ComplexOtherReasons => "complex for other reasons, high chance it can be optimized".to_string(),
        }
    }
}

pub struct AnalyzeProgramComplexity {
    analytics_directory: AnalyticsDirectory,
    classifications: HashMap<u32, ProgramComplexityClassification>,
}

impl AnalyzeProgramComplexity {
    pub fn new(analytics_directory: AnalyticsDirectory) -> Self {
        Self {
            analytics_directory,
            classifications: HashMap::new(),
        }
    }

    fn classify(parsed_program: &ParsedProgram) -> ProgramComplexityClassification {
        let number_of_instructions: usize = parsed_program.instruction_vec.len();
        if number_of_instructions > CONSIDER_ANY_PROGRAM_LONGER_THAN {
            return ProgramComplexityClassification::ComplexAndLong;
        }
        if parsed_program.has_two_or_more_seq() {
            return ProgramComplexityClassification::ComplexTwoOrMoreSeq;
        }
        if parsed_program.has_one_seq_and_other_stuff() {
            return ProgramComplexityClassification::ComplexOneSeqAndOtherStuff;
        }
        if number_of_instructions < IGNORE_ANY_PROGRAM_SHORTER_THAN {
            return ProgramComplexityClassification::SimpleAndShort;
        }
        let has_loops: bool = parsed_program.has_one_or_more_loops();
        if !has_loops {
            if number_of_instructions < IGNORE_PROGRAM_WITHOUT_LOOPS_SHORTER_THAN {
                return ProgramComplexityClassification::SimpleWithoutLoops;
            }
        }
        let has_seq_inside_loops: bool = parsed_program.has_one_or_more_seq_inside_loops();
        if has_seq_inside_loops {
            return ProgramComplexityClassification::ComplexNestedSeq;
        } else {
            if number_of_instructions < IGNORE_PROGRAM_WITHOUT_NESTED_SEQ_SHORTER_THAN {
                return ProgramComplexityClassification::MediumWithLoops;
            }
        }
        return ProgramComplexityClassification::ComplexOtherReasons;
    }

    fn save_all(&self) -> Result<(), Box<dyn Error>> {
        // Convert from dictionary to array
        let mut records = Vec::<RecordProgram>::new();
        for (key, value) in &self.classifications {
            let record = RecordProgram {
                program_id: *key,
                optimizable: value.optimizable_string(),
                comment: value.comment()
            };
            records.push(record);
        }

        // Move the lowest program ids to the top
        // Move the highest program ids to the bottom
        records.sort_unstable_by_key(|item| (item.program_id));

        // Save as a CSV file
        let output_path: PathBuf = self.analytics_directory.complexity_all_file();
        create_csv_file(&records, &output_path)
    }

    /// Extract program ids of those programs that has little/no chance of being optimized
    fn extract_dont_optimize_program_ids(&self) -> Vec<u32> {
        let mut program_ids = Vec::<u32>::new();
        for (key, value) in &self.classifications {
            if !value.is_optimizable() {
                program_ids.push(*key);
            }
        }
        program_ids.sort();
        program_ids
    }

    fn save_dont_optimize(&self) -> Result<(), Box<dyn Error>> {
        let program_ids = self.extract_dont_optimize_program_ids();
        let output_path: PathBuf = self.analytics_directory.complexity_dont_optimize_file();
        save_program_ids_csv_file(&program_ids, &output_path)
    }
}

impl BatchProgramAnalyzerPlugin for AnalyzeProgramComplexity {
    fn plugin_name(&self) -> &'static str {
        "AnalyzeProgramComplexity"
    }
    
    fn analyze(&mut self, context: &BatchProgramAnalyzerContext) -> Result<(), Box<dyn Error>> {
        let classification = Self::classify(&context.parsed_program);
        self.classifications.insert(context.program_id, classification);
        Ok(())
    }

    fn save(&self) -> Result<(), Box<dyn Error>> {
        self.save_all()?;
        self.save_dont_optimize()?;
        Ok(())
    }

    fn human_readable_summary(&self) -> String {
        let program_ids = self.extract_dont_optimize_program_ids();
        let dont_optimize_count = program_ids.len();
        let total_count = self.classifications.len();
        let mut optimize_count: usize = 0;
        if total_count > dont_optimize_count {
            optimize_count = total_count - dont_optimize_count;
        }
        let ratio = ((optimize_count * 100) as f32) / (total_count.max(1) as f32);
        format!("optimize: {}, dontoptimize: {}, optimize/total: {:.1}%", optimize_count, dont_optimize_count, ratio)
    }
}

trait HasOneOrMoreLoops {
    fn has_one_or_more_loops(&self) -> bool;
}

impl HasOneOrMoreLoops for ParsedProgram {
    fn has_one_or_more_loops(&self) -> bool {
        for instruction in &self.instruction_vec {
            if instruction.instruction_id == InstructionId::LoopBegin {
                return true;
            }
            if instruction.instruction_id == InstructionId::LoopEnd {
                return true;
            }
        }
        false
    }
}

trait HasOneOrMoreSeqInsideLoops {
    fn has_one_or_more_seq_inside_loops(&self) -> bool;
}

impl HasOneOrMoreSeqInsideLoops for ParsedProgram {
    fn has_one_or_more_seq_inside_loops(&self) -> bool {
        let mut depth: i32 = 0;
        for instruction in &self.instruction_vec {
            match instruction.instruction_id {
                InstructionId::LoopBegin => {
                    depth += 1;
                },
                InstructionId::LoopEnd => {
                    depth -= 1;
                },
                InstructionId::EvalSequence => {
                    if depth > 0 {
                        return true;
                    }
                }
                _ => {}
            }
        }
        false
    }
}

trait HasTwoOrMoreSeq {
    fn has_two_or_more_seq(&self) -> bool;
}

impl HasTwoOrMoreSeq for ParsedProgram {
    fn has_two_or_more_seq(&self) -> bool {
        let mut count: usize = 0;
        for instruction in &self.instruction_vec {
            if instruction.instruction_id == InstructionId::EvalSequence {
                count += 1;
            }
        }
        count >= 2
    }
}

trait HasOneSeqAndOtherStuff {
    fn has_one_seq_and_other_stuff(&self) -> bool;
}

impl HasOneSeqAndOtherStuff for ParsedProgram {
    fn has_one_seq_and_other_stuff(&self) -> bool {
        let mut count_seq: usize = 0;
        let mut count_other: usize = 0;
        for instruction in &self.instruction_vec {
            if instruction.instruction_id == InstructionId::EvalSequence {
                count_seq += 1;
            } else {
                count_other += 1;
            }
        }
        (count_seq >= 1) && (count_other >= ONE_SEQ_AND_NUMBER_OF_LINES_OF_OTHER_STUFF)
    }
}

#[derive(Serialize)]
struct RecordProgram {
    #[serde(rename = "program id")]
    program_id: u32,
    #[serde(rename = "is optimizable")]
    optimizable: String,
    comment: String,
}


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

    fn has_one_or_more_loops(input0: &str) -> String {
        let result = ParsedProgram::parse_program(input0);
        let parsed_program: ParsedProgram = match result {
            Ok(value) => value,
            Err(error) => {
                return format!("BOOM: {:?}", error);
            }
        };
        parsed_program.has_one_or_more_loops().to_string()
    }

    #[test]
    fn test_10000_has_one_or_more_loops() {
        assert_eq!(has_one_or_more_loops(""), "false");
        assert_eq!(has_one_or_more_loops("; comment\nmul $0,1\n\n; comment"), "false");
        assert_eq!(has_one_or_more_loops("mul $0,7\nlpb $0\ndiv $0,3\nadd $0,10\nlpe"), "true");
        assert_eq!(has_one_or_more_loops("lpb $0\nlpb $1\nlpe\nlpe"), "true");
        assert_eq!(has_one_or_more_loops("; junk\nlpe\n; junk"), "true");
    }

    fn has_one_or_more_seq_inside_loops(input0: &str) -> String {
        let result = ParsedProgram::parse_program(input0);
        let parsed_program: ParsedProgram = match result {
            Ok(value) => value,
            Err(error) => {
                return format!("BOOM: {:?}", error);
            }
        };
        parsed_program.has_one_or_more_seq_inside_loops().to_string()
    }

    #[test]
    fn test_20000_has_one_or_more_seq_inside_loops() {
        assert_eq!(has_one_or_more_seq_inside_loops(""), "false");
        assert_eq!(has_one_or_more_seq_inside_loops("; comment\nmul $0,1\n\n; comment"), "false");
        assert_eq!(has_one_or_more_seq_inside_loops("lpb $0\nsub $0,1\nlpe"), "false");
        assert_eq!(has_one_or_more_seq_inside_loops("lpb $0\nseq $0,40\nlpe"), "true");
        assert_eq!(has_one_or_more_seq_inside_loops("lpb $0\nmov $1,$0\nlpb $1\nsub $1,1\nlpe\nsub $0,1\nlpe"), "false");
        assert_eq!(has_one_or_more_seq_inside_loops("lpb $0\nmov $1,$0\nlpb $1\nseq $1,40\nlpe\nsub $0,1\nlpe"), "true");
    }

    fn has_two_or_more_seq(input0: &str) -> String {
        let result = ParsedProgram::parse_program(input0);
        let parsed_program: ParsedProgram = match result {
            Ok(value) => value,
            Err(error) => {
                return format!("BOOM: {:?}", error);
            }
        };
        parsed_program.has_two_or_more_seq().to_string()
    }

    #[test]
    fn test_30000_has_two_or_more_seq() {
        assert_eq!(has_two_or_more_seq(""), "false");
        assert_eq!(has_two_or_more_seq("; comment\nmul $0,1\n\n; comment"), "false");
        assert_eq!(has_two_or_more_seq("lpb $0\nsub $0,1\nlpe"), "false");
        assert_eq!(has_two_or_more_seq("lpb $0\nseq $0,40\nlpe"), "false");
        assert_eq!(has_two_or_more_seq("lpb $0\nmov $1,$0\nlpb $1\nsub $1,1\nlpe\nsub $0,1\nlpe"), "false");
        assert_eq!(has_two_or_more_seq("lpb $0\nmov $1,$0\nlpb $1\nseq $1,40\nlpe\nsub $0,1\nlpe"), "false");
        assert_eq!(has_two_or_more_seq("seq $0,40"), "false");
        assert_eq!(has_two_or_more_seq("seq $0,40\nseq $0,40"), "true");
        assert_eq!(has_two_or_more_seq("seq $0,40\nmul $0,100\nseq $0,40"), "true");
    }

    fn has_one_seq_and_other_stuff(input0: &str) -> String {
        let result = ParsedProgram::parse_program(input0);
        let parsed_program: ParsedProgram = match result {
            Ok(value) => value,
            Err(error) => {
                return format!("BOOM: {:?}", error);
            }
        };
        parsed_program.has_one_seq_and_other_stuff().to_string()
    }

    #[test]
    fn test_40000_has_one_seq_and_other_stuff() {
        assert_eq!(has_one_seq_and_other_stuff("add $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1"), "false");
        assert_eq!(has_one_seq_and_other_stuff("seq $0,40\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1"), "false");
        assert_eq!(has_one_seq_and_other_stuff("seq $0,40\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1\nadd $0,1"), "true");
    }
}