seq-runtime 5.6.4

Runtime library for the Seq programming language
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
//! File I/O Operations for Seq
//!
//! Provides file reading operations for Seq programs.
//!
//! # Usage from Seq
//!
//! ```seq
//! "config.json" file-slurp  # ( String -- String ) read entire file
//! "config.json" file-exists?  # ( String -- Int ) 1 if exists, 0 otherwise
//! "data.txt" [ process-line ] file-for-each-line+  # ( String Quotation -- String Int )
//! ```
//!
//! # Example
//!
//! ```seq
//! : main ( -- Int )
//!   "config.json" file-exists? if
//!     "config.json" file-slurp write_line
//!   else
//!     "File not found" write_line
//!   then
//!   0
//! ;
//! ```

use crate::stack::{Stack, pop, push};
use crate::value::{Value, VariantData};
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::sync::Arc;

/// Read entire file contents as a string
///
/// Stack effect: ( String -- String Bool )
///
/// Takes a file path, attempts to read the entire file.
/// Returns (contents true) on success, or ("" false) on failure.
/// Errors are values, not crashes.
/// Panics only for internal bugs (wrong stack type).
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer with a String value on top
/// - Caller must ensure stack is not concurrently modified
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_slurp(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file-slurp: stack is empty");

    let (rest, value) = unsafe { pop(stack) };

    match value {
        Value::String(path) => match fs::read_to_string(path.as_str()) {
            Ok(contents) => {
                let stack = unsafe { push(rest, Value::String(contents.into())) };
                unsafe { push(stack, Value::Bool(true)) }
            }
            Err(_) => {
                let stack = unsafe { push(rest, Value::String("".into())) };
                unsafe { push(stack, Value::Bool(false)) }
            }
        },
        _ => panic!("file-slurp: expected String path on stack, got {:?}", value),
    }
}

/// Check if a file exists
///
/// Stack effect: ( String -- Int )
///
/// Takes a file path and returns 1 if the file exists, 0 otherwise.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer with a String value on top
/// - Caller must ensure stack is not concurrently modified
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_exists(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file-exists?: stack is empty");

    let (rest, value) = unsafe { pop(stack) };

    match value {
        Value::String(path) => {
            let exists = Path::new(path.as_str()).exists();
            unsafe { push(rest, Value::Bool(exists)) }
        }
        _ => panic!(
            "file-exists?: expected String path on stack, got {:?}",
            value
        ),
    }
}

