Perl: prototype in anonymous subroutine - namespaces

I am currently learning about Perls system of typeglobs and namespaces. So I wrote a module that takes two arguments the value and the name of a constant and exports the constant to the caller. The $package variable is equal to caller[2].
*{"$package::$name"} = sub () { return $value; };
This code above does the job of exporting a anonymous subroutine into the callers symboltable. Because my goal is to build my own constant-implementation the subroutine has a empty prototype which means its a read-only subroutine.
But this is my problem: the prototype does not work. So
print &TestConst; #works well
print TestConst(); #works well
print TestConst; #Name "main::TestConst" used only once: possible typo at testscript.pl line 7.
Is there something wrong in my thoughts? Is there another way of doing it?

You can define all the symbols you want during runtime, but prototypes will only affect code compiled afterwards since prototypes affect how calls to the sub are parsed and compiled. For example:
use strict;
use warnings;
package Foo;
BEGIN {
*Foo::bar = sub () { 42 };
}
*Foo::baz = sub () { 43 };
my $bar = bar;
my $baz = baz;
print "bar = [$bar], baz = [$baz]\n";
If we run this, it dies with:
Bareword "baz" not allowed while "strict subs" in use at tprot.pl line
13.
That's a compile-time error caused by strict: the compiler saw the symbol baz and didn't know what it was, because the typeglob *Foo::baz does not get altered until runtime. But bar worked fine because it was defined in a BEGIN block, which executes immediately during compilation.
IOW, because barewords are ambiguous, Perl needs to know at compile-time whether it's a sub or something else. So you can install these during import (which executes in an implicit BEGIN block) but not at runtime.
Additionally, prototypes affect compilation semantics; a constant subroutine (like those made by constant.pm) gets optimized away. Other prototypes cause the parser to change its behavior (e.g. subs which can take code blocks.) The compiler has to know about all this stuff before calls to the sub are actually encountered in the code, so they can be parsed correctly. The code runs after everything is already parsed.
Calling a sub with explicit parens or with an ampersand does not have this restriction because Perl is smart enough at runtime to know that these are subroutine calls, and to look them up dynamically in the symbol table.

Related

TCL API coverage : check if a TCL command have been called and tested exaustively in a test suite

