duskphantom_frontend/preprocess/timing.rs
1// Copyright 2024 Duskphantom Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// SPDX-License-Identifier: Apache-2.0
16
17pub fn process(input: &str) -> String {
18 // Replace `starttime\(\)` with `_sysy_starttime($LN)` if character before is not connected
19 let regex = regex::Regex::new(r"([^A-Za-z0-9_]|^)starttime\(\)").unwrap();
20 let replaced = regex.replace_all(input, "${1}_sysy_starttime($$LN)");
21
22 // Replace `stoptime\(\)` with `_sysy_stoptime($LN)` if character before is not connected
23 let regex = regex::Regex::new(r"([^A-Za-z0-9_]|^)stoptime\(\)").unwrap();
24 let replaced = regex.replace_all(&replaced, "${1}_sysy_stoptime($$LN)");
25
26 // Replace `$LN` with real line number
27 replaced
28 .split('\n')
29 .enumerate()
30 .map(|(ix, line)| line.replace("$LN", (ix + 1).to_string().as_str()))
31 .collect::<Vec<String>>()
32 .join("\n")
33}
34
35// Unit tests
36#[cfg(test)]
37pub mod tests_timing {
38 use insta::assert_snapshot;
39
40 use super::*;
41
42 #[test]
43 fn test_timing() {
44 let code = r#"
45 starttime();
46 starttime();
47 starttime();x1starttime();starttime();
48 stoptime();stoptime();_stoptime();
49 "#
50 .trim()
51 .split('\n')
52 .map(|s| s.trim())
53 .collect::<Vec<_>>()
54 .join("\n");
55 assert_snapshot!(process(&code), @r###"
56 _sysy_starttime(1);
57 _sysy_starttime(2);
58 _sysy_starttime(3);x1starttime();_sysy_starttime(3);
59 _sysy_stoptime(4);_sysy_stoptime(4);_stoptime();
60 "###);
61 }
62}