/// Process each line of a file with a quotation
///
/// Stack effect: ( String Quotation -- String Int )
///
/// Opens the file, calls the quotation with each line (including newline),
/// then closes the file.
///
/// Returns:
/// - Success: ( "" 1 )
/// - Error: ( "error message" 0 )
///
/// The quotation should have effect ( String -- ), receiving each line
/// and consuming it. Empty files return success without calling the quotation.
///
/// # Line Ending Normalization
///
/// Line endings are normalized to `\n` regardless of platform. Windows-style
/// `\r\n` endings are converted to `\n`. This ensures consistent behavior
/// when processing files across different operating systems.
///
/// # Example
///
/// ```seq
/// "data.txt" [ string-chomp process-line ] file-for-each-line+
/// if
///     "Done processing" write_line
/// else
///     "Error: " swap string-concat write_line
/// then
/// ```
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be a Quotation or Closure
/// - Second on stack must be a String (file path)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_for_each_line_plus(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file-for-each-line+: stack is empty");

    // Pop quotation
    let (stack, quot_value) = unsafe { pop(stack) };

    // Pop path
    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!(
            "file-for-each-line+: expected String path, got {:?}",
            path_value
        ),
    };

    // Open file
    let file = match File::open(path.as_str()) {
        Ok(f) => f,
        Err(e) => {
            // Return error: ( "error message" 0 )
            let stack = unsafe { push(stack, Value::String(e.to_string().into())) };
            return unsafe { push(stack, Value::Int(0)) };
        }
    };

    // Extract function pointer and optionally closure environment
    let (wrapper, env_data, env_len): (usize, *const Value, usize) = match quot_value {
        Value::Quotation { wrapper, .. } => {
            if wrapper == 0 {
                panic!("file-for-each-line+: quotation wrapper function pointer is null");
            }
            (wrapper, std::ptr::null(), 0)
        }
        Value::Closure { fn_ptr, ref env } => {
            if fn_ptr == 0 {
                panic!("file-for-each-line+: closure function pointer is null");
            }
            (fn_ptr, env.as_ptr(), env.len())
        }
        _ => panic!(
            "file-for-each-line+: expected Quotation or Closure, got {:?}",
            quot_value
        ),
    };

    // Read lines and call quotation/closure for each
    let reader = BufReader::new(file);
    let mut current_stack = stack;

    for line_result in reader.lines() {
        match line_result {
            Ok(mut line_str) => {
                // `BufReader::lines()` strips all line endings (\n, \r\n, \r)
                // We add back \n to match read_line behavior and ensure consistent newlines
                line_str.push('\n');

                // Push line onto stack
                current_stack = unsafe { push(current_stack, Value::String(line_str.into())) };

                // Call the quotation or closure
                if env_data.is_null() {
                    // Quotation: just stack -> stack
                    let fn_ref: unsafe extern "C" fn(Stack) -> Stack =
                        unsafe { std::mem::transmute(wrapper) };
                    current_stack = unsafe { fn_ref(current_stack) };
                } else {
                    // Closure: stack, env_ptr, env_len -> stack
                    let fn_ref: unsafe extern "C" fn(Stack, *const Value, usize) -> Stack =
                        unsafe { std::mem::transmute(wrapper) };
                    current_stack = unsafe { fn_ref(current_stack, env_data, env_len) };
                }

                // Yield to scheduler for cooperative multitasking
                may::coroutine::yield_now();
            }
            Err(e) => {
                // I/O error mid-file
                let stack = unsafe { push(current_stack, Value::String(e.to_string().into())) };
                return unsafe { push(stack, Value::Bool(false)) };
            }
        }
    }

    // Success: ( "" true )
    let stack = unsafe { push(current_stack, Value::String("".into())) };
    unsafe { push(stack, Value::Bool(true)) }
}

/// Write string to file (creates or overwrites)
///
/// Stack effect: ( String String -- Bool )
///
/// Takes content and path, writes content to file.
/// Creates the file if it doesn't exist, overwrites if it does.
/// Returns true on success, false on failure.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String), second must be content (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_spit(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file.spit: stack is empty");

    // Pop path (top of stack)
    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("file.spit: expected String path, got {:?}", path_value),
    };

    // Pop content
    let (stack, content_value) = unsafe { pop(stack) };
    let content = match content_value {
        Value::String(s) => s,
        _ => panic!(
            "file.spit: expected String content, got {:?}",
            content_value
        ),
    };

    match fs::write(path.as_str(), content.as_str()) {
        Ok(()) => unsafe { push(stack, Value::Bool(true)) },
        Err(_) => unsafe { push(stack, Value::Bool(false)) },
    }
}

/// Append string to file (creates if doesn't exist)
///
/// Stack effect: ( String String -- Bool )
///
/// Takes content and path, appends content to file.
/// Creates the file if it doesn't exist.
/// Returns true on success, false on failure.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String), second must be content (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_append(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file.append: stack is empty");

    // Pop path (top of stack)
    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("file.append: expected String path, got {:?}", path_value),
    };

    // Pop content
    let (stack, content_value) = unsafe { pop(stack) };
    let content = match content_value {
        Value::String(s) => s,
        _ => panic!(
            "file.append: expected String content, got {:?}",
            content_value
        ),
    };

    let result = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path.as_str())
        .and_then(|mut file| file.write_all(content.as_str().as_bytes()));

    match result {
        Ok(()) => unsafe { push(stack, Value::Bool(true)) },
        Err(_) => unsafe { push(stack, Value::Bool(false)) },
    }
}

/// Delete a file
///
/// Stack effect: ( String -- Bool )
///
/// Takes a file path and deletes the file.
/// Returns true on success, false on failure (including if file doesn't exist).
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_delete(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file.delete: stack is empty");

    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("file.delete: expected String path, got {:?}", path_value),
    };

    match fs::remove_file(path.as_str()) {
        Ok(()) => unsafe { push(stack, Value::Bool(true)) },
        Err(_) => unsafe { push(stack, Value::Bool(false)) },
    }
}

