horkos 0.2.0

Cloud infrastructure language where insecure code won't compile
Documentation
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Project management for multi-file Horkos projects.
//!
//! Handles:
//! - Entry point discovery (convention over configuration)
//! - Import resolution
//! - Dependency graph construction
//! - Compilation ordering

use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};

use crate::errors::Diagnostic;

/// A Horkos project with resolved entry points and dependencies.
#[derive(Debug)]
pub struct Project {
    /// Project root directory
    pub root: PathBuf,
    /// Entry point file(s)
    pub entries: Vec<PathBuf>,
    /// All discovered .hk files
    pub files: Vec<PathBuf>,
    /// Dependency graph: file → files it imports
    pub dependencies: HashMap<PathBuf, Vec<PathBuf>>,
    /// Compilation order (topologically sorted)
    pub compile_order: Vec<PathBuf>,
}

/// How the entry point was determined
#[derive(Debug, Clone)]
pub enum EntrySource {
    /// Explicitly specified via CLI
    Explicit(PathBuf),
    /// Found via convention (src/main.hk)
    Convention(PathBuf),
}

/// Errors that can occur during project discovery
#[derive(Debug)]
pub enum ProjectError {
    /// No entry point found
    NoEntryPoint { root: PathBuf },
    /// Specified entry point doesn't exist
    EntryNotFound { path: PathBuf },
    /// Circular import detected
    CircularImport { cycle: Vec<PathBuf> },
    /// Import resolution failed
    ImportNotFound { from: PathBuf, import_path: String },
    /// IO error
    Io(std::io::Error),
}

impl std::fmt::Display for ProjectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ProjectError::NoEntryPoint { root } => {
                write!(
                    f,
                    "No entry point found in {}\n\n\
                     Create src/main.hk or specify a file:\n\
                     \n\
                         horkos compile src/infrastructure.hk -o terraform/\n",
                    root.display()
                )
            }
            ProjectError::EntryNotFound { path } => {
                write!(f, "Entry point not found: {}", path.display())
            }
            ProjectError::CircularImport { cycle } => {
                let cycle_str: Vec<_> = cycle.iter().map(|p| p.display().to_string()).collect();
                write!(f, "Circular import detected:\n  {}", cycle_str.join(""))
            }
            ProjectError::ImportNotFound { from, import_path } => {
                write!(
                    f,
                    "Cannot resolve import '{}' from {}",
                    import_path,
                    from.display()
                )
            }
            ProjectError::Io(e) => write!(f, "IO error: {}", e),
        }
    }
}

impl std::error::Error for ProjectError {}

impl From<std::io::Error> for ProjectError {
    fn from(e: std::io::Error) -> Self {
        ProjectError::Io(e)
    }
}

impl Project {
    /// Discover a project from a root directory or explicit entry point.
    ///
    /// Resolution order:
    /// 1. Explicit path (if provided)
    /// 2. Convention: src/main.hk
    /// 3. Error
    pub fn discover(
        root: impl AsRef<Path>,
        explicit_entry: Option<impl AsRef<Path>>,
    ) -> Result<Self, ProjectError> {
        let root = root.as_ref().to_path_buf();

        // 1. Resolve entry point
        let entry = Self::find_entry_point(&root, explicit_entry)?;

        // 2. Discover all files starting from entry
        let mut files = Vec::new();
        let mut dependencies = HashMap::new();
        Self::discover_files_recursive(&entry, &root, &mut files, &mut dependencies)?;

        // 3. Compute compilation order (topological sort)
        let compile_order = Self::topological_sort(&files, &dependencies)?;

        Ok(Project {
            root,
            entries: vec![entry],
            files,
            dependencies,
            compile_order,
        })
    }

