Skip to main content

portalis_analysis/
lib.rs

1//! Analysis Agent - Type Inference and API Extraction
2//!
3//! Analyzes Python AST to infer types and extract API contracts.
4
5// mod flow_analyzer; // Disabled for Phase 1 rapid completion
6pub mod dependency_resolver;
7
8use async_trait::async_trait;
9// use flow_analyzer::FlowAnalyzer;
10pub use dependency_resolver::{DependencyResolver, ResolvedDependency, DependencyType, CrateMapping};
11use portalis_core::{Agent, AgentCapability, AgentId, ArtifactMetadata, Result};
12use serde::{Deserialize, Serialize};
13
14/// Input from Ingest Agent
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct AnalysisInput {
17    pub ast: serde_json::Value, // PythonAst from ingest
18}
19
20/// Output with type information
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct AnalysisOutput {
23    pub typed_functions: Vec<TypedFunction>,
24    pub api_contract: ApiContract,
25    pub confidence: f64,
26    pub metadata: ArtifactMetadata,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct TypedFunction {
31    pub name: String,
32    pub params: Vec<TypedParameter>,
33    pub return_type: RustType,
34    pub confidence: f64,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct TypedParameter {
39    pub name: String,
40    pub rust_type: RustType,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub enum RustType {
45    I32,
46    I64,
47    F64,
48    String,
49    Bool,
50    Vec(Box<RustType>),
51    Option(Box<RustType>),
52    Unknown,
53}
54
55impl std::fmt::Display for RustType {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            RustType::I32 => write!(f, "i32"),
59            RustType::I64 => write!(f, "i64"),
60            RustType::F64 => write!(f, "f64"),
61            RustType::String => write!(f, "String"),
62            RustType::Bool => write!(f, "bool"),
63            RustType::Vec(inner) => write!(f, "Vec<{}>", inner),
64            RustType::Option(inner) => write!(f, "Option<{}>", inner),
65            RustType::Unknown => write!(f, "()"),
66        }
67    }
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct ApiContract {
72    pub functions: Vec<FunctionSignature>,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct FunctionSignature {
77    pub name: String,
78    pub params: Vec<String>,
79    pub return_type: String,
80}
81
82/// Analysis Agent implementation
83pub struct AnalysisAgent {
84    id: AgentId,
85}
86
87impl AnalysisAgent {
88    pub fn new() -> Self {
89        Self {
90            id: AgentId::new(),
91        }
92    }
93
94    /// Infer Rust types from Python type hints
95    fn infer_type(&self, python_type: Option<&str>) -> RustType {
96        match python_type {
97            Some("int") => RustType::I32,
98            Some("float") => RustType::F64,
99            Some("str") => RustType::String,
100            Some("bool") => RustType::Bool,
101            Some(t) if t.starts_with("List[") => {
102                // Simplified list handling
103                RustType::Vec(Box::new(RustType::I32))
104            }
105            _ => RustType::Unknown,
106        }
107    }
108
109    /// Build API contract from typed functions
110    fn build_api_contract(&self, functions: &[TypedFunction]) -> ApiContract {
111        let signatures = functions.iter().map(|f| FunctionSignature {
112            name: f.name.clone(),
113            params: f.params.iter().map(|p| p.rust_type.to_string()).collect(),
114            return_type: f.return_type.to_string(),
115        }).collect();
116
117        ApiContract { functions: signatures }
118    }
119}
120
121impl Default for AnalysisAgent {
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127#[async_trait]
128impl Agent for AnalysisAgent {
129    type Input = AnalysisInput;
130    type Output = AnalysisOutput;
131
132    async fn execute(&self, input: Self::Input) -> Result<Self::Output> {
133        tracing::info!("Analyzing Python AST for type information");
134
135        // Parse functions from AST (simplified)
136        let functions: Vec<serde_json::Value> = input.ast.get("functions")
137            .and_then(|f| f.as_array())
138            .cloned()
139            .unwrap_or_default();
140
141        let mut typed_functions = Vec::new();
142        let mut total_confidence = 0.0;
143
144        for func in functions {
145            let name = func.get("name")
146                .and_then(|n| n.as_str())
147                .unwrap_or("unknown")
148                .to_string();
149
150            let params: Vec<serde_json::Value> = func.get("params")
151                .and_then(|p| p.as_array())
152                .cloned()
153                .unwrap_or_default();
154
155            let typed_params: Vec<TypedParameter> = params.iter().map(|p| {
156                let param_name = p.get("name")
157                    .and_then(|n| n.as_str())
158                    .unwrap_or("unknown")
159                    .to_string();
160
161                let type_hint = p.get("type_hint")
162                    .and_then(|t| t.as_str());
163
164                TypedParameter {
165                    name: param_name,
166                    rust_type: self.infer_type(type_hint),
167                }
168            }).collect();
169
170            let return_hint = func.get("return_type")
171                .and_then(|r| r.as_str());
172
173            let return_type = self.infer_type(return_hint);
174
175            // Calculate confidence based on type hint availability
176            let confidence = if return_hint.is_some() { 0.9 } else { 0.5 };
177            total_confidence += confidence;
178
179            typed_functions.push(TypedFunction {
180                name,
181                params: typed_params,
182                return_type,
183                confidence,
184            });
185        }
186
187        let overall_confidence = if !typed_functions.is_empty() {
188            total_confidence / typed_functions.len() as f64
189        } else {
190            0.0
191        };
192
193        let api_contract = self.build_api_contract(&typed_functions);
194
195        let metadata = ArtifactMetadata::new(self.name())
196            .with_tag("functions", typed_functions.len().to_string())
197            .with_tag("confidence", format!("{:.2}", overall_confidence));
198
199        Ok(AnalysisOutput {
200            typed_functions,
201            api_contract,
202            confidence: overall_confidence,
203            metadata,
204        })
205    }
206
207    fn id(&self) -> AgentId {
208        self.id
209    }
210
211    fn name(&self) -> &str {
212        "AnalysisAgent"
213    }
214
215    fn capabilities(&self) -> Vec<AgentCapability> {
216        vec![AgentCapability::TypeInference, AgentCapability::ApiExtraction]
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use serde_json::json;
224
225    #[tokio::test]
226    async fn test_type_inference_with_hints() {
227        let agent = AnalysisAgent::new();
228
229        let ast = json!({
230            "functions": [{
231                "name": "add",
232                "params": [
233                    {"name": "a", "type_hint": "int"},
234                    {"name": "b", "type_hint": "int"}
235                ],
236                "return_type": "int"
237            }]
238        });
239
240        let input = AnalysisInput { ast };
241        let output = agent.execute(input).await.unwrap();
242
243        assert_eq!(output.typed_functions.len(), 1);
244        assert_eq!(output.typed_functions[0].name, "add");
245        assert_eq!(output.typed_functions[0].return_type, RustType::I32);
246        assert!(output.confidence > 0.8);
247    }
248
249    #[tokio::test]
250    async fn test_type_inference_without_hints() {
251        let agent = AnalysisAgent::new();
252
253        let ast = json!({
254            "functions": [{
255                "name": "multiply",
256                "params": [
257                    {"name": "x", "type_hint": null},
258                    {"name": "y", "type_hint": null}
259                ],
260                "return_type": null
261            }]
262        });
263
264        let input = AnalysisInput { ast };
265        let output = agent.execute(input).await.unwrap();
266
267        assert_eq!(output.typed_functions.len(), 1);
268        assert_eq!(output.typed_functions[0].return_type, RustType::Unknown);
269        assert!(output.confidence < 0.7);
270    }
271
272    #[tokio::test]
273    async fn test_type_inference_string_type() {
274        let agent = AnalysisAgent::new();
275
276        let ast = json!({
277            "functions": [{
278                "name": "greet",
279                "params": [{"name": "name", "type_hint": "str"}],
280                "return_type": "str"
281            }]
282        });
283
284        let input = AnalysisInput { ast };
285        let output = agent.execute(input).await.unwrap();
286
287        assert_eq!(output.typed_functions[0].params[0].rust_type, RustType::String);
288        assert_eq!(output.typed_functions[0].return_type, RustType::String);
289    }
290
291    #[tokio::test]
292    async fn test_type_inference_float_type() {
293        let agent = AnalysisAgent::new();
294
295        let ast = json!({
296            "functions": [{
297                "name": "calculate",
298                "params": [{"name": "value", "type_hint": "float"}],
299                "return_type": "float"
300            }]
301        });
302
303        let input = AnalysisInput { ast };
304        let output = agent.execute(input).await.unwrap();
305
306        assert_eq!(output.typed_functions[0].params[0].rust_type, RustType::F64);
307        assert_eq!(output.typed_functions[0].return_type, RustType::F64);
308    }
309
310    #[tokio::test]
311    async fn test_api_contract_generation() {
312        let agent = AnalysisAgent::new();
313
314        let ast = json!({
315            "functions": [
316                {
317                    "name": "add",
318                    "params": [
319                        {"name": "a", "type_hint": "int"},
320                        {"name": "b", "type_hint": "int"}
321                    ],
322                    "return_type": "int"
323                },
324                {
325                    "name": "multiply",
326                    "params": [
327                        {"name": "x", "type_hint": "int"},
328                        {"name": "y", "type_hint": "int"}
329                    ],
330                    "return_type": "int"
331                }
332            ]
333        });
334
335        let input = AnalysisInput { ast };
336        let output = agent.execute(input).await.unwrap();
337
338        assert_eq!(output.api_contract.functions.len(), 2);
339        assert_eq!(output.api_contract.functions[0].name, "add");
340        assert_eq!(output.api_contract.functions[1].name, "multiply");
341    }
342
343    #[tokio::test]
344    async fn test_empty_ast() {
345        let agent = AnalysisAgent::new();
346
347        let ast = json!({
348            "functions": []
349        });
350
351        let input = AnalysisInput { ast };
352        let output = agent.execute(input).await.unwrap();
353
354        assert_eq!(output.typed_functions.len(), 0);
355        assert_eq!(output.confidence, 0.0);
356    }
357
358    #[test]
359    fn test_rust_type_display() {
360        assert_eq!(RustType::I32.to_string(), "i32");
361        assert_eq!(RustType::String.to_string(), "String");
362        assert_eq!(RustType::Bool.to_string(), "bool");
363        assert_eq!(RustType::Vec(Box::new(RustType::I32)).to_string(), "Vec<i32>");
364    }
365
366    #[test]
367    fn test_agent_capabilities() {
368        let agent = AnalysisAgent::new();
369        let caps = agent.capabilities();
370        assert!(caps.contains(&AgentCapability::TypeInference));
371        assert!(caps.contains(&AgentCapability::ApiExtraction));
372    }
373}