-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMeTTa
executable file
·544 lines (446 loc) · 17.8 KB
/
MeTTa
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
#!/bin/bash
export RPWD=$PWD
IS_SOURCED=$( [[ "${BASH_SOURCE[0]}" != "${0}" ]] && echo 1 || echo 0)
# Function to exit the script properly
if [ "$IS_SOURCED" -eq "0" ]; then SCRIPT=$(readlink -f "$0"); else SCRIPT=$(readlink -f "${BASH_SOURCE[0]}"); fi
export MeTTa=$(basename "$SCRIPT")
export METTALOG_DIR=$(dirname "$SCRIPT")
#echo "METTALOG_DIR=$METTALOG_DIR"
cd "$METTALOG_DIR" || { echo "Failed to navigate to $METTALOG_DIR"; [[ "$IS_SOURCED" == "1" ]] && return 1 || exit 1; }
should_compile=0
never_compile=0
CMD_TIMEOUT=0
repl_flag=enable
use_rc_file=~/.mettalogrc
# Initialize the variable to indicate whether to use the test script
use_test_script=0
# Iterate over all command-line arguments
for arg in "$@"; do
# Check if the argument is a directory
if [ -d "$arg" ]; then
use_test_script=1
else
# Check for specific flags
case "$arg" in
--fres*|--fail*|--contin*|--clean)
use_test_script=1
;;
esac
fi
done
# Execute the test script if the condition is met
if [[ "$use_test_script" -eq 1 ]]; then
exec ./scripts/test_in_metta.sh -y --report=n "$@"
fi
#export TEE_FILE=${TEE_FILE:-"$METTALOG_DIR/TEE.ansi"}
set -e
function load_rc_file {
local file="$1" # Use the argument as the file
local METTALOG_OPTIONS_LOCAL=()
local multiline_accumulator=""
local verbose="${VERBOSE:-0}" # Use the VERBOSE environment variable or default to '0' (not verbose)
if [[ -f "$file" ]]; then
while IFS= read -r line || [[ -n "$line" ]]; do
# Trim leading and trailing whitespace
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue # Skip empty lines
# Check for line continuation (trailing '\')
if [[ "$line" =~ \\$ ]]; then
multiline_accumulator+="${line%\\} "
continue
else
line="$multiline_accumulator$line"
multiline_accumulator=""
fi
[[ $line =~ ^# ]] && continue # Skip lines that start with a comment
METTALOG_OPTIONS_LOCAL+=("$line")
# Verbose logging
[[ "$verbose" == "1" ]] && echo "Loaded option: $line"
done < "$file"
fi
local do_args="${METTALOG_OPTIONS_LOCAL[@]}"
[[ -z "$do_args" ]] && return
echo "handle_args ${do_args}"
handle_args "${do_args}"
}
add_to_list() {
local item="$1"
local -n list_ref="$2"
if [[ ! " ${list_ref[*]} " =~ " $item " ]]; then
list_ref+=("$item")
fi
}
function print_help {
echo " Usage: ${MeTTa} [options] <metta-files|directories> ... [-- arg ...passed to your program...]"
echo " $0 --help Display this message"
echo " $0 --version Display version information"
cat << EOF
-x state Start from state (must be first)
-g goal Run goal (may be repeated)
-t toplevel Toplevel goal
-f file User initialisation file
-F file Site initialisation file
-l file Script source file
-s file Script source file
-p alias=path Define file search path 'alias'
Compilation:
${MeTTa} [options] [-o executable] -c metta-file1 -c metta-file2 ... to compile into executable ...
-O Optimised compilation
--debug[=bool] Do (not) generate debug info
--traditional Disable extensions of version (SWI-Prolog version 7)
--abi-version Display ABI version key (and exit)
--arch Display architecture (and exit)
--dump-runtime-variables[=format]
Dump link info in sh(1) format (and exit)
Running:
--rc File read command line arguments from a file
--repl Start the REPL (Read-Eval-Print Loop) after processing metta files.
If no metta files are provided, this is the default behavior.
--home[=DIR] Print home or use DIR as SWI-Prolog home
--stack-limit=size[BKMG] Specify maximum size of stacks
--table-space=size[BKMG] Specify maximum size of SLG tables
--shared-table-space=size[BKMG] Maximum size of *shared* SLG tables
--pce[=bool] Make the xpce gui available
--packs[=bool] Do (not) attach add-ons
--pldoc[=port] Start PlDoc server [at port]
--python[=bool] Enable or disable Python support (default: $python_flag)
--tty[=bool] (Dis)allow tty control
--quiet[=bool] (-q) Do (not) suppress informational messages
Testing:
--test Use the test options:
--continue Continue running tests (Generating any missing html files)
--failures Rerun unsuccessfull tests only
--regressions Rerun only tests in which we previously scored 100%
--timeout=seconds Kill the script after so many seconds.
--html[=bool] Save an HTML file containing terminal output in the same
directory as the input file or directory.
Defaults to true if exactly one metta file or directory argument was provided
--fresh Clean up by deleting any .answers files under directory
--clean Clean up by deleting all .html files under directory
Debugging:
--exec=skip Skip over !exec dirrectives
--eval=debug Recursively trace Evaluation
--case=debug Show extra debug info about case statements
--signals[=bool] Do (not) modify signal handling
--threads[=bool] Do (not) allow for threads
--debug-on-interrupt[=bool] Trap the debugger on interrupt
--prolog Drop to the host system debugger
--on-error=style One of print, halt or status
--on-warning=style One of print, halt or status
Boolean options may be written as --name=bool, --name, --no-name or --noname.
Both '-' or '_' are accepted as word-separator for long options.
Configuration File:
This script reads options from the ~/.mettalogrc file, one option per line.
Options specified in ~/.mettalogrc are processed before command-line arguments.
WAS: $0 ${SWI_OPTIONS[*]} -l $METTALOG_DIR/metta_vspace/$PYSWIP_VERSION/metta_interp.pl -- --python=$python_flag ${PRE_METTALOG_OPTIONS[*]} ${METTALOG_OPTIONS[*]} \\
$METTA_CMD
EOF
}
# Initialize variables
SWI_OPTIONS=()
METTALOG_OPTIONS=()
PRE_METTALOG_OPTIONS=()
SWI_FLAG_WITH_ARG=false
python_flag=enable
LIST_OF_FILE_ARGS=()
PYSWIP_VERSION="pyswip"
wants_print_help=0
remove_quotes() {
local value="$1"
echo "${value//\"/}"
}
DefaultSav="Sav.$(hostname).MeTTaLog"
function handle_args {
SWI_FLAG_WITH_ARG=false
METTA_FLAG_WITH_ARG=false
SKIP_TO_METTALOG_OPTIONS=false
NEXT_ARG_IS_RC_FILE=false
PrevDir="${RPWD:-$(pwd)}" # Default to current directory if PrevDir is not set
for arg in "$@"; do
# Check if the previous argument was --rc
if [[ "$NEXT_ARG_IS_RC_FILE" == true ]]; then
rc_file_path="$PrevDir/$arg" # Resolve file path relative to PrevDir
rc_file_path="$(realpath "$rc_file_path")" # Resolve to absolute path
load_rc_file "$rc_file_path"
NEXT_ARG_IS_RC_FILE=false
continue
fi
if [[ $SKIP_TO_METTALOG_OPTIONS == true ]]; then
METTALOG_OPTIONS+=("$arg")
continue
fi
if [[ "$arg" == "--" ]]; then
METTALOG_OPTIONS+=("$arg")
SKIP_TO_METTALOG_OPTIONS=true
continue
fi
# Add support for --rc followed by a file
if [[ "$arg" == "--rc" ]]; then
NEXT_ARG_IS_RC_FILE=true
continue
fi
arg=$(remove_quotes "$arg") # Remove the quotes
# track file paths but keep going
if [[ -f "$arg" || -d "$arg" ]]; then
arg_realpath="$(realpath "$arg")"
if [[ -f "$arg_realpath" || -d "$arg_realpath" ]]; then
add_to_list "$arg_realpath" LIST_OF_FILE_ARGS
fi
fi
if [[ "$arg" =~ ^--timeout=([0-9]+)$ ]]; then
export TIMEOUT="${BASH_REMATCH[1]}"
#echo "$0 TIMEOUT=$TIMEOUT"
CMD_TIMEOUT=$TIMEOUT
METTALOG_OPTIONS=("--timeout=$TIMEOUT" "${METTALOG_OPTIONS[@]}")
continue
elif [[ "$arg" =~ ^--python=(enable|false)$ ]]; then
python_flag="${BASH_REMATCH[1]}"
elif [[ "$arg" == "--python" ]]; then
python_flag=enable
elif [[ "$arg" == "--no-python" ]]; then
python_flag=false
elif [[ "$arg" == "--repl" ]]; then
repl_flag=true
elif [[ "$arg" == "--no-repl" ]]; then
repl_flag=false
elif [[ "$arg" == "--html" ]]; then
html_flag=enable
elif [[ "$arg" == "--no-html" ]]; then
html_flag=false
elif [[ "$arg" == "--prolog" ]]; then
add_to_list "$arg" METTALOG_OPTIONS
repl_flag=false
fi
[[ "$arg" == "--help" || "$arg" == "-h" ]] && { wants_print_help=1; EXIT_SCRIPT=0; }
[[ "$arg" =~ ^--dump-runtime-variables.*$ || "$arg" == "--abi-version" || "$arg" == "--version" || "$arg" == "--arch" ]] && { swipl $@; EXIT_SCRIPT=0; }
[[ "$SWI_FLAG_WITH_ARG" == true ]] && { SWI_OPTIONS+=("$arg"); SWI_FLAG_WITH_ARG=false; continue; }
[[ "$METTA_FLAG_WITH_ARG" == true ]] && { METTALOG_OPTIONS+=("\"$arg\""); METTA_FLAG_WITH_ARG=false; continue; }
# These options require an argument (like a filename)
case $arg in
--v*)
PYSWIP_VERSION="pyswip${arg#*v}"
rm -f "${DefaultSav}"
never_compile=1
continue
;;
-x|-g|-t|-f|-F|-l|-s|-p|--on-error|--on-warning|--home|--stack-limit|--table-space|--shared-table-space|--pldoc)
SWI_OPTIONS+=("$arg")
SWI_FLAG_WITH_ARG=true
continue
;;
-G|-L|-F)
METTALOG_OPTIONS+=("$arg")
METTA_FLAG_WITH_ARG=true
continue
;;
# These options don't require an argument
-O|--traditional|--tty*|--packs*|--signals*|--threads*|--debug*|--debug-on-interrupt*|--quiet*|--pce*)
SWI_OPTIONS+=("$arg")
continue
;;
---*)
DASH2="-${arg#*---}"
METTALOG_OPTIONS=("$DASH2" "${METTALOG_OPTIONS[@]}")
continue
;;
*)
if [[ -f "$arg" || -d "$arg" ]]; then
arg_realpath="$(realpath "$arg")"
if [[ -f "$arg_realpath" || -d "$arg_realpath" ]]; then
add_to_list "$arg_realpath" LIST_OF_FILE_ARGS
fi
add_to_list "$arg" METTALOG_OPTIONS
else
add_to_list "$arg" METTALOG_OPTIONS
fi
;;
esac
done
}
# First process arguments from ~/.mettalogrc
# Then process actual command-line arguments
#handle_args "$@"
for arg in "$@"; do
arg=$(remove_quotes "$arg") # Remove the quotes
if [[ -f "$arg" || -d "$arg" ]]; then
arg_realpath="$(realpath "$arg")"
if [[ -f "$arg_realpath" || -d "$arg_realpath" ]]; then
add_to_list "$arg_realpath" LIST_OF_FILE_ARGS
fi
elif [[ "$arg" =~ ^--rc=(.*) ]]; then
use_rc_file=""
continue
fi
done
# Then process actual command-line arguments
#echo "LIST_OF_FILE_ARGS[0]=${LIST_OF_FILE_ARGS[0]}"
DIRNAME="${LIST_OF_FILE_ARGS[0]}"
if [[ -f "$DIRNAME" ]]; then
HTML_OUT="$DIRNAME".html
DIRNAME=$(dirname "${DIRNAME}")
elif [[ -d "$DIRNAME" ]]; then
HTML_OUT="${DIRNAME}/Result.html"
else
DIRNAME="${PWD}"
HTML_OUT="${DIRNAME}/Result.html"
fi
DIR_RC="$DIRNAME/.mettalogrc"
#echo "DIR_RC=$DIR_RC"
if [[ -z "${use_rc_file}" ]]; then
:
elif [[ -f "$DIR_RC" ]]; then
use_rc_file="${DIR_RC}"
else
echo "; No RC file (.mettalogrc) for directory: $DIRNAME"
fi
handle_args "$@"
load_rc_file $use_rc_file
echo "Debug: SWI_OPTIONS: ${SWI_OPTIONS[@]}"
echo "Debug: PRE_METTALOG_OPTIONS: ${PRE_METTALOG_OPTIONS[@]}"
echo "Debug: LIST_OF_FILE_ARGS: ${LIST_OF_FILE_ARGS[@]}"
echo "Debug: METTALOG_OPTIONS: ${METTALOG_OPTIONS[@]}"
# Decide on enabling the REPL
if [[ "$repl_flag" == "enable" ]]; then
[[ ${#LIST_OF_FILE_ARGS[@]} -eq 0 ]] && repl_flag=true || true
#handle_args --repl
fi
if [[ "$repl_flag" == "true" ]]; then
CMD_TIMEOUT=0
fi
# Store the initial PYTHONPATH for later comparison
initial_pythonpath="$PYTHONPATH"
# Add DIRNAME to PYTHONPATH if it's a valid path and not already present
if [[ -d "$DIRNAME" && ":$PYTHONPATH:" != *":$DIRNAME:"* ]]; then
export PYTHONPATH="${PYTHONPATH:+${PYTHONPATH}:}$DIRNAME"
fi
# Add metta_vspace to PYTHONPATH if not already present
[[ ":$PYTHONPATH:" != *":$METTALOG_DIR/metta_vspace:"* ]] && export PYTHONPATH="${PYTHONPATH:+${PYTHONPATH}:}$METTALOG_DIR/metta_vspace"
# If PYTHONPATH has changed, echo the new value
if [[ "$PYTHONPATH" != "$initial_pythonpath" ]]; then
: #echo ";; Updated PYTHONPATH: $PYTHONPATH"
fi
export RUST_BACKTRACE=full
# Directory containing the .pl files
pl_directory="metta_vspace/$PYSWIP_VERSION"
# Initialize a flag to check if any file is newer or if reference file is missing
if [[ $never_compile -eq 0 ]]; then
# Reference file
reference_file=$(find . -maxdepth 1 -type f -name "${DefaultSav}*" -not -name "*.*" -printf "%T@ %p\n" | sort -k1,1nr | head -n 1 | cut -f2- -d" ")
if [[ -z "$reference_file" ]]; then
reference_file="$METTALOG_DIR/${DefaultSav}"
fi
# Check if ${DefaultSav} exists
if [[ ! -e "$reference_file" ]]; then
echo "Reference file $reference_file does not exist. Compiler will be called."
should_compile=1
else
# Iterate over each .pl file to check if it's newer
for pl_file in "$pl_directory"/*_*.pl; do
if [[ ! -e "$pl_file" ]]; then
echo "No matching .pl files found in $pl_directory."
#exit 1
fi
# Check if this .pl file is newer than the reference file
if [[ "$pl_file" -nt "$reference_file" ]]; then
echo "$pl_file is newer than $reference_file."
should_compile=1
break # No need to check further, exit loop
fi
done
fi
fi
# If any newer file found or reference file missing, call the compiler
if [[ $should_compile -eq 1 ]]; then
#if [[ -f "$reference_file" ]]; then
# echo "Calling compiler from $reference_file..."
# swipl -x $reference_file -g qsave_program -g halt
#else
rm -f $reference_file
if [[ "$never_compile" -eq 0 ]]; then
echo "Compiling $reference_file"
swipl -l metta_vspace/$PYSWIP_VERSION/metta_interp.pl -g qcompile_mettalog -- --exeout=$reference_file
fi
fi
reference_file=$(find . -maxdepth 1 -type f -name "${DefaultSav}*" -not -name "*.*" -printf "%T@ %p\n" | sort -k1,1nr | head -n 1 | cut -f2- -d" ")
if [[ -z "$reference_file" ]]; then
reference_file="$METTALOG_DIR/${DefaultSav}"
fi
if [[ -f "$reference_file" ]]; then
MLOG="$reference_file --"
if [[ "${#SWI_OPTIONS[@]}" -gt 0 ]]; then
MLOG="swipl -x $reference_file ${SWI_OPTIONS[*]} --"
fi
if [[ "$never_compile" -eq 1 ]]; then
MLOG="swipl ${SWI_OPTIONS[*]} -l $METTALOG_DIR/metta_vspace/$PYSWIP_VERSION/metta_interp.pl --"
fi
else
MLOG="swipl ${SWI_OPTIONS[*]} -l $METTALOG_DIR/metta_vspace/$PYSWIP_VERSION/metta_interp.pl --"
fi
METTA_CMD="$MLOG --python=$python_flag ${PRE_METTALOG_OPTIONS[*]} ${METTALOG_OPTIONS[*]}"
OS=$(uname)
TIMEOUT_CMD="timeout"
if [[ "$OS" == "Darwin" ]]; then
# macOS
if command -v gtimeout >/dev/null 2>&1; then
TIMEOUT_CMD="gtimeout"
else
echo "Please install coreutils using Homebrew to get the gtimeout command."
[[ "$IS_SOURCED" == "1" ]] && return 1 || exit 1
fi
fi
# Initialize the variable to store the exit status of METTA_CMD
METTA_CMD_EXIT_STATUS=666
TEMP_EXIT_CODE_FILE="$(mktemp)"
# Set a trap to ensure stty sane is run on script exit or interruption
cleanup() {
stty sane
if [[ -f "$TEMP_EXIT_CODE_FILE" ]]; then
METTA_CMD_EXIT_STATUS=$(<"$TEMP_EXIT_CODE_FILE")
rm -f "$TEMP_EXIT_CODE_FILE"
else
METTA_CMD_EXIT_STATUS=${METTA_CMD_EXIT_STATUS:-$?}
fi
echo "Exit code of METTA_CMD: $METTA_CMD_EXIT_STATUS"
[[ $IS_SOURCED -eq 1 ]] && return $METTA_CMD_EXIT_STATUS || exit $METTA_CMD_EXIT_STATUS
}
#echo "CMD_TIMEOUT=$CMD_TIMEOUT"
if [[ -n "$CMD_TIMEOUT" && "$CMD_TIMEOUT" -gt 0 ]]; then
METTA_CMD="$TIMEOUT_CMD --foreground --preserve-status --signal=SIGTERM --kill-after=5s $CMD_TIMEOUT ${METTA_CMD}"
fi
cd "${RPWD}"
export CMD_TIMEOUT
set +e
# Conditional to check if html_flag is enabled
if [[ "$html_flag" == "enable" ]]; then
# Generate a random filename for TEE_FILE with date,time,PID
random_suffix=$(date +"%Y%m%d_%H%M")_$$
TEE_FILE="$METTALOG_DIR/TEE_$random_suffix.ansi"
export TEE_FILE
export TYPESCRIPT=1
if [[ "$OS" == "Darwin" ]]; then # macOS
METTA_CMD="/usr/bin/script -q -f -a \"$TEE_FILE\" \"$METTA_CMD\""
else # Assume Linux
METTA_CMD="/usr/bin/script -q -f --force -e -a \"$TEE_FILE\" -c \"$METTA_CMD\""
fi
[[ "$wants_print_help" == "1" ]] && { print_help; }
echo "; "
echo "; Afterwhich ansi2html -u < $TEE_FILE > \"$HTML_OUT\""
echo "; "
[[ -n "${EXIT_SCRIPT+x}" ]] && { [[ "$IS_SOURCED" == "1" ]] && return "$EXIT_SCRIPT" || exit "$EXIT_SCRIPT"; }
( touch "$TEE_FILE"
chmod 777 "$TEE_FILE"
cat /dev/null > "$TEE_FILE"
eval "$METTA_CMD"
echo $? > "$TEMP_EXIT_CODE_FILE"
ansi2html -u < "$TEE_FILE" >"$HTML_OUT" ) || true
rm -f "$TEE_FILE"
cleanup
else
[[ "$wants_print_help" == "1" ]] && { print_help; [[ "$IS_SOURCED" == "1" ]] && return "$EXIT_SCRIPT" || exit "$EXIT_SCRIPT"; }
[[ -n "${EXIT_SCRIPT+x}" ]] && { [[ "$IS_SOURCED" == "1" ]] && return "$EXIT_SCRIPT" || exit "$EXIT_SCRIPT"; }
( eval "$METTA_CMD"
echo $? > "$TEMP_EXIT_CODE_FILE" )
#rm -f "$TEE_FILE"
cleanup
fi