    /// Find the entry point file.
    fn find_entry_point(
        root: &Path,
        explicit: Option<impl AsRef<Path>>,
    ) -> Result<PathBuf, ProjectError> {
        // 1. Explicit override wins
        if let Some(path) = explicit {
            let path = path.as_ref();
            let full_path = if path.is_absolute() {
                path.to_path_buf()
            } else {
                root.join(path)
            };

            if full_path.exists() {
                return Ok(full_path.canonicalize()?);
            }
            return Err(ProjectError::EntryNotFound { path: full_path });
        }

        // 2. Convention: src/main.hk
        let main_path = root.join("src/main.hk");
        if main_path.exists() {
            return Ok(main_path.canonicalize()?);
        }

        // 3. Convention: main.hk (in root)
        let main_root = root.join("main.hk");
        if main_root.exists() {
            return Ok(main_root.canonicalize()?);
        }

        // 4. No entry point found
        Err(ProjectError::NoEntryPoint {
            root: root.to_path_buf(),
        })
    }

    /// Recursively discover all files by following imports.
    fn discover_files_recursive(
        file: &Path,
        project_root: &Path,
        files: &mut Vec<PathBuf>,
        dependencies: &mut HashMap<PathBuf, Vec<PathBuf>>,
    ) -> Result<(), ProjectError> {
        let canonical = file.canonicalize()?;

        // Already processed
        if files.contains(&canonical) {
            return Ok(());
        }

        files.push(canonical.clone());

        // Parse file to extract imports
        let source = std::fs::read_to_string(&canonical)?;
        let imports = Self::extract_imports(&source);

        // Resolve each import
        let mut deps = Vec::new();
        for import_path in imports {
            // Skip .tf imports (they're external)
            if import_path.ends_with(".tf") {
                continue;
            }

            let resolved = Self::resolve_import(&import_path, &canonical, project_root)?;
            deps.push(resolved.clone());

            // Recursively discover
            Self::discover_files_recursive(&resolved, project_root, files, dependencies)?;
        }

        dependencies.insert(canonical, deps);
        Ok(())
    }

    /// Extract import paths from source code (quick parse, not full lexer).
    fn extract_imports(source: &str) -> Vec<String> {
        let mut imports = Vec::new();

        for line in source.lines() {
            let line = line.trim();
            if line.starts_with("import ") {
                // Parse: import "path" as alias
                // or: import "path"
                if let Some(start) = line.find('"') {
                    if let Some(end) = line[start + 1..].find('"') {
                        let path = &line[start + 1..start + 1 + end];
                        imports.push(path.to_string());
                    }
                }
            }
        }

        imports
    }

    /// Resolve an import path to an actual file.
    fn resolve_import(
        import_path: &str,
        from_file: &Path,
        project_root: &Path,
    ) -> Result<PathBuf, ProjectError> {
        let from_dir = from_file.parent().unwrap_or(project_root);

        // Relative import: "./foo.hk" or "../foo.hk"
        if import_path.starts_with("./") || import_path.starts_with("../") {
            let resolved = from_dir.join(import_path);
            if resolved.exists() {
                return Ok(resolved.canonicalize()?);
            }

            // Try adding .hk extension
            let with_ext = from_dir.join(format!("{}.hk", import_path.trim_end_matches(".hk")));
            if with_ext.exists() {
                return Ok(with_ext.canonicalize()?);
            }

            return Err(ProjectError::ImportNotFound {
                from: from_file.to_path_buf(),
                import_path: import_path.to_string(),
            });
        }

        // Absolute import from project: "network/vpc.hk"
        let from_src = project_root.join("src").join(import_path);
        if from_src.exists() {
            return Ok(from_src.canonicalize()?);
        }

        // Try from project root directly
        let from_root = project_root.join(import_path);
        if from_root.exists() {
            return Ok(from_root.canonicalize()?);
        }

        Err(ProjectError::ImportNotFound {
            from: from_file.to_path_buf(),
            import_path: import_path.to_string(),
        })
    }

