slang-users mailing list

[2008 Date Index] [2008 Thread Index] [Other years]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]

Re: [slang-users] Support for assertions?


On Sat, 6 Dec 2008 23:08:09 +0000 (UTC), Jörg Sommer <joerg@xxxxxxxxxxxx>
wrote:
> do you plan to add support for assertion? I would like to write something
> like assert(a == 4) and if it is false I want to get an AssertError with
> the message “Assertion failed: a == 4”—or something this way.

I had not planned on it but I will think about it for 2.2.

> I can't solve it easily with a function, because a function gets the
> value of “a == 4” and not the expression. Using eval in the assert
> function might not work, because a might be a local variable in the
> calling function.

The following (convoluted) function might work.  You would use it as
in the following example:

define slsh_main ()
{
   variable foo = 1;

   assert ("foo==2");
}

define assert(expr)
{
   variable info = _get_frame_info (-1);
   variable localvars = info.locals;
   variable a = Assoc_Type[];
   foreach (localvars)
     {
	variable lvar = ();
	try
	  {
	     a[lvar] = _get_frame_variable (-1, lvar);
	  }
	catch VariableUninitializedError;
     }
   variable inited_vars = assoc_get_keys (a);
   variable uninited_vars = String_Type[0];
   foreach (localvars)
     {
	lvar = ();
	if (assoc_key_exists (a, lvar))
	  continue;
	uninited_vars = [uninited_vars, lvar];
     }
   if (length (uninited_vars))
     uninited_vars = strcat ("variable ", strjoin (uninited_vars, ","), ";");
   else
     uninited_vars = "";

   variable fmt = "private define %s (%s) { %s %s;}";
   variable dummy = "__assert_internal_function";
   variable fun = sprintf (fmt, dummy, strjoin (inited_vars, ","), 
			   uninited_vars, expr);
   eval ("_use_frame_namespace(-1); $fun"$);

  foreach lvar (inited_vars)
     {
	a[lvar];
     }
   ifnot (eval ("_use_frame_namespace(-1); $dummy;"$))
     {
	throw RunTimeError, 
	  sprintf ("Assertion failed: %s at %S:%S", 
		   expr, info.file, info.line);
     }
}

Thanks,
--John



[2008 date index] [2008 thread index]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]