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
use crate::error::*;
use crate::prelude::*;

use crate::{func_object, func_object_void};

use std::process::exit;
use std::time::SystemTime;
use std::fs;
use std::collections::HashMap;

use num::bigint::ToBigInt;

use std::io::{self, Write};

use glob::glob;
use std::result::Result;

use std::convert::TryInto;

func_object_void!(Print, (0..), _c, args -> {
    let mut first = true;
    for arg in args.iter() {
        if !first {
            print!("\t");
        } else {
            first = false;
        }
        print!("{}", arg.to_string()?);
    }
    io::stdout().flush()?;
});

func_object_void!(Printr, (0..), _c, args -> {
    let mut first = true;
    for arg in args.iter() {
        if !first {
            print!("\t");
        } else {
            first = false;
        }
        print!("{}", arg.to_string()?);
    }
    print!("\r");
    io::stdout().flush()?;
});

func_object_void!(Println, (0..), _c, args -> {
    let mut first = true;
    for arg in args.iter() {
        if !first {
            print!("\t");
        } else {
            first = false;
        }
        print!("{}", arg.to_string()?);
    }
    println!();
});

func_object_void!(Eprint, (0..), _c, args -> {
    let mut first = true;
    for arg in args.iter() {
        if !first {
            eprint!("\t");
        } else {
            first = false;
        }
        eprint!("{}", arg.to_string()?);
    }
    io::stdout().flush()?;
});

func_object_void!(Eprintr, (0..), _c, args -> {
    let mut first = true;
    for arg in args.iter() {
        if !first {
            eprint!("\t");
        } else {
            first = false;
        }
        eprint!("{}", arg.to_string()?);
    }
    eprint!("\r");
    io::stdout().flush()?;
});

func_object_void!(Eprintln, (0..), _c, args -> {
    let mut first = true;
    for arg in args.iter() {
        if !first {
            eprint!("\t");
        } else {
            first = false;
        }
        eprint!("{}", arg.to_string()?);
    }
    eprintln!();
});

func_object!(Exit, (1..=1), _c, args -> {
    let arg_any = args[0].as_any();
    if let Some(int_obj) = arg_any.downcast_ref::<ObjectCell<IntObject>>() {
        let int_obj = int_obj.try_borrow()?;
        exit(int_obj.to_i64()? as i32)
    } else {
        exit(if args[0].truthy() { 1 } else { 0 })
    }
});

func_object!(Type, (1..=1), _c, args -> {
    Ok(StringObject::new(args[0].technetium_type_name()))
});

func_object!(Hash, (1..=1), _c, args -> {
    let hash = args[0].technetium_hash().ok_or_else(|| RuntimeError::type_error(format!("Unhashable type: {}", args[0].technetium_type_name())))?;
    let hash = hash.to_bigint().unwrap();
    Ok(IntObject::new_big(hash))
});

func_object_void!(Lock, (1..=1), _c, args -> {
    args[0].lock_immutable()
});

func_object!(Clone_, (1..=1), context, args -> {
    Ok(args[0].technetium_clone(context)?)
});

func_object!(Assert, (1..=2), _c, args -> {
    if !args[0].truthy() {
        let message = if let Some(val) = args.get(1) {
            Some(val.to_string()?)
        } else {
            None
        };
        Err(RuntimeError::assertion_error(message))
    } else {
        Ok(UnitObject::new())
    }
});

func_object!(Version, (0..=0), _c, args -> {
    let (major, minor, patch) = (env!("CARGO_PKG_VERSION_MAJOR"), env!("CARGO_PKG_VERSION_MINOR"), env!("CARGO_PKG_VERSION_PATCH"));
    
    Ok(ObjectRef::new(Tuple {
        contents: vec![
            IntObject::new(major.parse::<i64>().unwrap()),
            IntObject::new(minor.parse::<i64>().unwrap()),
            IntObject::new(patch.parse::<i64>().unwrap()),
        ]
    }))
});

#[derive(Debug, Clone)]
pub struct Range {
    pub start: i64,
    pub end: i64,
    pub step: i64,
}

impl Object for ObjectCell<Range> {
    fn technetium_clone(&self, _context: &mut RuntimeContext<'_>) -> RuntimeResult<ObjectRef> {
        let this = self.try_borrow()?;
        Ok(ObjectRef::new(this.clone()))
    }

    fn technetium_type_name(&self) -> String {
        "range".to_string()
    }

    fn make_iter(&self, _context: &mut RuntimeContext<'_>) -> RuntimeResult<ObjectRef> {
        let this = self.try_borrow()?;
        Ok(RangeIterator::new(this.clone()))
    }

