#! /usr/bin/python3
# Last edited on 2026-01-10 10:11:52 by stolfi
# python3 functions that check args and print error messages.
# To be imported by other python scripts.

import sys, os;
 
def check_num_arg(name, x, xmin, xmax):
  # Checksthat {x} is an integer in {xmin..xmax}:
  if x == "" or x == None:
    arg_error("must define {%s}" % name); 
  if fullmatch(r"[-+]?[0-9]+", x) == None: 
    arg_error("invalid arg value {%s} = '%s'" % (name, x)); 
  xnum = int(x);
  if (xnum < xmin) or (xnum > xmax): 
    arg_error("bad arg value {%s} = %d should be in %d..%d" % (name, xnum, xmin, xmax)); 
  return x;
  # ......................................................................
 
def arg_error(msg):
  sys.stderr.write("** %s\n" % msg);
  assert False
  # ......................................................................
 
def prog_error(msg):
  sys.stderr.write("** PROG ERROR: %s\n" % msg);
  assert False
  # ......................................................................
  
def file_line_error(filename,lnum,msg,line):
  sys.stderr.write("%s:%d: ** %s\n" % (filename, lnum, msg));
  if line != None and line != "": sys.stderr.write("  [[%s]]\n" % line)
  assert False
  # ......................................................................
  
def file_line_warning(filename,lnum,msg,line):
  sys.stderr.write("%s:%d: !! %s\n" % (filename, lnum, msg));
  if line != None and line != "": sys.stderr.write("  [[%s]]\n" % line)
  return
  # ......................................................................
   
def debug(name, arg):
  sys.stderr.write(f"{name}");
  if isinstance(arg, list) or isinstance(arg, tuple) or isinstance(arg, dict):
    sys.stderr.write(f" (length = {len(arg)}):\n")
    sys.stderr.write(r"  ")
  else:
    sys.stderr.write(r" = ")
  sys.stderr.write(f"{arg}\n")
  return
  # ----------------------------------------------------------------------
