When I use DecoupledIO, it seems that it generates errors caused by Reference io is not fully initialized.
This is because I have to initialize Output, in this case, bits, and valid or ready(depending on flipped or not)
Let's assume that bits and valid is Output.
when I use following statement:
when(reset.toBool) {
bits := 0.U
valid := true.B
}
it generates error.
But when the initialize statement exist outside of when statement, it does not produce errors.
So, how to solve such initialization problems?
Do I always have to initialize such values outside of when statement although I want to put it inside when(reset.toBool) statement?
Even, the router example in the wiki page produces error even though I follow the guide described by unconnected wire section(this was due to the fact that all init statement exist inside when statement)
This is a good question but a little hard to explain. When you wrap the output initialization in the when(io.reset) it creates a edge case where the wire may not be initialized if reset is not been asserted. The easiest fix is to do both
bits := 0.U
valid := true.B
when(reset.toBool) {
bits := 0.U
valid := true.B
}
Last connect semantics will ensure that the reset and decoupled behavior is take precedence but that you will have covered the edge case. The chisel team is aware of this problem and looking for a more elegant situation. See Chisel Issue 703
Related
How can I throw standard system exceptions (and if possible, create custom exceptions and throw them too).
The simplest thing that comes to mind, is to just divide a variable by zero, but that's just a hack at best.
I did find mentions of a function AppGenerateException in the CmpApp library, but I can't find any documentation for it, nor any examples. Can anybody point me to some documentation for this?
Out of curiosity I checked the AppGenerateException and got it working. Got some help from this Codesys help page.
I still think this is not the best way to achieve what you need, but it could work.
Unfortunately, I have 64 bit system and the TRY..CATCH is not yet working in other that 32 bit systems as far as I know, so I couldn't test catching.
Add the following libraries:
CmpApp
SysExcept
Then the following code seems to work. Set ThrowErr to true to get the system exception.
PROGRAM PRG_TestThrow
VAR CONSTANT
MY_PRIVATE_EXCEPTION : DWORD := 32001;
END_VAR
VAR
ThrowErr : BOOL; //Set this to TRUE to throw an error
//The next two are for getting App instance
_pApp : POINTER TO CmpApp.APPLICATION;
_Result : SysExcept.SysTypes.RTS_IEC_RESULT;
END_VAR
//Get App instance
_pApp := AppGetCurrent(pResult := ADR(_Result));
IF ThrowErr THEN
ThrowErr := FALSE;
IF _pApp <> 0 THEN
//Throw divide by zero exception
AppGenerateException(pApp:=_pApp, ulException:=RtsExceptions.RTSEXCPT_DIVIDEBYZERO);
//You could use probably any available number as your own custom exception.
//For example the following works BUT not sure if it's ok to this.
//AppGenerateException(pApp:=_pApp, ulException:=MY_PRIVATE_EXCEPTION);
//See RtsExceptions type for available exception codes.
//For my Codesys version, it has largest exception number of 0x2000 so all larger number are free (for now...)
END_IF
END_IF
It seems that it's possibly to use any custom exception code like:
AppGenerateException(pApp:=_pApp, ulException:=MY_PRIVATE_EXCEPTION);
But it's not documented so I would be careful.
In C when I return a pointer of a stack-created variable from a function, the memory discards after the function is returned, thus making the pointer impossible to dereference. But in Go, the compiler is not giving me any errors. Does that mean that this is safe to do?
package main
import (
"fmt"
)
func main() {
fmt.Println(*(something()))
}
func something() *string {
s := "a"
return &s
}
Yes, this is safe and a normal pattern in Go programming. Go uses escape analysis to move any values with pointers that escape the stack to the heap automatically. You don't need to be concerned with where values are allocated.
From the Go FAQ: "How do I know whether a variable is allocated on the heap or the stack?"
if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors
You can see these optimization choices during compilation by using the -gcflags -m option.
Yes, in Golang it is fine to return a pointer to a local variable. Golang will manage the objects lifetime for you and free it when all pointers to it are gone.
In another answer I point out all the differences between C/C++ pointers and Golang pointers: What is the meaning of '*' and '&' in Golang?
So I'm just starting to learn Eiffel. One of the first exercises in the book I'm using says to make a function that does base^exp without using ^. I've copied my code below.
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create power(2;3)
printf("2 to the power of 3 is " + answer)
end
power(base : REAL; exp : INTEGER) : REAL
-- computers base raised to the bower of exp without using ^
local
remain : INTEGER
do
remain := exp
if remain = 0 then
result := 1
else
from
until
remain = 0
loop
result := result * result
remain := remain -1
end
end
end
end
How do I use this? Do I need it on the same level as feature{NONE}'s make? I know how I'm calling it is wrong, and I can't find anything in the chapter I just read, or online on how to pass parameters into it or how to use it's results.
There are several issues with the original code:
create is used to create an object, but you are not going to create anything, but to get a result of a computation of the function power by calling it. Therefore the keyword create is not needed.
You are using an entity answer to report the result of evaluation on a screen. However it is not declared anywhere. I believe the proper place would be a local variable declaration section.
The entity answer is not initialized to the result of the function power. This is usually done by an assignment instruction.
Feature arguments are separated by a comma, not by a semicolon.
From the original code it's unclear what is the type of the variable answer. Assuming it matches the type of the function power, before adding it to a string, it needs to be converted to a string. This is done by calling the feature out.
The standard feature for printing a string to a console is print, not printf.
Combining the critical points above, we get
make
-- Run application.
local
answer: REAL
do
answer := power(2, 3)
print ("2 to the power of 3 is " + answer.out)
end
After that the code can be compiled. Now less critical points:
It is a good style to put features to a dedicated feature clauses, so I would add a line like feature -- Basic operations before the feature power.
The implementation of the feature power has at least two problems. I'm not going to detail them here, but would give two hints instead:
by default numeric Result is initialized to 0, this needs to be taken into account for operations that use it without first assigning any other value
even though an argument base is passed to the function power it remains unused in the original version of the code
How can I avoid getting an error when passing as argument to the function do-http-request an invalid host.
Is there any way that I can catch the error like the Java's exception-handling mechanism ?
Sure, CL has a very nice condition system. One easy option would be wrapping the call to do-http-request in ignore-errors, which returns nil (and the condition as a second value) if an error condition was signalled in the wrapped code. You could then check for nil afterwards.
If you want something more like exception handling in Java, just use handler-case and add an appropriate error clause (I don't have AllegroServe installed, but I suppose you get a socket-error for providing a wrong URL – just change that part if I misread):
(handler-case
(do-http-request …)
(socket-error ()
…))
If you need finally-like functionality, use unwind-protect:
(unwind-protect
(handler-case
(do-http-request …)
(socket-error (condition) ; bind the signalled condition
…) ; code to run when a socket-error was signalled
(:no-error (value) ; bind the returned value
…)) ; code to run when no condition was signalled
…) ; cleanup code (finally)
You can even get more fancy, and e.g. use handler-bind to handle the condition stack upwards by invoking a restart somewhere down the stack, without unwinding it. For example, if do-http-request provided a restart to try again with another URL, you could handle your error condition by invoking that restart with a new URL to retry. I just mention this for the sake of completeness – it would be overkill for your use case, but being able to resume (possibly expensive) computations easily can be a rather convenient feature.
Do you check for data validity in every constructor, or do you just assume the data is correct and throw exceptions in the specific function that has a problem with the parameter?
A constructor is a function too - why differentiate?
Creating an object implies that all the integrity checks have been done. It's perfectly reasonable to check parameters in a constructor and throw an exception once an illegal value has been detected.
Among all this simplifies debugging. When your program throws exception in a constructor you can observe a stack trace and often immediately see the cause. If you delay the check you'll then have to do more investigation to detect what earlier event causes the current error.
It's always better to have a fully-constructed object with all the invariants "satisfied" from the very beginning. Beware, however, of throwing exceptions from constructor in non-managed languages since that may result in a memory leak.
I always coerce values in constructors. If the users can't be bothered to follow the rules, I just silently enforce them without telling them.
So, if they pass a value of 107%, I'll set it to 100%. I just make it clear in the documentation that that's what happens.
Only if there's no obvious logical coercion do I throw an exception back to them. I like to call this the "principal of most astonishment to those too lazy or stupid to read the documentation".
If you throw in the constructor, the stack trace is more likely to show where the wrong values are coming from.
I agree with sharptooth in the general case, but there are sometimes objects that can have states in which some functions are valid and some are not. In these situations it's better to defer checks to the functions with these particular dependencies.
Usually you'll want to validate in a constructor, if only because that means your objects will always be in a valid state. But some kinds of objects need function-specific checks, and that's OK too.
This is a difficult question. I have changed my habit related to this question several times in the last years, so here are some thoughts coming to my mind :
Checking the arguments in the constructor is like checking the arguments for a traditional method... so I would not differentiate here...
Checking the arguments of a method of course does help to ensure parameters passed are correct, but also introduces a lot of more code you have to write, which not always pays off in my opinion... Especially when you do write short methods which delegate quite frequently to other methods, I guess you would end up with 50 % of your code just doing parameter checks...
Furthermore consider that very often when you write a unit test for your class, you don't want to have to pass in valid parameters for all methods... Quite often it does make sense to only pass those parameters important for the current test case, so having checks would slow you down in writing unit tests...
I think this really depends on the situation... what I ended up is to only write parameter checks when I know that the parameters do come from an external system (like user input, databases, web services, or something like that...). If data comes from my own system, I don't write tests most of the time.
I always try to fail as early as possible. So I definitively check the parameters in the constructor.
In theory, the calling code should always ensure that preconditions are met, before calling a function. The same goes for constructors.
In practice, programmers are lazy, and to be sure it's best to still check preconditions. Asserts come in handy there.
Example. Excuse my non-curly brace syntax:
// precondition b<>0
function divide(a,b:double):double;
begin
assert(b<>0); // in case of a programming error.
result := a / b;
end;
// calling code should be:
if foo<>0 then
bar := divide(1,0)
else
// do whatever you need to do when foo equals 0
Alternatively, you can always change the preconditions. In case of a constructor this is not really handy.
// no preconditions.. still need to check the result
function divide(a,b:double; out hasResult:boolean):double;
begin
hasResult := b<>0;
if not hasResult then
Exit;
result := a / b;
end;
// calling code:
bar := divide(1,0,result);
if not result then
// do whatever you need to do when the division failed
Always fail as soon as possible. A good example of this practice is exhibited by the runtime ..
* if you try and use an invalid index for an array you get an exception.
* casting fails immediately when attempted not at some later stage.
Imagine what a disaster code be if a bad cast remained in a reference and everytime you tried to use that you got an exception. The only sensible approach is to fail as soon as possible and try and avoid bad / invalid state asap.