Supposing I have a TCL API like :
namespaceXY::apiXY <value> -opt1 <value1> -opt2 <value2> -opt3 <value3>
This API is used (or maybe not) in a test suite (i.e thousands of tests).
How I can check if my API have been called + tested exhaustively (all options have been called/tested).
Many thanks
You can set an execution trace on the command. That way the signature of your command won't change. So you still get the same results if any code does info args namespaceXY::apiXY. Also error messages are not affected.
proc cmdtracer {cmd op} {
global cmdtracer
dict incr cmdtracer $cmd
}
trace add execution namespaceXY::apiXY enter cmdtracer
In the end you'll have a cmdtracer dict that contains the counts of each way the command was called. You will have to figure out yourself how to check if all options have been tested. There is not enough information in your question to provide suggestions for that part.
See #SchelteBron's answer for covering commands.
Exhaustively testing all options is going to be tricky, since they could potentially all interact in complex ways and some may be mutually-exclusive (think about the standard Tcl lsearch command for example). However, auditing that all options are at least called in your own commands can be done by additional audit-only probes. Checking all the sensible combinations of them is a manual task; you probably need a coverage tool for that.
Auditing Options in C Commands
Assuming that you're dealing with the case where you've got a C command that uses Tcl_GetIndexFromObj() to parse the option name (this is common and recommended) and where you don't mind having a threading hazard (also pretty common) the idea is simple. Make an integer variable (probably with file scope) in your C code, bind it to a Tcl variable with Tcl_LinkVar(), then use the resulting index from your (successful) Tcl_GetIndexFromObj() call to set a bit in that integer variable that says that the option was parsed.
#ifdef AUDIT_OPTIONS
static int foobar_optionTracker;
#endif
// in the implementation function, called FoobarImpl here for sake of argument
int index;
if (Tcl_GetIndexFromObj(interp, objPtr, optionNameTable, "option", 0, &index) != TCL_OK) {
return TCL_ERROR;
}
#ifdef AUDIT_OPTIONS
foobar_optionTracker |= 1 << index;
// Theoretically should call Tcl_UpdateLinkedVar() here, but for audit-only its not important
#endif
switch (index) {
// ...
}
// In your command registration function
Tcl_CreateObjCommand(interp, "foobar", FoobarImpl, NULL, NULL);
#ifdef AUDIT_OPTIONS
Tcl_LinkVar(interp, "optionTracker(foobar)", (void*) &foobar_optionTracker, TCL_LINK_INT);
#endif
With that in place, you can just read the array element optionTracker(foobar) from your Tcl test control code to see what options have been parsed (assuming you're happy with a bit-mask) in the foobar command since the last time the mask was reset. You reset the mask by just writing 0 to it.
Note that there's also Tcl_GetIndexFromObjStruct() in the C API, but auditing coverage of that is not significantly different from above.
Auditing Options in Tcl Commands
The equivalent of Tcl_GetIndexFromObj() in pure Tcl code is tcl::prefix match, but that doesn't return an index. Instead it returns the full option name that you can use with switch. Auditing that is most easily done with a full array. (This is morally the same as what the version for the C code does, but adapted to work with the optimal tools in a particular language.)
proc foobar {mandatoryArgument1 mandatoryArgument2 args} {
# Parse other things here, set up the TABLE of option descriptors, etc.
foreach option $args {
set option [tcl::prefix match $TABLE $option]
if {$::DoAudit} {
set ::foobarAudit($option) 1
}
switch -- $option {
# etc...
}
}
You can use things like array size foobarAudit to count the number of options actually used, or parray foobarAudit to print out what was actually used.

Ada package function identifier expected

Learning Ada and trying to make a stack ADT and I'm using this webpage to figure it out.
http://www.functionx.com/ada/Lesson06.htm
eightqueens.adb
with Ada.Text_IO;
use Ada.Text_IO;
with Stack;
use Stack;
procedure EightQueens is
begin
put_line ("awd");
end EightQueens;
stack.ads
package Stack is
function awd () return Integer;
end Stack;
stack.adb
package body Stack is
function awd () return integer is
begin
return 1;
end awd;
end Stack;
Error is
stack.ads:2:19: identifier expected
I'm most certain I did everything correctly.
Ada doesn't use empty parentheses, either for defining or for calling functions or procedures.
And for future reference, the phrase "I'm most certain I did everything correctly." is a red flag indicating that you've almost certainly done something wrong.
Just to elaborate, there are some syntactic decisions that Ada made that IMHO are superior to what you may be used to from C-syntax languages.
Functions with no parameters don't use empty parenthesis in their calls. This allows you to change a contant to a function call without having to recode any of the clients.
Arrays use parentheses like function calls do, rather than some unique syntax. This allows you to change an array constant to a function call without having to recode any of the clients.
To look at it another way, a constant is just a simplified version of a parameterless function, for when you can get away with always returning the same value. Likewise, a constant array is a simplified version of a parametered function call, for when you can get away with always returning the same value. If you later discover you need a more complex implementation, that's not the client's concern, and should not affect their code.

View nested private function definitions in PowerShell

PowerShell provides a simple technique to view the contents of a function, e.g.
Get-Content function:MyFuncName # (A)
or equivalently
(Get-ChildItem function:MyFuncName).definition # (B)
where MyFuncName is the name of my function. That is great for simple functions (i.e. functions that use only base language constructs and do not call other functions). But consider the function foo shown below that contains a call to the function bar. In a typical scenario these would both be contained in the same module whose public API consists solely of the function foo and thus it is the only function exported.
function foo ()
{
$p = bar "here"
"result is '$p'"
}
function bar ([string] $s)
{
$s + $s
}
Export-ModuleMember foo
Is there any way to view the nested, non-exported functions (like function bar) within another function in a fashion comparable to (A) or (B) above? (That is, without opening the .psm1 file in an editor :-)
I'm not sure if you can do it for a particular function in a module but you can do it for the whole module:
Import-Module C:\Test.psm1
(Get-Module Test).Definition
I think the fact that function foo calls function bar is not known until runtime.
Update
Where there's a will, there's a way :-) Here's how you can access private module members. Invoke the module with a scriptblock. Inside the scriptblock the private members are visible.
Import-Module C:\Test.psm1
$module = Get-Module Test
& $module { (get-item function:bar).Definition }
Thanks to PowerTips :-) http://powershell.com/cs/blogs/tips/archive/2009/09/18/accessing-hidden-module-members.aspx
Update 2
After finding the little PowerTip snippet I was kinda curious what was really going on... The snippet uses the call operator & with two arguments.
The module object (System.Management.Automation.PSModuleInfo)
A script block
So what's really going on is the Invoke method of the PSModuleInfo type is being called. The code in the script block runs within the same session state as the rest of the module code so it has access to the private members. This code does the exact same thing as the PowerTip snippet:
$module = Get-Module Test
$module.Invoke( { (get-item function:bar).Definition } )
Check out the invoke method here: http://msdn.microsoft.com/en-us/library/system.management.automation.psmoduleinfo.invoke(v=vs.85).aspx
No. The method you're using is getting the definition of the function via the function provider in the local scope. It will only see functions that have been defined in the local scope or that are visible in parent scopes.
When you call a function, it runs in it's own scope. Any functions the function creates will be created in that child scope, and only exist during the time that function is running. When the function is done, the scope it was running it gets disposed of, and all the functions it created go with it.

