lashlang 0.1.0-alpha.55

Lashlang: compact CodeAct language for model-authored REPL blocks in the lash agent runtime.
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
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    ArtifactStoreError, HostRequirementsRef, LashlangArtifactStore, LashlangHostEnvironment,
    LinkError, LinkedModule, ModuleArtifact, ModuleIntrospection, ModuleIntrospectionError,
    ModuleRef, ParseError, Span, format_link_diagnostic, format_parse_diagnostic, parse,
};

pub struct ModuleCompileRequest<'a> {
    pub source: &'a str,
    pub environment: &'a LashlangHostEnvironment,
    pub artifact_store: Option<&'a dyn LashlangArtifactStore>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModuleCompileOutput {
    pub artifact: ModuleArtifact,
    pub module_ref: ModuleRef,
    pub host_requirements_ref: HostRequirementsRef,
    pub introspection: ModuleIntrospection,
}

/// Parse, link, inspect, and optionally persist a Lashlang module.
///
/// `parse` and `LinkedModule::link` remain public for tooling and low-level
/// tests. Host integrations should prefer this facade so diagnostics,
/// artifact identity, persistence, and introspection are produced consistently.
pub async fn compile_module(
    request: ModuleCompileRequest<'_>,
) -> Result<ModuleCompileOutput, ModuleCompileError> {
    let program =
        parse(request.source).map_err(|err| ModuleCompileError::parse(request.source, err))?;
    let linked = LinkedModule::link(program, request.environment)
        .map_err(|err| ModuleCompileError::link(request.source, err))?;
    let introspection = linked
        .artifact
        .introspect()
        .map_err(ModuleCompileError::introspection)?;
    if let Some(store) = request.artifact_store {
        store
            .put_module_artifact(&linked.artifact)
            .await
            .map_err(ModuleCompileError::persist)?;
    }
    Ok(ModuleCompileOutput {
        module_ref: linked.module_ref,
        host_requirements_ref: linked.host_requirements_ref,
        artifact: linked.artifact,
        introspection,
    })
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModuleCompileStage {
    Parse,
    Link,
    Persist,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModuleCompileDiagnostic {
    pub stage: ModuleCompileStage,
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub column: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diagnostic: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Error, Serialize, Deserialize)]
#[serde(tag = "stage", content = "error", rename_all = "snake_case")]
pub enum ModuleCompileError {
    #[error("{0}")]
    Parse(ModuleCompileDiagnostic),
    #[error("{0}")]
    Link(ModuleCompileDiagnostic),
    #[error("{0}")]
    Persist(ModuleCompileDiagnostic),
}

impl ModuleCompileError {
    fn parse(source: &str, err: ParseError) -> Self {
        let offset = err.offset();
        let (line, column) = source_location(source, offset);
        Self::Parse(ModuleCompileDiagnostic {
            stage: ModuleCompileStage::Parse,
            message: err.to_string(),
            offset: Some(offset),
            span: None,
            line: Some(line),
            column: Some(column),
            diagnostic: Some(format_parse_diagnostic(source, &err)),
        })
    }

    fn link(source: &str, err: LinkError) -> Self {
        let span = err.span();
        let offset = span.map(|span| span.start);
        let (line, column) = offset
            .map(|offset| source_location(source, offset))
            .map(|(line, column)| (Some(line), Some(column)))
            .unwrap_or((None, None));
        Self::Link(ModuleCompileDiagnostic {
            stage: ModuleCompileStage::Link,
            message: err.to_string(),
            offset,
            span,
            line,
            column,
            diagnostic: Some(format_link_diagnostic(source, &err)),
        })
    }

    fn introspection(err: ModuleIntrospectionError) -> Self {
        Self::Link(ModuleCompileDiagnostic {
            stage: ModuleCompileStage::Link,
            message: err.to_string(),
            offset: None,
            span: None,
            line: None,
            column: None,
            diagnostic: Some(err.to_string()),
        })
    }

    fn persist(err: ArtifactStoreError) -> Self {
        Self::Persist(ModuleCompileDiagnostic {
            stage: ModuleCompileStage::Persist,
            message: err.to_string(),
            offset: None,
            span: None,
            line: None,
            column: None,
            diagnostic: Some(err.to_string()),
        })
    }

    pub fn diagnostic(&self) -> &ModuleCompileDiagnostic {
        match self {
            Self::Parse(diagnostic) | Self::Link(diagnostic) | Self::Persist(diagnostic) => {
                diagnostic
            }
        }
    }
}

impl std::fmt::Display for ModuleCompileDiagnostic {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.diagnostic.as_deref().unwrap_or(self.message.as_str()))
    }
}