    fn call_method(&self, method: &str, args: &[ObjectRef], _context: &mut RuntimeContext<'_>) -> RuntimeResult<ObjectRef> {
        let this = self.try_borrow()?;
        match method {
            "length" => {
                if args.len() > 0 {
                    return Err(RuntimeError::type_error("Expected no arguments to range.len()"));
                }
                Ok(IntObject::new(
                    std::cmp::max(0,
                            (this.end - this.start) / this.step
                    )
                ))
            }
            _ => {
                Err(RuntimeError::attribute_error(format!(
                    "Cannot call method {} of {}",
                    method,
                    self.technetium_type_name()
                )))
            }
        }
    }
}

pub struct RangeIterator {
    inner: Range,
    curr: i64,
}

impl RangeIterator {
    pub fn new(inner: Range) -> ObjectRef {
        ObjectRef::new(RangeIterator {
            curr: inner.start,
            inner,
        })
    }
}

impl Object for ObjectCell<RangeIterator> {
    fn technetium_type_name(&self) -> String {
        "iterator(range)".to_string()
    }

    fn take_iter(&self, _context: &mut RuntimeContext<'_>) -> RuntimeResult<Option<ObjectRef>> {
        let mut this = self.try_borrow_mut()?;
        let step = this.inner.step;
        let end = this.inner.end;
        let _curr = &mut this.curr;
        if (step < 0 && *_curr <= end) || (step > 0 && *_curr >= end) {
            return Ok(None);
        }
        let old = *_curr;
        *_curr += step;
        Ok(Some(IntObject::new(old)))
    }
}

func_object!(RangeFunc, (1..=3), _c, args -> {
    if args.len() == 1 {
        downcast!((int_obj: IntObject = args[0]) -> {
            Ok(ObjectRef::new(Range {
                start: 0,
                end: int_obj.to_i64()?,
                step: 1,
            }))
        } else {
            Err(RuntimeError::type_error("Expected integer arguments to range"))
        })
    } else if args.len() == 2 {
        if let Some(int_obj_a) = args[0].as_any().downcast_ref::<ObjectCell<IntObject>>() {
            if let Some(int_obj_b) = args[1].as_any().downcast_ref::<ObjectCell<IntObject>>() {
                let int_obj_a = int_obj_a.try_borrow()?;
                let int_obj_b = int_obj_b.try_borrow()?;
                Ok(ObjectRef::new(Range {
                    start: int_obj_a.to_i64()?,
                    end: int_obj_b.to_i64()?,
                    step: 1,
                }))
            } else {
                Err(RuntimeError::type_error("Expected integer arguments to range"))
            }
        } else {
            Err(RuntimeError::type_error("Expected integer arguments to range"))
        }
    } else {
        if let Some(int_obj_a) = args[0].as_any().downcast_ref::<ObjectCell<IntObject>>() {
            if let Some(int_obj_b) = args[1].as_any().downcast_ref::<ObjectCell<IntObject>>() {
                if let Some(int_obj_c) = args[2].as_any().downcast_ref::<ObjectCell<IntObject>>() {
                    let int_obj_a = int_obj_a.try_borrow()?;
                    let int_obj_b = int_obj_b.try_borrow()?;
                    let int_obj_c = int_obj_c.try_borrow()?;
                    Ok(ObjectRef::new(Range {
                        start: int_obj_a.to_i64()?,
                        end: int_obj_b.to_i64()?,
                        step: int_obj_c.to_i64()?,
                    }))
                } else {
                    Err(RuntimeError::type_error("Expected integer arguments to range"))
                }
            } else {
                Err(RuntimeError::type_error("Expected integer arguments to range"))
            }
        } else {
            Err(RuntimeError::type_error("Expected integer arguments to range"))
        }
    }
});

func_object_void!(Sleep, (1..=1), _c, args -> {
    let duration: std::time::Duration = {
        downcast!((val: IntObject = args[0]) -> {
            std::time::Duration::from_secs(val
                .to_i64()?
                .try_into()
                .map_err(|_| RuntimeError::type_error("Argument to sleep must be non-negative"))?)
        } else {
            downcast!((val: FloatObject = args[0]) -> {
                std::time::Duration::from_secs_f64(val.val)
            } else {
                return Err(RuntimeError::type_error("Expected numeric type argument to sleep"));
            })
        })
    };
    std::thread::sleep(duration);
});

