using the add function in a modular project - module

I have modeled my project in alloy, and I want to separate the run part from the modeled part of my project.
In some fact and predicate I use the add function in cardinality comparison.
Here is an example :
#relation1 = add[ #(relation2), 1]
When the run part and the model part are in the same file all work successfully.
But when I separate them in 2 files, I have the following syntax error :
The name "add" cannot be found.
I thought it needed to open the integer module where there is an add function, so I have opened it it the header of the model part.
But then the runtime ask me to specify the scope of this/Univ.
You must specify a scope for sig "this/Univ"
Here is an example :
first the model in one module
module solo
open util/ordering [A] as chain
//open util/integer
sig A{ b : set B}
fact { all a : A - chain/last | #(a.next.b) = add[ #(a.b), 2]}
sig B{}
then the run part in another module :
module due
open solo
run {#(solo/chain/first.b) = 2 }for 10 B, 5 A
when I call it like this I have the "the name add cannot be found" error.
When I uncomment the integer module opening, I have the "You must specify a scope for sig "this/Univ"" error.
What should I do that to make it works?

If I'm not mistaken + is the union operator and thus can't be used to perform additions.
Which version of alloy are you using ?
I think the add[Int,Int] function was added recently, before it used to be plus[int,int].
You might want to try plus[Int,Int] and see if it solves your problem.
Else it would be nice to have access to your models. Maybe the error comes from elsewhere.

Related

How to use :since with CompUnit

I am trying to create a cache of POD6 by precompiling them using the CompUnit set of classes.
I can create, store and retrieve pod as follows:
use v6.c;
use nqp;
my $precomp-store = CompUnit::PrecompilationStore::File.new(prefix=>'cache'.IO);
my $precomp = CompUnit::PrecompilationRepository::Default.new(store=> $precomp-store );
my $key = nqp::sha1('test.pod6');
'test.pod6'.IO.spurt(q:to/CONTENT/);
=begin pod
=TITLE More and more
Some more text
=end pod
CONTENT
$precomp.precompile('test.pod6'.IO, $key, :force);
my $handle = $precomp.load($key, )[0];
my $resurrected = nqp::atkey($handle.unit,'$=pod')[0];
say $resurrected ~~ Pod::Block::Named;
So now I change the POD, how do I use the :since flag? I thought that if :since contains a time after the compilation, then the value of the handle would be Nil. That does not seem to be the case.
my $new-handle = $precomp.load($key, :since('test.pod6'.IO.modified));
say 'I got a new handle' with $new-handle;
Output is 'I got a new handle'.
What I am doing wrong?
Here is a pastebin link with code and output: https://pastebin.com/wtA9a0nP
Module loading code caches look ups and essentially start with:
$lock.protect: {
return %loaded{$id} if %loaded{$id}:exists;
}
So the question becomes "how do I load a module and then unload it (so i can load it again)?" to which the answer is: you cannot unload a module. You can however change the filename, distribution longname ( via changing the name, auth, api, or version ), or precomp id -- whatever a specific CompUnit::Repository uses to uniquely identify modules -- to bypass the cache.
What seems to be overlooked is that $key is intended to represent an immutable name, such that it will always point at the same content. What version of foo.pm should be loaded for Module Used::Inside::A if foo.pm is being loaded by Module A and B at the same time, Module A loads foo first, and then Module B modifies foo? The old version Module A loaded, or the ( possibly conflicting with previous version ) Module B loaded version? And how would this differentiation work for precomp file generation themselves ( which again can happen in parallel )?
Of course if we ignore the above we could add code to make expensive .IO.modified calls for every single module load for all CompUnit::Repository types ( slowing down startup speed ) to say "hey this immutable thing changed". But the granularity of file system modified timestamps on some OS's made the check pretty fragile ( especially for multi-threaded module loading with precomp files being generated ), meaning that even more expensive calls to get a checksum would be necessary every single time.

How to share a variable between two routers module in cro?

I try to use Cro to create a Rest API that will publish messages in rabbitMQ. I would like to split my routes in different modules and compose them with an "include". But I would like to be able to share the same connection to rabbitMQ in each of those modules too. I try with "our" but it does not work :
File 1:
unit module XXX::YYY;
use Cro::HTTP::Router;
use Cro::HTTP::Server;
use Cro::HTTP::Log::File;
use XXX::YYY::Route1;
use Net::AMQP;
our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;
my $application = route {
include <api v1 run> => run-routes;
}
...
File 2:
unit module XXX::YYY::Route1;
use UUID;
use Cro::HTTP::Router;
use JSON::Fast;
use Net::AMQP;
my $channel = $XXX::YYY::rabbitConnection.open-channel().result;
$channel.declare-queue("test_task", durable=> True );
sub run-routes() is export { ... }
Error message:
===SORRY!===
No such method 'open-channel' for invocant of type 'Any'
Thanks!
When you define your exportable route function you can specify arguments then in your composing module you can create the shared objects and pass them to the routes. For example in your router module :
sub run-routes ($rmq) is export{
route {
... $rmq is available in here
}
}
Then in your main router you can create your Queue and pass it in when including
my $rmq = # Insert queue creation code here
include product => run-routes( $rmq );
I've not tried this but I can't see any reason why it shouldn't work.
The answer by #Scimon is certainly correct, but it does not addresses the OP. On the other hand, the two comments by #ugexe and #raiph are spot-on, so I'll try to summarize them here and explain what's going on.
The error itself
This is the error:
Error message:
===SORRY!=== No such method 'open-channel' for invocant of type 'Any'
It indicates the invocant ($XXX::YYY::rabbitConnection) is of type Any, which is the type usually assigned to variables when they don't have a defined value; that is, basically, $XXX::YYY::rabbitConnection is not defined. It certainly is not since XXX::YYY is not included among the imported modules, as indicated by #ugexe.
The additioal problem indicated by the OP
That module was eliminated from the imported list because, as indicated by the OP
I certainly code it the wrong way because if i try to add use
XXX::YYY;, i get a Circular module loading detected error
But of course. since use XXX::YYY::Route1; which is file 2, is included in File 1.
The final solution is to reorganize files
That circular dependence probably points out to the fact that they should be in the same file, or else common code should be factored out to a third file, which would be eventually be included by both. So you should have something like
unit module XXX::YYY::Common;
use Net::AMQP;
our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;
And then
use XXX::YYY::Common;
in both modules.

Undefined global variable when using QuestaSim

I have a variable defined in foo_const.v which is defined like this in foo_const.v:
localparam NUM_BITS = 32;
Then I have another file foo_const_slice.v which does this:
localparam SLICE_ADDR_BITS = NUM_BITS;
This compiles fine with the vcs command:
vcs -sverilog foo_const.v foo_const_slice.v
But when I try to use QuestaSim:
vlog -work work -sv foo_const.v foo_const_slice.v
I get the following error message:
** Error: foo_const_slice.v(46): (vlog-2730) Undefined variable: 'NUM_BITS'.
The problem is that by default, each file that vlog compiles goes into a separate compilation unit, just like C/C++ and many other languages. By default, vcs concatenates all files together into a single compilation unit.
Although there is a way to change the default (you can look it up in the user manual), the proper way to code this is to put your parameters in a package, and import the package where needed.
Dave

How do I reload a module in an active Julia session after an edit?

2018 Update: Be sure to check all the responses, as the answer to this question has changed multiple times over the years. At the time of this update, the Revise.jl answer is probably the best solution.
I have a file "/SomeAbsolutePath/ctbTestModule.jl", the contents of which are:
module ctbTestModule
export f1
f1(x) = x + 1
end
I fire up Julia in a terminal, which runs "~/.juliarc.jl". The startup code includes the line:
push!(LOAD_PATH, "/SomeAbsolutePath/")
Hence I can immediately type into the Julia console:
using ctbTestModule
to load my module. As expected f1(1) returns 2. Now I suddenly decide I want to edit f1. I open up "/SomeAbsolutePath/ctbTestModule.jl" in an editor, and change the contents to:
module ctbTestModule
export f1
f1(x) = x + 2
end
I now try to reload the module in my active Julia session. I try
using ctbTestModule
but f1(1) still returns 2. Next I try:
reload("ctbTestModule")
as suggested here, but f1(1) still returns 2. Finally, I try:
include("/SomeAbsolutePath/ctbTestModule.jl")
as suggested here, which is not ideal since I have to type out the full absolute path since the current directory might not be "/SomeAbsolutePath". I get the warning message Warning: replacing module ctbTestModule which sounds promising, but f1(1) still returns 2.
If I close the current Julia session, start a new one, and type in using ctbTestModule, I now get the desired behaviour, i.e. f1(1) returns 3. But obviously I want to do this without re-starting Julia.
So, what am I doing wrong?
Other details: Julia v0.2 on Ubuntu 14.04.
The basis of this problem is the confluence of reloading a module, but not being able to redefine a thing in the module Main (see the documentation here) -- that is at least until the new function workspace() was made available on July 13 2014. Recent versions of the 0.3 pre-release should have it.
Before workspace()
Consider the following simplistic module
module TstMod
export f
function f()
return 1
end
end
Then use it....
julia> using TstMod
julia> f()
1
If the function f() is changed to return 2 and the module is reloaded, f is in fact updated. But not redefined in module Main.
julia> reload("TstMod")
Warning: replacing module TstMod
julia> TstMod.f()
2
julia> f()
1
The following warnings make the problem clear
julia> using TstMod
Warning: using TstMod.f in module Main conflicts with an existing identifier.
julia> using TstMod.f
Warning: ignoring conflicting import of TstMod.f into Main
Using workspace()
However, the new function workspace() clears Main preparing it for reloading TstMod
julia> workspace()
julia> reload("TstMod")
julia> using TstMod
julia> f()
2
Also, the previous Main is stored as LastMain
julia> whos()
Base Module
Core Module
LastMain Module
Main Module
TstMod Module
ans Nothing
julia> LastMain.f()
1
Use the package Revise, e.g.
Pkg.add("Revise") # do this only once
include("src/my_module.jl")
using Revise
import my_module
You may need to start this in a new REPL session. Notice the use of import instead of using, because using does not redefine the function in the Main module (as explained by #Maciek Leks and #waTeim).
Other solutions: Two advantages of Revise.jl compared to workspace() are that (1) it is much faster, and (2) it is future-proof, as workspace() was deprecated in 0.7, as discussed in this GitHub issue:
julia> VERSION
v"0.7.0-DEV.3089"
julia> workspace()
ERROR: UndefVarError: workspace not defined
and a GitHub contributor recommended Revise.jl:
Should we add some mesage like "workspace is deprecated, check out Revise.jl instead"?
Even in Julia 0.6.3, the three previous solutions of workspace(), import, and reload fail when a module called other modules, such as DataFrames. With all three methods, I got the same error when I called that module the second time in the same REPL:
ERROR: LoadError: MethodError: all(::DataFrames.##58#59, ::Array{Any,1}) is ambiguous. Candidates: ...
I also got many warning messages such as:
WARNING: Method definition macroexpand(Module, ANY) in module Compat at /Users/mmorin/.julia/v0.6/Compat/src/Compat.jl:87 overwritten in module Compat at /Users/mmorin/.julia/v0.6/Compat/src/Compat.jl:87.
Restarting the Julia session worked, but it was cumbersome. I found this issue in the Reexport package, with a similar error message:
MethodError: all(::Reexport.##2#6, ::Array{Any,1}) is ambiguous.
and followed the suggestion of one contributor:
Does this happen without using workspace()? That function is notorious for interacting poorly with packages, which is partly why it was deprecated in 0.7.
In my humble opinion, the better way is to use import from the very beginning instead of using for the reported issue.
Consider the module:
module ModuleX1
export produce_text
produce_text() = begin
println("v1.0")
end
println("v1.0 loaded")
end
Then in REPL:
julia> import ModuleX1
v1.0 loaded
julia> ModuleX1.produce_text()
v1.0
Update the code of the module and save it:
module ModuleX1
export produce_text
produce_text() = begin
println("v2.0")
end
println("v2.0 loaded")
end
Next, in the REPL:
julia> reload("ModuleX1")
Warning: replacing module ModuleX1
v2.0 loaded
julia> ModuleX1.produce_text()
v2.0
Advantages of using import over using:
avoiding ambiguity in function calls (What to call: ModuleX1.produce_text() or produce_text() after reloading?)
do not have to call workspace() in order to get rid of ambiguity
Disadvantages of using import over using:
a fully qualified name in every call for every exported name is needed
Edited: Discarded "full access to the module, even to the not-exported names" from "Disadvantages..." according to the conversation below.
workspace() has been deprecated.
You can reload("MyModule") in an active REPL session, and it works as expected: changes made to the source file that contains MyModule are reflected in the active REPL session.
This applies to modules that have been brought into scope by either import MyModule or using MyModule
I wanted to create a new module from scratch, and tried the different answers with 1.0 and didn’t get a satisfactory result, but I found the following worked for me:
From the Julia REPL in the directory I want to use for my project I run
pkg> generate MyModule
This creates a subdirectory like the following structure:
MyModule
├── Project.toml
└── src
└── MyModule.jl
I put my module code in MyModule.jl. I change to the directory MyModule (or open it in my IDE) and add a file Scratch.jl with the following code:
using Pkg
Pkg.activate(".")
using Revise
import MyModule # or using MyModule
Then I can add my code to test below and everything updates without reloading the REPL.
I battled to get Revise.jl to work for me, probably because I also use code generation with OOPMacro #class . I had to also call revise(...) See https://timholy.github.io/Revise.jl/stable/limitations/#Limitations-1.
I have been struggling with this problem for up to 5 years and finally got something that works for me that don't involve manually running my main module in the IDE repl after EVERY SMALL CHANGE :'(
Here is some of my code I use to force a revise and exit early when running tests when there were revise errors:
# Common code I include into my test files now:
using Pkg
using Revise
# force include module
Pkg.activate("MyModule")
include("../src/MyModule.jl")
Pkg.activate("MyModule/test")
using Revise
# if there were any revise errors which means some compilation error or
# some change that requires a manual rerun or restart.
# then force you to fix it, rather that running lying tests..
for (k, e) in Revise.queue_errors
if !isnothing(e)
warn(logger, "Something went wrong while revising, you probably have a compile error in this file:")
throw(e)
end
end
module TestSomethingModule
using Revise
using MyModule
revise(MyModule)
...
# then you can call MyModule.doSomithing in a test and it actually updates
end

How does R3 use the Needs field of a script header? Is there any impact on namespaces?

I'd like to know the behaviour of R3 when processing the Needs field of a script header and what implications for word binding it has.
Background. I'm currently trying to port some R2 scripts to R3 in order to learn R3. In R2 the Needs field of a script header was essentially just documentation, though I made use of it with a custom function to reference scripts that are required to make my script run.
R3 appears to call the Needs referenced scripts itself, but the binding seems different to DOing the other scripts.
For example when %test-parent.r is:
REBOL [
title: {test parent}
needs: [%test-child.r]
]
parent: now
?? parent
?? child
and %test-child is:
REBOL [
title: {test child}
]
child: now
?? child
R3 Alpha (Saphiron build 22-Feb-2013/11:09:25) returns:
>> do %test-parent.r
Script: "test parent" Version: none Date: none
child: 9-May-2013/22:51:52+10:00
parent: 9-May-2013/22:51:52+10:00
** Script error: child has no value
** Where: get ajoin case ?? catch either either -apply- do
** Near: get :name
I don't understand why test-parent cannot access Child set by %test-child.r
If I remove the Needs field from test-parent.r header and instead insert a line to just DO %test-child.r then there is no error and the script performs as expected.
Ah, you've run into Rebol 3's policy to "do what you say, it can't read your mind". R3's Needs header is part of its module system, so anything you load with Needs is actually imported as a module, even if it isn't declared as such.
Loading scripts with Needs is a quick way to get them treated as modules even in the original author didn't declare them as such. Modules get their own contexts where their words are defined. Loading a script as a module is a great way to use a script that isn't that tidy, that leaks words into the shared script context. Like your %test-child.r script, it leaks the word child into the script context, what if you didn't want that to happen? Load it with Needs or import and that will clean that right up.
If you want a script treated as a script, use do to run it. Regular scripts use a (mostly) shared context, so when you do a script it has effect on the same context as the script you called it from. That is why the child: now statement affected child in the parent script. Sometimes that's what you want to do, which is why we worked so hard to make scripts work that way in R3.
If you are going to use Needs or import to load your own scripts, you might as well make them modules and export what you want, like this:
REBOL [
type: module
title: {test child}
exports: [child]
]
child: now
?? child
As before, you don't even have to include the type: module if you are going to be using Needs or import anyway, but it would help just in case you run your module with do. R3 assumes that if you declare your module to be a module, that you wrote it to be a module and depend on it working that way even if it's called with do. At the least, declaring a type header is a stronger statement than not declaring a type header at all, so it takes precedence in the conflicting "do what you say" situation.
Look here for more details about how the module system works: How are words bound within a Rebol module?