-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio.affine
More file actions
275 lines (240 loc) · 7.65 KB
/
Copy pathio.affine
File metadata and controls
275 lines (240 loc) · 7.65 KB
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
// SPDX-License-Identifier: PMPL-1.0-or-later
// SPDX-FileCopyrightText: 2025 hyperpolymath
//
// AffineScript Standard Library - Input/Output
//
// Builtin functions (implemented in interpreter runtime):
// print(args...) -> () (print to stdout)
// println(args...) -> () (print with newline to stdout)
// eprint(args...) -> () (print to stderr)
// eprintln(args...) -> () (print with newline to stderr)
// read_file(path) -> Result<String, String>
// write_file(path, data) -> Result<(), String>
// append_file(path, data) -> Result<(), String>
// file_exists(path) -> Bool
// is_directory(path) -> Bool
// getenv(name) -> Option<String>
// getcwd() -> Result<String, String>
// read_line() -> Result<String, String>
// exit(code) -> Never
// show(value) -> String
// time_now() -> Float (CPU time in seconds)
// Cross-module imports (ADR-011: explicit `use module::{...}`)
use string::{ split };
// ============================================================================
// Console Output
// ============================================================================
// print, println, eprint, eprintln are builtins — see module header
/// Print formatted string (simple placeholder substitution)
///
/// Format placeholders:
/// {} — insert next argument via show()
///
/// Example:
/// printf("Hello, {}! You are {} years old.", ["Alice", 30])
fn printf(format: String, args: [Any]) -> () {
let flen = len(format);
let arg_idx = 0;
let i = 0;
while i < flen {
if i + 1 < flen && string_sub(format, i, 2) == "{}" {
if arg_idx < len(args) {
print(show(args[arg_idx]));
arg_idx = arg_idx + 1;
} else {
print("{}");
}
i = i + 2;
} else {
print(string_sub(format, i, 1));
i = i + 1;
}
}
}
/// Print formatted string with trailing newline
fn println_fmt(format: String, args: [Any]) -> () {
printf(format, args);
println("");
}
/// Print debug representation of any value
fn debug<T>(value: T) -> () {
eprintln("DEBUG: " ++ show(value));
}
/// Print error with newline to stderr (convenience wrapper)
fn error(msg: String) -> () {
eprintln("[ERROR] " ++ msg);
}
/// Print warning with newline to stderr
fn warn(msg: String) -> () {
eprintln("[WARN] " ++ msg);
}
// ============================================================================
// File Operations (builtins)
// ============================================================================
// read_file, write_file, append_file, file_exists are builtins — see module header
/// Read file as a list of lines
fn read_lines(path: String) -> Result<[String], String> {
match read_file(path) {
Ok(content) => Ok(split(content, "\n")),
Err(msg) => Err(msg)
}
}
/// Get file size by reading and measuring content length
///
/// Note: this reads the entire file; a more efficient builtin would be
/// preferable for large files once the runtime supports stat().
fn file_size(path: String) -> Result<Int, String> {
match read_file(path) {
Ok(content) => Ok(len(content)),
Err(msg) => Err(msg)
}
}
// ============================================================================
// Directory Operations
// ============================================================================
// is_directory is a builtin — see module header
/// List directory contents (builtin — returns sorted entries, excluding . and ..)
extern fn list_dir(path: String) -> Result<[String], String>;
/// Create directory with permissions 0o755
extern fn create_dir(path: String) -> Result<(), String>;
/// Remove an empty directory
extern fn remove_dir(path: String) -> Result<(), String>;
// ============================================================================
// Path Operations
// ============================================================================
/// Join path components with the system separator (/)
fn path_join(components: [String]) -> String {
let result = "";
let mut first = true;
for component in components {
if first {
result = component;
first = false;
} else {
result = result ++ "/" ++ component;
}
}
result
}
/// Extract the file extension from a path (without the leading dot)
///
/// Returns None if no extension is found.
/// Example: path_extension("file.txt") => Some("txt")
fn path_extension(path: String) -> Option<String> {
let plen = len(path);
let i = plen - 1;
while i >= 0 {
let ch = string_get(path, i);
if ch == '.' {
if i == plen - 1 {
// Trailing dot, no extension
return None;
}
return Some(string_sub(path, i + 1, plen - i - 1));
}
if ch == '/' {
// Hit a directory separator before finding a dot
return None;
}
i = i - 1;
}
None
}
/// Get the filename component from a path
///
/// Example: path_filename("/home/user/file.txt") => "file.txt"
fn path_filename(path: String) -> String {
let plen = len(path);
if plen == 0 {
return "";
}
let i = plen - 1;
while i >= 0 {
if string_get(path, i) == '/' {
return string_sub(path, i + 1, plen - i - 1);
}
i = i - 1;
}
// No separator found; entire path is the filename
path
}
/// Get the directory component from a path
///
/// Example: path_dirname("/home/user/file.txt") => "/home/user"
fn path_dirname(path: String) -> String {
let plen = len(path);
if plen == 0 {
return ".";
}
let i = plen - 1;
while i >= 0 {
if string_get(path, i) == '/' {
if i == 0 {
return "/";
}
return string_sub(path, 0, i);
}
i = i - 1;
}
// No separator found; directory is the current directory
"."
}
/// Get the filename without its extension (stem)
///
/// Example: path_stem("archive.tar.gz") => "archive.tar"
fn path_stem(path: String) -> String {
let filename = path_filename(path);
let flen = len(filename);
let i = flen - 1;
while i > 0 {
if string_get(filename, i) == '.' {
return string_sub(filename, 0, i);
}
i = i - 1;
}
filename
}
// ============================================================================
// Process Operations
// ============================================================================
// getenv, getcwd, exit are builtins — see module header
/// Set environment variable
extern fn setenv(name: String, value: String) -> Result<(), String>;
/// Change current working directory
extern fn chdir(path: String) -> Result<(), String>;
// ============================================================================
// Input Operations
// ============================================================================
// read_line is a builtin — see module header
/// Read all input from stdin until EOF
fn read_stdin() -> Result<String, String> {
let parts = [];
let done = false;
while !done {
match read_line() {
Ok(line) => {
parts = parts ++ [line];
},
Err(_) => {
done = true;
}
}
}
Ok(join(parts, "\n"))
}
/// Prompt user for input and return their response
fn prompt(message: String) -> Result<String, String> {
print(message);
read_line()
}
// ============================================================================
// Timing
// ============================================================================
// time_now is a builtin — see module header
/// Measure the wall-clock time of a function call (in seconds)
fn timed<T>(f: () -> T) -> (T, Float) {
let start = time_now();
let result = f();
let elapsed = time_now() - start;
(result, elapsed)
}