/// Get file size in bytes
///
/// Stack effect: ( String -- Int Bool )
///
/// Takes a file path and returns (size, success).
/// Returns (size, true) on success, (0, false) on failure.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_file_size(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "file.size: stack is empty");

    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("file.size: expected String path, got {:?}", path_value),
    };

    match fs::metadata(path.as_str()) {
        Ok(metadata) => {
            let size = metadata.len() as i64;
            let stack = unsafe { push(stack, Value::Int(size)) };
            unsafe { push(stack, Value::Bool(true)) }
        }
        Err(_) => {
            let stack = unsafe { push(stack, Value::Int(0)) };
            unsafe { push(stack, Value::Bool(false)) }
        }
    }
}

// =============================================================================
// Directory Operations
// =============================================================================

/// Check if a directory exists
///
/// Stack effect: ( String -- Bool )
///
/// Takes a path and returns true if it exists and is a directory.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_dir_exists(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "dir.exists?: stack is empty");

    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("dir.exists?: expected String path, got {:?}", path_value),
    };

    let exists = Path::new(path.as_str()).is_dir();
    unsafe { push(stack, Value::Bool(exists)) }
}

/// Create a directory (and parent directories if needed)
///
/// Stack effect: ( String -- Bool )
///
/// Takes a path and creates the directory and any missing parent directories.
/// Returns true on success, false on failure.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_dir_make(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "dir.make: stack is empty");

    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("dir.make: expected String path, got {:?}", path_value),
    };

    match fs::create_dir_all(path.as_str()) {
        Ok(()) => unsafe { push(stack, Value::Bool(true)) },
        Err(_) => unsafe { push(stack, Value::Bool(false)) },
    }
}

/// Delete an empty directory
///
/// Stack effect: ( String -- Bool )
///
/// Takes a path and deletes the directory (must be empty).
/// Returns true on success, false on failure.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_dir_delete(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "dir.delete: stack is empty");

    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("dir.delete: expected String path, got {:?}", path_value),
    };

    match fs::remove_dir(path.as_str()) {
        Ok(()) => unsafe { push(stack, Value::Bool(true)) },
        Err(_) => unsafe { push(stack, Value::Bool(false)) },
    }
}

/// List directory contents
///
/// Stack effect: ( String -- List Bool )
///
/// Takes a directory path and returns (list-of-names, success).
/// Returns a list of filenames (strings) on success.
///
/// # Safety
/// - `stack` must be a valid, non-null stack pointer
/// - Top of stack must be path (String)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_dir_list(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "dir.list: stack is empty");

    let (stack, path_value) = unsafe { pop(stack) };
    let path = match path_value {
        Value::String(s) => s,
        _ => panic!("dir.list: expected String path, got {:?}", path_value),
    };

    match fs::read_dir(path.as_str()) {
        Ok(entries) => {
            let mut names: Vec<Value> = Vec::new();
            for entry in entries.flatten() {
                if let Some(name) = entry.file_name().to_str() {
                    names.push(Value::String(name.to_string().into()));
                }
            }
            let list = Value::Variant(Arc::new(VariantData::new(
                crate::seqstring::global_string("List".to_string()),
                names,
            )));
            let stack = unsafe { push(stack, list) };
            unsafe { push(stack, Value::Bool(true)) }
        }
        Err(_) => {
            let empty_list = Value::Variant(Arc::new(VariantData::new(
                crate::seqstring::global_string("List".to_string()),
                vec![],
            )));
            let stack = unsafe { push(stack, empty_list) };
            unsafe { push(stack, Value::Bool(false)) }
        }
    }
}

// Public re-exports
pub use patch_seq_dir_delete as dir_delete;
pub use patch_seq_dir_exists as dir_exists;
pub use patch_seq_dir_list as dir_list;
pub use patch_seq_dir_make as dir_make;
pub use patch_seq_file_append as file_append;
pub use patch_seq_file_delete as file_delete;
pub use patch_seq_file_exists as file_exists;
pub use patch_seq_file_for_each_line_plus as file_for_each_line_plus;
pub use patch_seq_file_size as file_size;
pub use patch_seq_file_slurp as file_slurp;
pub use patch_seq_file_spit as file_spit;

#[cfg(test)]
mod tests;