use crate::types::{ApiType, ApiUsage};
use jsxbin_parser::types::Token;
use log::{debug, trace};
use std::collections::HashMap;
pub struct ApiDetector;
impl ApiDetector {
pub fn extract_from_tokens(tokens: &[Token]) -> Vec<ApiUsage> {
debug!("Extracting API usage from tokens");
let mut apis: HashMap<String, (ApiType, usize)> = HashMap::new();
Self::scan_tokens_for_apis(tokens, &mut apis);
let result: Vec<ApiUsage> = apis
.into_iter()
.map(|(api_name, (api_type, count))| ApiUsage {
api_name,
api_type,
count,
locations: Vec::new(),
})
.collect();
debug!("Found {} API usages", result.len());
result
}
fn scan_tokens_for_apis(tokens: &[Token], apis: &mut HashMap<String, (ApiType, usize)>) {
for token in tokens {
match token {
Token::Identifier(name) => {
if let Some(api_type) = Self::classify_api(name) {
trace!("Found API: {} ({:?})", name, api_type);
apis.entry(name.clone())
.and_modify(|(_, count)| *count += 1)
.or_insert((api_type, 1));
}
}
Token::MemberAccess { object, property, .. } => {
if let Token::Identifier(prop_name) = &*property.token {
if let Some(api_type) = Self::classify_api(prop_name) {
trace!("Found API (member): {}", prop_name);
apis.entry(prop_name.clone())
.and_modify(|(_, count)| *count += 1)
.or_insert((api_type, 1));
}
}
}
Token::FunctionCall { callee, .. } => {
if let Token::Identifier(func_name) = &*callee.token {
if let Some(api_type) = Self::classify_api(func_name) {
trace!("Found API (function call): {}", func_name);
apis.entry(func_name.clone())
.and_modify(|(_, count)| *count += 1)
.or_insert((api_type, 1));
}
}
}
_ => {}
}
}
}
fn classify_api(name: &str) -> Option<ApiType> {
match name {
"activeDocument"
| "documents"
| "open"
| "close"
| "save"
| "export"
| "importFile" => Some(ApiType::Document),
"artLayers"
| "layers"
| "layerSets"
| "groupLayers"
| "createLayer"
| "deleteLayer"
| "mergeDown" => Some(ApiType::Layer),
"selection"
| "select"
| "deselect"
| "selectAll"
| "invert"
| "feather"
| "expand"
| "contract" => Some(ApiType::Selection),
"transform"
| "scale"
| "rotate"
| "skew"
| "flip"
| "flipHorizontal"
| "flipVertical" => Some(ApiType::Transform),
"applyFilter"
| "blur"
| "sharpen"
| "distort"
| "stylize"
| "render" => Some(ApiType::Effects),
"textLayers"
| "textRange"
| "addText"
| "textItem"
| "font"
| "fontSize" => Some(ApiType::Text),
"pathItems"
| "paths"
| "createPath"
| "bezier"
| "stroke"
| "fill" => Some(ApiType::Shape),
"color"
| "colorModel"
| "RGB"
| "CMYK"
| "setRGBColor"
| "setCMYKColor" => Some(ApiType::Color),
_ => None,
}
}
pub fn get_known_apis() -> Vec<&'static str> {
vec![
"activeDocument",
"documents",
"open",
"close",
"save",
"export",
"importFile",
"artLayers",
"layers",
"layerSets",
"groupLayers",
"createLayer",
"deleteLayer",
"mergeDown",
"selection",
"select",
"deselect",
"selectAll",
"invert",
"feather",
"expand",
"contract",
"transform",
"scale",
"rotate",
"skew",
"flip",
"flipHorizontal",
"flipVertical",
"applyFilter",
"blur",
"sharpen",
"distort",
"stylize",
"render",
"textLayers",
"textRange",
"addText",
"textItem",
"font",
"fontSize",
"pathItems",
"paths",
"createPath",
"bezier",
"stroke",
"fill",
"color",
"colorModel",
"RGB",
"CMYK",
"setRGBColor",
"setCMYKColor",
]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_classify_document_api() {
assert_eq!(
ApiDetector::classify_api("activeDocument"),
Some(ApiType::Document)
);
assert_eq!(ApiDetector::classify_api("save"), Some(ApiType::Document));
}
#[test]
fn test_classify_layer_api() {
assert_eq!(
ApiDetector::classify_api("artLayers"),
Some(ApiType::Layer)
);
}
#[test]
fn test_unknown_api() {
assert_eq!(ApiDetector::classify_api("unknownFunction"), None);
}
#[test]
fn test_extract_from_tokens() {
let tokens = vec![
Token::Identifier("activeDocument".to_string()),
Token::Identifier("selection".to_string()),
Token::Identifier("activeDocument".to_string()),
];
let apis = ApiDetector::extract_from_tokens(&tokens);
assert!(apis.len() >= 2);
let active_doc = apis.iter().find(|a| a.api_name == "activeDocument");
assert!(active_doc.is_some());
assert_eq!(active_doc.unwrap().count, 2);
}
}