    /// Topological sort to determine compilation order.
    /// Returns files in order: dependencies before dependents.
    fn topological_sort(
        files: &[PathBuf],
        dependencies: &HashMap<PathBuf, Vec<PathBuf>>,
    ) -> Result<Vec<PathBuf>, ProjectError> {
        let mut in_degree: HashMap<PathBuf, usize> = HashMap::new();
        let mut reverse_deps: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();

        // Initialize
        for file in files {
            in_degree.entry(file.clone()).or_insert(0);
            reverse_deps.entry(file.clone()).or_default();
        }

        // Build reverse dependency graph and count in-degrees
        for (file, deps) in dependencies {
            for dep in deps {
                if files.contains(dep) {
                    *in_degree.entry(file.clone()).or_insert(0) += 1;
                    reverse_deps
                        .entry(dep.clone())
                        .or_default()
                        .push(file.clone());
                }
            }
        }

        // Kahn's algorithm
        let mut queue: VecDeque<PathBuf> = in_degree
            .iter()
            .filter(|(_, deg)| **deg == 0)
            .map(|(f, _)| f.clone())
            .collect();

        let mut order = Vec::new();

        while let Some(file) = queue.pop_front() {
            order.push(file.clone());

            if let Some(dependents) = reverse_deps.get(&file) {
                for dependent in dependents {
                    if let Some(deg) = in_degree.get_mut(dependent) {
                        *deg -= 1;
                        if *deg == 0 {
                            queue.push_back(dependent.clone());
                        }
                    }
                }
            }
        }

        // Check for cycles
        if order.len() != files.len() {
            // Find a cycle for error reporting
            let in_cycle: Vec<_> = files
                .iter()
                .filter(|f| !order.contains(f))
                .cloned()
                .collect();

            return Err(ProjectError::CircularImport { cycle: in_cycle });
        }

        Ok(order)
    }

    /// Get all files that need to be compiled.
    pub fn files_to_compile(&self) -> &[PathBuf] {
        &self.compile_order
    }

    /// Check if a file is an entry point.
    pub fn is_entry(&self, file: &Path) -> bool {
        self.entries.iter().any(|e| e == file)
    }
}