fn source_location(source: &str, offset: usize) -> (usize, usize) {
    let offset = offset.min(source.len());
    let mut line = 1usize;
    let mut line_start = 0usize;
    for (idx, ch) in source.char_indices() {
        if idx >= offset {
            break;
        }
        if ch == '\n' {
            line += 1;
            line_start = idx + ch.len_utf8();
        }
    }
    let column = source[line_start..offset].chars().count() + 1;
    (line, column)
}

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

    #[tokio::test(flavor = "current_thread")]
    async fn compile_module_facade_returns_artifact_and_introspection() {
        let environment = LashlangHostEnvironment {
            abilities: crate::LashlangAbilities::default()
                .with_processes()
                .with_process_signals(),
            ..LashlangHostEnvironment::default()
        };
        let output = compile_module(ModuleCompileRequest {
            source: "process echo(value: str) { finish value }",
            environment: &environment,
            artifact_store: None,
        })
        .await
        .expect("module should compile");

        assert_eq!(output.introspection.exported_processes.len(), 1);
        assert_eq!(
            output.introspection.exported_processes[0]
                .definition
                .process_name,
            "echo"
        );
        assert_eq!(output.module_ref, output.artifact.module_ref);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn compile_module_facade_reports_parse_errors() {
        let environment = LashlangHostEnvironment::default();
        let err = compile_module(ModuleCompileRequest {
            source: "if true",
            environment: &environment,
            artifact_store: None,
        })
        .await
        .expect_err("parse should fail");

        let ModuleCompileError::Parse(diagnostic) = err else {
            panic!("expected parse error");
        };
        assert_eq!(diagnostic.stage, ModuleCompileStage::Parse);
        assert_eq!(diagnostic.line, Some(1));
        assert!(
            diagnostic
                .diagnostic
                .expect("diagnostic")
                .contains("line 1")
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn compile_module_facade_reports_link_errors() {
        let environment = LashlangHostEnvironment::default();
        let err = compile_module(ModuleCompileRequest {
            source: "process echo(value: str) { finish value }",
            environment: &environment,
            artifact_store: None,
        })
        .await
        .expect_err("link should fail");

        let ModuleCompileError::Link(diagnostic) = err else {
            panic!("expected link error");
        };
        assert_eq!(diagnostic.stage, ModuleCompileStage::Link);
        assert_eq!(diagnostic.line, Some(1));
        assert!(diagnostic.message.contains("processes"));
    }

    struct FailingStore;

    #[async_trait::async_trait]
    impl LashlangArtifactStore for FailingStore {
        async fn put_module_artifact(
            &self,
            _artifact: &ModuleArtifact,
        ) -> Result<(), ArtifactStoreError> {
            Err(ArtifactStoreError::Backend("disk full".to_string()))
        }

        async fn get_module_artifact(
            &self,
            _module_ref: &ModuleRef,
        ) -> Result<Option<std::sync::Arc<ModuleArtifact>>, ArtifactStoreError> {
            Ok(None)
        }

        async fn put_artifact_bytes(
            &self,
            _artifact_ref: &str,
            _descriptor: &str,
            _bytes: &[u8],
        ) -> Result<(), ArtifactStoreError> {
            Ok(())
        }

        async fn get_artifact_bytes(
            &self,
            _artifact_ref: &str,
        ) -> Result<Option<Vec<u8>>, ArtifactStoreError> {
            Ok(None)
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn compile_module_facade_reports_persistence_errors() {
        let environment = LashlangHostEnvironment {
            abilities: crate::LashlangAbilities::default().with_processes(),
            ..LashlangHostEnvironment::default()
        };
        let store = FailingStore;
        let err = compile_module(ModuleCompileRequest {
            source: "process echo(value: str) { finish value }",
            environment: &environment,
            artifact_store: Some(&store),
        })
        .await
        .expect_err("persist should fail");

        let ModuleCompileError::Persist(diagnostic) = err else {
            panic!("expected persist error");
        };
        assert_eq!(diagnostic.stage, ModuleCompileStage::Persist);
        assert!(diagnostic.message.contains("disk full"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn compile_module_facade_reports_rich_introspection() {
        let mut resources = crate::LashlangHostCatalog::new();
        resources.add_module_operation(
            ["files"],
            "File",
            "read",
            "files.read",
            crate::TypeExpr::Ref("File".into()),
            crate::TypeExpr::Str,
        );
        resources.add_value_constructor(
            ["files", "Open"],
            crate::TypeExpr::Object(vec![crate::TypeField {
                name: "path".into(),
                ty: crate::TypeExpr::Str,
                optional: false,
            }]),
            crate::TypeExpr::Ref("File".into()),
        );
        resources
            .add_trigger_source_constructor(
                ["ui", "button"],
                crate::TypeExpr::Object(Vec::new()),
                crate::NamedDataType::object(
                    "ui.ButtonPressed",
                    vec![crate::TypeField {
                        name: "color".into(),
                        ty: crate::TypeExpr::Str,
                        optional: false,
                    }],
                )
                .expect("valid event type"),
            )
            .expect("valid trigger source");
        let environment = LashlangHostEnvironment {
            resources,
            abilities: crate::LashlangAbilities::default()
                .with_processes()
                .with_process_signals(),
            language_features: crate::LashlangLanguageFeatures::default().with_label_annotations(),
        };
        let output = compile_module(ModuleCompileRequest {
            source: r#"
@label(title: "Watcher", description: "Tracks button presses")
process watch(event: ui.ButtonPressed, file: File) signals { done: str } -> str {
  opened = files.Open({ path: "inbox.txt" })
  text = await files.read(file)?
  finish event.color
}
source = ui.button({})
submit source
"#,
            environment: &environment,
            artifact_store: None,
        })
        .await
        .expect("module should compile");

        let process = output
            .introspection
            .exported_processes
            .iter()
            .find(|process| process.definition.process_name == "watch")
            .expect("watch process introspection");
        assert_eq!(process.label.as_ref().expect("label").title, "Watcher");
        assert_eq!(process.params.len(), 2);
        assert_eq!(process.signals[0].name, "done");
        assert_eq!(
            process.return_type.as_ref().expect("return type").display,
            "str"
        );
        assert!(process.canonical_source.contains("process watch"));
        assert!(
            output
                .introspection
                .required_module_instances
                .iter()
                .any(|module| module.alias == "files"
                    && module
                        .operations
                        .iter()
                        .any(|op| op.host_operation == "files.read"))
        );
        assert!(
            output
                .introspection
                .value_constructors
                .iter()
                .any(|constructor| constructor.key == "files.Open")
        );
        assert!(
            output
                .introspection
                .trigger_source_requirements
                .iter()
                .any(|source| source.source_type == "ui.button"
                    && source.event_type_name == "ui.ButtonPressed")
        );
        assert!(
            output
                .introspection
                .named_data_types
                .iter()
                .any(|ty| ty.name == "ui.ButtonPressed")
        );
    }
}