Fortran 90: How to use a module in a function

I am trying to write a fortran program that uses green's functions to solve the heat equation. I am useing fortran 90 as opposed to 77 in part because I am under the impression that it is pretty much a replica of fortran 77 but with a few very helpful features thrown in. Though the main reason is for free form coding. I have some "useful" constants and variables in a module named "useful." I want to include those variables and constants in most of my programs, subroutines, functions, etc. I am just learning fortran. I have programed in perl, C++, java, matlab, and mathematica. I am finding it very difficult. I do not understand the difference between a program and a subroutine. I definitely have no clear idea of what a module is. I have spent the past 12 hours researching these terms and have yet to get concise distinctions and definitions. I get an assortment of samples that show how to declare these things, but very little that actually delineates what they are supposed to be used for.
I would really appreciate an explanation as to why my function, "x" is not able to "use" my "useful" module.
Also, a clarification of the previously mentioned fortran features would be really helpful.
module useful
integer, parameter :: N=2
double precision, parameter :: xmin=1, xmax=10, pi=3.1415926535898
double complex :: green(N,N), solution(N), k=(2.0,0.0)
end module useful
program main
use useful
!real*8 :: delta = 2**-7
do n1 = 1, N
do n2 = 1, N
green(n1,n2) = exp((0,1)*k*abs(x(n2)-x(n1)))/(4*pi*abs(x(n2)-x(n1)))
print *, x(n2)
end do
end do
end program main
function x(n1)
use useful
real :: n1, x
x=n1*(xmax-xmin)/N
end function x
Let start with some definitions.
Fortran programs are composed of program units. In so-called Fortran 2008 (current standard) there are five types of program units:
main program;
external subprogram;
module;
submodule;
block data program unit.
Let me concentrate your attention on the first three.
Main program
As standard claims it is
program unit that is not a subprogram,
module, submodule, or block data
program unit.
Not very useful definition. =) What you should know is that main program unit starts with keyword PROGRAM, it is the entry point of application and obviously a program shall consist of exactly one main program.
A program may also consist any number (including zero) of other kinds of program units.
External subprogram
A subprogram defines a procedure. There are two types of procedures and of course two types of subprograms to define them:
function subprograms to define functions;
subroutine subprograms to define subroutines.
A function subprogram is a subprogram that has a FUNCTION statement as its first statement.
A subroutine subprogram is a subprogram that has a SUBROUTINE statement as its first statement.
Also both procedures and subprograms differ in place of their appearance in program. You can use:
external subprograms to define external procedures;
internal subprograms to define internal procedures;
module subprograms to define module procedures.
external subprogram
subprogram that is not contained in a
main program, module, submodule, or
another subprogram
internal subprogram
subprogram that is contained in a main program or
another subprogram
module subprogram
subprogram that is contained in a module or submodule
but is not an internal subprogram
Module
It is just a definitions (type denitions, procedure denitions, etc.) container.
Now small example.
main.f90
! Main program unit.
PROGRAM main
USE foo
IMPLICIT NONE
CALL external_bar
CALL internal_bar
CALL module_bar
CONTAINS
! Internal subprogram defines internal procedure.
SUBROUTINE internal_bar
PRINT *, "inside internal procedure"
END SUBROUTINE internal_bar
END PROGRAM main
foo.f90
! Module program unit.
MODULE foo
IMPLICIT NONE
CONTAINS
! Module subprogram defines module procedure.
SUBROUTINE module_bar
PRINT *, "inside module procedure"
END SUBROUTINE module_bar
END MODULE foo
bar.f90
! External subprogram program unit.
! External subprogram defines external procedure.
SUBROUTINE external_bar
PRINT *, "inside external procedure"
END SUBROUTINE external_bar
A module is a higher level of organization than a subroutine or function.
Function "x" should be able to use the module useful. I think it more likely that program "main" is having difficulty correctly accessing "x". You would do better to also place function "x" into the module after a "contains" statement. In this case remove the "use useful" statement from "x". Then the program main would have full knowledge of the interface ... in Fortran nomenclature, the interface is explicit. This ensures that the passing of arguments is consistent.
It would help if you showed the error messages from the compiler.
Fortran 95/2003 is much more than FORTRAN 77 with a few extra useful features. The changes are much larger. Trying to learn it from the web is not a good idea. I suggest that you find a copy of the book "Fortran 95/2003 Explained" by Metcalf, Reid and Cohen.
I see two problems in your program.
The main subroutine doesn't know what x() is. Is it a real function, integer function, etc.? You can either add the following to your main program
real, external :: x
Or (as others suggested) move function X() into your module.
To do this, add a "contains" statement near the end of the module and
put the function between the "contains" and the "end module".
You have an argument mismatch. In the main program, N1 is explicitly declared as a real variable. In function X(), N1 is declared as a real. You need to fix this.
I would strongly suggest that you add "implicit none" statements to your main program,
module, and function. This will force you to implicitly type each variable and function.