/// Compile an entire project with cross-file type resolution.
pub fn compile_project(
    root: impl AsRef<Path>,
    entry: Option<impl AsRef<Path>>,
    output_dir: impl AsRef<Path>,
) -> Result<(), Vec<Diagnostic>> {
    let root = root.as_ref();
    let output_dir = output_dir.as_ref();

    // Discover project
    let project =
        Project::discover(root, entry).map_err(|e| vec![Diagnostic::error(e.to_string())])?;

    // Create output directory
    std::fs::create_dir_all(output_dir).map_err(|e| {
        vec![Diagnostic::error(format!(
            "Failed to create output directory: {}",
            e
        ))]
    })?;

    // Create global symbol table for cross-file type resolution
    let mut globals = crate::GlobalSymbolTable::new();

    // Register import path mappings for all discovered files
    for file in project.dependencies.keys() {
        // Register this file's import paths
        for import_path in
            Project::extract_imports(&std::fs::read_to_string(file).unwrap_or_default())
        {
            if import_path.ends_with(".hk") {
                if let Ok(resolved) = Project::resolve_import(&import_path, file, &project.root) {
                    globals.register_import_path(&import_path, &resolved);
                }
            }
        }
    }

    // Compile each file in dependency order, building global symbol table
    let mut all_hcl = String::new();
    let mut all_overrides = Vec::new();
    let options = crate::CompileOptions::default();

    for file in project.files_to_compile() {
        let source = std::fs::read_to_string(file).map_err(|e| {
            vec![Diagnostic::error(format!(
                "Failed to read {}: {}",
                file.display(),
                e
            ))]
        })?;

        let filename = file.to_string_lossy();

        // Compile with access to global symbol table
        let (hcl, typed_ast, overrides) =
            crate::compile_and_extract(&source, &filename, &options, Some(&globals))?;

        // Collect preferred param overrides for info messages
        all_overrides.extend(overrides);

        // Extract and register this file's exports for subsequent files
        let exports = crate::extract_exports(&typed_ast, file);
        globals.register(exports);

        // Add file header
        all_hcl.push_str(&format!(
            "# =============================================================================\n\
             # Generated from: {}\n\
             # =============================================================================\n\n",
            file.strip_prefix(root).unwrap_or(file).display()
        ));
        all_hcl.push_str(&hcl);
        all_hcl.push_str("\n\n");
    }

    // Emit info messages for preferred param overrides
    for override_info in &all_overrides {
        eprintln!(
            "  \x1b[36minfo\x1b[0m: {} disabled for {} (recommended: {})",
            override_info.param_name, override_info.resource_name, override_info.recommended
        );
    }

    // Write combined output
    let output_file = output_dir.join("main.tf");
    std::fs::write(&output_file, &all_hcl).map_err(|e| {
        vec![Diagnostic::error(format!(
            "Failed to write {}: {}",
            output_file.display(),
            e
        ))]
    })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_project() -> TempDir {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();

        // Create main.hk
        fs::write(
            src.join("main.hk"),
            r#"
import "./network/vpc.hk" as vpc

val sg = Network.createSecurityGroup(vpc: vpc.mainVpc, name: "web")
"#,
        )
        .unwrap();

        // Create network/vpc.hk
        let network = src.join("network");
        fs::create_dir_all(&network).unwrap();
        fs::write(
            network.join("vpc.hk"),
            r#"
val mainVpc = Network.createVpc("main", cidr: "10.0.0.0/16")
"#,
        )
        .unwrap();

        dir
    }

    #[test]
    fn test_find_entry_point_convention() {
        let dir = create_test_project();
        let entry = Project::find_entry_point(dir.path(), None::<&Path>).unwrap();
        assert!(entry.ends_with("main.hk"));
    }

    #[test]
    fn test_find_entry_point_explicit() {
        let dir = create_test_project();
        let entry = Project::find_entry_point(dir.path(), Some("src/network/vpc.hk")).unwrap();
        assert!(entry.ends_with("vpc.hk"));
    }

    #[test]
    fn test_extract_imports() {
        let source = r#"
import "./network/vpc.hk" as vpc
import "legacy.tf" as legacy
val x = 42
import "./storage/s3.hk" as s3
"#;
        let imports = Project::extract_imports(source);
        assert_eq!(
            imports,
            vec!["./network/vpc.hk", "legacy.tf", "./storage/s3.hk",]
        );
    }

    #[test]
    fn test_discover_project() {
        let dir = create_test_project();
        let project = Project::discover(dir.path(), None::<&Path>).unwrap();

        assert_eq!(project.files.len(), 2);
        assert_eq!(project.compile_order.len(), 2);

        // vpc.hk should be compiled before main.hk (dependency order)
        let vpc_idx = project
            .compile_order
            .iter()
            .position(|p| p.ends_with("vpc.hk"))
            .unwrap();
        let main_idx = project
            .compile_order
            .iter()
            .position(|p| p.ends_with("main.hk"))
            .unwrap();
        assert!(
            vpc_idx < main_idx,
            "vpc.hk should be compiled before main.hk"
        );
    }

    #[test]
    fn test_circular_import_detected() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();

        // Create circular imports: a.hk → b.hk → a.hk
        fs::write(src.join("main.hk"), r#"import "./a.hk" as a"#).unwrap();
        fs::write(src.join("a.hk"), r#"import "./b.hk" as b"#).unwrap();
        fs::write(src.join("b.hk"), r#"import "./a.hk" as a"#).unwrap();

        let result = Project::discover(dir.path(), None::<&Path>);
        assert!(matches!(result, Err(ProjectError::CircularImport { .. })));
    }
}