// Staleness is a special feature that replicates the features of most build systems like make,
// where you can check if a file has been modified since the last time the build script was run.
// This feature needs to make use of a cache that can keep track of last modified times. For now,
// this information will be stored in a serialized HashMap with canonical paths in
// [script_parent_directory]/.tcmake/stale.cache
func_object!(Stale, (1..), _c, args -> {
    let mut cache_location = crate::get_tcmake_dir().unwrap();
    cache_location.push("stale.cache");
    let previous_timestamps: Option<HashMap<PathBuf, SystemTime>> = {
        if !cache_location.exists() {
            None
        } else {
            let cache = fs::read(&cache_location);
            if let Ok(file) = cache {
                bincode::deserialize(&file).ok()
            } else {
                warn!("Error reading cache location to find previous time stamps for stale(): {:?}", cache.err().unwrap());
                None
            }
        }
    };
    let old_timestamps = previous_timestamps.unwrap_or_else(|| HashMap::new());
    // Files to check passed by the user. Might be expanded from globs, might include directories,
    // and could be passed in either from all arguments, or might be passed in as a list
    // Should all be canonicalized!
    let file_checks_raw: Vec<String> = {
        if args.len() == 1 {
            if let Some(list_obj) = args[0].as_any().downcast_ref::<ObjectCell<List>>() {
                let mut res = vec![];
                let list_obj = list_obj.try_borrow()?;
                let list = &list_obj.contents;
                for inner_obj in list.iter() {
                    if let Some(string_obj) = inner_obj.as_any().downcast_ref::<ObjectCell<StringObject>>() {
                        let string_obj = string_obj.try_borrow()?;
                        let string = &string_obj.val;
                        res.push(string.clone());
                    } else {
                        return Err(RuntimeError::type_error("Got a list containing a {:?} as an argument to stale(). Most likely expected a list of strings."));
                    }
                }
                res
            } else if let Some(string_obj) = args[0].as_any().downcast_ref::<ObjectCell<StringObject>>() {
                let string_obj = string_obj.try_borrow()?;
                let string = &string_obj.val;
                vec![string.clone()]
            } else {
                return Err(RuntimeError::type_error("Expected either a string or a list to be passed to stale()."));
            }
        } else {
            let mut res = vec![];
            for arg in args.iter() {
                if let Some(string_obj) = arg.as_any().downcast_ref::<ObjectCell<StringObject>>() {
                    let string_obj = string_obj.try_borrow()?;
                    let string = &string_obj.val;
                    res.push(string.clone())
                } else {
                    return Err(RuntimeError::type_error("Expected either a string or a list to be passed to stale()."));
                }
            }
            res
        }
    };
    let mut file_checks: Vec<PathBuf> = vec![];
    // Push the current script path, if it exists
    // This is older behavior, which I think isn't necessary.
    // match crate::CURR_SCRIPT_PATH.get() {
    //     Some(path) => {
    //         file_checks.push(path.clone());
    //     },
    //     None => { }
    // }

    for file in file_checks_raw.iter() {
        let mut ct = 0;
        for string in glob(file)
            .map_err(|e| RuntimeError::type_error(format!("Invalid or unknown file or pattern in call to stale(): {:?}", e).to_string()))?
            .filter_map(Result::ok) {
            let p = PathBuf::from(string).canonicalize();
            if p.is_err() {
                warn!("Error canonicalizing path ({:?}) in stale(). Will return true anyway.", p);
                return Ok(BoolObject::new(true));
            }
            file_checks.push(p.unwrap());
            ct += 1;
        }
        if ct == 0 {
            let mut e = RuntimeError::type_error(format!("File or pattern does not exist that was passed to stale(): {:?}", file).to_string());
            e.err = RuntimeErrorType::IOError;
            return Err(e);
        }
    }

    let mut new_timestamps = old_timestamps.clone();
    let mut changed_timestamps = vec![];

    for file in file_checks.iter() {
        let res = fs::metadata(file)?;
        let modified = res.modified()?;
        if old_timestamps.contains_key(file) {
            let old_modified = old_timestamps.get(file).unwrap();
            if old_modified < &modified {
                new_timestamps.insert(file.clone(), modified);
                let fix_encoding = file.to_str().map(ToOwned::to_owned);
                if let Some(name) = fix_encoding {
                    changed_timestamps.push(StringObject::new(name));
                } else {
                    return Err(RuntimeError {
                        err: RuntimeErrorType::IOError,
                        help: "Error converting path name into valid Unicode. This might have happened if a file checked in stale() has invalid unicode in its name".to_string(),
                        symbols: vec![],
                    })
                }
            }
        } else {
            new_timestamps.insert(file.clone(), modified);
            let fix_encoding = file.to_str().map(ToOwned::to_owned);
            if let Some(name) = fix_encoding {
                changed_timestamps.push(StringObject::new(name));
            } else {
                return Err(RuntimeError {
                    err: RuntimeErrorType::IOError,
                    help: "Error converting path name into valid Unicode. This might have happened if a file checked in stale() has invalid unicode in its name".to_string(),
                    symbols: vec![],
                })
            }
        }
    }

    // Write out the cache again
    if changed_timestamps.len() > 0 {
        // It kind of makes sense to ignore failure to write out to the cache. This just means
        // stale will always return true if there's some weird error.
        let e = fs::write(cache_location, &bincode::serialize(&new_timestamps).unwrap());
        if e.is_err() {
            warn!("Error writing to cache location: {:?}. Won't update cache, but will return true anyway.", e);
        }
    }
    Ok(ObjectRef::new(List {
        contents: changed_timestamps
    }))
});