Accessing the Body of a Function with Lua

I'm going back to the basics here but in Lua, you can define a table like so:
myTable = {}
myTable [1] = 12
Printing the table reference itself brings back a pointer to it. To access its elements you need to specify an index (i.e. exactly like you would an array)
print(myTable ) --prints pointer
print(myTable[1]) --prints 12
Now functions are a different story. You can define and print a function like so:
myFunc = function() local x = 14 end --Defined function
print(myFunc) --Printed pointer to function
Is there a way to access the body of a defined function. I am trying to put together a small code visualizer and would like to 'seed' a given function with special functions/variables to allow a visualizer to 'hook' itself into the code, I would need to be able to redefine the function either from a variable or a string.
There is no way to get access to body source code of given function in plain Lua. Source code is thrown away after compilation to byte-code.
Note BTW that function may be defined in run-time with loadstring-like facility.
Partial solutions are possible — depending on what you actually want to achieve.
You may get source code position from the debug library — if debug library is enabled and debug symbols are not stripped from the bytecode. After that you may load actual source file and extract code from there.
You may decorate functions you're interested in manually with required metadata. Note that functions in Lua are valid table keys, so you may create a function-to-metadata table. You would want to make this table weak-keyed, so it would not prevent functions from being collected by GC.
If you would need a solution for analyzing Lua code, take a look at Metalua.
Check out Lua Introspective Facilities in the debugging library.
The main introspective function in the
debug library is the debug.getinfo
function. Its first parameter may be a
function or a stack level. When you
call debug.getinfo(foo) for some
function foo, you get a table with
some data about that function. The
table may have the following fields:
The field you would want is func I think.
Using the debug library is your only bet. Using that, you can get either the string (if the function is defined in a chunk that was loaded with 'loadstring') or the name of the file in which the function was defined; together with the line-numbers at which the function definition starts and ends. See the documentation.
Here at my current job we have patched Lua so that it even gives you the column numbers for the start and end of the function, so you can get the function source using that. The patch is not very difficult to reproduce, but I don't think I'll be allowed to post it here :-(
You could accomplish this by creating an environment for each function (see setfenv) and using global (versus local) variables. Variables created in the function would then appear in the environment table after the function is executed.
env = {}
myFunc = function() x = 14 end
setfenv(myFunc, env)
myFunc()
print(myFunc) -- prints pointer
print(env.x) -- prints 14
Alternatively, you could make use of the Debug Library:
> myFunc = function() local x = 14 ; debug.debug() end
> myFunc()
> lua_debug> _, x = debug.getlocal(3, 1)
> lua_debug> print(x) -- prints 14
It would probably be more useful to you to retrieve the local variables with a hook function instead of explicitly entering debug mode (i.e. adding the debug.debug() call)
There is also a Debug Interface in the Lua C API.